context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using JoinRpg.Data.Write.Interfaces; using JoinRpg.DataModel; using JoinRpg.Domain; using JoinRpg.Services.Interfaces; namespace JoinRpg.Services.Impl { [UsedImplicitly] public class FieldSetupServiceImpl: DbServiceImplBase, IFieldSetupService { public async Task AddField(int projectId, ProjectFieldType fieldType, string name, string fieldHint, bool canPlayerEdit, bool canPlayerView, bool isPublic, FieldBoundTo fieldBoundTo, MandatoryStatus mandatoryStatus, List<int> showForGroups, bool validForNpc, bool includeInPrint, bool showForUnapprovedClaims, int price, string masterFieldHint) { var project = await ProjectRepository.GetProjectAsync(projectId); project.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); var field = new ProjectField { FieldType = fieldType, FieldBoundTo = fieldBoundTo, FieldName = Required(name), Description = new MarkdownString(fieldHint), MasterDescription = new MarkdownString(masterFieldHint), CanPlayerEdit = canPlayerEdit, CanPlayerView = canPlayerView, ValidForNpc = validForNpc, IsPublic = isPublic, ProjectId = projectId, Project = project, //We require it for CreateOrUpdateSpecailGroup IsActive = true, MandatoryStatus = mandatoryStatus, AvailableForCharacterGroupIds = await ValidateCharacterGroupList(projectId, showForGroups), IncludeInPrint = includeInPrint, ShowOnUnApprovedClaims = showForUnapprovedClaims, Price = price, }; CreateOrUpdateSpecialGroup(field); UnitOfWork.GetDbSet<ProjectField>().Add(field); await UnitOfWork.SaveChangesAsync(); } public async Task UpdateFieldParams(int projectId, int fieldId, string name, string fieldHint, bool canPlayerEdit, bool canPlayerView, bool isPublic, MandatoryStatus mandatoryStatus, List<int> showForGroups, bool validForNpc, bool includeInPrint, bool showForUnapprovedClaims, int price, string masterFieldHint) { var field = await ProjectRepository.GetProjectField(projectId, fieldId); field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); // If we are changing field.CanPlayerEdit, we should update variants to match if (field.CanPlayerEdit != canPlayerEdit) { foreach (var variant in field.DropdownValues) { variant.PlayerSelectable = canPlayerEdit; } } field.FieldName = Required(name); field.Description = new MarkdownString(fieldHint); field.MasterDescription = new MarkdownString(masterFieldHint); field.CanPlayerEdit = canPlayerEdit; field.CanPlayerView = canPlayerView; field.IsPublic = isPublic; field.IsActive = true; field.MandatoryStatus = mandatoryStatus; field.ValidForNpc = validForNpc; field.AvailableForCharacterGroupIds = await ValidateCharacterGroupList(projectId, showForGroups); field.IncludeInPrint = includeInPrint; field.ShowOnUnApprovedClaims = showForUnapprovedClaims; field.Price = price; CreateOrUpdateSpecialGroup(field); await UnitOfWork.SaveChangesAsync(); } public async Task<ProjectField> DeleteField(int projectId, int projectFieldId) { ProjectField field = await ProjectRepository.GetProjectField(projectId, projectFieldId); await DeleteField(field); return field; } /// <summary> /// Deletes field by its object. We assume here that field represents really existed field in really existed project /// </summary> /// <param name="field">Field to delete</param> public async Task DeleteField(ProjectField field) { field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); foreach (var fieldValueVariant in field.DropdownValues.ToArray()) //Required, cause we modify fields inside. { DeleteFieldVariantValueImpl(fieldValueVariant); } var characterGroup = field.CharacterGroup; // SmartDelete will nullify all depend properties if (SmartDelete(field)) { SmartDelete(characterGroup); } else if (characterGroup != null) { characterGroup.IsActive = false; } await UnitOfWork.SaveChangesAsync(); } public FieldSetupServiceImpl(IUnitOfWork unitOfWork) : base(unitOfWork) { } public async Task CreateFieldValueVariant(CreateFieldValueVariantRequest request) { var field = await ProjectRepository.GetProjectField(request.ProjectId, request.ProjectFieldId); field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); CreateFieldValueVariantImpl(request, field); await UnitOfWork.SaveChangesAsync(); } private void CreateFieldValueVariantImpl(CreateFieldValueVariantRequest request, ProjectField field) { var fieldValue = new ProjectFieldDropdownValue() { Description = new MarkdownString(request.Description), Label = request.Label, IsActive = true, WasEverUsed = false, ProjectId = field.ProjectId, ProjectFieldId = field.ProjectFieldId, Project = field.Project, ProjectField = field, MasterDescription = new MarkdownString(request.MasterDescription), ProgrammaticValue = request.ProgrammaticValue, Price = request.Price, PlayerSelectable = request.PlayerSelectable && field.CanPlayerEdit }; CreateOrUpdateSpecialGroup(fieldValue); field.DropdownValues.Add(fieldValue); } private void CreateOrUpdateSpecialGroup(ProjectFieldDropdownValue fieldValue) { var field = fieldValue.ProjectField; if (!field.HasSpecialGroup()) { return; } CreateOrUpdateSpecialGroup(field); if (fieldValue.CharacterGroup == null) { fieldValue.CharacterGroup = new CharacterGroup() { AvaiableDirectSlots = 0, HaveDirectSlots = false, ParentCharacterGroupIds = new[] { field.CharacterGroup.CharacterGroupId }, ProjectId = fieldValue.ProjectId, IsRoot = false, IsSpecial = true, ResponsibleMasterUserId = null, }; MarkCreatedNow(fieldValue.CharacterGroup); } UpdateSpecialGroupProperties(fieldValue); } private void UpdateSpecialGroupProperties(ProjectFieldDropdownValue fieldValue) { var field = fieldValue.ProjectField; var characterGroup = fieldValue.CharacterGroup; var specialGroupName = fieldValue.GetSpecialGroupName(); Debug.Assert(characterGroup != null, "characterGroup != null"); if (characterGroup.IsPublic != field.IsPublic || characterGroup.IsActive != fieldValue.IsActive || characterGroup.Description != fieldValue.Description || characterGroup.CharacterGroupName != specialGroupName) { characterGroup.IsPublic = field.IsPublic; characterGroup.IsActive = fieldValue.IsActive; characterGroup.Description = fieldValue.Description; characterGroup.CharacterGroupName = specialGroupName; MarkChanged(characterGroup); } } private void CreateOrUpdateSpecialGroup(ProjectField field) { if (!field.HasSpecialGroup()) { return; } if (field.CharacterGroup == null) { field.CharacterGroup = new CharacterGroup() { AvaiableDirectSlots = 0, HaveDirectSlots = false, ParentCharacterGroupIds = new[] { field.Project.RootGroup.CharacterGroupId }, ProjectId = field.ProjectId, IsRoot = false, IsSpecial = true, ResponsibleMasterUserId = null, }; MarkCreatedNow(field.CharacterGroup); } foreach (var fieldValue in field.DropdownValues) { if (fieldValue.CharacterGroup == null) continue; //We can't convert to LINQ because of RSRP-457084 UpdateSpecialGroupProperties(fieldValue); } UpdateSpecialGroupProperties(field); } private void UpdateSpecialGroupProperties(ProjectField field) { var characterGroup = field.CharacterGroup; var specialGroupName = field.GetSpecialGroupName(); if (characterGroup.IsPublic != field.IsPublic || characterGroup.IsActive != field.IsActive || characterGroup.Description != field.Description || characterGroup.CharacterGroupName != specialGroupName) { characterGroup.IsPublic = field.IsPublic; characterGroup.IsActive = field.IsActive; characterGroup.Description = field.Description; characterGroup.CharacterGroupName = specialGroupName; MarkChanged(characterGroup); } } public async Task UpdateFieldValueVariant(UpdateFieldValueVariantRequest request) { var field = await ProjectRepository.GetFieldValue(request.ProjectId, request.ProjectFieldId, request.ProjectFieldDropdownValueId); field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); field.Description = new MarkdownString(request.Description); field.Label = request.Label; field.IsActive = true; field.MasterDescription = new MarkdownString(request.MasterDescription); field.ProgrammaticValue = request.ProgrammaticValue; field.Price = request.Price; field.PlayerSelectable = request.PlayerSelectable; CreateOrUpdateSpecialGroup(field); await UnitOfWork.SaveChangesAsync(); } public async Task<ProjectFieldDropdownValue> DeleteFieldValueVariant(int projectId, int projectFieldId, int valueId) { var value = await ProjectRepository.GetFieldValue(projectId, projectFieldId, valueId); value.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); DeleteFieldVariantValueImpl(value); await UnitOfWork.SaveChangesAsync(); return value; } private void DeleteFieldVariantValueImpl(ProjectFieldDropdownValue value) { var characterGroup = value.CharacterGroup; // SmartDelete will nullify all depend properties if (SmartDelete(value)) { SmartDelete(characterGroup); } else { if (characterGroup != null) { characterGroup.IsActive = false; } } } public async Task MoveField(int projectId, int projectcharacterfieldid, short direction) { var field = await ProjectRepository.GetProjectField(projectId, projectcharacterfieldid); field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); field.Project.ProjectFieldsOrdering = field.Project.GetFieldsContainer().Move(field, direction).GetStoredOrder(); await UnitOfWork.SaveChangesAsync(); } public async Task MoveFieldVariant(int projectid, int projectFieldId, int projectFieldVariantId, short direction) { var field = await ProjectRepository.GetProjectField(projectid, projectFieldId); field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); field.ValuesOrdering = field.GetFieldValuesContainer() .Move(field.DropdownValues.Single(v => v.ProjectFieldDropdownValueId == projectFieldVariantId), direction) .GetStoredOrder(); await UnitOfWork.SaveChangesAsync(); } public async Task CreateFieldValueVariants(int projectId, int projectFieldId, string valuesToAdd) { var field = await ProjectRepository.GetProjectField(projectId, projectFieldId); field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); foreach (var label in valuesToAdd.Split('\n').Select(v => v.Trim()).Where(v => !string.IsNullOrEmpty(v))) { CreateFieldValueVariantImpl(new CreateFieldValueVariantRequest(field.ProjectId, label, null, field.ProjectFieldId, null, null, 0, true), field); } await UnitOfWork.SaveChangesAsync(); } public async Task MoveFieldAfter(int projectId, int projectFieldId, int? afterFieldId) { var field = await ProjectRepository.GetProjectField(projectId, projectFieldId); var afterField = afterFieldId == null ? null : await ProjectRepository.GetProjectField(projectId, (int)afterFieldId); field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields); field.Project.ProjectFieldsOrdering = field.Project.GetFieldsContainer().MoveAfter(field, afterField).GetStoredOrder(); await UnitOfWork.SaveChangesAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO { /* * This class is used to access a contiguous block of memory, likely outside * the GC heap (or pinned in place in the GC heap, but a MemoryStream may * make more sense in those cases). It's great if you have a pointer and * a length for a section of memory mapped in by someone else and you don't * want to copy this into the GC heap. UnmanagedMemoryStream assumes these * two things: * * 1) All the memory in the specified block is readable or writable, * depending on the values you pass to the constructor. * 2) The lifetime of the block of memory is at least as long as the lifetime * of the UnmanagedMemoryStream. * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream * currently will do NOTHING to free this memory. * 4) All calls to Write and WriteByte may not be threadsafe currently. * * It may become necessary to add in some sort of * DeallocationMode enum, specifying whether we unmap a section of memory, * call free, run a user-provided delegate to free the memory, etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. * Check for problems when using this in the negative parts of a * process's address space. We may need to use unsigned longs internally * and change the overflow detection logic. * * -----SECURITY MODEL AND SILVERLIGHT----- * A few key notes about exposing UMS in silverlight: * 1. No ctors are exposed to transparent code. This version of UMS only * supports byte* (not SafeBuffer). Therefore, framework code can create * a UMS and hand it to transparent code. Transparent code can use most * operations on a UMS, but not operations that directly expose a * pointer. * * 2. Scope of "unsafe" and non-CLS compliant operations reduced: The * Whidbey version of this class has CLSCompliant(false) at the class * level and unsafe modifiers at the method level. These were reduced to * only where the unsafe operation is performed -- i.e. immediately * around the pointer manipulation. Note that this brings UMS in line * with recent changes in pu/clr to support SafeBuffer. * * 3. Currently, the only caller that creates a UMS is ResourceManager, * which creates read-only UMSs, and therefore operations that can * change the length will throw because write isn't supported. A * conservative option would be to formalize the concept that _only_ * read-only UMSs can be creates, and enforce this by making WriteX and * SetLength SecurityCritical. However, this is a violation of * security inheritance rules, so we must keep these safe. The * following notes make this acceptable for future use. * a. a race condition in WriteX that could have allowed a thread to * read from unzeroed memory was fixed * b. memory region cannot be expanded beyond _capacity; in other * words, a UMS creator is saying a writable UMS is safe to * write to anywhere in the memory range up to _capacity, specified * in the ctor. Even if the caller doesn't specify a capacity, then * length is used as the capacity. */ /// <summary> /// Stream over a memory pointer or over a SafeBuffer /// </summary> public class UnmanagedMemoryStream : Stream { [System.Security.SecurityCritical] // auto-generated private SafeBuffer _buffer; [SecurityCritical] private unsafe byte* _mem; private long _length; private long _capacity; private long _position; private long _offset; private FileAccess _access; private bool _isOpen; private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync /// <summary> /// This code is copied from system\buffer.cs in mscorlib /// </summary> /// <param name="src"></param> /// <param name="len"></param> [System.Security.SecurityCritical] // auto-generated private unsafe static void ZeroMemory(byte* src, long len) { while (len-- > 0) *(src + len) = 0; } /// <summary> /// Creates a closed stream. /// </summary> // Needed for subclasses that need to map a file, etc. [System.Security.SecuritySafeCritical] // auto-generated protected UnmanagedMemoryStream() { unsafe { _mem = null; } _isOpen = false; } /// <summary> /// Creates a stream over a SafeBuffer. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) { Initialize(buffer, offset, length, FileAccess.Read, false); } /// <summary> /// Creates a stream over a SafeBuffer. /// </summary> [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="access"></param> [System.Security.SecuritySafeCritical] // auto-generated protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } [System.Security.SecurityCritical] // auto-generated private void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.ByteLength < (ulong)(offset + length)) { throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException(nameof(access)); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); } // check for wraparound unsafe { byte* pointer = null; try { buffer.AcquirePointer(ref pointer); if ((pointer + offset + length) < pointer) { throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _length = length; _capacity = length; _access = access; _isOpen = true; } /// <summary> /// Creates a stream over a byte*. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length) { Initialize(pointer, length, length, FileAccess.Read, false); } /// <summary> /// Creates a stream over a byte*. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> [System.Security.SecurityCritical] // auto-generated private unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { if (pointer == null) throw new ArgumentNullException(nameof(pointer)); if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", SR.ArgumentOutOfRange_NeedNonNegNum); if (length > capacity) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity); Contract.EndContractBlock(); // Check for wraparound. if (((byte*)((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (_isOpen) throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); _mem = pointer; _offset = 0; _length = length; _capacity = capacity; _access = access; _isOpen = true; } /// <summary> /// Returns true if the stream can be read; otherwise returns false. /// </summary> public override bool CanRead { [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } /// <summary> /// Returns true if the stream can seek; otherwise returns false. /// </summary> public override bool CanSeek { [Pure] get { return _isOpen; } } /// <summary> /// Returns true if the stream can be written to; otherwise returns false. /// </summary> public override bool CanWrite { [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } /// <summary> /// Closes the stream. The stream's memory needs to be dealt with separately. /// </summary> /// <param name="disposing"></param> [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { _isOpen = false; unsafe { _mem = null; } // Stream allocates WaitHandles for async calls. So for correctness // call base.Dispose(disposing) for better perf, avoiding waiting // for the finalizers to run on those types. base.Dispose(disposing); } /// <summary> /// Since it's a memory stream, this method does nothing. /// </summary> public override void Flush() { if (!_isOpen) throw Error.GetStreamIsClosed(); } /// <summary> /// Since it's a memory stream, this method does nothing specific. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Flush(); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } /// <summary> /// Number of bytes in the stream. /// </summary> public override long Length { get { if (!_isOpen) throw Error.GetStreamIsClosed(); return Interlocked.Read(ref _length); } } /// <summary> /// Number of bytes that can be written to the stream. /// </summary> public long Capacity { get { if (!_isOpen) throw Error.GetStreamIsClosed(); return _capacity; } } /// <summary> /// ReadByte will read byte at the Position in the stream /// </summary> public override long Position { get { if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); return Interlocked.Read(ref _position); } [System.Security.SecuritySafeCritical] // auto-generated set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); if (IntPtr.Size == 4) { unsafe { // On 32 bit process, ensure we don't wrap around. if (value > (long)Int32.MaxValue || _mem + value < _mem) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } } Interlocked.Exchange(ref _position, value); } } /// <summary> /// Pointer to memory at the current Position in the stream. /// </summary> [CLSCompliant(false)] public unsafe byte* PositionPointer { [System.Security.SecurityCritical] // auto-generated_required get { if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); // Use a temp to avoid a race long pos = Interlocked.Read(ref _position); if (pos > _capacity) throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition); byte* ptr = _mem + pos; return ptr; } [System.Security.SecurityCritical] // auto-generated_required set { if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); if (value < _mem) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, value - _mem); } } /// <summary> /// Reads bytes from stream and puts them into the buffer /// </summary> /// <param name="buffer">Buffer to read the bytes to.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <returns>Number of bytes actually read.</returns> [System.Security.SecuritySafeCritical] // auto-generated public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanRead) throw Error.GetReadNotSupported(); // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = len - pos; if (n > count) n = count; if (n <= 0) return 0; int nInt = (int)n; // Safe because n <= count, which is an Int32 if (nInt < 0) return 0; // _position could be beyond EOF Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. unsafe { fixed (byte* pBuffer = buffer) { if (_buffer != null) { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Buffer.MemoryCopy(source: pointer + pos + _offset, destination: pBuffer + offset, destinationSizeInBytes: nInt, sourceBytesToCopy: nInt); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } else { Buffer.MemoryCopy(source: _mem + pos, destination: pBuffer + offset, destinationSizeInBytes: nInt, sourceBytesToCopy: nInt); } } } Interlocked.Exchange(ref _position, pos + n); return nInt; } /// <summary> /// Reads bytes from stream and puts them into the buffer /// </summary> /// <param name="buffer">Buffer to read the bytes to.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <param name="cancellationToken">Token that can be used to cancel this operation.</param> /// <returns>Task that can be used to access the number of bytes actually read.</returns> public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Read(...) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<Int32>(cancellationToken); try { Int32 n = Read(buffer, offset, count); Task<Int32> t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n)); } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } /// <summary> /// Returns the byte at the stream current Position and advances the Position. /// </summary> /// <returns></returns> [System.Security.SecuritySafeCritical] // auto-generated public override int ReadByte() { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanRead) throw Error.GetReadNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); if (pos >= len) return -1; Interlocked.Exchange(ref _position, pos + 1); int result; if (_buffer != null) { unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); result = *(pointer + pos + _offset); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { result = _mem[pos]; } } return result; } /// <summary> /// Advanced the Position to specific location in the stream. /// </summary> /// <param name="offset">Offset from the loc parameter.</param> /// <param name="loc">Origin for the offset parameter.</param> /// <returns></returns> public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) throw Error.GetStreamIsClosed(); switch (loc) { case SeekOrigin.Begin: if (offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset); break; case SeekOrigin.Current: long pos = Interlocked.Read(ref _position); if (offset + pos < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset + pos); break; case SeekOrigin.End: long len = Interlocked.Read(ref _length); if (len + offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, len + offset); break; default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } long finalPos = Interlocked.Read(ref _position); Debug.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } /// <summary> /// Sets the Length of the stream. /// </summary> /// <param name="value"></param> [System.Security.SecuritySafeCritical] // auto-generated public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); if (value > _capacity) throw new IOException(SR.IO_FixedCapacity); long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); if (value > len) { unsafe { ZeroMemory(_mem + len, value - len); } } Interlocked.Exchange(ref _length, value); if (pos > value) { Interlocked.Exchange(ref _position, value); } } /// <summary> /// Writes buffer into the stream /// </summary> /// <param name="buffer">Buffer that will be written.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Number of bytes to write.</param> [System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..) if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + count; // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) { throw new NotSupportedException(SR.IO_FixedCapacity); } if (_buffer == null) { // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } } unsafe { fixed (byte* pBuffer = buffer) { if (_buffer != null) { long bytesLeft = _capacity - pos; if (bytesLeft < count) { throw new ArgumentException(SR.Arg_BufferTooSmall); } byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Buffer.MemoryCopy(source: pBuffer + offset, destination: pointer + pos + _offset, destinationSizeInBytes: count, sourceBytesToCopy: count); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } else { Buffer.MemoryCopy(source: pBuffer + offset, destination: _mem + pos, destinationSizeInBytes: count, sourceBytesToCopy: count); } } } Interlocked.Exchange(ref _position, n); return; } /// <summary> /// Writes buffer into the stream. The operation completes synchronously. /// </summary> /// <param name="buffer">Buffer that will be written.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Number of bytes to write.</param> /// <param name="cancellationToken">Token that can be used to cancel the operation.</param> /// <returns>Task that can be awaited </returns> public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Write(..) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); return Task.FromException(ex); } } /// <summary> /// Writes a byte to the stream and advances the current Position. /// </summary> /// <param name="value"></param> [System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) throw new NotSupportedException(SR.IO_FixedCapacity); // Check to see whether we are now expanding the stream and must // zero any memory in the middle. // don't do if created from SafeBuffer if (_buffer == null) { if (pos > len) { unsafe { ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); *(pointer + pos + _offset) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { _mem[pos] = value; } } Interlocked.Exchange(ref _position, n); } } }
/* * Copyright (c) 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.IO; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes.Scripting; namespace OpenSim.Region.Framework.Scenes { public class SceneObjectPartInventory : IEntityInventory { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_inventoryFileName = String.Empty; private int m_inventoryFileNameSerial = 0; /// <value> /// The part to which the inventory belongs. /// </value> private SceneObjectPart m_part; /// <summary> /// Serial count for inventory file , used to tell if inventory has changed /// no need for this to be part of Database backup /// </summary> protected uint m_inventorySerial = 0; /// <summary> /// Holds in memory prim inventory /// </summary> protected TaskInventoryDictionary m_items = new TaskInventoryDictionary(); /// <summary> /// Tracks whether inventory has changed since the last persistent backup /// </summary> internal bool HasInventoryChanged; /// <value> /// Inventory serial number /// </value> protected internal uint Serial { get { return m_inventorySerial; } set { m_inventorySerial = value; } } /// <value> /// Raw inventory data /// </value> protected internal TaskInventoryDictionary Items { get { return m_items; } set { m_items = value; m_inventorySerial++; } } /// <summary> /// Constructor /// </summary> /// <param name="part"> /// A <see cref="SceneObjectPart"/> /// </param> public SceneObjectPartInventory(SceneObjectPart part) { m_part = part; } /// <summary> /// Force the task inventory of this prim to persist at the next update sweep /// </summary> public void ForceInventoryPersistence() { HasInventoryChanged = true; } /// <summary> /// Reset UUIDs for all the items in the prim's inventory. This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// </summary> /// <param name="linkNum">Link number for the part</param> public void ResetInventoryIDs() { lock (Items) { if (0 == Items.Count) return; HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); Items.Clear(); foreach (TaskInventoryItem item in items) { item.ResetIDs(m_part.UUID); Items.Add(item.ItemID, item); } } } /// <summary> /// Change every item in this inventory to a new owner. /// </summary> /// <param name="ownerId"></param> public void ChangeInventoryOwner(UUID ownerId) { lock (Items) { if (0 == Items.Count) { return; } HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); foreach (TaskInventoryItem item in items) { if (ownerId != item.OwnerID) { item.LastOwnerID = item.OwnerID; item.OwnerID = ownerId; } } } } /// <summary> /// Change every item in this inventory to a new group. /// </summary> /// <param name="groupID"></param> public void ChangeInventoryGroup(UUID groupID) { lock (Items) { if (0 == Items.Count) { return; } HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); foreach (TaskInventoryItem item in items) { if (groupID != item.GroupID) { item.GroupID = groupID; } } } } /// <summary> /// Start all the scripts contained in this prim's inventory /// </summary> public void CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource) { lock (m_items) { foreach (TaskInventoryItem item in Items.Values) { if ((int)InventoryType.LSL == item.InvType) { CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); } } } } /// <summary> /// Stop all the scripts in this prim. /// </summary> public void RemoveScriptInstances() { lock (Items) { foreach (TaskInventoryItem item in Items.Values) { if ((int)InventoryType.LSL == item.InvType) { RemoveScriptInstance(item.ItemID); m_part.RemoveScriptEvents(item.ItemID); } } } } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="item"></param> /// <returns></returns> public void CreateScriptInstance(TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource) { // m_log.InfoFormat( // "[PRIM INVENTORY]: " + // "Starting script {0}, {1} in prim {2}, {3}", // item.Name, item.ItemID, Name, UUID); if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) return; m_part.AddFlag(PrimFlags.Scripted); if (!m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts) { if (stateSource == 1 && // Prim crossing m_part.ParentGroup.Scene.m_trustBinaries) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; m_part.ParentGroup.Scene.EventManager.TriggerRezScript( m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource); m_part.ParentGroup.AddActiveScriptCount(1); m_part.ScheduleFullUpdate(); return; } m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString(), this, delegate(string id, object sender, AssetBase asset) { if (null == asset) { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't start script {0}, {1} since asset ID {2} could not be found", item.Name, item.ItemID, item.AssetID); } else { if (m_part.ParentGroup.m_savedScriptState != null) RestoreSavedScriptState(item.OldItemID, item.ItemID); m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; string script = Utils.BytesToString(asset.Data); m_part.ParentGroup.Scene.EventManager.TriggerRezScript( m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); m_part.ParentGroup.AddActiveScriptCount(1); m_part.ScheduleFullUpdate(); } }); } } static System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); private void RestoreSavedScriptState(UUID oldID, UUID newID) { if (m_part.ParentGroup.m_savedScriptState.ContainsKey(oldID)) { string fpath = Path.Combine("ScriptEngines/"+m_part.ParentGroup.Scene.RegionInfo.RegionID.ToString(), newID.ToString()+".state"); FileStream fs = File.Create(fpath); Byte[] buffer = enc.GetBytes(m_part.ParentGroup.m_savedScriptState[oldID]); fs.Write(buffer,0,buffer.Length); fs.Close(); m_part.ParentGroup.m_savedScriptState.Remove(oldID); } } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="itemId"> /// A <see cref="UUID"/> /// </param> public void CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource) { lock (m_items) { if (m_items.ContainsKey(itemId)) { CreateScriptInstance(m_items[itemId], startParam, postOnRez, engine, stateSource); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2}", itemId, m_part.Name, m_part.UUID); } } } /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> public void RemoveScriptInstance(UUID itemId) { if (m_items.ContainsKey(itemId)) { m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId); m_part.ParentGroup.AddActiveScriptCount(-1); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2}", itemId, m_part.Name, m_part.UUID); } } /// <summary> /// Check if the inventory holds an item with a given name. /// This method assumes that the task inventory is already locked. /// </summary> /// <param name="name"></param> /// <returns></returns> private bool InventoryContainsName(string name) { foreach (TaskInventoryItem item in Items.Values) { if (item.Name == name) return true; } return false; } /// <summary> /// For a given item name, return that name if it is available. Otherwise, return the next available /// similar name (which is currently the original name with the next available numeric suffix). /// </summary> /// <param name="name"></param> /// <returns></returns> private string FindAvailableInventoryName(string name) { if (!InventoryContainsName(name)) return name; int suffix=1; while (suffix < 256) { string tryName=String.Format("{0} {1}", name, suffix); if (!InventoryContainsName(tryName)) return tryName; suffix++; } return String.Empty; } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative /// name is chosen. /// </summary> /// <param name="item"></param> public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop) { AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced. /// </summary> /// <param name="item"></param> public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) { List<TaskInventoryItem> il = new List<TaskInventoryItem>(m_items.Values); foreach (TaskInventoryItem i in il) { if (i.Name == item.Name) { if (i.InvType == (int)InventoryType.LSL) RemoveScriptInstance(i.ItemID); RemoveInventoryItem(i.ItemID); break; } } AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. /// </summary> /// <param name="name">The name that the new item should have.</param> /// <param name="item"> /// The item itself. The name within this structure is ignored in favour of the name /// given in this method's arguments /// </param> /// <param name="allowedDrop"> /// Item was only added to inventory because AllowedDrop is set /// </param> protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop) { name = FindAvailableInventoryName(name); if (name == String.Empty) return; item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Name = name; lock (m_items) { m_items.Add(item.ItemID, item); if (allowedDrop) m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP); else m_part.TriggerScriptChangedEvent(Changed.INVENTORY); } m_inventorySerial++; //m_inventorySerial += 2; HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; } /// <summary> /// Restore a whole collection of items to the prim's inventory at once. /// We assume that the items already have all their fields correctly filled out. /// The items are not flagged for persistence to the database, since they are being restored /// from persistence rather than being newly added. /// </summary> /// <param name="items"></param> public void RestoreInventoryItems(ICollection<TaskInventoryItem> items) { lock (m_items) { foreach (TaskInventoryItem item in items) { m_items.Add(item.ItemID, item); m_part.TriggerScriptChangedEvent(Changed.INVENTORY); } } m_inventorySerial++; } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="itemID"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(UUID itemId) { TaskInventoryItem item; m_items.TryGetValue(itemId, out item); return item; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory.</param> /// <returns>false if the item did not exist, true if the update occurred successfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { lock (m_items) { if (m_items.ContainsKey(item.ItemID)) { item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Flags = m_items[item.ItemID].Flags; if (item.AssetID == UUID.Zero) { item.AssetID = m_items[item.ItemID].AssetID; } else if ((InventoryType)item.Type == InventoryType.Notecard) { ScenePresence presence = m_part.ParentGroup.Scene.GetScenePresence(item.OwnerID); if (presence != null) { presence.ControllingClient.SendAgentAlertMessage( "Notecard saved", false); } } m_items[item.ItemID] = item; m_inventorySerial++; m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; return true; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to retrieve item ID {0} from prim {1}, {2} but the item does not exist in this inventory", item.ItemID, m_part.Name, m_part.UUID); } } return false; } /// <summary> /// Remove an item from this prim's inventory /// </summary> /// <param name="itemID"></param> /// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist /// in this prim's inventory.</returns> public int RemoveInventoryItem(UUID itemID) { lock (m_items) { if (m_items.ContainsKey(itemID)) { int type = m_items[itemID].InvType; if (type == 10) // Script { m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); } m_items.Remove(itemID); m_inventorySerial++; m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; int scriptcount = 0; lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Type == 10) { scriptcount++; } } } if (scriptcount <= 0) { m_part.RemFlag(PrimFlags.Scripted); } m_part.ScheduleFullUpdate(); return type; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to remove item ID {0} from prim {1}, {2} but the item does not exist in this inventory", itemID, m_part.Name, m_part.UUID); } } return -1; } public string GetInventoryFileName() { if (m_inventoryFileName == String.Empty) m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; if (m_inventoryFileNameSerial < m_inventorySerial) { m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; } return m_inventoryFileName; } /// <summary> /// Return the name with which a client can request a xfer of this prim's inventory metadata /// </summary> /// <param name="client"></param> /// <param name="localID"></param> public bool GetInventoryFileName(IClientAPI client, uint localID) { // m_log.DebugFormat( // "[PRIM INVENTORY]: Received request from client {0} for inventory file name of {1}, {2}", // client.AgentId, Name, UUID); if (m_inventorySerial > 0) { client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial, Utils.StringToBytes(GetInventoryFileName())); return true; } else { client.SendTaskInventory(m_part.UUID, 0, new byte[0]); return false; } } /// <summary> /// Serialize all the metadata for the items in this prim's inventory ready for sending to the client /// </summary> /// <param name="xferManager"></param> public void RequestInventoryFile(IClientAPI client, IXfer xferManager) { byte[] fileData = new byte[0]; // Confusingly, the folder item has to be the object id, while the 'parent id' has to be zero. This matches // what appears to happen in the Second Life protocol. If this isn't the case. then various functionality // isn't available (such as drag from prim inventory to agent inventory) InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { UUID ownerID = item.OwnerID; uint everyoneMask = 0; uint baseMask = item.BasePermissions; uint ownerMask = item.CurrentPermissions; invString.AddItemStart(); invString.AddNameValueLine("item_id", item.ItemID.ToString()); invString.AddNameValueLine("parent_id", m_part.UUID.ToString()); invString.AddPermissionsStart(); invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask)); invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask)); invString.AddNameValueLine("group_mask", Utils.UIntToHexString(0)); invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask)); invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions)); invString.AddNameValueLine("creator_id", item.CreatorID.ToString()); invString.AddNameValueLine("owner_id", ownerID.ToString()); invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString()); invString.AddNameValueLine("group_id", item.GroupID.ToString()); invString.AddSectionEnd(); invString.AddNameValueLine("asset_id", item.AssetID.ToString()); invString.AddNameValueLine("type", TaskInventoryItem.Types[item.Type]); invString.AddNameValueLine("inv_type", TaskInventoryItem.InvTypes[item.InvType]); invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags)); invString.AddSaleStart(); invString.AddNameValueLine("sale_type", "not"); invString.AddNameValueLine("sale_price", "0"); invString.AddSectionEnd(); invString.AddNameValueLine("name", item.Name + "|"); invString.AddNameValueLine("desc", item.Description + "|"); invString.AddNameValueLine("creation_date", item.CreationDate.ToString()); invString.AddSectionEnd(); } } fileData = Utils.StringToBytes(invString.BuildString); //m_log.Debug(Utils.BytesToString(fileData)); //m_log.Debug("[PRIM INVENTORY]: RequestInventoryFile fileData: " + Utils.BytesToString(fileData)); if (fileData.Length > 2) { xferManager.AddNewFile(m_inventoryFileName, fileData); } } /// <summary> /// Process inventory backup /// </summary> /// <param name="datastore"></param> public void ProcessInventoryBackup(IRegionDataStore datastore) { if (HasInventoryChanged) { lock (Items) { datastore.StorePrimInventory(m_part.UUID, Items.Values); } HasInventoryChanged = false; } } public class InventoryStringBuilder { public string BuildString = String.Empty; public InventoryStringBuilder(UUID folderID, UUID parentID) { BuildString += "\tinv_object\t0\n\t{\n"; AddNameValueLine("obj_id", folderID.ToString()); AddNameValueLine("parent_id", parentID.ToString()); AddNameValueLine("type", "category"); AddNameValueLine("name", "Contents|"); AddSectionEnd(); } public void AddItemStart() { BuildString += "\tinv_item\t0\n"; AddSectionStart(); } public void AddPermissionsStart() { BuildString += "\tpermissions 0\n"; AddSectionStart(); } public void AddSaleStart() { BuildString += "\tsale_info\t0\n"; AddSectionStart(); } protected void AddSectionStart() { BuildString += "\t{\n"; } public void AddSectionEnd() { BuildString += "\t}\n"; } public void AddLine(string addLine) { BuildString += addLine; } public void AddNameValueLine(string name, string value) { BuildString += "\t\t"; BuildString += name + "\t"; BuildString += value + "\n"; } public void Close() { } } public uint MaskEffectivePermissions() { uint mask=0x7fffffff; foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType != (int)InventoryType.Object) { if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } else { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~(uint)PermissionMask.Modify; } return mask; } public void ApplyNextOwnerPermissions() { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Modify; item.CurrentPermissions |= 8; } item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryonePermissions &= item.NextPermissions; } m_part.TriggerScriptChangedEvent(Changed.OWNER); } public void ApplyGodPermissions(uint perms) { foreach (TaskInventoryItem item in m_items.Values) { item.CurrentPermissions = perms; item.BasePermissions = perms; } } public bool ContainsScripts() { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { return true; } } return false; } public List<UUID> GetInventoryList() { List<UUID> ret = new List<UUID>(); foreach (TaskInventoryItem item in m_items.Values) ret.Add(item.ItemID); return ret; } public string[] GetScriptAssemblies() { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); List<string> ret = new List<string>(); if (engines == null) // No engine at all return new string[0]; foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { foreach (IScriptModule e in engines) { if (e != null) { string n = e.GetAssemblyName(item.ItemID); if (n != String.Empty) { if (!ret.Contains(n)) ret.Add(n); break; } } } } } return ret.ToArray(); } public Dictionary<UUID, string> GetScriptStates() { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); if (engines == null) // No engine at all return ret; foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { foreach (IScriptModule e in engines) { if (e != null) { string n = e.GetXMLState(item.ItemID); if (n != String.Empty) { if (!ret.ContainsKey(item.ItemID)) ret[item.ItemID] = n; break; } } } } } return ret; } public bool CanBeDeleted() { if (!ContainsScripts()) return true; IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) // No engine at all return true; foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { foreach (IScriptModule e in engines) { if (!e.CanBeDeleted(item.ItemID)) return false; } } } return true; } } }
using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Timers; using Platform.IO; using Platform.Text; namespace Platform.VirtualFileSystem.Providers.Shadow { /// <summary> /// Summary description for ShadowNodeContent. /// </summary> internal class ShadowNodeContent : AbstractNodeContent { private IFile file; private readonly ShadowFile shadowFile; private readonly IFileSystem tempFileSystem; internal long targetLength = -1; internal byte[] targetMd5; internal bool hasCreationTime; internal DateTime creationTime; internal bool hasLastWriteTime; internal DateTime lastWriteTime; public ShadowNodeContent(ShadowFile shadowFile, IFile file, IFileSystem tempFileSystem) { var buffer = new StringBuilder(file.Address.Uri.Length * 3); this.shadowFile = shadowFile; this.tempFileSystem = tempFileSystem; this.file = tempFileSystem.ResolveFile(GenerateName()); buffer.Append(ComputeHash(file.Address.Uri).TrimRight('=')); var value = (string)file.Address.QueryValues["length"]; if (value != null) { this.targetLength = Convert.ToInt64(value); buffer.Append('_').Append(value); } value = (string)file.Address.QueryValues["md5sum"]; if (value != null) { this.targetMd5 = Convert.FromBase64String(value); buffer.Append('_').Append(value); } value = (string)file.Address.QueryValues["creationtime"]; if (value != null) { this.hasCreationTime = true; this.creationTime = Convert.ToDateTime(value); buffer.Append('_').Append(this.creationTime.Ticks.ToString()); } value = (string)file.Address.QueryValues["writetime"]; if (value != null) { this.hasLastWriteTime = true; this.lastWriteTime = Convert.ToDateTime(value); buffer.Append('_').Append(this.lastWriteTime.Ticks.ToString()); } value = buffer.ToString(); } private static string ComputeHash(string s) { var encoding = Encoding.ASCII; var algorithm = new MD5CryptoServiceProvider(); var output = (algorithm.ComputeHash(encoding.GetBytes(s))); return TextConversion.ToBase32String(output); } protected virtual string GenerateName() { return "VFSSHADOWS.TMP/" + Guid.NewGuid().ToString("N") + "." + this.shadowFile.Address.Extension; } public override Stream GetInputStream() { string encoding; return GetInputStream(out encoding); } private class ShadowOutputStream : StreamWrapper { private readonly IFile file; private readonly IFile shadowFile; public ShadowOutputStream(Stream stream, IFile shadowedFile, IFile file) : base(stream) { this.file = file; this.shadowFile = shadowedFile; } public override void Close() { base.Close(); var dest = this.shadowFile.ParentDirectory.ResolveFile(this.file.Address.Name); this.file.MoveTo(dest.ParentDirectory, true); dest.RenameTo(this.shadowFile.Address.Name, true); } } private class ShadowInputStream : StreamWrapper { private Timer timer; private readonly IFile file; public ShadowInputStream(Stream stream, IFile file) : base(stream) { this.file = file; SetupTimer(); } ~ShadowInputStream() { Close(); } private void SetupTimer() { TimeSpan period; period = TimeSpan.FromMinutes(30); if (this.timer != null) { this.timer.Dispose(); } this.timer = new Timer(period.TotalMilliseconds); this.timer.AutoReset = true; this.timer.Elapsed += new ElapsedEventHandler(TimerElapsed); this.timer.Start(); } protected virtual void TimerElapsed(object sender, ElapsedEventArgs e) { lock (this) { try { this.file.Delete(); this.timer.Stop(); this.timer.Close(); } catch (Exception) { } } } private bool closed = false; public override void Close() { lock (this) { if (this.closed) { return; } this.closed = true; } base.Close (); this.file.Refresh(); try { if (this.file.Exists) { this.file.Delete(); } } catch (Exception) { SetupTimer(); } } } private class StreamCloser { private readonly Stream stream; private readonly Timer timer; public StreamCloser(Stream stream, Timer timer) { this.stream = stream; this.timer = timer; } public void TimerElapsed(object sender, ElapsedEventArgs e) { this.stream.Close(); this.timer.Close(); } } internal IFile GetReadFile(TimeSpan timeout) { lock (this) { var timer = new Timer(timeout.TotalMilliseconds); timer.Elapsed += new ElapsedEventHandler(new StreamCloser(GetInputStream(), timer).TimerElapsed); timer.AutoReset = false; timer.Start(); return this.file; } } public override void Delete() { this.shadowFile.GetContent().Delete(); } protected override Stream DoGetInputStream(out string encoding, FileMode mode, FileShare sharing) { Stream retval; lock (this) { long? length = 0; bool error = false; DateTime? creationTime = null; DateTime? lastWriteTime = null; this.file.Attributes.Refresh(); this.shadowFile.Attributes.Refresh(); try { if (this.file.Exists) { length = this.file.Length ?? 0; creationTime = this.file.Attributes.CreationTime; lastWriteTime = this.file.Attributes.LastWriteTime; } else { error = true; } } catch (IOException) { error = true; } if (!error && length == this.shadowFile.Length && creationTime == this.shadowFile.Attributes.CreationTime && lastWriteTime == this.shadowFile.Attributes.LastWriteTime && (mode == FileMode.Open || mode == FileMode.OpenOrCreate)) { try { retval = new ShadowInputStream(this.file.GetContent().GetInputStream(out encoding, sharing), this.file); return retval; } catch (IOException) { } } this.file = this.tempFileSystem.ResolveFile(GenerateName()); switch (mode) { case FileMode.Create: this.file.Create(); break; case FileMode.CreateNew: if (this.shadowFile.Exists) { throw new IOException("File exists"); } this.file.Create(); break; case FileMode.OpenOrCreate: try { this.shadowFile.CopyTo(this.file, true); } catch (FileNotFoundException) { this.file.Create(); } break; case FileMode.Open: default: this.file.ParentDirectory.Create(true); this.shadowFile.CopyTo(this.file, true); break; } this.file.Attributes.CreationTime = this.shadowFile.Attributes.CreationTime; this.file.Attributes.LastWriteTime = this.shadowFile.Attributes.LastWriteTime; retval = new ShadowInputStream(this.file.GetContent().GetInputStream(out encoding, sharing), this.file); return retval; } } protected override Stream DoGetOutputStream(string encoding, FileMode mode, FileShare sharing) { IFile file; file = this.tempFileSystem.ResolveFile(GenerateName()); switch (mode) { case FileMode.Truncate: file.Create(); break; } return new ShadowOutputStream(file.GetContent().GetOutputStream(encoding, sharing), this.shadowFile.ShadowedFile, file); } } }
using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration { /// <summary> /// Initializes a new instance of the Configuration class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> /// <param name="usedBy">Appends user agent header</param> public Configuration(ApiClient apiClient = null, Dictionary<String, String> defaultHeader = null, string username = null, string password = null, string accessToken = null, Dictionary<String, String> apiKey = null, Dictionary<String, String> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 100000, string usedBy = null ) { if (apiClient == null) ApiClient = ApiClient.Default; else ApiClient = apiClient; Username = username; Password = password; AccessToken = accessToken; if (defaultHeader != null) DefaultHeader = defaultHeader; if (apiKey != null) ApiKey = apiKey; if (apiKeyPrefix != null) ApiKeyPrefix = apiKeyPrefix; TempFolderPath = tempFolderPath; DateTimeFormat = dateTimeFormat; Timeout = timeout; UsedBy = usedBy; } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> public Configuration(ApiClient apiClient) { if (apiClient == null) ApiClient = ApiClient.Default; else ApiClient = apiClient; } /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "1.0.0"; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default = new Configuration(); /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// </summary> /// <value>Timeout.</value> public int Timeout { get { return ApiClient.RestClient.Timeout; } set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The API client.</value> public ApiClient ApiClient; private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); /// <summary> /// Gets or sets the default header. /// </summary> public Dictionary<String, String> DefaultHeader { get { return _defaultHeaderMap; } set { _defaultHeaderMap = value; } } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { _defaultHeaderMap.Add(key, value); } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public String Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public String Password { get; set; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public String AccessToken { get; set; } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public Dictionary<String, String> ApiKey = new Dictionary<String, String>(); /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>(); /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix(string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } private string _tempFolderPath = Path.GetTempPath(); /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public String TempFolderPath { get { return _tempFolderPath; } set { if (String.IsNullOrEmpty(value)) { _tempFolderPath = value; return; } // create the directory if it does not exist if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) _tempFolderPath = value; else _tempFolderPath = value + Path.DirectorySeparatorChar; } } private const string ISO8601_DATETIME_FORMAT = "o"; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public String DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Gets or sets additional agent information when a tool using SDK needs to be recognized /// </summary> public string UsedBy { get; private set; } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (IO.Swagger) Debug Report:\n"; report += " OS: " + Environment.OSVersion + "\n"; report += " .NET Framework Version: " + Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; report += " Version of the API: 1.0\n"; report += " SDK Package Version: 1.0.0\n"; return report; } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using SharpVectors.Dom.Svg; using SharpVectors.Dom.Css; namespace SharpVectors.Renderer.Gdi { public class GdiSvgPaint : SvgPaint { private SvgStyleableElement _element; private PaintServer ps; public GdiSvgPaint(SvgStyleableElement elm, string propName) : base(elm.GetComputedStyle("").GetPropertyValue(propName)) { _element = elm; } #region Private methods private int getOpacity(string fillOrStroke) { double alpha = 255; string opacity; opacity = _element.GetPropertyValue(fillOrStroke + "-opacity"); if(opacity.Length > 0) alpha *= SvgNumber.ParseToFloat(opacity); opacity = _element.GetPropertyValue("opacity"); if(opacity.Length > 0) alpha *= SvgNumber.ParseToFloat(opacity); alpha = Math.Min(alpha, 255); alpha = Math.Max(alpha, 0); return Convert.ToInt32(alpha); } private LineCap getLineCap() { switch(_element.GetPropertyValue("stroke-linecap")) { case "round": return LineCap.Round; case "square": return LineCap.Square; default: return LineCap.Flat; } } private LineJoin getLineJoin() { switch(_element.GetPropertyValue("stroke-linejoin")) { case "round": return LineJoin.Round; case "bevel": return LineJoin.Bevel; default: return LineJoin.Miter; } } private float getStrokeWidth() { string strokeWidth = _element.GetPropertyValue("stroke-width"); if(strokeWidth.Length == 0) strokeWidth = "1px"; SvgLength strokeWidthLength = new SvgLength(_element, "stroke-width", SvgLengthDirection.Viewport, strokeWidth); return (float)strokeWidthLength.Value; } private float getMiterLimit() { string miterLimitStr = _element.GetPropertyValue("stroke-miterlimit"); if(miterLimitStr.Length == 0) miterLimitStr = "4"; float miterLimit = SvgNumber.ParseToFloat(miterLimitStr); if(miterLimit<1) throw new SvgException(SvgExceptionType.SvgInvalidValueErr, "stroke-miterlimit can not be less then 1"); return miterLimit; } private float[] getDashArray(float strokeWidth) { string dashArray = _element.GetPropertyValue("stroke-dasharray"); if(dashArray.Length == 0 || dashArray == "none") { return null; } else { SvgNumberList list = new SvgNumberList(dashArray); uint len = list.NumberOfItems; float[] fDashArray = new float[len]; for(uint i = 0; i<len; i++) { //divide by strokeWidth to take care of the difference between Svg and GDI+ fDashArray[i] = list.GetItem(i).Value / strokeWidth; } if(len % 2 == 1) { //odd number of values, duplicate float[] tmpArray = new float[len*2]; fDashArray.CopyTo(tmpArray, 0); fDashArray.CopyTo(tmpArray, (int)len); fDashArray = tmpArray; } return fDashArray; } } private float getDashOffset(float strokeWidth) { string dashOffset = _element.GetPropertyValue("stroke-dashoffset"); if(dashOffset.Length > 0) { //divide by strokeWidth to take care of the difference between Svg and GDI+ SvgLength dashOffsetLength = new SvgLength(_element, "stroke-dashoffset", SvgLengthDirection.Viewport, dashOffset); return (float)dashOffsetLength.Value; } else { return 0; } } private PaintServer getPaintServer(string uri) { string absoluteUri = _element.ResolveUri(uri); return PaintServer.CreatePaintServer(_element.OwnerDocument, absoluteUri); } #endregion #region Public methods public Brush GetBrush(GraphicsPath gp) { return GetBrush(gp, "fill"); } private Brush GetBrush(GraphicsPath gp, string propPrefix) { SvgPaint fill; if(PaintType == SvgPaintType.None) { return null; } else if(PaintType == SvgPaintType.CurrentColor) { fill = new GdiSvgPaint(_element, "color"); } else { fill = this; } if(fill.PaintType == SvgPaintType.Uri || fill.PaintType == SvgPaintType.UriCurrentColor || fill.PaintType == SvgPaintType.UriNone || fill.PaintType == SvgPaintType.UriRgbColor || fill.PaintType == SvgPaintType.UriRgbColorIccColor) { ps = getPaintServer(fill.Uri); if(ps != null) { Brush br = ps.GetBrush(gp.GetBounds()); if (br is LinearGradientBrush) { LinearGradientBrush lgb = (LinearGradientBrush)br; int opacityl = getOpacity(propPrefix); for (int i = 0; i < lgb.InterpolationColors.Colors.Length; i++) { lgb.InterpolationColors.Colors[i] = Color.FromArgb(opacityl, lgb.InterpolationColors.Colors[i]); } for (int i = 0; i < lgb.LinearColors.Length; i++) { lgb.LinearColors[i] = Color.FromArgb(opacityl, lgb.LinearColors[i]); } } else if (br is PathGradientBrush) { PathGradientBrush pgb = (PathGradientBrush)br; int opacityl = getOpacity(propPrefix); for (int i = 0; i < pgb.InterpolationColors.Colors.Length; i++) { pgb.InterpolationColors.Colors[i] = Color.FromArgb(opacityl, pgb.InterpolationColors.Colors[i]); } for (int i = 0; i < pgb.SurroundColors.Length; i++) { pgb.SurroundColors[i] = Color.FromArgb(opacityl, pgb.SurroundColors[i]); } } return br; } else { if(PaintType == SvgPaintType.UriNone || PaintType == SvgPaintType.Uri) { return null; } else if(PaintType == SvgPaintType.UriCurrentColor) { fill = new GdiSvgPaint(_element, "color"); } else { fill = this; } } } SolidBrush brush = new SolidBrush( ((RgbColor)fill.RgbColor).GdiColor ); int opacity = getOpacity(propPrefix); brush.Color = Color.FromArgb(opacity, brush.Color); return brush; } public Pen GetPen(GraphicsPath gp) { float strokeWidth = getStrokeWidth(); if(strokeWidth == 0) return null; GdiSvgPaint stroke; if(PaintType == SvgPaintType.None) { return null; } else if(PaintType == SvgPaintType.CurrentColor) { stroke = new GdiSvgPaint(_element, "color"); } else { stroke = this; } Pen pen = new Pen(stroke.GetBrush(gp, "stroke"), strokeWidth); pen.StartCap = pen.EndCap = getLineCap(); pen.LineJoin = getLineJoin(); pen.MiterLimit = getMiterLimit(); float[] fDashArray = getDashArray(strokeWidth); if(fDashArray != null) { // Do not draw if dash array had a zero value in it for(int i=0;i<fDashArray.Length;i++) { if(fDashArray[i] == 0) return null; } pen.DashPattern = fDashArray; } pen.DashOffset = getDashOffset(strokeWidth); return pen; } #endregion #region Public properties public PaintServer PaintServer { get { return ps; } } #endregion } }
// // ComboBoxEntryBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; #else using Foundation; using AppKit; #endif namespace Xwt.Mac { public class ComboBoxEntryBackend: ViewBackend<NSComboBox,IComboBoxEventSink>, IComboBoxEntryBackend { ComboDataSource tsource; TextEntryBackend entryBackend; int textColumn; public ComboBoxEntryBackend () { } public override void Initialize () { base.Initialize (); ViewObject = new MacComboBox (EventSink, ApplicationContext); } protected override Size GetNaturalSize () { var s = base.GetNaturalSize (); return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height); } #region IComboBoxEntryBackend implementation public ITextEntryBackend TextEntryBackend { get { if (entryBackend == null) entryBackend = new Xwt.Mac.TextEntryBackend ((MacComboBox)ViewObject); return entryBackend; } } #endregion #region IComboBoxBackend implementation public void SetViews (CellViewCollection views) { } public void SetSource (IListDataSource source, IBackend sourceBackend) { tsource = new ComboDataSource (source); tsource.TextColumn = textColumn; Widget.UsesDataSource = true; Widget.DataSource = tsource; } public int SelectedRow { get { return (int) Widget.SelectedIndex; } set { Widget.SelectItem (value); } } public void SetTextColumn (int column) { textColumn = column; if (tsource != null) tsource.TextColumn = column; } #endregion } #if MONOMAC class MacComboBox: NSComboBox, IViewObject #else class MacComboBox : NSComboBox, IViewObject, INSComboBoxDelegate #endif { IComboBoxEventSink eventSink; ITextEntryEventSink entryEventSink; ApplicationContext context; int cacheSelectionStart, cacheSelectionLength; bool checkMouseMovement; public MacComboBox (IComboBoxEventSink eventSink, ApplicationContext context) { this.context = context; this.eventSink = eventSink; #if !MONOMAC Delegate = this; #endif } public void SetEntryEventSink (ITextEntryEventSink entryEventSink) { this.entryEventSink = entryEventSink; } public NSView View { get { return this; } } public ViewBackend Backend { get; set; } #if !MONOMAC [Export ("comboBoxSelectionDidChange:")] public new void SelectionChanged (NSNotification notification) { if (entryEventSink != null) { context.InvokeUserCode (delegate { entryEventSink.OnChanged (); eventSink.OnSelectionChanged (); }); } } #endif public override void DidChange (NSNotification notification) { base.DidChange (notification); if (entryEventSink != null) { context.InvokeUserCode (delegate { entryEventSink.OnChanged (); entryEventSink.OnSelectionChanged (); }); } } public override void KeyUp (NSEvent theEvent) { base.KeyUp (theEvent); HandleSelectionChanged (); } NSTrackingArea trackingArea; public override void UpdateTrackingAreas () { if (trackingArea != null) { RemoveTrackingArea (trackingArea); trackingArea.Dispose (); } var viewBounds = this.Bounds; var options = NSTrackingAreaOptions.MouseMoved | NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseEnteredAndExited; trackingArea = new NSTrackingArea (viewBounds, options, this, null); AddTrackingArea (trackingArea); } public override void RightMouseDown (NSEvent theEvent) { base.RightMouseDown (theEvent); var p = ConvertPointFromView (theEvent.LocationInWindow, null); ButtonEventArgs args = new ButtonEventArgs (); args.X = p.X; args.Y = p.Y; args.Button = PointerButton.Right; context.InvokeUserCode (delegate { eventSink.OnButtonPressed (args); }); } public override void RightMouseUp (NSEvent theEvent) { base.RightMouseUp (theEvent); var p = ConvertPointFromView (theEvent.LocationInWindow, null); ButtonEventArgs args = new ButtonEventArgs (); args.X = p.X; args.Y = p.Y; args.Button = PointerButton.Right; context.InvokeUserCode (delegate { eventSink.OnButtonReleased (args); }); } public override void MouseDown (NSEvent theEvent) { base.MouseDown (theEvent); var p = ConvertPointFromView (theEvent.LocationInWindow, null); ButtonEventArgs args = new ButtonEventArgs (); args.X = p.X; args.Y = p.Y; args.Button = PointerButton.Left; context.InvokeUserCode (delegate { eventSink.OnButtonPressed (args); }); } public override void MouseUp (NSEvent theEvent) { base.MouseUp (theEvent); var p = ConvertPointFromView (theEvent.LocationInWindow, null); ButtonEventArgs args = new ButtonEventArgs (); args.X = p.X; args.Y = p.Y; args.Button = (PointerButton) (int)theEvent.ButtonNumber + 1; context.InvokeUserCode (delegate { eventSink.OnButtonReleased (args); }); } public override void MouseEntered (NSEvent theEvent) { base.MouseEntered (theEvent); checkMouseMovement = true; context.InvokeUserCode (delegate { eventSink.OnMouseEntered (); }); } public override void MouseExited (NSEvent theEvent) { base.MouseExited (theEvent); context.InvokeUserCode (delegate { eventSink.OnMouseExited (); }); checkMouseMovement = false; HandleSelectionChanged (); } public override void MouseMoved (NSEvent theEvent) { base.MouseMoved (theEvent); if (!checkMouseMovement) return; var p = ConvertPointFromView (theEvent.LocationInWindow, null); MouseMovedEventArgs args = new MouseMovedEventArgs ((long) TimeSpan.FromSeconds (theEvent.Timestamp).TotalMilliseconds, p.X, p.Y); context.InvokeUserCode (delegate { eventSink.OnMouseMoved (args); }); if (checkMouseMovement) HandleSelectionChanged (); } void HandleSelectionChanged () { if (entryEventSink == null || CurrentEditor == null) return; if (cacheSelectionStart != CurrentEditor.SelectedRange.Location || cacheSelectionLength != CurrentEditor.SelectedRange.Length) { cacheSelectionStart = (int)CurrentEditor.SelectedRange.Location; cacheSelectionLength = (int)CurrentEditor.SelectedRange.Length; context.InvokeUserCode (delegate { entryEventSink.OnSelectionChanged (); }); } } } class ComboDataSource: NSComboBoxDataSource { NSComboBox comboBox; IListDataSource source; public int TextColumn; public ComboDataSource (IListDataSource source) { this.source = source; source.RowChanged += SourceChanged; source.RowDeleted += SourceChanged; source.RowInserted += SourceChanged; source.RowsReordered += SourceChanged; } void SourceChanged (object sender, ListRowEventArgs e) { // FIXME: we need to find a more efficient way comboBox?.ReloadData (); } public override NSObject ObjectValueForItem (NSComboBox comboBox, nint index) { SetComboBox (comboBox); return NSObject.FromObject (source.GetValue ((int) index, TextColumn)); } public override nint ItemCount (NSComboBox comboBox) { SetComboBox (comboBox); return source.RowCount; } void SetComboBox (NSComboBox comboBox) { if (this.comboBox == null) { this.comboBox = comboBox; source.RowChanged += SourceChanged; source.RowDeleted += SourceChanged; source.RowInserted += SourceChanged; source.RowsReordered += SourceChanged; } if (this.comboBox != comboBox) throw new InvalidOperationException ("This ComboDataSource is already bound to an other ComboBox"); } protected override void Dispose (bool disposing) { if (source != null) { source.RowChanged -= SourceChanged; source.RowDeleted -= SourceChanged; source.RowInserted -= SourceChanged; source.RowsReordered -= SourceChanged; source = null; } base.Dispose (disposing); } } }
using System.Collections.ObjectModel; using System.Linq; using System.Drawing; using System.IO; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using TribalWars.Villages; using TribalWars.Worlds; namespace TribalWars.Browsers.Reporting { /// <summary> /// Wrapper for a collection of Reports with the same defending village /// Plus a wrapper of the estimated current situation /// </summary> public class VillageReportCollection : Collection<Report>, IXmlSerializable { #region Fields private CurrentSituation _currentSituation; private bool _reportsLoaded; #endregion #region Properties /// <summary> /// Gets the current (assumed) situation /// of the village /// </summary> public CurrentSituation CurrentSituation { get { return _currentSituation; } } /// <summary> /// Gets a value indicating whether the existing reports have been loaded /// </summary> public bool ReportsLoaded { get { return _reportsLoaded; } } /// <summary> /// Gets the village location /// </summary> public Point VillageLocation { get { return _currentSituation.Village.Location; } } /// <summary> /// Gets the location of the saved reports /// </summary> public string File { get { return string.Format("{0}{1}-{2}.txt", World.Default.Structure.CurrentWorldReportsDirectory, _currentSituation.Village.X, _currentSituation.Village.Y); } } #endregion #region Constructors public VillageReportCollection(Village village) { Load(village); } #endregion #region Public Methods /// <summary> /// Loads the existing reports for the village /// </summary> public void Load(Village village) { if (!_reportsLoaded) { _reportsLoaded = true; _currentSituation = new CurrentSituation(village); if (System.IO.File.Exists(File)) { var sets = new XmlReaderSettings(); sets.IgnoreWhitespace = true; sets.CloseInput = true; using (XmlReader r = XmlReader.Create(File, sets)) { ReadXml(r); } } } } /// <summary> /// Saves the report collection /// </summary> public void Save() { if (_reportsLoaded) { var sets = new XmlWriterSettings(); sets.Indent = true; sets.IndentChars = " "; using (XmlWriter w = XmlWriter.Create(File, sets)) { WriteXml(w); } } } /// <summary> /// Saves only the user comments /// </summary> public void SaveComments() { if (!new FileInfo(File).Exists) { Save(); } else { var xdoc = XDocument.Load(File); xdoc.Descendants("Comments").First().Value = _currentSituation.Village.Comments; xdoc.Save(File); } } /// <summary> /// Saves a report in the correct Collections /// and updates the current situation of the villages /// </summary> public static void Save(Report report) { Village vil = report.Defender.Village; if (vil != null) { vil.Reports.CurrentSituation.UpdateDefender(report); vil.Reports.Add(report); vil.Reports.Save(); } vil = report.Attacker.Village; if (vil != null) { vil.Reports.Add(report); vil.Reports.CurrentSituation.UpdateAttacker(report); vil.Reports.Save(); } } #endregion #region Private Methods /// <summary> /// Cancel the addition if we already have this report /// </summary> protected override void InsertItem(int index, Report item) { bool addReport = true; foreach (Report report in Items) { if (report.Equals(item)) addReport = false; } if (addReport) base.InsertItem(index, item); } #endregion #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader r) { _currentSituation.ReadXml(r); r.ReadStartElement(); while (r.IsStartElement("Report")) { var report = new Report(); report.ReadXml(r); Add(report); } } public void WriteXml(XmlWriter w) { w.WriteStartDocument(); _currentSituation.WriteXml(w); w.WriteStartElement("Reports"); foreach (Report report in Items) { report.WriteXml(w); } w.WriteEndElement(); w.WriteEndDocument(); } #endregion } }
using Assent; using BTDB.Buffer; using BTDB.EventStoreLayer; using BTDB.FieldHandler; using BTDB.ODBLayer; using BTDB.StreamLayer; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using BTDB.Encrypted; using Xunit; namespace BTDBTest { public class TypeSerializersTest { ITypeSerializers _ts; ITypeSerializersMapping _mapping; public TypeSerializersTest() { _ts = new TypeSerializers(); _mapping = _ts.CreateMapping(); } [Fact] public void CanSerializeString() { var writer = new ByteBufferWriter(); var storedDescriptorCtx = _mapping.StoreNewDescriptors(writer, "Hello"); storedDescriptorCtx.FinishNewDescriptors(writer); storedDescriptorCtx.StoreObject(writer, "Hello"); storedDescriptorCtx.CommitNewDescriptors(); var reader = new ByteBufferReader(writer.Data); var obj = _mapping.LoadObject(reader); Assert.Equal("Hello", obj); } [Fact] public void CanSerializeInt() { var writer = new ByteBufferWriter(); var storedDescriptorCtx = _mapping.StoreNewDescriptors(writer, 12345); storedDescriptorCtx.FinishNewDescriptors(writer); storedDescriptorCtx.StoreObject(writer, 12345); storedDescriptorCtx.CommitNewDescriptors(); var reader = new ByteBufferReader(writer.Data); var obj = _mapping.LoadObject(reader); Assert.Equal(12345, obj); } [Fact] public void CanSerializeSimpleTypes() { CanSerializeSimpleValue((byte)42); CanSerializeSimpleValue((sbyte)-20); CanSerializeSimpleValue((short)-1234); CanSerializeSimpleValue((ushort)1234); CanSerializeSimpleValue((uint)123456789); CanSerializeSimpleValue(-123456789012L); CanSerializeSimpleValue(123456789012UL); CanSerializeSimpleValue(new Version(4,3,2,1)); } void CanSerializeSimpleValue(object value) { var writer = new ByteBufferWriter(); var storedDescriptorCtx = _mapping.StoreNewDescriptors(writer, value); storedDescriptorCtx.FinishNewDescriptors(writer); storedDescriptorCtx.StoreObject(writer, value); storedDescriptorCtx.CommitNewDescriptors(); var reader = new ByteBufferReader(writer.Data); var obj = _mapping.LoadObject(reader); Assert.Equal(value, obj); } public class SimpleDto { public string StringField { get; set; } public int IntField { get; set; } } public class SimpleDtoWithoutDefaultConstructor { public SimpleDtoWithoutDefaultConstructor(string a) { StringField = a; } public string StringField { get; set; } public int IntField { get; set; } } [Fact] public void CanSerializeSimpleDto() { var writer = new ByteBufferWriter(); var value = new SimpleDto { IntField = 42, StringField = "Hello" }; var storedDescriptorCtx = _mapping.StoreNewDescriptors(writer, value); storedDescriptorCtx.FinishNewDescriptors(writer); storedDescriptorCtx.StoreObject(writer, value); storedDescriptorCtx.CommitNewDescriptors(); var reader = new ByteBufferReader(writer.Data); _mapping.LoadTypeDescriptors(reader); var obj = (SimpleDto)_mapping.LoadObject(reader); Assert.Equal(value.IntField, obj.IntField); Assert.Equal(value.StringField, obj.StringField); } [Fact] public void CanSerializeSimpleDtoWithoutDefaultConstructor() { var writer = new ByteBufferWriter(); var value = new SimpleDtoWithoutDefaultConstructor("Hello") { IntField = 42 }; var storedDescriptorCtx = _mapping.StoreNewDescriptors(writer, value); storedDescriptorCtx.FinishNewDescriptors(writer); storedDescriptorCtx.StoreObject(writer, value); storedDescriptorCtx.CommitNewDescriptors(); var reader = new ByteBufferReader(writer.Data); _mapping.LoadTypeDescriptors(reader); var obj = (SimpleDtoWithoutDefaultConstructor)_mapping.LoadObject(reader); Assert.Equal(value.IntField, obj.IntField); Assert.Equal(value.StringField, obj.StringField); } void TestSerialization(object value) { var writer = new ByteBufferWriter(); var storedDescriptorCtx = _mapping.StoreNewDescriptors(writer, value); storedDescriptorCtx.FinishNewDescriptors(writer); storedDescriptorCtx.StoreObject(writer, value); storedDescriptorCtx.CommitNewDescriptors(); var reader = new ByteBufferReader(writer.Data); _mapping.LoadTypeDescriptors(reader); Assert.Equal(value, _mapping.LoadObject(reader)); Assert.True(reader.Eof); _mapping = _ts.CreateMapping(); reader = new ByteBufferReader(writer.Data); _mapping.LoadTypeDescriptors(reader); Assert.Equal(value, _mapping.LoadObject(reader)); Assert.True(reader.Eof); } #pragma warning disable 659 public class ClassWithList : IEquatable<ClassWithList> { public List<int> List { get; set; } public bool Equals(ClassWithList other) { if (List == other.List) return true; if (List == null || other.List == null) return false; if (List.Count != other.List.Count) return false; return List.Zip(other.List, (i1, i2) => i1 == i2).All(p => p); } public override bool Equals(object obj) { return Equals(obj as ClassWithList); } } [Fact] public void ListCanHaveContent() { TestSerialization(new ClassWithList { List = new List<int> { 1, 2, 3 } }); } [Fact] public void ListCanBeEmpty() { TestSerialization(new ClassWithList { List = new List<int>() }); } [Fact] public void ListCanBeNull() { TestSerialization(new ClassWithList { List = null }); } public class ClassWithDict : IEquatable<ClassWithDict> { public Dictionary<int, string> Dict { get; set; } public bool Equals(ClassWithDict other) { if (Dict == other.Dict) return true; if (Dict == null || other.Dict == null) return false; if (Dict.Count != other.Dict.Count) return false; foreach (var pair in Dict) { if (!other.Dict.ContainsKey(pair.Key)) return false; if (other.Dict[pair.Key] != pair.Value) return false; } return true; } public override bool Equals(object obj) { return Equals(obj as ClassWithDict); } } [Fact] public void DictionaryCanHaveContent() { TestSerialization(new ClassWithDict { Dict = new Dictionary<int, string> { { 1, "a" }, { 2, "b" }, { 3, "c" } } }); } [Fact] public void DictionaryCanBeEmpty() { TestSerialization(new ClassWithDict { Dict = new Dictionary<int, string>() }); } [Fact] public void DictionaryCanBeNull() { TestSerialization(new ClassWithDict { Dict = null }); } [Fact] public void BasicDescribe() { var ts = new TypeSerializers(); var res = new object[] { "", 1, 1U, (byte) 1, (sbyte) 1, (short) 1, (ushort) 1, 1L, 1UL, (double)1, (decimal)1, new DateTime(), new TimeSpan(), Guid.Empty, new byte[0], ByteBuffer.NewEmpty(), false, new EncryptedString() }.Select(o => ts.DescriptorOf(o).Describe()); this.Assent(string.Join("\n", res)); } [Fact] [MethodImpl(MethodImplOptions.NoInlining)] public void CheckCompatibilityOfRegistrationOfBasicTypeDescriptors() { this.Assent(string.Join("\n", BasicSerializersFactory.TypeDescriptors.Select(o => o.Name))); } public class SelfPointing1 { public SelfPointing1 Self1 { get; set; } public SelfPointing2 Self2 { get; set; } public int Other1 { get; set; } } public class SelfPointing2 { public SelfPointing1 Self1 { get; set; } public SelfPointing2 Self2 { get; set; } public string Other2 { get; set; } } public enum TestEnum { Item1, Item2 } [Fact] [MethodImpl(MethodImplOptions.NoInlining)] public void ComplexDescribe() { var ts = new TypeSerializers(); var res = new object[] { new List<int>(), new Dictionary<string,double>(), new SimpleDto(), new ClassWithList(), new ClassWithDict(), new SelfPointing1(), new SelfPointing2(), new TestEnum() }.Select(o => ts.DescriptorOf(o).Describe()); this.Assent(string.Join("\n", res)); } [Fact] public void BasicEnumTest1() { TestSerialization(TestEnum.Item1); } [Fact] public void BasicEnumTest2() { TestSerialization(TestEnum.Item2); } dynamic ConvertToDynamicThroughSerialization(object value) { var writer = new ByteBufferWriter(); var storedDescriptorCtx = _mapping.StoreNewDescriptors(writer, value); storedDescriptorCtx.FinishNewDescriptors(writer); storedDescriptorCtx.StoreObject(writer, value); storedDescriptorCtx.CommitNewDescriptors(); var originalDescription = _ts.DescriptorOf(value).Describe(); var reader = new ByteBufferReader(writer.Data); var ts = new TypeSerializers(); ts.SetTypeNameMapper(new ToDynamicMapper()); var mapping = ts.CreateMapping(); mapping.LoadTypeDescriptors(reader); var obj = (dynamic)mapping.LoadObject(reader); Assert.Equal(originalDescription, ts.DescriptorOf((object)obj).Describe()); return obj; } public class ToDynamicMapper : ITypeNameMapper { public string ToName(Type type) { return type.FullName; } public Type ToType(string name) { return null; } } [Fact] public void CanDeserializeSimpleDtoToDynamic() { var value = new SimpleDto { IntField = 42, StringField = "Hello" }; var obj = ConvertToDynamicThroughSerialization(value); Assert.Equal(value.IntField, obj.IntField); Assert.Equal(value.StringField, obj.StringField); Assert.Throws<MemberAccessException>(() => { var garbage = obj.Garbage; }); var descriptor = _ts.DescriptorOf((object)obj); Assert.NotNull(descriptor); Assert.True(descriptor.ContainsField("IntField")); Assert.False(descriptor.ContainsField("Garbage")); } [Fact] public void CanDeserializeListToDynamic() { var value = new List<SimpleDto> { new SimpleDto { IntField = 42, StringField = "Hello" } }; var obj = ConvertToDynamicThroughSerialization(value); Assert.Equal(value.Count, obj.Count); Assert.Equal(value[0].IntField, obj[0].IntField); Assert.Equal(value[0].StringField, obj[0].StringField); } [Fact] public void CanDeserializeDictionaryToDynamic() { var value = new Dictionary<int, SimpleDto> { { 10, new SimpleDto { IntField = 42, StringField = "Hello" } } }; var obj = ConvertToDynamicThroughSerialization(value); Assert.Equal(value.Count, obj.Count); Assert.Equal(value[10].IntField, obj[10].IntField); Assert.Equal(value[10].StringField, obj[10].StringField); } [Fact] public void CanDeserializeEnumToDynamic() { var value = (object)TestEnum.Item1; var obj = ConvertToDynamicThroughSerialization(value); Assert.Equal(value.ToString(), obj.ToString()); Assert.Equal(value.GetHashCode(), obj.GetHashCode()); Assert.True(obj.Equals(value)); Assert.False(obj.Equals(TestEnum.Item2)); } [Fact] public void CanDeserializeFlagsEnumToDynamic() { var value = (object)(AttributeTargets.Method | AttributeTargets.Property); var obj = ConvertToDynamicThroughSerialization(value); Assert.Equal(value.ToString(), obj.ToString()); Assert.Equal(value.GetHashCode(), obj.GetHashCode()); Assert.True(obj.Equals(value)); Assert.False(obj.Equals(AttributeTargets.Method)); } public class SimpleDtoWithNullable { public int? IntField { get; set; } } [Fact] public void CanDeserializeNullableToDynamic() { var value = new SimpleDtoWithNullable {IntField = 1}; var obj = ConvertToDynamicThroughSerialization(value); Assert.Equal(1, obj.IntField); } public class ClassWithIDict : IEquatable<ClassWithIDict> { public IDictionary<Guid, IList<SimpleDto>> Dict { get; set; } public bool Equals(ClassWithIDict other) { if (Dict == other.Dict) return true; if (Dict == null || other.Dict == null) return false; if (Dict.Count != other.Dict.Count) return false; foreach (var pair in Dict) { if (!other.Dict.ContainsKey(pair.Key)) return false; if (!other.Dict[pair.Key].SequenceEqual(pair.Value, new SimpleDtoComparer())) return false; } return true; } public override bool Equals(object obj) { return Equals(obj as ClassWithIDict); } public class SimpleDtoComparer : IEqualityComparer<SimpleDto> { public bool Equals(SimpleDto x, SimpleDto y) { return x.IntField == y.IntField && x.StringField == y.StringField; } public int GetHashCode(SimpleDto obj) { return obj.IntField; } } } #pragma warning restore 659 [Fact] public void DictionaryAsIfaceCanHaveContent() { TestSerialization(new ClassWithIDict { Dict = new Dictionary<Guid, IList<SimpleDto>> { { Guid.NewGuid(), new List<SimpleDto> { new SimpleDto {IntField = 1,StringField = "a" } } }, { Guid.NewGuid(), new List<SimpleDto> { new SimpleDto {IntField = 2,StringField = "b" } } }, { Guid.NewGuid(), new List<SimpleDto> { new SimpleDto {IntField = 3,StringField = "c" } } } } }); } class GenericClass<T> { public T Value { get; set; } public override bool Equals(object obj) { return obj is GenericClass<T> wrapper && EqualityComparer<T>.Default.Equals(Value, wrapper.Value); } public override int GetHashCode() { return Value?.GetHashCode() ?? 0; } } [Fact] public void CanSerializeGenericType() { TestSerialization(new GenericClass<int> { Value = 42 }); } class ClassWithIOrderedDictionary : IEquatable<ClassWithIOrderedDictionary> { public IOrderedDictionary<int, int> IOrderedDictionary { get; set; } public override bool Equals(object obj) { return Equals(obj as ClassWithIOrderedDictionary); } public bool Equals(ClassWithIOrderedDictionary other) { if (other == null) return false; if (IOrderedDictionary == other.IOrderedDictionary) return true; if (IOrderedDictionary == null || other.IOrderedDictionary == null) return false; if (IOrderedDictionary.Count != other.IOrderedDictionary.Count) return false; foreach (var pair in IOrderedDictionary) { if (!other.IOrderedDictionary.ContainsKey(pair.Key)) return false; if (other.IOrderedDictionary[pair.Key] != pair.Value) return false; } return true; } public override int GetHashCode() { return IOrderedDictionary?.GetHashCode() ?? 0; } } class DummyOrderedDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IOrderedDictionary<TKey, TValue> { public IOrderedDictionaryEnumerator<TKey, TValue> GetAdvancedEnumerator(AdvancedEnumeratorParam<TKey> param) => throw new NotImplementedException(); public IEnumerable<KeyValuePair<TKey, TValue>> GetDecreasingEnumerator(TKey start) => throw new NotImplementedException(); public IEnumerable<KeyValuePair<TKey, TValue>> GetIncreasingEnumerator(TKey start) => throw new NotImplementedException(); public IEnumerable<KeyValuePair<TKey, TValue>> GetReverseEnumerator() => throw new NotImplementedException(); public long RemoveRange(TKey start, bool includeStart, TKey end, bool includeEnd) => throw new NotImplementedException(); } [Fact] public void CanSerializeIOrderedDictionaryType() { TestSerialization(new ClassWithIOrderedDictionary { IOrderedDictionary = new DummyOrderedDictionary<int, int> { [1] = 2, [2] = 3, } }); } public class ClassWithBoxedIEnumerable { public object Value { get; set; } public override bool Equals(object obj) { if (obj is ClassWithBoxedIEnumerable o) { var enumA = ((IEnumerable)Value).GetEnumerator(); var enumB = ((IEnumerable)o.Value).GetEnumerator(); enumA.Reset(); enumB.Reset(); while (enumA.MoveNext() | enumB.MoveNext()) { if (!enumA.Current.Equals(enumB.Current)) return false; } return true; } return false; } public override int GetHashCode() { return Value?.GetHashCode() ?? 0; } } [Fact] public void CanSerializeBoxedList() { TestSerialization(new ClassWithBoxedIEnumerable { Value = new List<int> { 1,2,3 } }); } [Fact] public void CanSerializeBoxedDictionary() { TestSerialization(new ClassWithBoxedIEnumerable { Value = new Dictionary<int, int> { [1] = 2, [2] = 3 } }); } class MyList<T> : List<T> { } [Fact(Skip = "By design - not supported yet")] public void CanSerializeBoxedCustomList() { TestSerialization(new ClassWithBoxedIEnumerable { Value = new MyList<int> { 1,2,3 } }); } [Fact(Skip = "By design - not supported yet")] public void CanSerializeBoxedIOrderedDictionary() { TestSerialization(new ClassWithBoxedIEnumerable { Value = new DummyOrderedDictionary<int, int> { [1] = 2, [2] = 3 } }); } } }
#if !SILVERLIGHT using NUnit.Framework; #else using Microsoft.Silverlight.Testing; #endif using System; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls.Primitives; using System.Windows.Threading; using System.Diagnostics; using System.Text; using System.Linq; using System.Reflection; using System.Collections.Generic; namespace DevExpress { public class WpfTestWindow { public static readonly DependencyProperty MethodsToSkipProperty = DependencyProperty.RegisterAttached("MethodsToSkip", typeof(IEnumerable<string>), typeof(WpfTestWindow), new PropertyMetadata(Enumerable.Empty<string>())); public static IEnumerable<string> GetMethodsToSkip(DependencyObject obj) { return (IEnumerable<string>)obj.GetValue(MethodsToSkipProperty); } public static void SetMethodsToSkip(DependencyObject obj, IEnumerable<string> value) { obj.SetValue(MethodsToSkipProperty, value); } #if SILVERLIGHT WorkItemTest workItemTest; #endif TestWindow window; Window realWindow; static WpfTestWindow() { #if !SILVERLIGHT DispatcherHelper.ForceIncreasePriorityContextIdleMessages(); #endif } public WpfTestWindow() { MethodsToSkip = Enumerable.Empty<string>(); } public virtual int TimeoutInSeconds { get { return 5; } } protected virtual TestWindow CreateTestWindow() { return TestWindow.GetContainer(); } protected virtual Window CreateRealWindow() { return new Window(); } protected virtual void SetUpCore() { #if SILVERLIGHT System.Windows.Browser.HtmlPage.Plugin.Focus(); workItemTest = new WorkItemTest() { UnitTestHarness = DevExpress.TestHelper.TestHarness }; #endif } protected virtual void TearDownCore() { if(realWindow != null) { #if !SILVERLIGHT realWindow.SourceInitialized -= OnRealWindowSourceInitialized; #endif realWindow.Close(); realWindow.Content = null; } if (window != null) { window.Close(); window.Content = null; window.MaxWidth = double.PositiveInfinity; window.MinWidth = 0.0; window.MaxHeight = double.PositiveInfinity; window.MinHeight = 0.0; window.Width = double.NaN; window.Height = double.NaN; } window = null; realWindow = null; DispatcherHelper.DoEvents(); } IEnumerable<string> MethodsToSkip; static Type voidType = typeof(void); protected virtual void FixtureSetUpCore() { List<string> methodsToSkip = new List<string>(); MethodsToSkip = methodsToSkip; } protected virtual void FixtureTearDownCore() { } [SetUp] public void SetUp() { SetUpCore(); } [TearDown] public void TearDown() { TearDownCore(); } [TestFixtureSetUp] public void FixtureSetUp() { FixtureSetUpCore(); } [TestFixtureTearDown] public void FixtureTearDown() { #if SILVERLIGHT System.Windows.Media.CompositionTarget.Rendering -= CompositionTarget_Rendering; #endif FixtureTearDownCore(); } public TestWindow Window { get { if(window == null) { window = CreateTestWindow(); SetMethodsToSkip(window, MethodsToSkip); SetThemeForWindow(window); } return window; } } public Window RealWindow { get { if(realWindow == null) { realWindow = CreateRealWindow(); #if !SILVERLIGHT realWindow.SourceInitialized += OnRealWindowSourceInitialized; #endif SetThemeForWindow(realWindow); } return realWindow; } } void OnRealWindowSourceInitialized(object sender, EventArgs e) { CheckToSkip(MethodsToSkip); } protected virtual void SetThemeForWindow(System.Windows.Controls.ContentControl window) { } public virtual void EnqueueCallback(Action testCallbackDelegate) { #if SILVERLIGHT workItemTest.EnqueueCallback(testCallbackDelegate); #else testCallbackDelegate(); #endif } protected sealed class TimeoutGuard : IDisposable { DispatcherTimer timer = new DispatcherTimer(); public TimeoutGuard(int timeoutInSeconds, string message) { timer.Interval = new TimeSpan(0, 0, timeoutInSeconds); timer.Tick += (s, e) => { timer.Stop(); throw new Exception(message); }; timer.Start(); } public void Dispose() { if(timer.IsEnabled) timer.Stop(); } } #if !SILVERLIGHT public virtual void EnqueueDialog(Action testCallbackDelegate, string message = null) { using(new TimeoutGuard(TimeoutInSeconds, GetActionTimeOutMessage(message, testCallbackDelegate))) { testCallbackDelegate(); } } public virtual void EnqueueDialog<T>(Func<T> testCallbackDelegate, Action<T> result, string message = null) { T resultValue = default(T); using(new TimeoutGuard(TimeoutInSeconds, GetActionTimeOutMessage(message, testCallbackDelegate))) { resultValue = testCallbackDelegate(); } result(resultValue); } #else public virtual void EnqueueDialog(Func<Task> testCallbackDelegate, string message = null) { bool done = false; EnqueueCallback(() => testCallbackDelegate().ContinueWith(t => done = true)); EnqueueConditional(() => done, GetActionTimeOutMessage(message, testCallbackDelegate)); } public virtual void EnqueueDialog<T>(Func<Task<T>> testCallbackDelegate, Action<T> result, string message = null) { T resultValue = default(T); bool done = false; EnqueueCallback(() => testCallbackDelegate().ContinueWith(t => { resultValue = t.Result; done = true; })); EnqueueConditional(() => done, GetActionTimeOutMessage(message, testCallbackDelegate)); EnqueueCallback(() => result(resultValue)); } #endif public void EnqueueTestWindowMainCallback(Action testCallbackDelegate) { EnqueueShowWindow(); EnqueueLastCallback(testCallbackDelegate); } public void EnqueueRealWindowMainCallback(Action testCallbackDelegate) { EnqueueShowRealWindow(); EnqueueLastCallback(testCallbackDelegate); } public virtual void EnqueueLastCallback(Action testCallbackDelegate) { EnqueueCallback(testCallbackDelegate); EnqueueTestComplete(); } public void EnqueueDelay(int delayInMillisceconds) { EnqueueDelay(TimeSpan.FromMilliseconds(delayInMillisceconds)); } public void EnqueueDelay(TimeSpan delay) { #if SILVERLIGHT DateTime? start = null; workItemTest.EnqueueConditional(() => { if(start == null) { start = DateTime.Now; } return delay < DateTime.Now - start; }); #else DateTime start = DateTime.Now; while(delay > DateTime.Now - start) { DispatcherHelper.DoEvents(); } #endif } public virtual void EnqueueConditional(Func<bool> conditionalDelegate, string message) { #if SILVERLIGHT DateTime? start = null; workItemTest.EnqueueConditional(() => { if(start == null) { start = DateTime.Now; } if (TimeSpan.FromSeconds(TimeoutInSeconds) < DateTime.Now - start) { throw new Exception(GetTimeOutMessage(message, conditionalDelegate)); } return conditionalDelegate(); }); #else Assert.AreEqual(true, conditionalDelegate(), GetTimeOutMessage(message, conditionalDelegate)); #endif } public virtual void EnqueueWait(Func<bool> conditionalDelegate) { EnqueWaitForObject(() => conditionalDelegate() ? conditionalDelegate : null, o => { }); } #if SILVERLIGHT public virtual void EnqueWaitForAsync(Task task) { if(task == null) return; EnqueWaitForObject(() => task.Wait(1) ? task : null, o => { }); } public virtual void EnqueWaitForObject(Func<object> getObject, Action<object> setObject) { EnqueueConditional(() => { object obj = getObject(); if(obj != null) { setObject(obj); return true; } return false; }); } public virtual void EnqueDelayOrWaitForObject(Func<object> getObject, Action<object> setObject, int delayInMillisceconds = 5000) { DateTime? start= null; workItemTest.EnqueueConditional(() => { if(start == null) start = DateTime.Now; object obj = getObject(); if(obj != null) { setObject(obj); return true; } return TimeSpan.FromMilliseconds(delayInMillisceconds) < DateTime.Now - start; }); } #else public virtual void EnqueueWaitRealWindow(Func<bool> conditionalDelegate) { EnqueWaitForObjectRealWindow(() => conditionalDelegate() ? conditionalDelegate : null, o => { }); } public virtual void EnqueWaitForAsync(Thread t) { EnqueWaitForAsync(t, DispatcherPriority.Background); } public virtual void EnqueWaitForAsync(Thread t, DispatcherPriority priority) { if(t == null) return; EnqueWaitForObject(() => t.Join(1) ? t : null, o => { }, priority); } public virtual void EnqueWaitForAsync(ManualResetEvent e) { EnqueWaitForAsync(e, DispatcherPriority.Background); } public virtual void EnqueWaitForAsync(ManualResetEvent e, DispatcherPriority priority) { if(e == null) return; EnqueWaitForObject(() => e.WaitOne(1) ? e : null, o => { }, priority); } public virtual void EnqueWaitForAsync(Task task) { EnqueWaitForAsync(task, DispatcherPriority.Background); } public virtual void EnqueWaitForAsync(Task task, DispatcherPriority priority) { if(task == null) return; EnqueWaitForObject(() => task.Wait(1) ? task : null, o => { }, priority); } public virtual void EnqueWaitForObject(Func<object> getObject, Action<object> setObject) { EnqueWaitForObject(getObject, setObject, DispatcherPriority.Background); } public virtual void EnqueWaitForObjectRealWindow(Func<object> getObject, Action<object> setObject) { EnqueWaitForObjectRealWindow(getObject, setObject, DispatcherPriority.Background); } public virtual void EnqueWaitForObjectRealWindow(Func<object> getObject, Action<object> setObject, DispatcherPriority priority) { EnqueueCallback(() => { DateTime start = DateTime.Now; while(TimeSpan.FromSeconds(TimeoutInSeconds) > DateTime.Now - start) { object obj = getObject(); if(obj != null) { setObject(obj); return; } DispatcherHelper.DoEvents(priority); } throw new Exception(GetTimeOutMessage(null, () => false)); }); } public virtual void EnqueWaitForObject(Func<object> getObject, Action<object> setObject, DispatcherPriority priority) { EnqueueCallback(() => { DateTime start = DateTime.Now; while(TimeSpan.FromSeconds(TimeoutInSeconds) > DateTime.Now - start) { object obj = getObject(); if(obj != null) { setObject(obj); return; } DispatcherHelper.UpdateLayoutAndDoEvents(Window, priority); } throw new Exception(GetTimeOutMessage(null, () => false)); }); } public virtual void EnqueDelayOrWaitForObject(Func<object> getObject, Action<object> setObject, int delayInMillisceconds) { EnqueueCallback(() => { DateTime start = DateTime.Now; while(TimeSpan.FromMilliseconds(delayInMillisceconds) > DateTime.Now - start) { object obj = getObject(); if(obj != null) { setObject(obj); return; } DispatcherHelper.UpdateLayoutAndDoEvents(Window); } }); } #endif string GetActionTimeOutMessage(string message, Delegate testDelegate) { return string.IsNullOrEmpty(message) ? string.Format("Action aborted with timeout {0} seconds: {1}", TimeoutInSeconds, testDelegate.Method) : message; } protected string GetTimeOutMessage(string message, Func<bool> conditionalDelegate) { return string.IsNullOrEmpty(message) ? string.Format("The condition failed with timeout {0} seconds: {1}", TimeoutInSeconds, conditionalDelegate.Method) : message; } public virtual void EnqueueConditional(Func<bool> conditionalDelegate) { EnqueueConditional(conditionalDelegate, null); } public virtual void EnqueueTestComplete() { #if SILVERLIGHT workItemTest.EnqueueTestComplete(); #endif } public virtual void EnqueueShowRealWindow() { EnqueueLoadedEventAction(RealWindow, () => RealWindow.Show()); #if SILVERLIGHT EnqueueDelay(100); EnqueueWindowUpdateLayout(); #endif } public virtual void EnqueueShowWindow() { EnqueueShowWindow(Window); #if SILVERLIGHT EnqueueDelay(100); EnqueueWindowUpdateLayout(); #endif } public virtual void EnqueueShowWindow(TestWindow window) { EnqueueLoadedEventAction(window, () => window.Show()); } public virtual void EnqueueWindowUpdateLayout() { EnqueueCallback(delegate { DispatcherHelper.UpdateLayoutAndDoEvents(Window); }); } #if !SILVERLIGHT public virtual void EnqueueWindowUpdateLayout(DispatcherPriority priority) { EnqueueCallback(delegate { DispatcherHelper.UpdateLayoutAndDoEvents(Window, priority); }); } #endif public void EnqueueLoadedEventAction(FrameworkElement element, Action action) { EnqueueLoadedEventAction(() => element, action); } public void EnqueueLoadedEventAction(Func<FrameworkElement> getElement, Action action) { EnqueueWaitEventEventAction(getElement, action, (getElementDelegate, handler) => getElementDelegate().Loaded += handler); } public void EnqueueClickButton(Func<ButtonBase> getButtonDelegate) { EnqueueWaitEventEventAction(() => getButtonDelegate(), () => UITestHelper.ClickButton(getButtonDelegate()), (getElementDelegate_, handler) => ((ButtonBase)getElementDelegate_()).Click += handler); } public void EnqueueClickButton(ButtonBase button) { EnqueueClickButton(() => button); } protected delegate void SubscribeDelegate(Func<FrameworkElement> getElementDelegate, RoutedEventHandler handler); protected void EnqueueWaitEventEventAction(Func<FrameworkElement> getElementDelegate, Action action, SubscribeDelegate subscribeDelegate) { #if SILVERLIGHT bool eventFired = false; EnqueueCallback(() => subscribeDelegate(getElementDelegate, delegate { eventFired = true; })); EnqueueCallback(action); EnqueueConditional(() => eventFired); #else action(); #endif } #if SILVERLIGHT bool rendered; protected void EnqueueWaitRenderAction() { EnqueueCallback(() => { System.Windows.Media.CompositionTarget.Rendering -= CompositionTarget_Rendering; System.Windows.Media.CompositionTarget.Rendering += CompositionTarget_Rendering; rendered = false; }); EnqueueConditional(() => { if(rendered) { rendered = false; return true; } return false; }); } void CompositionTarget_Rendering(object sender, EventArgs e) { System.Windows.Media.CompositionTarget.Rendering -= CompositionTarget_Rendering; rendered = true; } #else protected void EnqueueWaitRenderAction() { } #endif public static void CheckToSkip(IEnumerable<string> methodsToSkip) { if (methodsToSkip.Count() == 0) return; } } }
// // Copyright (c) 2006-2018 Erik Ylvisaker // // 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 AgateLib.Quality; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using System.Collections; using System.Collections.Generic; namespace AgateLib.Input { /// <summary> /// Provides a mapping from keyboard keys to gamepad inputs. /// </summary> public class KeyboardGamepadMap : IDictionary<Microsoft.Xna.Framework.Input.Keys, KeyMapItem> { private static KeyboardGamepadMap defaultValue; public static KeyboardGamepadMap Default { get { if (defaultValue == null) { defaultValue = new KeyboardGamepadMap { { Microsoft.Xna.Framework.Input.Keys.W, KeyMapItem.ToLeftStick(PlayerIndex.One, Axis.Y, -1) }, { Microsoft.Xna.Framework.Input.Keys.A, KeyMapItem.ToLeftStick(PlayerIndex.One, Axis.X, -1) }, { Microsoft.Xna.Framework.Input.Keys.D, KeyMapItem.ToLeftStick(PlayerIndex.One, Axis.X, 1) }, { Microsoft.Xna.Framework.Input.Keys.S, KeyMapItem.ToLeftStick(PlayerIndex.One, Axis.Y, 1) }, { Microsoft.Xna.Framework.Input.Keys.F, KeyMapItem.ToButton(PlayerIndex.One, Buttons.LeftStick) }, { Microsoft.Xna.Framework.Input.Keys.I, KeyMapItem.ToRightStick(PlayerIndex.One, Axis.Y, -1) }, { Microsoft.Xna.Framework.Input.Keys.J, KeyMapItem.ToRightStick(PlayerIndex.One, Axis.X, -1) }, { Microsoft.Xna.Framework.Input.Keys.L, KeyMapItem.ToRightStick(PlayerIndex.One, Axis.X, 1) }, { Microsoft.Xna.Framework.Input.Keys.K, KeyMapItem.ToRightStick(PlayerIndex.One, Axis.Y, 1) }, { Microsoft.Xna.Framework.Input.Keys.OemSemicolon, KeyMapItem.ToButton(PlayerIndex.One, Buttons.RightStick) }, { Microsoft.Xna.Framework.Input.Keys.Up, KeyMapItem.ToButton(PlayerIndex.One, Buttons.DPadUp) }, { Microsoft.Xna.Framework.Input.Keys.Down, KeyMapItem.ToButton(PlayerIndex.One, Buttons.DPadDown) }, { Microsoft.Xna.Framework.Input.Keys.Left, KeyMapItem.ToButton(PlayerIndex.One, Buttons.DPadLeft) }, { Microsoft.Xna.Framework.Input.Keys.Right, KeyMapItem.ToButton(PlayerIndex.One, Buttons.DPadRight) }, { Microsoft.Xna.Framework.Input.Keys.Back, KeyMapItem.ToButton(PlayerIndex.One, Buttons.Back) }, { Microsoft.Xna.Framework.Input.Keys.Enter, KeyMapItem.ToButton(PlayerIndex.One, Buttons.Start) }, { Microsoft.Xna.Framework.Input.Keys.Space, KeyMapItem.ToButton(PlayerIndex.One, Buttons.A) }, { Microsoft.Xna.Framework.Input.Keys.LeftControl, KeyMapItem.ToButton(PlayerIndex.One, Buttons.X) }, { Microsoft.Xna.Framework.Input.Keys.LeftAlt, KeyMapItem.ToButton(PlayerIndex.One, Buttons.B) }, { Microsoft.Xna.Framework.Input.Keys.LeftShift, KeyMapItem.ToButton(PlayerIndex.One, Buttons.Y) }, { Microsoft.Xna.Framework.Input.Keys.Z, KeyMapItem.ToButton(PlayerIndex.One, Buttons.LeftShoulder) }, { Microsoft.Xna.Framework.Input.Keys.X, KeyMapItem.ToButton(PlayerIndex.One, Buttons.RightShoulder) }, { Microsoft.Xna.Framework.Input.Keys.Q, KeyMapItem.ToLeftTrigger(PlayerIndex.One) }, { Microsoft.Xna.Framework.Input.Keys.E, KeyMapItem.ToRightTrigger(PlayerIndex.One) }, }; } return defaultValue; } set { Require.ArgumentNotNull(value, nameof(Default), "Default keymap must not be null."); defaultValue = value; } } private readonly Dictionary<Keys, KeyMapItem> keyMap = new Dictionary<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>(); /// <summary> /// The number of items in the keymap. /// </summary> public int Count => keyMap.Count; /// <summary> /// Adds a new mapping. /// </summary> /// <param name="keyCode"></param> /// <param name="keyMapItem"></param> public void Add(Microsoft.Xna.Framework.Input.Keys keyCode, KeyMapItem keyMapItem) { keyMap.Add(keyCode, keyMapItem); } /// <summary> /// Returns true if the key is mapped. /// </summary> /// <param name="key"></param> /// <returns></returns> public bool ContainsKey(Microsoft.Xna.Framework.Input.Keys key) { return keyMap.ContainsKey(key); } /// <summary> /// Removes a key mapping. /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Remove(Microsoft.Xna.Framework.Input.Keys key) { return keyMap.Remove(key); } /// <summary> /// Attemps to get a key mapping, returning true if successful. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool TryGetValue(Microsoft.Xna.Framework.Input.Keys key, out KeyMapItem value) { return keyMap.TryGetValue(key, out value); } /// <summary> /// Gets or sets a key mapping. /// </summary> /// <param name="key"></param> /// <returns></returns> public KeyMapItem this[Microsoft.Xna.Framework.Input.Keys key] { get => keyMap[key]; set => keyMap[key] = value; } /// <summary> /// Gets the collection of mapped keys. /// </summary> public ICollection<Microsoft.Xna.Framework.Input.Keys> Keys => keyMap.Keys; /// <summary> /// Get the collection of map values. /// </summary> public ICollection<KeyMapItem> Values => keyMap.Values; /// <summary> /// Enumerates the key-value pairs. /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>> GetEnumerator() { return keyMap.GetEnumerator(); } /// <summary> /// Clears the key map. /// </summary> public void Clear() { keyMap.Clear(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)keyMap).GetEnumerator(); } void ICollection<KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>>.Add(KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem> item) { keyMap.Add(item.Key, item.Value); } bool ICollection<KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>>.Contains(KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem> item) { return ((IDictionary<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>)keyMap).Contains(item); } void ICollection<KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>>.CopyTo(KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>[] array, int arrayIndex) { ((IDictionary<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>)keyMap).CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>>.Remove(KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem> item) { return ((IDictionary<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>)keyMap).Remove(item); } bool ICollection<KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>>.IsReadOnly => ((ICollection<KeyValuePair<Microsoft.Xna.Framework.Input.Keys, KeyMapItem>>)keyMap).IsReadOnly; } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using Microsoft.Deployment.WindowsInstaller; namespace WixSharp { /// <summary> /// Defines System.Windows.Forms.<see cref="T:System.Windows.Forms.Form" />, which is to be used as the for custom MSI dialog. /// <para> /// As opposite to the WixSharp.<see cref="T:WixSharp.WixForm" /> based custom dialogs <c>WixCLRDialog</c> is instantiated not at /// compile but at run time. Thus it is possible to implement comprehensive deployment algorithms in any of the available Form event handlers. /// </para> /// <para> /// The usual usability scenario is the injection of the managed Custom Action (for displaying the <c>WixCLRDialog</c>) /// into the sequence of the standard dialogs (WixSharp.<see cref="T:WixSharp.CustomUI"/>). /// </para> /// <para> /// While it is possible to construct <see cref="T:WixSharp.CustomUI"/> instance manually it is preferred to use /// Factory methods of <see cref="T:WixSharp.CustomUIBuilder"/> (e.g. InjectPostLicenseClrDialog) for this. /// </para> /// <code> /// static public void Main() /// { /// ManagedAction showDialog; /// /// var project = new Project("CustomDialogTest", /// showDialog = new ShowClrDialogAction("ShowProductActivationDialog")); /// /// project.UI = WUI.WixUI_Common; /// project.CustomUI = CustomUIBuilder.InjectPostLicenseClrDialog(showDialog.Id, " LicenseAccepted = \"1\""); /// /// Compiler.BuildMsi(project); /// } /// ... /// public class CustomActions /// { /// [CustomAction] /// public static ActionResult ShowProductActivationDialog(Session session) /// { /// return WixCLRDialog.ShowAsMsiDialog(new CustomDialog(session)); /// } /// } /// ... /// public partial class CustomDialog : WixCLRDialog /// { /// private GroupBox groupBox1; /// private Button cancelBtn; /// ... /// </code> /// <para> /// The all communications with the installation in progress are to be done by modifying the MSI properties or executing MSI actions /// via <c>Session</c> object.</para> /// <para> /// When closing the dialog make sure you set the DeialogResul properly. <c>WixCLRDialog</c> offers three predefined routines for setting the /// DialogResult: /// <para>- MSINext</para> /// <para>- MSIBack</para> /// <para>- MSICancel</para> /// By invoking these routines from the corresponding event handlers you can control your MSI UI sequence: /// <code> /// void cancelBtn_Click(object sender, EventArgs e) /// { /// MSICancel(); /// } /// /// void nextBtn_Click(object sender, EventArgs e) /// { /// MSINext(); /// } /// /// void backBtn_Click(object sender, EventArgs e) /// { /// MSIBack(); /// } /// </code> /// </para> /// </summary> public partial class WixCLRDialog : Form { /// <summary> /// The MSI session /// </summary> public Session session; /// <summary> /// The WIN32 handle to the host window (parent MSI dialog). /// </summary> protected IntPtr hostWindow; /// <summary> /// Initializes a new instance of the <see cref="WixCLRDialog"/> class. /// <remarks> /// This constructor is to be used by the Visual Studio Form designer only. /// You should always use <c>WixCLRDialog(Session session)</c> constructor instead. /// </remarks> /// </summary> public WixCLRDialog() { InitializeComponent(); } /// <summary> /// Initializes a new instance of the <see cref="WixCLRDialog"/> class. /// </summary> /// <param name="session">The session.</param> public WixCLRDialog(Session session) { this.session = session; InitializeComponent(); } void InitializeComponent() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); } catch { } if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { try { if (this.DesignMode) return; this.VisibleChanged += form_VisibleChanged; this.FormClosed += WixPanel_FormClosed; this.Load += WixDialog_Load; Init(); } catch { } } } void WixDialog_Load(object sender, EventArgs e) { this.Text = Win32.GetWindowText(this.hostWindow); } /// <summary> /// Inits this instance. /// </summary> protected void Init() { this.hostWindow = GetMsiForegroundWindow(); this.Opacity = 0.0005; this.Text = Win32.GetWindowText(this.hostWindow); #if DEBUG //System.Diagnostics.Debugger.Launch(); #endif foreach (Process p in Process.GetProcessesByName("msiexec")) try { this.Icon = Icon.ExtractAssociatedIcon(p.MainModule.FileName); //service process throws on accessing MainModule break; } catch { } } IntPtr GetMsiForegroundWindow() { var proc = Process.GetProcessesByName("msiexec").Where(p => p.MainWindowHandle != IntPtr.Zero).FirstOrDefault(); if (proc != null) { Win32.ShowWindow(proc.MainWindowHandle, Win32.SW_RESTORE); Win32.SetForegroundWindow(proc.MainWindowHandle); return proc.MainWindowHandle; } else return IntPtr.Zero; } /// <summary> /// There is some strange resizing artefact (at least on Win7) when MoveWindow does not resize the window accurately. /// Thus special adjustment ('delta') is needed to fix the problem. /// <para> /// The delta value is used in the ReplaceHost method.</para> /// </summary> protected int delta = 4; /// <summary> /// 'Replaces' the current step dialog with the "itself". /// <para>It uses WIN32 API to hide the parent native MSI dialog and place managed form dialog (itself) /// at the same desktop location and with the same size as the parent.</para> /// </summary> protected void ReplaceHost() { try { Win32.RECT r; Win32.GetWindowRect(hostWindow, out r); Win32.MoveWindow(this.Handle, r.Left - delta, r.Top - delta, r.Right - r.Left + delta * 2, r.Bottom - r.Top + delta * 2, true); this.Opacity = 1; Application.DoEvents(); this.MaximumSize = this.MinimumSize = new Size(this.Width, this.Height); //prevent resizing hostWindow.Hide(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } /// <summary> /// Restores parent native MSI dialog after the previous <c>ReplaceHost</c> call. /// </summary> protected void RestoreHost() { Win32.RECT r; Win32.GetWindowRect(this.Handle, out r); Win32.RECT rHost; Win32.GetWindowRect(hostWindow, out rHost); Win32.MoveWindow(hostWindow, r.Left + delta, r.Top + delta, rHost.Right - rHost.Left, rHost.Bottom - rHost.Top, true); hostWindow.Show(); this.Opacity = 0.01; Application.DoEvents(); } private void WixPanel_FormClosed(object sender, FormClosedEventArgs e) { RestoreHost(); } bool initialized = false; private void form_VisibleChanged(object sender, EventArgs e) { if (Visible) { if (!initialized) { initialized = true; ReplaceHost(); this.Visible = true; Application.DoEvents(); } } } /// <summary> /// Closes the dialog and sets the <c>this.DialogResult</c> to the 'DialogResult.Cancel' value ensuring the /// setup is cancelled. /// </summary> public void MSICancel() { this.DialogResult = DialogResult.Cancel; Close(); } /// <summary> /// Closes the dialog and sets the <c>this.DialogResult</c> to the 'DialogResult.Retry' value ensuring the /// setup is resumed with the previous UI sequence dialog is displayed. /// </summary> public void MSIBack() { this.DialogResult = DialogResult.Retry; Close(); } /// <summary> /// Closes the dialog and sets the <c>this.DialogResult</c> to the 'DialogResult.OK' value ensuring the /// setup is resumed and the UI sequence advanced to the next step. /// </summary> public void MSINext() { this.DialogResult = DialogResult.OK; Close(); } /// <summary> /// Shows as specified managed dialog. /// <para>It uses WIN32 API to hide the parent native MSI dialog and place managed form dialog /// at the same desktop location and with the same size as the parent.</para> /// <para>It also ensures that after the managed dialog is closed the proper ActionResult is returned.</para> /// </summary> /// <param name="dialog">The dialog.</param> /// <returns>ActionResult value</returns> public static ActionResult ShowAsMsiDialog(WixCLRDialog dialog) { ActionResult retval = ActionResult.Success; try { using (dialog) { DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { dialog.session["Custom_UI_Command"] = "next"; retval = ActionResult.Success; } else if (result == DialogResult.Cancel) { dialog.session["Custom_UI_Command"] = "abort"; retval = ActionResult.UserExit; } if (result == DialogResult.Retry) { dialog.session["Custom_UI_Command"] = "back"; retval = ActionResult.Success; } } } catch (Exception e) { dialog.session.Log("Error: " + e.ToString()); retval = ActionResult.Failure; } #if DEBUG //System.Diagnostics.Debugger.Launch(); #endif return retval; } /// <summary> /// Gets the embedded MSI binary stream. /// </summary> /// <param name="binaryId">The binary id.</param> /// <returns>Stream instance</returns> public Stream GetMSIBinaryStream(string binaryId) { using (var sqlView = this.session.Database.OpenView("select Data from Binary where Name = '" + binaryId + "'")) { sqlView.Execute(); Stream data = sqlView.Fetch().GetStream(1); var retval = new MemoryStream(); int Length = 256; var buffer = new Byte[Length]; int bytesRead = data.Read(buffer, 0, Length); while (bytesRead > 0) { retval.Write(buffer, 0, bytesRead); bytesRead = data.Read(buffer, 0, Length); } return retval; } } } }
// 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 OLEDB.Test.ModuleCore; namespace System.Xml.Tests { public partial class TCLinePos : TCXMLReaderBaseGeneral { // Type is System.Xml.Tests.TCLinePos // Test Case public override void AddChildren() { // for function TestLinePos1 { this.AddChild(new CVariation(TestLinePos1) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Element") { Priority = 0 } }); } // for function TestLinePos2 { this.AddChild(new CVariation(TestLinePos2) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = CDATA") { Priority = 0 } }); } // for function TestLinePos4 { this.AddChild(new CVariation(TestLinePos4) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Comment") { Priority = 0 } }); } // for function TestLinePos6 { this.AddChild(new CVariation(TestLinePos6) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = EndElement") { Priority = 0 } }); } // for function TestLinePos7 { this.AddChild(new CVariation(TestLinePos7) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = EntityReference, not expanded") { Priority = 0 } }); } // for function TestLinePos9 { this.AddChild(new CVariation(TestLinePos9) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = ProcessingInstruction") { Priority = 0 } }); } // for function TestLinePos10 { this.AddChild(new CVariation(TestLinePos10) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = SignificantWhitespace") { Priority = 0 } }); } // for function TestLinePos11 { this.AddChild(new CVariation(TestLinePos11) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Text") { Priority = 0 } }); } // for function TestLinePos12 { this.AddChild(new CVariation(TestLinePos12) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Whitespace") { Priority = 0 } }); } // for function TestLinePos13 { this.AddChild(new CVariation(TestLinePos13) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = XmlDeclaration") { Priority = 0 } }); } // for function TestLinePos14 { this.AddChild(new CVariation(TestLinePos14) { Attribute = new Variation("LineNumber/LinePos after MoveToElement") }); } // for function TestLinePos15 { this.AddChild(new CVariation(TestLinePos15) { Attribute = new Variation("LineNumber/LinePos after MoveToFirstAttribute/MoveToNextAttribute") }); } // for function TestLinePos16 { this.AddChild(new CVariation(TestLinePos16) { Attribute = new Variation("LineNumber/LinePos after MoveToAttribute") }); } // for function TestLinePos18 { this.AddChild(new CVariation(TestLinePos18) { Attribute = new Variation("LineNumber/LinePos after Skip") }); } // for function TestLinePos19 { this.AddChild(new CVariation(TestLinePos19) { Attribute = new Variation("LineNumber/LinePos after ReadInnerXml") }); } // for function TestLinePos20 { this.AddChild(new CVariation(TestLinePos20) { Attribute = new Variation("LineNumber/LinePos after MoveToContent") }); } // for function TestLinePos21 { this.AddChild(new CVariation(TestLinePos21) { Attribute = new Variation("LineNumber/LinePos after ReadBase64 successive calls") }); } // for function TestLinePos22 { this.AddChild(new CVariation(TestLinePos22) { Attribute = new Variation("LineNumber/LinePos after ReadBinHex succesive calls") }); } // for function TestLinePos26 { this.AddChild(new CVariation(TestLinePos26) { Attribute = new Variation("LineNumber/LinePos after ReadEndElement") }); } // for function TestLinePos27 { this.AddChild(new CVariation(TestLinePos27) { Attribute = new Variation("LineNumber/LinePos after ReadString") }); } // for function TestLinePos39 { this.AddChild(new CVariation(TestLinePos39) { Attribute = new Variation("LineNumber/LinePos after element containing entities in attribute values") }); } // for function TestLinePos40 { this.AddChild(new CVariation(TestLinePos40) { Attribute = new Variation("LineNumber/LinePos when Read = false") }); } // for function TestLinePos41 { this.AddChild(new CVariation(TestLinePos41) { Attribute = new Variation("XmlTextReader:LineNumber and LinePos don't return the right position after ReadInnerXml is called") }); } // for function TestLinePos42 { this.AddChild(new CVariation(TestLinePos42) { Attribute = new Variation("XmlTextReader: LineNum and LinePosition incorrect for EndTag token and text element") }); } // for function TestLinePos43 { this.AddChild(new CVariation(TestLinePos43) { Attribute = new Variation("Bogus LineNumber value when reading attribute over XmlTextReader") }); } // for function TestLinePos44 { this.AddChild(new CVariation(TestLinePos44) { Attribute = new Variation("LineNumber and LinePosition on attribute with columns") }); } // for function TestLinePos45 { this.AddChild(new CVariation(TestLinePos45) { Attribute = new Variation("HasLineInfo") }); } // for function TestLinePos99 { this.AddChild(new CVariation(TestLinePos99) { Attribute = new Variation("XmlException LineNumber and LinePosition") }); } // for function ReadingNonWellFormedXmlThrows { this.AddChild(new CVariation(ReadingNonWellFormedXmlThrows) { Attribute = new Variation("Check error message on a non-wellformed XML") }); } // for function XmlExceptionAndXmlTextReaderLineNumberShouldBeSameAfterExceptionIsThrown { this.AddChild(new CVariation(XmlExceptionAndXmlTextReaderLineNumberShouldBeSameAfterExceptionIsThrown) { Attribute = new Variation("When an XmlException is thrown both XmlException.LineNumber and XmlTextReader.LineNumber should be same") }); } // for function XmlReaderShouldIncreaseLineNumberAfterNewLineInElementTag { this.AddChild(new CVariation(XmlReaderShouldIncreaseLineNumberAfterNewLineInElementTag) { Attribute = new Variation("Xml(Text)Reader does not increase line number for a new line in element end tag") }); } // for function LineNumberAndLinePositionAreCorrect { this.AddChild(new CVariation(LineNumberAndLinePositionAreCorrect) { Attribute = new Variation("LineNumber and LinePosition are not correct") }); } } } }
#define SQLITE_ASCII #define SQLITE_DISABLE_LFS #define SQLITE_ENABLE_OVERSIZE_CELL_CHECK #define SQLITE_MUTEX_OMIT #define SQLITE_OMIT_AUTHORIZATION #define SQLITE_OMIT_DEPRECATED #define SQLITE_OMIT_GET_TABLE #define SQLITE_OMIT_INCRBLOB #define SQLITE_OMIT_LOOKASIDE #define SQLITE_OMIT_SHARED_CACHE #define SQLITE_OMIT_UTF16 #define SQLITE_OMIT_WAL #define SQLITE_OS_WIN #define SQLITE_SYSTEM_MALLOC #define VDBE_PROFILE_OFF #define WINDOWS_MOBILE #define NDEBUG #define _MSC_VER #define YYFALLBACK #define SQLITE_HAS_CODEC namespace Community.CsharpSqlite { using sqlite3_value = Sqlite3.Mem; using System; public partial class Sqlite3 { /* ** 2010 February 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements routines used to report what compile-time options ** SQLite was built with. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-01-28 17:03:50 ed759d5a9edb3bba5f48f243df47be29e3fe8cd7 ** ************************************************************************* */ #if !SQLITE_OMIT_COMPILEOPTION_DIAGS //#include "sqliteInt.h" /* ** An array of names of all compile-time options. This array should ** be sorted A-Z. ** ** This array looks large, but in a typical installation actually uses ** only a handful of compile-time options, so most times this array is usually ** rather short and uses little memory space. */ static string[] azCompileOpt = { /* These macros are provided to "stringify" the value of the define ** for those options in which the value is meaningful. */ //#define CTIMEOPT_VAL_(opt) #opt //#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) #if SQLITE_32BIT_ROWID "32BIT_ROWID", #endif #if SQLITE_4_BYTE_ALIGNED_MALLOC "4_BYTE_ALIGNED_MALLOC", #endif #if SQLITE_CASE_SENSITIVE_LIKE "CASE_SENSITIVE_LIKE", #endif #if SQLITE_CHECK_PAGES "CHECK_PAGES", #endif #if SQLITE_COVERAGE_TEST "COVERAGE_TEST", #endif #if SQLITE_DEBUG "DEBUG", #endif #if SQLITE_DEFAULT_LOCKING_MODE "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), #endif #if SQLITE_DISABLE_DIRSYNC "DISABLE_DIRSYNC", #endif #if SQLITE_DISABLE_LFS "DISABLE_LFS", #endif #if SQLITE_ENABLE_ATOMIC_WRITE "ENABLE_ATOMIC_WRITE", #endif #if SQLITE_ENABLE_CEROD "ENABLE_CEROD", #endif #if SQLITE_ENABLE_COLUMN_METADATA "ENABLE_COLUMN_METADATA", #endif #if SQLITE_ENABLE_EXPENSIVE_ASSERT "ENABLE_EXPENSIVE_ASSERT", #endif #if SQLITE_ENABLE_FTS1 "ENABLE_FTS1", #endif #if SQLITE_ENABLE_FTS2 "ENABLE_FTS2", #endif #if SQLITE_ENABLE_FTS3 "ENABLE_FTS3", #endif #if SQLITE_ENABLE_FTS3_PARENTHESIS "ENABLE_FTS3_PARENTHESIS", #endif #if SQLITE_ENABLE_FTS4 "ENABLE_FTS4", #endif #if SQLITE_ENABLE_ICU "ENABLE_ICU", #endif #if SQLITE_ENABLE_IOTRACE "ENABLE_IOTRACE", #endif #if SQLITE_ENABLE_LOAD_EXTENSION "ENABLE_LOAD_EXTENSION", #endif #if SQLITE_ENABLE_LOCKING_STYLE "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), #endif #if SQLITE_ENABLE_MEMORY_MANAGEMENT "ENABLE_MEMORY_MANAGEMENT", #endif #if SQLITE_ENABLE_MEMSYS3 "ENABLE_MEMSYS3", #endif #if SQLITE_ENABLE_MEMSYS5 "ENABLE_MEMSYS5", #endif #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK "ENABLE_OVERSIZE_CELL_CHECK", #endif #if SQLITE_ENABLE_RTREE "ENABLE_RTREE", #endif #if SQLITE_ENABLE_STAT2 "ENABLE_STAT2", #endif #if SQLITE_ENABLE_UNLOCK_NOTIFY "ENABLE_UNLOCK_NOTIFY", #endif #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT "ENABLE_UPDATE_DELETE_LIMIT", #endif #if SQLITE_HAS_CODEC "HAS_CODEC", #endif #if SQLITE_HAVE_ISNAN "HAVE_ISNAN", #endif #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX "HOMEGROWN_RECURSIVE_MUTEX", #endif #if SQLITE_IGNORE_AFP_LOCK_ERRORS "IGNORE_AFP_LOCK_ERRORS", #endif #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS "IGNORE_FLOCK_LOCK_ERRORS", #endif #if SQLITE_INT64_TYPE "INT64_TYPE", #endif #if SQLITE_LOCK_TRACE "LOCK_TRACE", #endif #if SQLITE_MEMDEBUG "MEMDEBUG", #endif #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT "MIXED_ENDIAN_64BIT_FLOAT", #endif #if SQLITE_NO_SYNC "NO_SYNC", #endif #if SQLITE_OMIT_ALTERTABLE "OMIT_ALTERTABLE", #endif #if SQLITE_OMIT_ANALYZE "OMIT_ANALYZE", #endif #if SQLITE_OMIT_ATTACH "OMIT_ATTACH", #endif #if SQLITE_OMIT_AUTHORIZATION "OMIT_AUTHORIZATION", #endif #if SQLITE_OMIT_AUTOINCREMENT "OMIT_AUTOINCREMENT", #endif #if SQLITE_OMIT_AUTOINIT "OMIT_AUTOINIT", #endif #if SQLITE_OMIT_AUTOMATIC_INDEX "OMIT_AUTOMATIC_INDEX", #endif #if SQLITE_OMIT_AUTORESET "OMIT_AUTORESET", #endif #if SQLITE_OMIT_AUTOVACUUM "OMIT_AUTOVACUUM", #endif #if SQLITE_OMIT_BETWEEN_OPTIMIZATION "OMIT_BETWEEN_OPTIMIZATION", #endif #if SQLITE_OMIT_BLOB_LITERAL "OMIT_BLOB_LITERAL", #endif #if SQLITE_OMIT_BTREECOUNT "OMIT_BTREECOUNT", #endif #if SQLITE_OMIT_BUILTIN_TEST "OMIT_BUILTIN_TEST", #endif #if SQLITE_OMIT_CAST "OMIT_CAST", #endif #if SQLITE_OMIT_CHECK "OMIT_CHECK", #endif /* // redundant ** #if SQLITE_OMIT_COMPILEOPTION_DIAGS ** "OMIT_COMPILEOPTION_DIAGS", ** #endif */ #if SQLITE_OMIT_COMPLETE "OMIT_COMPLETE", #endif #if SQLITE_OMIT_COMPOUND_SELECT "OMIT_COMPOUND_SELECT", #endif #if SQLITE_OMIT_DATETIME_FUNCS "OMIT_DATETIME_FUNCS", #endif #if SQLITE_OMIT_DECLTYPE "OMIT_DECLTYPE", #endif #if SQLITE_OMIT_DEPRECATED "OMIT_DEPRECATED", #endif #if SQLITE_OMIT_DISKIO "OMIT_DISKIO", #endif #if SQLITE_OMIT_EXPLAIN "OMIT_EXPLAIN", #endif #if SQLITE_OMIT_FLAG_PRAGMAS "OMIT_FLAG_PRAGMAS", #endif #if SQLITE_OMIT_FLOATING_POINT "OMIT_FLOATING_POINT", #endif #if SQLITE_OMIT_FOREIGN_KEY "OMIT_FOREIGN_KEY", #endif #if SQLITE_OMIT_GET_TABLE "OMIT_GET_TABLE", #endif #if SQLITE_OMIT_INCRBLOB "OMIT_INCRBLOB", #endif #if SQLITE_OMIT_INTEGRITY_CHECK "OMIT_INTEGRITY_CHECK", #endif #if SQLITE_OMIT_LIKE_OPTIMIZATION "OMIT_LIKE_OPTIMIZATION", #endif #if SQLITE_OMIT_LOAD_EXTENSION "OMIT_LOAD_EXTENSION", #endif #if SQLITE_OMIT_LOCALTIME "OMIT_LOCALTIME", #endif #if SQLITE_OMIT_LOOKASIDE "OMIT_LOOKASIDE", #endif #if SQLITE_OMIT_MEMORYDB "OMIT_MEMORYDB", #endif #if SQLITE_OMIT_OR_OPTIMIZATION "OMIT_OR_OPTIMIZATION", #endif #if SQLITE_OMIT_PAGER_PRAGMAS "OMIT_PAGER_PRAGMAS", #endif #if SQLITE_OMIT_PRAGMA "OMIT_PRAGMA", #endif #if SQLITE_OMIT_PROGRESS_CALLBACK "OMIT_PROGRESS_CALLBACK", #endif #if SQLITE_OMIT_QUICKBALANCE "OMIT_QUICKBALANCE", #endif #if SQLITE_OMIT_REINDEX "OMIT_REINDEX", #endif #if SQLITE_OMIT_SCHEMA_PRAGMAS "OMIT_SCHEMA_PRAGMAS", #endif #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS "OMIT_SCHEMA_VERSION_PRAGMAS", #endif #if SQLITE_OMIT_SHARED_CACHE "OMIT_SHARED_CACHE", #endif #if SQLITE_OMIT_SUBQUERY "OMIT_SUBQUERY", #endif #if SQLITE_OMIT_TCL_VARIABLE "OMIT_TCL_VARIABLE", #endif #if SQLITE_OMIT_TEMPDB "OMIT_TEMPDB", #endif #if SQLITE_OMIT_TRACE "OMIT_TRACE", #endif #if SQLITE_OMIT_TRIGGER "OMIT_TRIGGER", #endif #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION "OMIT_TRUNCATE_OPTIMIZATION", #endif #if SQLITE_OMIT_UTF16 "OMIT_UTF16", #endif #if SQLITE_OMIT_VACUUM "OMIT_VACUUM", #endif #if SQLITE_OMIT_VIEW "OMIT_VIEW", #endif #if SQLITE_OMIT_VIRTUALTABLE "OMIT_VIRTUALTABLE", #endif #if SQLITE_OMIT_WAL "OMIT_WAL", #endif #if SQLITE_OMIT_WSD "OMIT_WSD", #endif #if SQLITE_OMIT_XFER_OPT "OMIT_XFER_OPT", #endif #if SQLITE_PERFORMANCE_TRACE "PERFORMANCE_TRACE", #endif #if SQLITE_PROXY_DEBUG "PROXY_DEBUG", #endif #if SQLITE_SECURE_DELETE "SECURE_DELETE", #endif #if SQLITE_SMALL_STACK "SMALL_STACK", #endif #if SQLITE_SOUNDEX "SOUNDEX", #endif #if SQLITE_TCL "TCL", #endif //#if SQLITE_TEMP_STORE "TEMP_STORE=1",//CTIMEOPT_VAL(SQLITE_TEMP_STORE), //#endif #if SQLITE_TEST "TEST", #endif #if SQLITE_THREADSAFE "THREADSAFE=2", // For C#, hardcode to = 2 CTIMEOPT_VAL(SQLITE_THREADSAFE), #else "THREADSAFE=0", // For C#, hardcode to = 0 #endif #if SQLITE_USE_ALLOCA "USE_ALLOCA", #endif #if SQLITE_ZERO_MALLOC "ZERO_MALLOC" #endif }; /* ** Given the name of a compile-time option, return true if that option ** was used and false if not. ** ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix ** is not required for a match. */ static int sqlite3_compileoption_used( string zOptName ) { if ( zOptName.EndsWith( "=" ) ) return 0; int i, n = 0; if ( zOptName.StartsWith( "SQLITE_", System.StringComparison.InvariantCultureIgnoreCase ) ) n = 7; //n = sqlite3Strlen30(zOptName); /* Since ArraySize(azCompileOpt) is normally in single digits, a ** linear search is adequate. No need for a binary search. */ if ( !String.IsNullOrEmpty( zOptName ) ) for ( i = 0; i < ArraySize( azCompileOpt ); i++ ) { int n1 = ( zOptName.Length-n < azCompileOpt[i].Length ) ? zOptName.Length-n : azCompileOpt[i].Length; if ( String.Compare( zOptName, n, azCompileOpt[i], 0, n1, StringComparison.InvariantCultureIgnoreCase ) == 0 ) return 1; } return 0; } /* ** Return the N-th compile-time option string. If N is out of range, ** return a NULL pointer. */ static string sqlite3_compileoption_get( int N ) { if ( N >= 0 && N < ArraySize( azCompileOpt ) ) { return azCompileOpt[N]; } return null; } #endif //* SQLITE_OMIT_COMPILEOPTION_DIAGS */ } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Diagnostics; using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.FlowControl; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.PipeWriterHelpers; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2 { internal class Http2OutputProducer : IHttpOutputProducer, IHttpOutputAborter, IValueTaskSource<FlushResult>, IDisposable { private int StreamId => _stream.StreamId; private readonly Http2FrameWriter _frameWriter; private readonly TimingPipeFlusher _flusher; private readonly KestrelTrace _log; // This should only be accessed via the FrameWriter. The connection-level output flow control is protected by the // FrameWriter's connection-level write lock. private readonly StreamOutputFlowControl _flowControl; private readonly MemoryPool<byte> _memoryPool; private readonly Http2Stream _stream; private readonly object _dataWriterLock = new object(); private readonly Pipe _pipe; private readonly ConcurrentPipeWriter _pipeWriter; private readonly PipeReader _pipeReader; private readonly ManualResetValueTaskSource<object?> _resetAwaitable = new ManualResetValueTaskSource<object?>(); private IMemoryOwner<byte>? _fakeMemoryOwner; private byte[]? _fakeMemory; private bool _startedWritingDataFrames; private bool _streamCompleted; private bool _suffixSent; private bool _streamEnded; private bool _writerComplete; // Internal for testing internal Task _dataWriteProcessingTask; internal bool _disposed; /// <summary>The core logic for the IValueTaskSource implementation.</summary> private ManualResetValueTaskSourceCore<FlushResult> _responseCompleteTaskSource = new ManualResetValueTaskSourceCore<FlushResult> { RunContinuationsAsynchronously = true }; // mutable struct, do not make this readonly // This object is itself usable as a backing source for ValueTask. Since there's only ever one awaiter // for this object's state transitions at a time, we allow the object to be awaited directly. All functionality // associated with the implementation is just delegated to the ManualResetValueTaskSourceCore. private ValueTask<FlushResult> GetWaiterTask() => new ValueTask<FlushResult>(this, _responseCompleteTaskSource.Version); ValueTaskSourceStatus IValueTaskSource<FlushResult>.GetStatus(short token) => _responseCompleteTaskSource.GetStatus(token); void IValueTaskSource<FlushResult>.OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _responseCompleteTaskSource.OnCompleted(continuation, state, token, flags); FlushResult IValueTaskSource<FlushResult>.GetResult(short token) => _responseCompleteTaskSource.GetResult(token); public Http2OutputProducer(Http2Stream stream, Http2StreamContext context, StreamOutputFlowControl flowControl) { _stream = stream; _frameWriter = context.FrameWriter; _flowControl = flowControl; _memoryPool = context.MemoryPool; _log = context.ServiceContext.Log; _pipe = CreateDataPipe(_memoryPool); _pipeWriter = new ConcurrentPipeWriter(_pipe.Writer, _memoryPool, _dataWriterLock); _pipeReader = _pipe.Reader; // No need to pass in timeoutControl here, since no minDataRates are passed to the TimingPipeFlusher. // The minimum output data rate is enforced at the connection level by Http2FrameWriter. _flusher = new TimingPipeFlusher(timeoutControl: null, _log); _flusher.Initialize(_pipeWriter); _dataWriteProcessingTask = ProcessDataWrites(); } public void StreamReset() { // Data background task must still be running. Debug.Assert(!_dataWriteProcessingTask.IsCompleted); // Response should have been completed. Debug.Assert(_responseCompleteTaskSource.GetStatus(_responseCompleteTaskSource.Version) == ValueTaskSourceStatus.Succeeded); _streamEnded = false; _suffixSent = false; _startedWritingDataFrames = false; _streamCompleted = false; _writerComplete = false; _pipe.Reset(); _pipeWriter.Reset(); _responseCompleteTaskSource.Reset(); // Trigger the data process task to resume _resetAwaitable.SetResult(null); } public void Complete() { lock (_dataWriterLock) { if (_writerComplete) { return; } _writerComplete = true; Stop(); // Make sure the writing side is completed. _pipeWriter.Complete(); if (_fakeMemoryOwner != null) { _fakeMemoryOwner.Dispose(); _fakeMemoryOwner = null; } if (_fakeMemory != null) { ArrayPool<byte>.Shared.Return(_fakeMemory); _fakeMemory = null; } } } // This is called when a CancellationToken fires mid-write. In HTTP/1.x, this aborts the entire connection. // For HTTP/2 we abort the stream. void IHttpOutputAborter.Abort(ConnectionAbortedException abortReason) { _stream.ResetAndAbort(abortReason, Http2ErrorCode.INTERNAL_ERROR); } void IHttpOutputAborter.OnInputOrOutputCompleted() { _stream.ResetAndAbort(new ConnectionAbortedException($"{nameof(Http2OutputProducer)}.{nameof(ProcessDataWrites)} has completed."), Http2ErrorCode.INTERNAL_ERROR); } public ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken)); } lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return default; } if (_startedWritingDataFrames) { // If there's already been response data written to the stream, just wait for that. Any header // should be in front of the data frames in the connection pipe. Trailers could change things. return _flusher.FlushAsync(this, cancellationToken); } else { // Flushing the connection pipe ensures headers already in the pipe are flushed even if no data // frames have been written. return _frameWriter.FlushAsync(this, cancellationToken); } } } public ValueTask<FlushResult> Write100ContinueAsync() { lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return default; } return _frameWriter.Write100ContinueAsync(StreamId); } } public void WriteResponseHeaders(int statusCode, string? reasonPhrase, HttpResponseHeaders responseHeaders, bool autoChunk, bool appCompleted) { lock (_dataWriterLock) { // The HPACK header compressor is stateful, if we compress headers for an aborted stream we must send them. // Optimize for not compressing or sending them. if (_streamCompleted) { return; } // If the responseHeaders will be written as the final HEADERS frame then // set END_STREAM on the HEADERS frame. This avoids the need to write an // empty DATA frame with END_STREAM. // // The headers will be the final frame if: // 1. There is no content // 2. There is no trailing HEADERS frame. Http2HeadersFrameFlags http2HeadersFrame; if (appCompleted && !_startedWritingDataFrames && (_stream.ResponseTrailers == null || _stream.ResponseTrailers.Count == 0)) { _streamEnded = true; _stream.DecrementActiveClientStreamCount(); http2HeadersFrame = Http2HeadersFrameFlags.END_STREAM; } else { http2HeadersFrame = Http2HeadersFrameFlags.NONE; } _frameWriter.WriteResponseHeaders(StreamId, statusCode, http2HeadersFrame, responseHeaders); } } public Task WriteDataAsync(ReadOnlySpan<byte> data, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); // This length check is important because we don't want to set _startedWritingDataFrames unless a data // frame will actually be written causing the headers to be flushed. if (_streamCompleted || data.Length == 0) { return Task.CompletedTask; } _startedWritingDataFrames = true; _pipeWriter.Write(data); return _flusher.FlushAsync(this, cancellationToken).GetAsTask(); } } public ValueTask<FlushResult> WriteStreamSuffixAsync() { lock (_dataWriterLock) { if (_streamCompleted) { return GetWaiterTask(); } _streamCompleted = true; _suffixSent = true; _pipeWriter.Complete(); return GetWaiterTask(); } } public ValueTask<FlushResult> WriteRstStreamAsync(Http2ErrorCode error) { lock (_dataWriterLock) { // Always send the reset even if the response body is _completed. The request body may not have completed yet. Stop(); return _frameWriter.WriteRstStreamAsync(StreamId, error); } } public void Advance(int bytes) { lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return; } _startedWritingDataFrames = true; _pipeWriter.Advance(bytes); } } public Span<byte> GetSpan(int sizeHint = 0) { lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return GetFakeMemory(sizeHint).Span; } return _pipeWriter.GetSpan(sizeHint); } } public Memory<byte> GetMemory(int sizeHint = 0) { lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return GetFakeMemory(sizeHint); } return _pipeWriter.GetMemory(sizeHint); } } public void CancelPendingFlush() { lock (_dataWriterLock) { if (_streamCompleted) { return; } _pipeWriter.CancelPendingFlush(); } } public ValueTask<FlushResult> WriteDataToPipeAsync(ReadOnlySpan<byte> data, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken)); } lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); // This length check is important because we don't want to set _startedWritingDataFrames unless a data // frame will actually be written causing the headers to be flushed. if (_streamCompleted || data.Length == 0) { return default; } _startedWritingDataFrames = true; _pipeWriter.Write(data); return _flusher.FlushAsync(this, cancellationToken); } } public ValueTask<FlushResult> FirstWriteAsync(int statusCode, string? reasonPhrase, HttpResponseHeaders responseHeaders, bool autoChunk, ReadOnlySpan<byte> data, CancellationToken cancellationToken) { lock (_dataWriterLock) { WriteResponseHeaders(statusCode, reasonPhrase, responseHeaders, autoChunk, appCompleted: false); return WriteDataToPipeAsync(data, cancellationToken); } } ValueTask<FlushResult> IHttpOutputProducer.WriteChunkAsync(ReadOnlySpan<byte> data, CancellationToken cancellationToken) { throw new NotImplementedException(); } public ValueTask<FlushResult> FirstWriteChunkedAsync(int statusCode, string? reasonPhrase, HttpResponseHeaders responseHeaders, bool autoChunk, ReadOnlySpan<byte> data, CancellationToken cancellationToken) { throw new NotImplementedException(); } public void Stop() { lock (_dataWriterLock) { if (_streamCompleted) { return; } _streamCompleted = true; _pipeReader.CancelPendingRead(); _frameWriter.AbortPendingStreamDataWrites(_flowControl); } } public void Reset() { } private async Task ProcessDataWrites() { // ProcessDataWrites runs for the lifetime of the Http2OutputProducer, and is designed to be reused by multiple streams. // When Http2OutputProducer is no longer used (e.g. a stream is aborted and will no longer be used, or the connection is closed) // it should be disposed so ProcessDataWrites exits. Not disposing won't cause a memory leak in release builds, but in debug // builds active tasks are rooted on Task.s_currentActiveTasks. Dispose could be removed in the future when active tasks are // tracked by a weak reference. See https://github.com/dotnet/runtime/issues/26565 do { FlushResult flushResult = default; ReadResult readResult = default; try { do { var firstWrite = true; readResult = await _pipeReader.ReadAsync(); if (readResult.IsCanceled) { // Response body is aborted, break and complete reader. break; } else if (readResult.IsCompleted && _stream.ResponseTrailers?.Count > 0) { // Output is ending and there are trailers to write // Write any remaining content then write trailers _stream.ResponseTrailers.SetReadOnly(); _stream.DecrementActiveClientStreamCount(); if (readResult.Buffer.Length > 0) { // It is faster to write data and trailers together. Locking once reduces lock contention. flushResult = await _frameWriter.WriteDataAndTrailersAsync(StreamId, _flowControl, readResult.Buffer, firstWrite, _stream.ResponseTrailers); } else { flushResult = await _frameWriter.WriteResponseTrailersAsync(StreamId, _stream.ResponseTrailers); } } else if (readResult.IsCompleted && _streamEnded) { if (readResult.Buffer.Length != 0) { ThrowUnexpectedState(); } // Headers have already been written and there is no other content to write flushResult = await _frameWriter.FlushAsync(outputAborter: null, cancellationToken: default); } else { var endStream = readResult.IsCompleted; if (endStream) { _stream.DecrementActiveClientStreamCount(); } flushResult = await _frameWriter.WriteDataAsync(StreamId, _flowControl, readResult.Buffer, endStream, firstWrite, forceFlush: true); } firstWrite = false; _pipeReader.AdvanceTo(readResult.Buffer.End); } while (!readResult.IsCompleted); } catch (Exception ex) { _log.LogCritical(ex, nameof(Http2OutputProducer) + "." + nameof(ProcessDataWrites) + " observed an unexpected exception."); } await _pipeReader.CompleteAsync(); // Signal via WriteStreamSuffixAsync to the stream that output has finished. // Stream state will move to RequestProcessingStatus.ResponseCompleted _responseCompleteTaskSource.SetResult(flushResult); // Wait here for the stream to be reset or disposed. await new ValueTask(_resetAwaitable, _resetAwaitable.Version); _resetAwaitable.Reset(); } while (!_disposed); static void ThrowUnexpectedState() { throw new InvalidOperationException(nameof(Http2OutputProducer) + "." + nameof(ProcessDataWrites) + " observed an unexpected state where the streams output ended with data still remaining in the pipe."); } } internal Memory<byte> GetFakeMemory(int minSize) { // Try to reuse _fakeMemoryOwner if (_fakeMemoryOwner != null) { if (_fakeMemoryOwner.Memory.Length < minSize) { _fakeMemoryOwner.Dispose(); _fakeMemoryOwner = null; } else { return _fakeMemoryOwner.Memory; } } // Try to reuse _fakeMemory if (_fakeMemory != null) { if (_fakeMemory.Length < minSize) { ArrayPool<byte>.Shared.Return(_fakeMemory); _fakeMemory = null; } else { return _fakeMemory; } } // Requesting a bigger buffer could throw. if (minSize <= _memoryPool.MaxBufferSize) { // Use the specified pool as it fits. _fakeMemoryOwner = _memoryPool.Rent(minSize); return _fakeMemoryOwner.Memory; } else { // Use the array pool. Its MaxBufferSize is int.MaxValue. return _fakeMemory = ArrayPool<byte>.Shared.Rent(minSize); } } [StackTraceHidden] private void ThrowIfSuffixSentOrCompleted() { if (_suffixSent) { ThrowSuffixSent(); } if (_writerComplete) { ThrowWriterComplete(); } } [StackTraceHidden] private static void ThrowSuffixSent() { throw new InvalidOperationException("Writing is not allowed after writer was completed."); } [StackTraceHidden] private static void ThrowWriterComplete() { throw new InvalidOperationException("Cannot write to response after the request has completed."); } private static Pipe CreateDataPipe(MemoryPool<byte> pool) => new Pipe(new PipeOptions ( pool: pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.ThreadPool, pauseWriterThreshold: 1, resumeWriterThreshold: 1, useSynchronizationContext: false, minimumSegmentSize: pool.GetMinimumSegmentSize() )); public void Dispose() { if (_disposed) { return; } _disposed = true; // Set awaitable after disposed is true to ensure ProcessDataWrites exits successfully. _resetAwaitable.SetResult(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 System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using Mono.Data.SqliteClient; using OpenMetaverse; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Statistics; namespace OpenSim.Region.UserStatistics { public class Default_Report : IStatsController { public string ReportName { get { return "Home"; } } #region IStatsController Members public Hashtable ProcessModel(Hashtable pParams) { SqliteConnection conn = (SqliteConnection)pParams["DatabaseConnection"]; List<Scene> m_scene = (List<Scene>)pParams["Scenes"]; stats_default_page_values mData = rep_DefaultReport_data(conn, m_scene); mData.sim_stat_data = (Dictionary<UUID,USimStatsData>)pParams["SimStats"]; mData.stats_reports = (Dictionary<string, IStatsController>) pParams["Reports"]; Hashtable nh = new Hashtable(); nh.Add("hdata", mData); nh.Add("Reports", pParams["Reports"]); return nh; } public string RenderView(Hashtable pModelResult) { stats_default_page_values mData = (stats_default_page_values) pModelResult["hdata"]; return rep_Default_report_view(mData); } #endregion public string rep_Default_report_view(stats_default_page_values values) { StringBuilder output = new StringBuilder(); const string TableClass = "defaultr"; const string TRClass = "defaultr"; const string TDHeaderClass = "header"; const string TDDataClass = "content"; //const string TDDataClassRight = "contentright"; const string TDDataClassCenter = "contentcenter"; const string STYLESHEET = @" <STYLE> body { font-size:15px; font-family:Helvetica, Verdana; color:Black; } TABLE.defaultr { } TR.defaultr { padding: 5px; } TD.header { font-weight:bold; padding:5px; } TD.content {} TD.contentright { text-align: right; } TD.contentcenter { text-align: center; } TD.align_top { vertical-align: top; } </STYLE> "; HTMLUtil.HtmlHeaders_O(ref output); HTMLUtil.InsertProtoTypeAJAX(ref output); string[] ajaxUpdaterDivs = new string[3]; int[] ajaxUpdaterSeconds = new int[3]; string[] ajaxUpdaterReportFragments = new string[3]; ajaxUpdaterDivs[0] = "activeconnections"; ajaxUpdaterSeconds[0] = 10; ajaxUpdaterReportFragments[0] = "activeconnectionsajax.html"; ajaxUpdaterDivs[1] = "activesimstats"; ajaxUpdaterSeconds[1] = 20; ajaxUpdaterReportFragments[1] = "simstatsajax.html"; ajaxUpdaterDivs[2] = "activelog"; ajaxUpdaterSeconds[2] = 5; ajaxUpdaterReportFragments[2] = "activelogajax.html"; HTMLUtil.InsertPeriodicUpdaters(ref output, ajaxUpdaterDivs, ajaxUpdaterSeconds, ajaxUpdaterReportFragments); output.Append(STYLESHEET); HTMLUtil.HtmlHeaders_C(ref output); HTMLUtil.AddReportLinks(ref output, values.stats_reports, ""); HTMLUtil.TABLE_O(ref output, TableClass); HTMLUtil.TR_O(ref output, TRClass); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("# Users Total"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("# Sessions Total"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Avg Client FPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Avg Client Mem Use"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Avg Sim FPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Avg Ping"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("KB Out Total"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("KB In Total"); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TR_O(ref output, TRClass); HTMLUtil.TD_O(ref output, TDDataClass); output.Append(values.total_num_users); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClass); output.Append(values.total_num_sessions); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.avg_client_fps); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.avg_client_mem_use); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.avg_sim_fps); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.avg_ping); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.total_kb_out); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.total_kb_in); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TABLE_C(ref output); HTMLUtil.HR(ref output, ""); HTMLUtil.TABLE_O(ref output, ""); HTMLUtil.TR_O(ref output, ""); HTMLUtil.TD_O(ref output, "align_top"); output.Append("<DIV id=\"activeconnections\">Active Connections loading...</DIV>"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, "align_top"); output.Append("<DIV id=\"activesimstats\">SimStats loading...</DIV>"); output.Append("<DIV id=\"activelog\">ActiveLog loading...</DIV>"); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TABLE_C(ref output); output.Append("</BODY></HTML>"); // TODO: FIXME: template return output.ToString(); } public stats_default_page_values rep_DefaultReport_data(SqliteConnection db, List<Scene> m_scene) { stats_default_page_values returnstruct = new stats_default_page_values(); returnstruct.all_scenes = m_scene.ToArray(); lock (db) { string SQL = @"SELECT COUNT(DISTINCT agent_id) as agents, COUNT(*) as sessions, AVG(avg_fps) as client_fps, AVG(avg_sim_fps) as savg_sim_fps, AVG(avg_ping) as sav_ping, SUM(n_out_kb) as num_in_kb, SUM(n_out_pk) as num_in_packets, SUM(n_in_kb) as num_out_kb, SUM(n_in_pk) as num_out_packets, AVG(mem_use) as sav_mem_use FROM stats_session_data;"; SqliteCommand cmd = new SqliteCommand(SQL, db); SqliteDataReader sdr = cmd.ExecuteReader(); if (sdr.HasRows) { sdr.Read(); returnstruct.total_num_users = Convert.ToInt32(sdr["agents"]); returnstruct.total_num_sessions = Convert.ToInt32(sdr["sessions"]); returnstruct.avg_client_fps = Convert.ToSingle(sdr["client_fps"]); returnstruct.avg_sim_fps = Convert.ToSingle(sdr["savg_sim_fps"]); returnstruct.avg_ping = Convert.ToSingle(sdr["sav_ping"]); returnstruct.total_kb_out = Convert.ToSingle(sdr["num_out_kb"]); returnstruct.total_kb_in = Convert.ToSingle(sdr["num_in_kb"]); returnstruct.avg_client_mem_use = Convert.ToSingle(sdr["sav_mem_use"]); } } return returnstruct; } } public struct stats_default_page_values { public int total_num_users; public int total_num_sessions; public float avg_client_fps; public float avg_client_mem_use; public float avg_sim_fps; public float avg_ping; public float total_kb_out; public float total_kb_in; public float avg_client_resends; public Scene[] all_scenes; public Dictionary<UUID, USimStatsData> sim_stat_data; public Dictionary<string, IStatsController> stats_reports; } }
// 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 GCPerfTestFramework.Metrics; using Microsoft.Xunit.Performance; using System.Collections.Generic; [assembly: CollectGCMetrics] namespace GCPerfTestFramework { public class PerfTests { const string ConcurrentGC = "COMPLUS_gcConcurrent"; const string ServerGC = "COMPLUS_gcServer"; [Benchmark] public void ClientSimulator_Concurrent() { var exe = ProcessFactory.ProbeForFile("GCSimulator.exe"); var env = new Dictionary<string, string>() { [ConcurrentGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, "-i 100", env); } } } [Benchmark] public void ClientSimulator_Server() { var exe = ProcessFactory.ProbeForFile("GCSimulator.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, "-i 100", env); } } } [Benchmark] public void ClientSimulator_Server_One_Thread() { var exe = ProcessFactory.ProbeForFile("GCSimulator.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, "-i 10 -notimer -dp 0.0", env); } } } [Benchmark] public void ClientSimulator_Server_Two_Threads() { var exe = ProcessFactory.ProbeForFile("GCSimulator.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, "-i 10 -notimer -dp 0.0 -t 2", env); } } } [Benchmark] public void ClientSimulator_Server_Four_Threads() { var exe = ProcessFactory.ProbeForFile("GCSimulator.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, "-i 10 -notimer -dp 0.0 -t 4", env); } } } [Benchmark] public void LargeStringConcat() { var exe = ProcessFactory.ProbeForFile("LargeStrings.exe"); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe); } } } [Benchmark] public void LargeStringConcat_Server() { var exe = ProcessFactory.ProbeForFile("LargeStrings.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, environmentVariables: env); } } } [Benchmark] public void LargeStringConcat_Workstation() { var exe = ProcessFactory.ProbeForFile("LargeStrings.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "0" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, environmentVariables: env); } } } [Benchmark] public void MidLife_Concurrent() { var exe = ProcessFactory.ProbeForFile("MidLife.exe"); var env = new Dictionary<string, string>() { [ConcurrentGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, environmentVariables: env); } } } [Benchmark] public void MidLife_Server() { var exe = ProcessFactory.ProbeForFile("MidLife.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, environmentVariables: env); } } } [Benchmark] public void MidLife_Workstation() { var exe = ProcessFactory.ProbeForFile("MidLife.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "0" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, environmentVariables: env); } } } [Benchmark] public void ConcurrentSpin() { var exe = ProcessFactory.ProbeForFile("ConcurrentSpin.exe"); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe); } } } [Benchmark] public void ConcurrentSpin_Server() { var exe = ProcessFactory.ProbeForFile("ConcurrentSpin.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "1" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, environmentVariables: env); } } } [Benchmark] public void ConcurrentSpin_Server_NonConcurrent() { var exe = ProcessFactory.ProbeForFile("ConcurrentSpin.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "1", [ConcurrentGC] = "0" }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, environmentVariables: env); } } } [Benchmark] public void ConcurrentSpin_Workstation() { var exe = ProcessFactory.ProbeForFile("ConcurrentSpin.exe"); var env = new Dictionary<string, string>() { [ServerGC] = "0", }; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { ProcessFactory.LaunchProcess(exe, environmentVariables: env); } } } } }
#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 using System; using System.IO; using System.Collections; using log4net.Filter; using log4net.Util; using log4net.Layout; using log4net.Core; namespace log4net.Appender { /// <summary> /// Abstract base class implementation of <see cref="IAppender"/>. /// </summary> /// <remarks> /// <para> /// This class provides the code for common functionality, such /// as support for threshold filtering and support for general filters. /// </para> /// <para> /// Appenders can also implement the <see cref="IOptionHandler"/> interface. Therefore /// they would require that the <see cref="M:IOptionHandler.ActivateOptions()"/> method /// be called after the appenders properties have been configured. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public abstract class AppenderSkeleton : IAppender, IBulkAppender, IOptionHandler, IFlushable { #region Protected Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para>Empty default constructor</para> /// </remarks> protected AppenderSkeleton() { m_errorHandler = new OnlyOnceErrorHandler(this.GetType().Name); } #endregion Protected Instance Constructors #region Finalizer /// <summary> /// Finalizes this appender by calling the implementation's /// <see cref="Close"/> method. /// </summary> /// <remarks> /// <para> /// If this appender has not been closed then the <c>Finalize</c> method /// will call <see cref="Close"/>. /// </para> /// </remarks> ~AppenderSkeleton() { // An appender might be closed then garbage collected. // There is no point in closing twice. if (!m_closed) { LogLog.Debug(declaringType, "Finalizing appender named ["+m_name+"]."); Close(); } } #endregion Finalizer #region Public Instance Properties /// <summary> /// Gets or sets the threshold <see cref="Level"/> of this appender. /// </summary> /// <value> /// The threshold <see cref="Level"/> of the appender. /// </value> /// <remarks> /// <para> /// All log events with lower level than the threshold level are ignored /// by the appender. /// </para> /// <para> /// In configuration files this option is specified by setting the /// value of the <see cref="Threshold"/> option to a level /// string, such as "DEBUG", "INFO" and so on. /// </para> /// </remarks> public Level Threshold { get { return m_threshold; } set { m_threshold = value; } } /// <summary> /// Gets or sets the <see cref="IErrorHandler"/> for this appender. /// </summary> /// <value>The <see cref="IErrorHandler"/> of the appender</value> /// <remarks> /// <para> /// The <see cref="AppenderSkeleton"/> provides a default /// implementation for the <see cref="ErrorHandler"/> property. /// </para> /// </remarks> virtual public IErrorHandler ErrorHandler { get { return this.m_errorHandler; } set { lock(this) { if (value == null) { // We do not throw exception here since the cause is probably a // bad config file. LogLog.Warn(declaringType, "You have tried to set a null error-handler."); } else { m_errorHandler = value; } } } } /// <summary> /// The filter chain. /// </summary> /// <value>The head of the filter chain filter chain.</value> /// <remarks> /// <para> /// Returns the head Filter. The Filters are organized in a linked list /// and so all Filters on this Appender are available through the result. /// </para> /// </remarks> virtual public IFilter FilterHead { get { return m_headFilter; } } /// <summary> /// Gets or sets the <see cref="ILayout"/> for this appender. /// </summary> /// <value>The layout of the appender.</value> /// <remarks> /// <para> /// See <see cref="RequiresLayout"/> for more information. /// </para> /// </remarks> /// <seealso cref="RequiresLayout"/> virtual public ILayout Layout { get { return m_layout; } set { m_layout = value; } } #endregion #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> virtual public void ActivateOptions() { } #endregion Implementation of IOptionHandler #region Implementation of IAppender /// <summary> /// Gets or sets the name of this appender. /// </summary> /// <value>The name of the appender.</value> /// <remarks> /// <para> /// The name uniquely identifies the appender. /// </para> /// </remarks> public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// Closes the appender and release resources. /// </summary> /// <remarks> /// <para> /// Release any resources allocated within the appender such as file handles, /// network connections, etc. /// </para> /// <para> /// It is a programming error to append to a closed appender. /// </para> /// <para> /// This method cannot be overridden by subclasses. This method /// delegates the closing of the appender to the <see cref="OnClose"/> /// method which must be overridden in the subclass. /// </para> /// </remarks> public void Close() { // This lock prevents the appender being closed while it is still appending lock(this) { if (!m_closed) { OnClose(); m_closed = true; } } } /// <summary> /// Performs threshold checks and invokes filters before /// delegating actual logging to the subclasses specific /// <see cref="M:Append(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// This method cannot be overridden by derived classes. A /// derived class should override the <see cref="M:Append(LoggingEvent)"/> method /// which is called by this method. /// </para> /// <para> /// The implementation of this method is as follows: /// </para> /// <para> /// <list type="bullet"> /// <item> /// <description> /// Checks that the severity of the <paramref name="loggingEvent"/> /// is greater than or equal to the <see cref="Threshold"/> of this /// appender.</description> /// </item> /// <item> /// <description> /// Checks that the <see cref="IFilter"/> chain accepts the /// <paramref name="loggingEvent"/>. /// </description> /// </item> /// <item> /// <description> /// Calls <see cref="M:PreAppendCheck()"/> and checks that /// it returns <c>true</c>.</description> /// </item> /// </list> /// </para> /// <para> /// If all of the above steps succeed then the <paramref name="loggingEvent"/> /// will be passed to the abstract <see cref="M:Append(LoggingEvent)"/> method. /// </para> /// </remarks> public void DoAppend(LoggingEvent loggingEvent) { // This lock is absolutely critical for correct formatting // of the message in a multi-threaded environment. Without // this, the message may be broken up into elements from // multiple thread contexts (like get the wrong thread ID). lock(this) { if (m_closed) { ErrorHandler.Error("Attempted to append to closed appender named ["+m_name+"]."); return; } // prevent re-entry if (m_recursiveGuard) { return; } try { m_recursiveGuard = true; if (FilterEvent(loggingEvent) && PreAppendCheck()) { this.Append(loggingEvent); } } catch(Exception ex) { ErrorHandler.Error("Failed in DoAppend", ex); } #if !MONO && !NET_2_0 && !NETSTANDARD1_3 // on .NET 2.0 (and higher) and Mono (all profiles), // exceptions that do not derive from System.Exception will be // wrapped in a RuntimeWrappedException by the runtime, and as // such will be catched by the catch clause above catch { // Catch handler for non System.Exception types ErrorHandler.Error("Failed in DoAppend (unknown exception)"); } #endif finally { m_recursiveGuard = false; } } } #endregion Implementation of IAppender #region Implementation of IBulkAppender /// <summary> /// Performs threshold checks and invokes filters before /// delegating actual logging to the subclasses specific /// <see cref="M:Append(LoggingEvent[])"/> method. /// </summary> /// <param name="loggingEvents">The array of events to log.</param> /// <remarks> /// <para> /// This method cannot be overridden by derived classes. A /// derived class should override the <see cref="M:Append(LoggingEvent[])"/> method /// which is called by this method. /// </para> /// <para> /// The implementation of this method is as follows: /// </para> /// <para> /// <list type="bullet"> /// <item> /// <description> /// Checks that the severity of the <paramref name="loggingEvents"/> /// is greater than or equal to the <see cref="Threshold"/> of this /// appender.</description> /// </item> /// <item> /// <description> /// Checks that the <see cref="IFilter"/> chain accepts the /// <paramref name="loggingEvents"/>. /// </description> /// </item> /// <item> /// <description> /// Calls <see cref="M:PreAppendCheck()"/> and checks that /// it returns <c>true</c>.</description> /// </item> /// </list> /// </para> /// <para> /// If all of the above steps succeed then the <paramref name="loggingEvents"/> /// will be passed to the <see cref="M:Append(LoggingEvent[])"/> method. /// </para> /// </remarks> public void DoAppend(LoggingEvent[] loggingEvents) { // This lock is absolutely critical for correct formatting // of the message in a multi-threaded environment. Without // this, the message may be broken up into elements from // multiple thread contexts (like get the wrong thread ID). lock(this) { if (m_closed) { ErrorHandler.Error("Attempted to append to closed appender named ["+m_name+"]."); return; } // prevent re-entry if (m_recursiveGuard) { return; } try { m_recursiveGuard = true; ArrayList filteredEvents = new ArrayList(loggingEvents.Length); foreach(LoggingEvent loggingEvent in loggingEvents) { if (FilterEvent(loggingEvent)) { filteredEvents.Add(loggingEvent); } } if (filteredEvents.Count > 0 && PreAppendCheck()) { this.Append((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); } } catch(Exception ex) { ErrorHandler.Error("Failed in Bulk DoAppend", ex); } #if !MONO && !NET_2_0 && !NETSTANDARD1_3 // on .NET 2.0 (and higher) and Mono (all profiles), // exceptions that do not derive from System.Exception will be // wrapped in a RuntimeWrappedException by the runtime, and as // such will be catched by the catch clause above catch { // Catch handler for non System.Exception types ErrorHandler.Error("Failed in Bulk DoAppend (unknown exception)"); } #endif finally { m_recursiveGuard = false; } } } #endregion Implementation of IBulkAppender /// <summary> /// Test if the logging event should we output by this appender /// </summary> /// <param name="loggingEvent">the event to test</param> /// <returns><c>true</c> if the event should be output, <c>false</c> if the event should be ignored</returns> /// <remarks> /// <para> /// This method checks the logging event against the threshold level set /// on this appender and also against the filters specified on this /// appender. /// </para> /// <para> /// The implementation of this method is as follows: /// </para> /// <para> /// <list type="bullet"> /// <item> /// <description> /// Checks that the severity of the <paramref name="loggingEvent"/> /// is greater than or equal to the <see cref="Threshold"/> of this /// appender.</description> /// </item> /// <item> /// <description> /// Checks that the <see cref="IFilter"/> chain accepts the /// <paramref name="loggingEvent"/>. /// </description> /// </item> /// </list> /// </para> /// </remarks> virtual protected bool FilterEvent(LoggingEvent loggingEvent) { if (!IsAsSevereAsThreshold(loggingEvent.Level)) { return false; } IFilter f = this.FilterHead; while(f != null) { switch(f.Decide(loggingEvent)) { case FilterDecision.Deny: return false; // Return without appending case FilterDecision.Accept: f = null; // Break out of the loop break; case FilterDecision.Neutral: f = f.Next; // Move to next filter break; } } return true; } #region Public Instance Methods /// <summary> /// Adds a filter to the end of the filter chain. /// </summary> /// <param name="filter">the filter to add to this appender</param> /// <remarks> /// <para> /// The Filters are organized in a linked list. /// </para> /// <para> /// Setting this property causes the new filter to be pushed onto the /// back of the filter chain. /// </para> /// </remarks> virtual public void AddFilter(IFilter filter) { if (filter == null) { throw new ArgumentNullException("filter param must not be null"); } if (m_headFilter == null) { m_headFilter = m_tailFilter = filter; } else { m_tailFilter.Next = filter; m_tailFilter = filter; } } /// <summary> /// Clears the filter list for this appender. /// </summary> /// <remarks> /// <para> /// Clears the filter list for this appender. /// </para> /// </remarks> virtual public void ClearFilters() { m_headFilter = m_tailFilter = null; } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Checks if the message level is below this appender's threshold. /// </summary> /// <param name="level"><see cref="Level"/> to test against.</param> /// <remarks> /// <para> /// If there is no threshold set, then the return value is always <c>true</c>. /// </para> /// </remarks> /// <returns> /// <c>true</c> if the <paramref name="level"/> meets the <see cref="Threshold"/> /// requirements of this appender. /// </returns> virtual protected bool IsAsSevereAsThreshold(Level level) { return ((m_threshold == null) || level >= m_threshold); } /// <summary> /// Is called when the appender is closed. Derived classes should override /// this method if resources need to be released. /// </summary> /// <remarks> /// <para> /// Releases any resources allocated within the appender such as file handles, /// network connections, etc. /// </para> /// <para> /// It is a programming error to append to a closed appender. /// </para> /// </remarks> virtual protected void OnClose() { // Do nothing by default } /// <summary> /// Subclasses of <see cref="AppenderSkeleton"/> should implement this method /// to perform actual logging. /// </summary> /// <param name="loggingEvent">The event to append.</param> /// <remarks> /// <para> /// A subclass must implement this method to perform /// logging of the <paramref name="loggingEvent"/>. /// </para> /// <para>This method will be called by <see cref="M:DoAppend(LoggingEvent)"/> /// if all the conditions listed for that method are met. /// </para> /// <para> /// To restrict the logging of events in the appender /// override the <see cref="M:PreAppendCheck()"/> method. /// </para> /// </remarks> abstract protected void Append(LoggingEvent loggingEvent); /// <summary> /// Append a bulk array of logging events. /// </summary> /// <param name="loggingEvents">the array of logging events</param> /// <remarks> /// <para> /// This base class implementation calls the <see cref="M:Append(LoggingEvent)"/> /// method for each element in the bulk array. /// </para> /// <para> /// A sub class that can better process a bulk array of events should /// override this method in addition to <see cref="M:Append(LoggingEvent)"/>. /// </para> /// </remarks> virtual protected void Append(LoggingEvent[] loggingEvents) { foreach(LoggingEvent loggingEvent in loggingEvents) { Append(loggingEvent); } } /// <summary> /// Called before <see cref="M:Append(LoggingEvent)"/> as a precondition. /// </summary> /// <remarks> /// <para> /// This method is called by <see cref="M:DoAppend(LoggingEvent)"/> /// before the call to the abstract <see cref="M:Append(LoggingEvent)"/> method. /// </para> /// <para> /// This method can be overridden in a subclass to extend the checks /// made before the event is passed to the <see cref="M:Append(LoggingEvent)"/> method. /// </para> /// <para> /// A subclass should ensure that they delegate this call to /// this base class if it is overridden. /// </para> /// </remarks> /// <returns><c>true</c> if the call to <see cref="M:Append(LoggingEvent)"/> should proceed.</returns> virtual protected bool PreAppendCheck() { if ((m_layout == null) && RequiresLayout) { ErrorHandler.Error("AppenderSkeleton: No layout set for the appender named ["+m_name+"]."); return false; } return true; } /// <summary> /// Renders the <see cref="LoggingEvent"/> to a string. /// </summary> /// <param name="loggingEvent">The event to render.</param> /// <returns>The event rendered as a string.</returns> /// <remarks> /// <para> /// Helper method to render a <see cref="LoggingEvent"/> to /// a string. This appender must have a <see cref="Layout"/> /// set to render the <paramref name="loggingEvent"/> to /// a string. /// </para> /// <para>If there is exception data in the logging event and /// the layout does not process the exception, this method /// will append the exception text to the rendered string. /// </para> /// <para> /// Where possible use the alternative version of this method /// <see cref="M:RenderLoggingEvent(TextWriter,LoggingEvent)"/>. /// That method streams the rendering onto an existing Writer /// which can give better performance if the caller already has /// a <see cref="TextWriter"/> open and ready for writing. /// </para> /// </remarks> protected string RenderLoggingEvent(LoggingEvent loggingEvent) { // Create the render writer on first use if (m_renderWriter == null) { m_renderWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); } lock (m_renderWriter) { // Reset the writer so we can reuse it m_renderWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); RenderLoggingEvent(m_renderWriter, loggingEvent); return m_renderWriter.ToString(); } } /// <summary> /// Renders the <see cref="LoggingEvent"/> to a string. /// </summary> /// <param name="loggingEvent">The event to render.</param> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Helper method to render a <see cref="LoggingEvent"/> to /// a string. This appender must have a <see cref="Layout"/> /// set to render the <paramref name="loggingEvent"/> to /// a string. /// </para> /// <para>If there is exception data in the logging event and /// the layout does not process the exception, this method /// will append the exception text to the rendered string. /// </para> /// <para> /// Use this method in preference to <see cref="M:RenderLoggingEvent(LoggingEvent)"/> /// where possible. If, however, the caller needs to render the event /// to a string then <see cref="M:RenderLoggingEvent(LoggingEvent)"/> does /// provide an efficient mechanism for doing so. /// </para> /// </remarks> protected void RenderLoggingEvent(TextWriter writer, LoggingEvent loggingEvent) { if (m_layout == null) { throw new InvalidOperationException("A layout must be set"); } if (m_layout.IgnoresException) { string exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // render the event and the exception m_layout.Format(writer, loggingEvent); writer.WriteLine(exceptionStr); } else { // there is no exception to render m_layout.Format(writer, loggingEvent); } } else { // The layout will render the exception m_layout.Format(writer, loggingEvent); } } /// <summary> /// Tests if this appender requires a <see cref="Layout"/> to be set. /// </summary> /// <remarks> /// <para> /// In the rather exceptional case, where the appender /// implementation admits a layout but can also work without it, /// then the appender should return <c>true</c>. /// </para> /// <para> /// This default implementation always returns <c>false</c>. /// </para> /// </remarks> /// <returns> /// <c>true</c> if the appender requires a layout object, otherwise <c>false</c>. /// </returns> virtual protected bool RequiresLayout { get { return false; } } #endregion /// <summary> /// Flushes any buffered log data. /// </summary> /// <remarks> /// This implementation doesn't flush anything and always returns true /// </remarks> /// <returns><c>True</c> if all logging events were flushed successfully, else <c>false</c>.</returns> public virtual bool Flush(int millisecondsTimeout) { return true; } #region Private Instance Fields /// <summary> /// The layout of this appender. /// </summary> /// <remarks> /// See <see cref="Layout"/> for more information. /// </remarks> private ILayout m_layout; /// <summary> /// The name of this appender. /// </summary> /// <remarks> /// See <see cref="Name"/> for more information. /// </remarks> private string m_name; /// <summary> /// The level threshold of this appender. /// </summary> /// <remarks> /// <para> /// There is no level threshold filtering by default. /// </para> /// <para> /// See <see cref="Threshold"/> for more information. /// </para> /// </remarks> private Level m_threshold; /// <summary> /// It is assumed and enforced that errorHandler is never null. /// </summary> /// <remarks> /// <para> /// It is assumed and enforced that errorHandler is never null. /// </para> /// <para> /// See <see cref="ErrorHandler"/> for more information. /// </para> /// </remarks> private IErrorHandler m_errorHandler; /// <summary> /// The first filter in the filter chain. /// </summary> /// <remarks> /// <para> /// Set to <c>null</c> initially. /// </para> /// <para> /// See <see cref="IFilter"/> for more information. /// </para> /// </remarks> private IFilter m_headFilter; /// <summary> /// The last filter in the filter chain. /// </summary> /// <remarks> /// See <see cref="IFilter"/> for more information. /// </remarks> private IFilter m_tailFilter; /// <summary> /// Flag indicating if this appender is closed. /// </summary> /// <remarks> /// See <see cref="Close"/> for more information. /// </remarks> private bool m_closed = false; /// <summary> /// The guard prevents an appender from repeatedly calling its own DoAppend method /// </summary> private bool m_recursiveGuard = false; /// <summary> /// StringWriter used to render events /// </summary> private ReusableStringWriter m_renderWriter = null; #endregion Private Instance Fields #region Constants /// <summary> /// Initial buffer size /// </summary> private const int c_renderBufferSize = 256; /// <summary> /// Maximum buffer size before it is recycled /// </summary> private const int c_renderBufferMaxCapacity = 1024; #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the AppenderSkeleton class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(AppenderSkeleton); #endregion Private Static Fields } }
//--------------------------------------------------------------------- // <copyright file="CellCreator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Data.Common.Utils; using System.Data.Mapping.ViewGeneration.Structures; using System.Collections.Generic; using System.Data.Mapping.ViewGeneration.Utils; using System.Diagnostics; using System.Data.Metadata.Edm; using System.Linq; namespace System.Data.Mapping.ViewGeneration { /// <summary> /// A class that handles creation of cells from the meta data information. /// </summary> internal class CellCreator : InternalBase { #region Constructors // effects: Creates a cell creator object for an entity container's // mappings (specified in "maps") internal CellCreator(StorageEntityContainerMapping containerMapping) { m_containerMapping = containerMapping; m_identifiers = new CqlIdentifiers(); } #endregion #region Fields // The mappings from the metadata for different containers private StorageEntityContainerMapping m_containerMapping; private int m_currentCellNumber; private CqlIdentifiers m_identifiers; // Keep track of all the identifiers to prevent clashes with _from0, // _from1, T, T1, etc // Keep track of names of // * Entity Containers // * Extent names // * Entity Types // * Complex Types // * Properties // * Roles #endregion #region Properties // effects: Returns the set of identifiers used in this internal CqlIdentifiers Identifiers { get { return m_identifiers; } } #endregion #region External methods // effects: Generates the cells for all the entity containers // specified in this. The generated cells are geared for query view generation internal List<Cell> GenerateCells(ConfigViewGenerator config) { List<Cell> cells = new List<Cell>(); // Get the cells from the entity container metadata ExtractCells(cells); ExpandCells(cells); // Get the identifiers from the cells m_identifiers.AddIdentifier(m_containerMapping.EdmEntityContainer.Name); m_identifiers.AddIdentifier(m_containerMapping.StorageEntityContainer.Name); foreach (Cell cell in cells) { cell.GetIdentifiers(m_identifiers); } return cells; } #endregion #region Private Methods /// <summary> /// Boolean members have a closed domain and are enumerated when domains are established i.e. (T, F) instead of (notNull). /// Query Rewriting is exercised over every domain of the condition member. If the member contains not_null condition /// for example, it cannot generate a view for partitions (member=T), (Member=F). For this reason we need to expand the cells /// in a predefined situation (below) to include sub-fragments mapping individual elements of the closed domain. /// Enums (a planned feature) need to be handled in a similar fashion. /// /// Find booleans that are projected with a not_null condition /// Expand ALL cells where they are projected. Why? See Unit Test case NullabilityConditionOnBoolean5.es /// Validation will fail because it will not be able to validate rewritings for partitions on the 'other' cells. /// </summary> private void ExpandCells(List<Cell> cells) { var sSideMembersToBeExpanded = new Set<MemberPath>(); foreach (Cell cell in cells) { //Find Projected members that are Boolean AND are mentioned in the Where clause with not_null condition foreach (var memberToExpand in cell.SQuery.GetProjectedMembers() .Where(member => IsBooleanMember(member)) .Where(boolMember => cell.SQuery.GetConjunctsFromWhereClause() .Where(restriction => restriction.Domain.Values.Contains(Constant.NotNull)) .Select(restriction => restriction.RestrictedMemberSlot.MemberPath).Contains(boolMember))) { sSideMembersToBeExpanded.Add(memberToExpand); } } //Foreach s-side members, find all c-side members it is mapped to // We need these because we need to expand all cells where the boolean candidate is projected or mapped member is projected, e.g: // (1) C[id, cdisc] WHERE d=true <=> T1[id, sdisc] WHERE sdisc=NOTNULL // (2) C[id, cdisc] WHERE d=false <=> T2[id, sdisc] // Here we need to know that because of T1.sdisc, we need to expand T2.sdisc. // This is done by tracking cdisc, and then seeing in cell 2 that it is mapped to T2.sdisc var cSideMembersForSSideExpansionCandidates = new Dictionary<MemberPath, Set<MemberPath>>(); foreach (Cell cell in cells) { foreach (var sSideMemberToExpand in sSideMembersToBeExpanded) { var cSideMembers = cell.SQuery.GetProjectedPositions(sSideMemberToExpand).Select(pos => ((MemberProjectedSlot)cell.CQuery.ProjectedSlotAt(pos)).MemberPath); Set<MemberPath> cSidePaths = null; if (!cSideMembersForSSideExpansionCandidates.TryGetValue(sSideMemberToExpand, out cSidePaths)) { cSidePaths = new Set<MemberPath>(); cSideMembersForSSideExpansionCandidates[sSideMemberToExpand] = cSidePaths; } cSidePaths.AddRange(cSideMembers); } } // Expand cells that project members collected earlier with T/F conditiions foreach (Cell cell in cells.ToArray()) { //Each member gets its own expansion. Including multiple condition candidates in one SQuery // "... <=> T[..] WHERE a=notnull AND b=notnull" means a and b get their own independent expansions // Note: this is not a cross-product foreach (var memberToExpand in sSideMembersToBeExpanded) { var mappedCSideMembers = cSideMembersForSSideExpansionCandidates[memberToExpand]; //Check if member is projected in this cell. if (cell.SQuery.GetProjectedMembers().Contains(memberToExpand)) { // Creationg additional cel can fail when the condition to be appended contradicts existing condition in the CellQuery // We don't add contradictions because they seem to cause unrelated problems in subsequent validation routines Cell resultCell = null; if (TryCreateAdditionalCellWithCondition(cell, memberToExpand, true /*condition value*/, ViewTarget.UpdateView /*s-side member*/, out resultCell)) { cells.Add(resultCell); } if (TryCreateAdditionalCellWithCondition(cell, memberToExpand, false /*condition value*/, ViewTarget.UpdateView /*s-side member*/, out resultCell)) { cells.Add(resultCell); } } else { //If the s-side member is not projected, see if the mapped C-side member(s) is projected foreach (var cMemberToExpand in cell.CQuery.GetProjectedMembers().Intersect(mappedCSideMembers)) { Cell resultCell = null; if (TryCreateAdditionalCellWithCondition(cell, cMemberToExpand, true /*condition value*/, ViewTarget.QueryView /*c-side member*/, out resultCell)) { cells.Add(resultCell); } if (TryCreateAdditionalCellWithCondition(cell, cMemberToExpand, false /*condition value*/, ViewTarget.QueryView /*c-side member*/, out resultCell)) { cells.Add(resultCell); } } } } } } /// <summary> /// Given a cell, a member and a boolean condition on that member, creates additional cell /// which with the specified restriction on the member in addition to original condition. /// e.i conjunction of original condition AND member in newCondition /// /// Creation fails when the original condition contradicts new boolean condition /// /// ViewTarget tells whether MemberPath is in Cquery or SQuery /// </summary> private bool TryCreateAdditionalCellWithCondition(Cell originalCell, MemberPath memberToExpand, bool conditionValue, ViewTarget viewTarget, out Cell result) { Debug.Assert(originalCell != null); Debug.Assert(memberToExpand != null); result = null; //Create required structures MemberPath leftExtent = originalCell.GetLeftQuery(viewTarget).SourceExtentMemberPath; MemberPath rightExtent = originalCell.GetRightQuery(viewTarget).SourceExtentMemberPath; //Now for the given left-side projected member, find corresponding right-side member that it is mapped to int indexOfBooLMemberInProjection = originalCell.GetLeftQuery(viewTarget).GetProjectedMembers().TakeWhile(path => !path.Equals(memberToExpand)).Count(); MemberProjectedSlot rightConditionMemberSlot = ((MemberProjectedSlot)originalCell.GetRightQuery(viewTarget).ProjectedSlotAt(indexOfBooLMemberInProjection)); MemberPath rightSidePath = rightConditionMemberSlot.MemberPath; List<ProjectedSlot> leftSlots = new List<ProjectedSlot>(); List<ProjectedSlot> rightSlots = new List<ProjectedSlot>(); //Check for impossible conditions (otehrwise we get inaccurate pre-validation errors) ScalarConstant negatedCondition = new ScalarConstant(!conditionValue); if (originalCell.GetLeftQuery(viewTarget).Conditions .Where(restriction => restriction.RestrictedMemberSlot.MemberPath.Equals(memberToExpand)) .Where(restriction => restriction.Domain.Values.Contains(negatedCondition)).Any() || originalCell.GetRightQuery(viewTarget).Conditions .Where(restriction => restriction.RestrictedMemberSlot.MemberPath.Equals(rightSidePath)) .Where(restriction => restriction.Domain.Values.Contains(negatedCondition)).Any()) { return false; } //End check //Create Projected Slots // Map all slots in original cell (not just keys) because some may be required (non nullable and no default) // and others may have not_null condition so MUST be projected. Rely on the user doing the right thing, otherwise // they will get the error message anyway for (int i = 0; i < originalCell.GetLeftQuery(viewTarget).NumProjectedSlots; i++) { leftSlots.Add(originalCell.GetLeftQuery(viewTarget).ProjectedSlotAt(i)); } for (int i = 0; i < originalCell.GetRightQuery(viewTarget).NumProjectedSlots; i++) { rightSlots.Add(originalCell.GetRightQuery(viewTarget).ProjectedSlotAt(i)); } //Create condition boolena expressions BoolExpression leftQueryWhereClause = BoolExpression.CreateLiteral(new ScalarRestriction(memberToExpand, new ScalarConstant(conditionValue)), null); leftQueryWhereClause = BoolExpression.CreateAnd(originalCell.GetLeftQuery(viewTarget).WhereClause, leftQueryWhereClause); BoolExpression rightQueryWhereClause = BoolExpression.CreateLiteral(new ScalarRestriction(rightSidePath, new ScalarConstant(conditionValue)), null); rightQueryWhereClause = BoolExpression.CreateAnd(originalCell.GetRightQuery(viewTarget).WhereClause, rightQueryWhereClause); //Create additional Cells CellQuery rightQuery = new CellQuery(rightSlots, rightQueryWhereClause, rightExtent, originalCell.GetRightQuery(viewTarget).SelectDistinctFlag); CellQuery leftQuery = new CellQuery(leftSlots, leftQueryWhereClause, leftExtent, originalCell.GetLeftQuery(viewTarget).SelectDistinctFlag); Cell newCell; if (viewTarget == ViewTarget.UpdateView) { newCell = Cell.CreateCS(rightQuery, leftQuery, originalCell.CellLabel, m_currentCellNumber); } else { newCell = Cell.CreateCS(leftQuery, rightQuery, originalCell.CellLabel, m_currentCellNumber); } m_currentCellNumber++; result = newCell; return true; } // effects: Given the metadata information for a container in // containerMap, generate the cells for it and modify cells to // contain the newly-generated cells private void ExtractCells(List<Cell> cells) { // extract entity mappings, i.e., for CPerson1, COrder1, etc foreach (StorageSetMapping extentMap in m_containerMapping.AllSetMaps) { // Get each type map in an entity set mapping, i.e., for // CPerson, CCustomer, etc in CPerson1 foreach (StorageTypeMapping typeMap in extentMap.TypeMappings) { StorageEntityTypeMapping entityTypeMap = typeMap as StorageEntityTypeMapping; Debug.Assert(entityTypeMap != null || typeMap is StorageAssociationTypeMapping, "Invalid typemap"); // A set for all the types in this type mapping Set<EdmType> allTypes = new Set<EdmType>(); if (entityTypeMap != null) { // Gather a set of all explicit types for an entity // type mapping in allTypes. Note that we do not have // subtyping in association sets allTypes.AddRange(entityTypeMap.Types); foreach (EdmType type in entityTypeMap.IsOfTypes) { IEnumerable<EdmType> typeAndSubTypes = MetadataHelper.GetTypeAndSubtypesOf(type, m_containerMapping.StorageMappingItemCollection.EdmItemCollection, false /*includeAbstractTypes*/); allTypes.AddRange(typeAndSubTypes); } } EntitySetBase extent = extentMap.Set; Debug.Assert(extent != null, "Extent map for a null extent or type of extentMap.Exent " + "is not Extent"); // For each table mapping for the type mapping, we create cells foreach (StorageMappingFragment fragmentMap in typeMap.MappingFragments) { ExtractCellsFromTableFragment(extent, fragmentMap, allTypes, cells); } } } } // effects: Given an extent's ("extent") table fragment that is // contained inside typeMap, determine the cells that need to be // created and add them to cells // allTypes corresponds to all the different types that the type map // represents -- this parameter has something useful only if extent // is an entity set private void ExtractCellsFromTableFragment(EntitySetBase extent, StorageMappingFragment fragmentMap, Set<EdmType> allTypes, List<Cell> cells) { // create C-query components MemberPath cRootExtent = new MemberPath(extent); BoolExpression cQueryWhereClause = BoolExpression.True; List<ProjectedSlot> cSlots = new List<ProjectedSlot>(); if (allTypes.Count > 0) { // Create a type condition for the extent, i.e., "extent in allTypes" cQueryWhereClause = BoolExpression.CreateLiteral(new TypeRestriction(cRootExtent, allTypes), null); } // create S-query components MemberPath sRootExtent = new MemberPath(fragmentMap.TableSet); BoolExpression sQueryWhereClause = BoolExpression.True; List<ProjectedSlot> sSlots = new List<ProjectedSlot>(); // Association or entity set // Add the properties and the key properties to a list and // then process them in ExtractProperties ExtractProperties(fragmentMap.AllProperties, cRootExtent, cSlots, ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause); // limitation of MSL API: cannot assign constant values to table columns CellQuery cQuery = new CellQuery(cSlots, cQueryWhereClause, cRootExtent, CellQuery.SelectDistinct.No /*no distinct flag*/); CellQuery sQuery = new CellQuery(sSlots, sQueryWhereClause, sRootExtent, fragmentMap.IsSQueryDistinct ? CellQuery.SelectDistinct.Yes : CellQuery.SelectDistinct.No); StorageMappingFragment fragmentInfo = fragmentMap as StorageMappingFragment; Debug.Assert((fragmentInfo != null), "CSMappingFragment should support Line Info"); CellLabel label = new CellLabel(fragmentInfo); Cell cell = Cell.CreateCS(cQuery, sQuery, label, m_currentCellNumber); m_currentCellNumber++; cells.Add(cell); } // requires: "properties" corresponds to all the properties that are // inside cNode.Value, e.g., cNode corresponds to an extent Person, // properties contains all the properties inside Person (recursively) // effects: Given C-side and S-side Cell Query for a cell, generates // the projected slots on both sides corresponding to // properties. Also updates the C-side whereclause corresponding to // discriminator properties on the C-side, e.g, isHighPriority private void ExtractProperties(IEnumerable<StoragePropertyMapping> properties, MemberPath cNode, List<ProjectedSlot> cSlots, ref BoolExpression cQueryWhereClause, MemberPath sRootExtent, List<ProjectedSlot> sSlots, ref BoolExpression sQueryWhereClause) { // For each property mapping, we add an entry to the C and S cell queries foreach (StoragePropertyMapping propMap in properties) { StorageScalarPropertyMapping scalarPropMap = propMap as StorageScalarPropertyMapping; StorageComplexPropertyMapping complexPropMap = propMap as StorageComplexPropertyMapping; StorageEndPropertyMapping associationEndPropertypMap = propMap as StorageEndPropertyMapping; StorageConditionPropertyMapping conditionMap = propMap as StorageConditionPropertyMapping; Debug.Assert(scalarPropMap != null || complexPropMap != null || associationEndPropertypMap != null || conditionMap != null, "Unimplemented property mapping"); if (scalarPropMap != null) { Debug.Assert(scalarPropMap.ColumnProperty != null, "ColumnMember for a Scalar Property can not be null"); // Add an attribute node to node MemberPath cAttributeNode = new MemberPath(cNode, scalarPropMap.EdmProperty); // Add a column (attribute) node the sQuery // unlike the C side, there is no nesting. Hence we // did not need an internal node MemberPath sAttributeNode = new MemberPath(sRootExtent, scalarPropMap.ColumnProperty); cSlots.Add(new MemberProjectedSlot(cAttributeNode)); sSlots.Add(new MemberProjectedSlot(sAttributeNode)); } // Note: S-side constants are not allowed since they can cause // problems -- for example, if such a cell says 5 for the // third field, we cannot guarantee the fact that an // application may not set that field to 7 in the C-space // Check if the property mapping is for a complex types if (complexPropMap != null) { foreach (StorageComplexTypeMapping complexTypeMap in complexPropMap.TypeMappings) { // Create a node for the complex type property and call recursively MemberPath complexMemberNode = new MemberPath(cNode, complexPropMap.EdmProperty); //Get the list of types that this type map represents Set<EdmType> allTypes = new Set<EdmType>(); // Gather a set of all explicit types for an entity // type mapping in allTypes. IEnumerable<EdmType> exactTypes = Helpers.AsSuperTypeList<ComplexType, EdmType>(complexTypeMap.Types); allTypes.AddRange(exactTypes); foreach (EdmType type in complexTypeMap.IsOfTypes) { allTypes.AddRange(MetadataHelper.GetTypeAndSubtypesOf(type, m_containerMapping.StorageMappingItemCollection.EdmItemCollection, false /*includeAbstractTypes*/)); } BoolExpression complexInTypes = BoolExpression.CreateLiteral(new TypeRestriction(complexMemberNode, allTypes), null); cQueryWhereClause = BoolExpression.CreateAnd(cQueryWhereClause, complexInTypes); // Now extract the properties of the complex type // (which could have other complex types) ExtractProperties(complexTypeMap.AllProperties, complexMemberNode, cSlots, ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause); } } // Check if the property mapping is for an associaion if (associationEndPropertypMap != null) { // create join tree node representing this relation end MemberPath associationEndNode = new MemberPath(cNode, associationEndPropertypMap.EndMember); // call recursively ExtractProperties(associationEndPropertypMap.Properties, associationEndNode, cSlots, ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause); } //Check if the this is a condition and add it to the Where clause if (conditionMap != null) { if (conditionMap.ColumnProperty != null) { //Produce a Condition Expression for the Condition Map. BoolExpression conditionExpression = GetConditionExpression(sRootExtent, conditionMap); //Add the condition expression to the exisiting S side Where clause using an "And" sQueryWhereClause = BoolExpression.CreateAnd(sQueryWhereClause, conditionExpression); } else { Debug.Assert(conditionMap.EdmProperty != null); //Produce a Condition Expression for the Condition Map. BoolExpression conditionExpression = GetConditionExpression(cNode, conditionMap); //Add the condition expression to the exisiting C side Where clause using an "And" cQueryWhereClause = BoolExpression.CreateAnd(cQueryWhereClause, conditionExpression); } } } } /// <summary> /// Takes in a JoinTreeNode and a Contition Property Map and creates an BoolExpression /// for the Condition Map. /// </summary> /// <param name="joinTreeNode"></param> /// <param name="conditionMap"></param> /// <returns></returns> private static BoolExpression GetConditionExpression(MemberPath member, StorageConditionPropertyMapping conditionMap) { //Get the member for which the condition is being specified EdmMember conditionMember = (conditionMap.ColumnProperty != null) ? conditionMap.ColumnProperty : conditionMap.EdmProperty; MemberPath conditionMemberNode = new MemberPath(member, conditionMember); //Check if this is a IsNull condition MemberRestriction conditionExpression = null; if (conditionMap.IsNull.HasValue) { // for conditions on scalars, create NodeValue nodes, otherwise NodeType Constant conditionConstant = (true == conditionMap.IsNull.Value) ? Constant.Null : Constant.NotNull; if (true == MetadataHelper.IsNonRefSimpleMember(conditionMember)) { conditionExpression = new ScalarRestriction(conditionMemberNode, conditionConstant); } else { conditionExpression = new TypeRestriction(conditionMemberNode, conditionConstant); } } else { conditionExpression = new ScalarRestriction(conditionMemberNode, new ScalarConstant(conditionMap.Value)); } Debug.Assert(conditionExpression != null); return BoolExpression.CreateLiteral(conditionExpression, null); } private static bool IsBooleanMember(MemberPath path) { PrimitiveType primitive = path.EdmType as PrimitiveType; return (primitive != null && primitive.PrimitiveTypeKind == PrimitiveTypeKind.Boolean); } #endregion #region String methods internal override void ToCompactString(System.Text.StringBuilder builder) { builder.Append("CellCreator"); // No state to really show i.e., m_maps } #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.Diagnostics; namespace System.Threading { // ManualResetEventSlim wraps a manual-reset event internally with a little bit of // spinning. When an event will be set imminently, it is often advantageous to avoid // a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to // a brief amount of spinning that should, on the average, make using the slim event // cheaper than using Win32 events directly. This can be reset manually, much like // a Win32 manual-reset would be. // // Notes: // We lazily allocate the Win32 event internally. Therefore, the caller should // always call Dispose to clean it up, just in case. This API is a no-op of the // event wasn't allocated, but if it was, ensures that the event goes away // eagerly, instead of waiting for finalization. /// <summary> /// Provides a slimmed down version of <see cref="System.Threading.ManualResetEvent"/>. /// </summary> /// <remarks> /// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [DebuggerDisplay("Set = {IsSet}")] public class ManualResetEventSlim : IDisposable { // These are the default spin counts we use on single-proc and MP machines. private const int DEFAULT_SPIN_SP = 1; private volatile object? m_lock; // A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated() private volatile ManualResetEvent? m_eventObj; // A true Win32 event used for waiting. // -- State -- // // For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. private volatile int m_combinedState; // ie a uint. Used for the state items listed below. // 1-bit for signalled state private const int SignalledState_BitMask = unchecked((int)0x80000000); // 1000 0000 0000 0000 0000 0000 0000 0000 private const int SignalledState_ShiftCount = 31; // 1-bit for disposed state private const int Dispose_BitMask = unchecked((int)0x40000000); // 0100 0000 0000 0000 0000 0000 0000 0000 // 11-bits for m_spinCount private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); // 0011 1111 1111 1000 0000 0000 0000 0000 private const int SpinCountState_ShiftCount = 19; private const int SpinCountState_MaxValue = (1 << 11) - 1; // 2047 // 19-bits for m_waiters. This allows support of 512K threads waiting which should be ample private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111 private const int NumWaitersState_ShiftCount = 0; private const int NumWaitersState_MaxValue = (1 << 19) - 1; // 512K-1 // ----------- // /// <summary> /// Gets the underlying <see cref="System.Threading.WaitHandle"/> object for this <see /// cref="ManualResetEventSlim"/>. /// </summary> /// <value>The underlying <see cref="System.Threading.WaitHandle"/> event object fore this <see /// cref="ManualResetEventSlim"/>.</value> /// <remarks> /// Accessing this property forces initialization of an underlying event object if one hasn't /// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>, /// the public Wait methods should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); if (m_eventObj == null) { // Lazily initialize the event object if needed. LazyInitializeEvent(); Debug.Assert(m_eventObj != null); } return m_eventObj; } } /// <summary> /// Gets whether the event is set. /// </summary> /// <value>true if the event has is set; otherwise, false.</value> public bool IsSet { get => 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask); private set => UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask); } /// <summary> /// Gets the number of spin waits that will be occur before falling back to a true wait. /// </summary> public int SpinCount { get => ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount); private set { Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); // Don't worry about thread safety because it's set one time from the constructor m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount); } } /// <summary> /// How many threads are waiting. /// </summary> private int Waiters { get => ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount); set { // setting to <0 would indicate an internal flaw, hence Assert is appropriate. Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. if (value >= NumWaitersState_MaxValue) throw new InvalidOperationException(SR.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); } } //----------------------------------------------------------------------------------- // Constructs a new event, optionally specifying the initial state and spin count. // The defaults are that the event is unsignaled and some reasonable default spin. // /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with an initial state of nonsignaled. /// </summary> public ManualResetEventSlim() : this(false) { } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a boolean value indicating whether to set the initial state to signaled. /// </summary> /// <param name="initialState">true to set the initial state signaled; false to set the initial state /// to nonsignaled.</param> public ManualResetEventSlim(bool initialState) { // Specify the default spin count, and use default spin if we're // on a multi-processor machine. Otherwise, we won't. Initialize(initialState, SpinWait.SpinCountforSpinBeforeWait); } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a Boolean value indicating whether to set the initial state to signaled and a specified /// spin count. /// </summary> /// <param name="initialState">true to set the initial state to signaled; false to set the initial state /// to nonsignaled.</param> /// <param name="spinCount">The number of spin waits that will occur before falling back to a true /// wait.</param> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than /// 0 or greater than the maximum allowed value.</exception> public ManualResetEventSlim(bool initialState, int spinCount) { if (spinCount < 0) { throw new ArgumentOutOfRangeException(nameof(spinCount)); } if (spinCount > SpinCountState_MaxValue) { throw new ArgumentOutOfRangeException( nameof(spinCount), SR.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); } // We will suppress default spin because the user specified a count. Initialize(initialState, spinCount); } /// <summary> /// Initializes the internal state of the event. /// </summary> /// <param name="initialState">Whether the event is set initially or not.</param> /// <param name="spinCount">The spin count that decides when the event will block.</param> private void Initialize(bool initialState, int spinCount) { m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; // the spinCount argument has been validated by the ctors. // but we now sanity check our predefined constants. Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount; } /// <summary> /// Helper to ensure the lock object is created before first use. /// </summary> private void EnsureLockObjectCreated() { if (m_lock != null) return; object newObj = new object(); Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value. } /// <summary> /// This method lazily initializes the event object. It uses CAS to guarantee that /// many threads racing to call this at once don't result in more than one event /// being stored and used. The event will be signaled or unsignaled depending on /// the state of the thin-event itself, with synchronization taken into account. /// </summary> private void LazyInitializeEvent() { bool preInitializeIsSet = IsSet; ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet); // We have to CAS this in case we are racing with another thread. We must // guarantee only one event is actually stored in this field. if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) { // Someone else set the value due to a race condition. Destroy the garbage event. newEventObj.Dispose(); } else { // Now that the event is published, verify that the state hasn't changed since // we snapped the preInitializeState. Another thread could have done that // between our initial observation above and here. The barrier incurred from // the CAS above (in addition to m_state being volatile) prevents this read // from moving earlier and being collapsed with our original one. bool currentIsSet = IsSet; if (currentIsSet != preInitializeIsSet) { Debug.Assert(currentIsSet, "The only safe concurrent transition is from unset->set: detected set->unset."); // We saw it as unsignaled, but it has since become set. lock (newEventObj) { // If our event hasn't already been disposed of, we must set it. if (m_eventObj == newEventObj) { newEventObj.Set(); } } } } } /// <summary> /// Sets the state of the event to signaled, which allows one or more threads waiting on the event to /// proceed. /// </summary> public void Set() { Set(false); } /// <summary> /// Private helper to actually perform the Set. /// </summary> /// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param> /// <exception cref="System.OperationCanceledException">The object has been canceled.</exception> private void Set(bool duringCancellation) { // We need to ensure that IsSet=true does not get reordered past the read of m_eventObj // This would be a legal movement according to the .NET memory model. // The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier. IsSet = true; // If there are waiting threads, we need to pulse them. if (Waiters > 0) { Debug.Assert(m_lock != null); // if waiters>0, then m_lock has already been created. lock (m_lock) { Monitor.PulseAll(m_lock); } } ManualResetEvent? eventObj = m_eventObj; // Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly // It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic if (eventObj != null && !duringCancellation) { // We must surround this call to Set in a lock. The reason is fairly subtle. // Sometimes a thread will issue a Wait and wake up after we have set m_state, // but before we have gotten around to setting m_eventObj (just below). That's // because Wait first checks m_state and will only access the event if absolutely // necessary. However, the coding pattern { event.Wait(); event.Dispose() } is // quite common, and we must support it. If the waiter woke up and disposed of // the event object before the setter has finished, however, we would try to set a // now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to // protect access to the event object when setting and disposing of it. We also // double-check that the event has not become null in the meantime when in the lock. lock (eventObj) { if (m_eventObj != null) { // If somebody is waiting, we must set the event. m_eventObj.Set(); } } } } /// <summary> /// Sets the state of the event to nonsignaled, which causes threads to block. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Reset() { ThrowIfDisposed(); // If there's an event, reset it. if (m_eventObj != null) { m_eventObj.Reset(); } // There is a race condition here. If another thread Sets the event, we will get into a state // where m_state will be unsignaled, yet the Win32 event object will have been signaled. // This could cause waiting threads to wake up even though the event is in an // unsignaled state. This is fine -- those that are calling Reset concurrently are // responsible for doing "the right thing" -- e.g. rechecking the condition and // resetting the event manually. // And finally set our state back to unsignaled. IsSet = false; } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set. /// </summary> /// <exception cref="System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal, /// while observing a <see cref="System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to /// observe.</param> /// <exception cref="System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="System.OperationCanceledException"><paramref name="cancellationToken"/> was /// canceled.</exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="int.MaxValue"/>.</exception> /// <exception cref="System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="System.TimeSpan"/> to measure the time interval, while observing a <see /// cref="System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="int.MaxValue"/>.</exception> /// <exception cref="System.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> /// <exception cref="System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a <see /// cref="System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="System.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); // an early convenience check if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } if (!IsSet) { if (millisecondsTimeout == 0) { // For 0-timeouts, we just return immediately. return false; } // We spin briefly before falling back to allocating and/or waiting on a true event. uint startTime = 0; bool bNeedTimeoutAdjustment = false; int realMillisecondsTimeout = millisecondsTimeout; // this will be adjusted if necessary. if (millisecondsTimeout != Timeout.Infinite) { // We will account for time spent spinning, so that we can decrement it from our // timeout. In most cases the time spent in this section will be negligible. But // we can't discount the possibility of our thread being switched out for a lengthy // period of time. The timeout adjustments only take effect when and if we actually // decide to block in the kernel below. startTime = TimeoutHelper.GetTime(); bNeedTimeoutAdjustment = true; } // Spin int spinCount = SpinCount; var spinner = new SpinWait(); while (spinner.Count < spinCount) { spinner.SpinOnce(sleep1Threshold: -1); if (IsSet) { return true; } if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count cancellationToken.ThrowIfCancellationRequested(); } // Now enter the lock and wait. Must be created before registering the cancellation callback, // which will try to take this lock. EnsureLockObjectCreated(); // We must register and unregister the token outside of the lock, to avoid deadlocks. using (cancellationToken.UnsafeRegister(s_cancellationTokenCallback, this)) { lock (m_lock!) { // Loop to cope with spurious wakeups from other waits being canceled while (!IsSet) { // If our token was canceled, we must throw and exit. cancellationToken.ThrowIfCancellationRequested(); // update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled) if (bNeedTimeoutAdjustment) { realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); if (realMillisecondsTimeout <= 0) return false; } // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock, // so after updating waiters, we must check IsSet again. // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the // read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange // operation which provides a full memory barrier. // If we see IsSet=false, then we are guaranteed that Set() will see that we are // waiting and will pulse the monitor correctly. Waiters++; if (IsSet) // This check must occur after updating Waiters. { Waiters--; // revert the increment. return true; } // Now finally perform the wait. try { // ** the actual wait ** if (!Monitor.Wait(m_lock, realMillisecondsTimeout)) return false; // return immediately if the timeout has expired. } finally { // Clean up: we're done waiting. Waiters--; } // Now just loop back around, and the right thing will happen. Either: // 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait) // or 2. the wait was successful. (the loop will break) } } } } // automatically disposes (and unregisters) the callback return true; // done. The wait was satisfied. } /// <summary> /// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; /// false to release only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(bool)"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if ((m_combinedState & Dispose_BitMask) != 0) return; // already disposed m_combinedState |= Dispose_BitMask; // set the dispose bit if (disposing) { // We will dispose of the event object. We do this under a lock to protect // against the race condition outlined in the Set method above. ManualResetEvent? eventObj = m_eventObj; if (eventObj != null) { lock (eventObj) { eventObj.Dispose(); m_eventObj = null; } } } } /// <summary> /// Throw ObjectDisposedException if the MRES is disposed /// </summary> private void ThrowIfDisposed() { if ((m_combinedState & Dispose_BitMask) != 0) throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed); } /// <summary> /// Private helper method to wake up waiters when a cancellationToken gets canceled. /// </summary> private static readonly Action<object?> s_cancellationTokenCallback = new Action<object?>(CancellationTokenCallback); private static void CancellationTokenCallback(object? obj) { Debug.Assert(obj is ManualResetEventSlim, "Expected a ManualResetEventSlim"); ManualResetEventSlim mre = (ManualResetEventSlim)obj; Debug.Assert(mre.m_lock != null); // the lock should have been created before this callback is registered for use. lock (mre.m_lock) { Monitor.PulseAll(mre.m_lock); // awaken all waiters } } /// <summary> /// Private helper method for updating parts of a bit-string state value. /// Mainly called from the IsSet and Waiters properties setters /// </summary> /// <remarks> /// Note: the parameter types must be int as CompareExchange cannot take a Uint /// </remarks> /// <param name="newBits">The new value</param> /// <param name="updateBitsMask">The mask used to set the bits</param> private void UpdateStateAtomically(int newBits, int updateBitsMask) { SpinWait sw = new SpinWait(); Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); while (true) { int oldState = m_combinedState; // cache the old value for testing in CAS // Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111] // then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111] int newState = (oldState & ~updateBitsMask) | newBits; if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState) { return; } sw.SpinOnce(sleep1Threshold: -1); } } /// <summary> /// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word. /// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> /// <param name="rightBitShiftCount"></param> /// <returns></returns> private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount) { // convert to uint before shifting so that right-shift does not replicate the sign-bit, // then convert back to int. return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount)); } /// <summary> /// Performs a Mask operation, but does not perform the shift. /// This is acceptable for boolean values for which the shift is unnecessary /// eg (val &amp; Mask) != 0 is an appropriate way to extract a boolean rather than using /// ((val &amp; Mask) &gt;&gt; shiftAmount) == 1 /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> private static int ExtractStatePortion(int state, int mask) { return state & mask; } } }
using System; using System.Collections.Generic; using Lucene.Net.Documents; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Search { using Index; using NUnit.Framework; using Support; using System.Threading.Tasks; using Util; /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SpanQuery = Lucene.Net.Search.Spans.SpanQuery; using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery; using Term = Lucene.Net.Index.Term; using TextField = TextField; [TestFixture] public class TestBooleanQuery : LuceneTestCase { [Test] public virtual void TestEquality() { BooleanQuery bq1 = new BooleanQuery(); bq1.Add(new TermQuery(new Term("field", "value1")), Occur.SHOULD); bq1.Add(new TermQuery(new Term("field", "value2")), Occur.SHOULD); BooleanQuery nested1 = new BooleanQuery(); nested1.Add(new TermQuery(new Term("field", "nestedvalue1")), Occur.SHOULD); nested1.Add(new TermQuery(new Term("field", "nestedvalue2")), Occur.SHOULD); bq1.Add(nested1, Occur.SHOULD); BooleanQuery bq2 = new BooleanQuery(); bq2.Add(new TermQuery(new Term("field", "value1")), Occur.SHOULD); bq2.Add(new TermQuery(new Term("field", "value2")), Occur.SHOULD); BooleanQuery nested2 = new BooleanQuery(); nested2.Add(new TermQuery(new Term("field", "nestedvalue1")), Occur.SHOULD); nested2.Add(new TermQuery(new Term("field", "nestedvalue2")), Occur.SHOULD); bq2.Add(nested2, Occur.SHOULD); Assert.IsTrue(bq1.Equals(bq2)); //Assert.AreEqual(bq1, bq2); } [Test] public virtual void TestException() { try { BooleanQuery.MaxClauseCount = 0; Assert.Fail(); } #pragma warning disable 168 catch (System.ArgumentException e) #pragma warning restore 168 { // okay } } // LUCENE-1630 [Test] public virtual void TestNullOrSubScorer() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(NewTextField("field", "a b c d", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.Reader; IndexSearcher s = NewSearcher(r); // this test relies upon coord being the default implementation, // otherwise scores are different! s.Similarity = new DefaultSimilarity(); BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("field", "a")), Occur.SHOULD); // LUCENE-2617: make sure that a term not in the index still contributes to the score via coord factor float score = s.Search(q, 10).MaxScore; Query subQuery = new TermQuery(new Term("field", "not_in_index")); subQuery.Boost = 0; q.Add(subQuery, Occur.SHOULD); float score2 = s.Search(q, 10).MaxScore; Assert.AreEqual(score * .5F, score2, 1e-6); // LUCENE-2617: make sure that a clause not in the index still contributes to the score via coord factor BooleanQuery qq = (BooleanQuery)q.Clone(); PhraseQuery phrase = new PhraseQuery(); phrase.Add(new Term("field", "not_in_index")); phrase.Add(new Term("field", "another_not_in_index")); phrase.Boost = 0; qq.Add(phrase, Occur.SHOULD); score2 = s.Search(qq, 10).MaxScore; Assert.AreEqual(score * (1 / 3F), score2, 1e-6); // now test BooleanScorer2 subQuery = new TermQuery(new Term("field", "b")); subQuery.Boost = 0; q.Add(subQuery, Occur.MUST); score2 = s.Search(q, 10).MaxScore; Assert.AreEqual(score * (2 / 3F), score2, 1e-6); // PhraseQuery w/ no terms added returns a null scorer PhraseQuery pq = new PhraseQuery(); q.Add(pq, Occur.SHOULD); Assert.AreEqual(1, s.Search(q, 10).TotalHits); // A required clause which returns null scorer should return null scorer to // IndexSearcher. q = new BooleanQuery(); pq = new PhraseQuery(); q.Add(new TermQuery(new Term("field", "a")), Occur.SHOULD); q.Add(pq, Occur.MUST); Assert.AreEqual(0, s.Search(q, 10).TotalHits); DisjunctionMaxQuery dmq = new DisjunctionMaxQuery(1.0f); dmq.Add(new TermQuery(new Term("field", "a"))); dmq.Add(pq); Assert.AreEqual(1, s.Search(dmq, 10).TotalHits); r.Dispose(); w.Dispose(); dir.Dispose(); } [Test] public virtual void TestDeMorgan() { Directory dir1 = NewDirectory(); RandomIndexWriter iw1 = new RandomIndexWriter(Random(), dir1, Similarity, TimeZone); Document doc1 = new Document(); doc1.Add(NewTextField("field", "foo bar", Field.Store.NO)); iw1.AddDocument(doc1); IndexReader reader1 = iw1.Reader; iw1.Dispose(); Directory dir2 = NewDirectory(); RandomIndexWriter iw2 = new RandomIndexWriter(Random(), dir2, Similarity, TimeZone); Document doc2 = new Document(); doc2.Add(NewTextField("field", "foo baz", Field.Store.NO)); iw2.AddDocument(doc2); IndexReader reader2 = iw2.Reader; iw2.Dispose(); BooleanQuery query = new BooleanQuery(); // Query: +foo -ba* query.Add(new TermQuery(new Term("field", "foo")), Occur.MUST); WildcardQuery wildcardQuery = new WildcardQuery(new Term("field", "ba*")); wildcardQuery.MultiTermRewriteMethod = (MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); query.Add(wildcardQuery, Occur.MUST_NOT); MultiReader multireader = new MultiReader(reader1, reader2); IndexSearcher searcher = NewSearcher(multireader); Assert.AreEqual(0, searcher.Search(query, 10).TotalHits); Task foo = new Task(TestDeMorgan); TaskScheduler es = TaskScheduler.Default; searcher = new IndexSearcher(multireader, es); if (VERBOSE) { Console.WriteLine("rewritten form: " + searcher.Rewrite(query)); } Assert.AreEqual(0, searcher.Search(query, 10).TotalHits); multireader.Dispose(); reader1.Dispose(); reader2.Dispose(); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestBS2DisjunctionNextVsAdvance() { Directory d = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), d, Similarity, TimeZone); int numDocs = AtLeast(300); for (int docUpto = 0; docUpto < numDocs; docUpto++) { string contents = "a"; if (Random().Next(20) <= 16) { contents += " b"; } if (Random().Next(20) <= 8) { contents += " c"; } if (Random().Next(20) <= 4) { contents += " d"; } if (Random().Next(20) <= 2) { contents += " e"; } if (Random().Next(20) <= 1) { contents += " f"; } Document doc = new Document(); doc.Add(new TextField("field", contents, Field.Store.NO)); w.AddDocument(doc); } w.ForceMerge(1); IndexReader r = w.Reader; IndexSearcher s = NewSearcher(r); w.Dispose(); for (int iter = 0; iter < 10 * RANDOM_MULTIPLIER; iter++) { if (VERBOSE) { Console.WriteLine("iter=" + iter); } IList<string> terms = new List<string>(Arrays.AsList("a", "b", "c", "d", "e", "f")); int numTerms = TestUtil.NextInt(Random(), 1, terms.Count); while (terms.Count > numTerms) { terms.RemoveAt(Random().Next(terms.Count)); } if (VERBOSE) { Console.WriteLine(" terms=" + terms); } BooleanQuery q = new BooleanQuery(); foreach (string term in terms) { q.Add(new BooleanClause(new TermQuery(new Term("field", term)), Occur.SHOULD)); } Weight weight = s.CreateNormalizedWeight(q); Scorer scorer = weight.GetScorer(s.m_leafContexts[0], null); // First pass: just use .NextDoc() to gather all hits IList<ScoreDoc> hits = new List<ScoreDoc>(); while (scorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { hits.Add(new ScoreDoc(scorer.DocID, scorer.GetScore())); } if (VERBOSE) { Console.WriteLine(" " + hits.Count + " hits"); } // Now, randomly next/advance through the list and // verify exact match: for (int iter2 = 0; iter2 < 10; iter2++) { weight = s.CreateNormalizedWeight(q); scorer = weight.GetScorer(s.m_leafContexts[0], null); if (VERBOSE) { Console.WriteLine(" iter2=" + iter2); } int upto = -1; while (upto < hits.Count) { int nextUpto; int nextDoc; int left = hits.Count - upto; if (left == 1 || Random().nextBoolean()) { // next nextUpto = 1 + upto; nextDoc = scorer.NextDoc(); } else { // advance int inc = TestUtil.NextInt(Random(), 1, left - 1); nextUpto = inc + upto; nextDoc = scorer.Advance(hits[nextUpto].Doc); } if (nextUpto == hits.Count) { Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, nextDoc); } else { ScoreDoc hit = hits[nextUpto]; Assert.AreEqual(hit.Doc, nextDoc); // Test for precise float equality: Assert.IsTrue(hit.Score == scorer.GetScore(), "doc " + hit.Doc + " has wrong score: expected=" + hit.Score + " actual=" + scorer.GetScore()); } upto = nextUpto; } } } r.Dispose(); d.Dispose(); } // LUCENE-4477 / LUCENE-4401: [Test] public virtual void TestBooleanSpanQuery() { bool failed = false; int hits = 0; Directory directory = NewDirectory(); Analyzer indexerAnalyzer = new MockAnalyzer(Random()); IndexWriterConfig config = new IndexWriterConfig(TEST_VERSION_CURRENT, indexerAnalyzer); IndexWriter writer = new IndexWriter(directory, config); string FIELD = "content"; Document d = new Document(); d.Add(new TextField(FIELD, "clockwork orange", Field.Store.YES)); writer.AddDocument(d); writer.Dispose(); IndexReader indexReader = DirectoryReader.Open(directory); IndexSearcher searcher = NewSearcher(indexReader); BooleanQuery query = new BooleanQuery(); SpanQuery sq1 = new SpanTermQuery(new Term(FIELD, "clockwork")); SpanQuery sq2 = new SpanTermQuery(new Term(FIELD, "clckwork")); query.Add(sq1, Occur.SHOULD); query.Add(sq2, Occur.SHOULD); TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, true); searcher.Search(query, collector); hits = collector.GetTopDocs().ScoreDocs.Length; foreach (ScoreDoc scoreDoc in collector.GetTopDocs().ScoreDocs) { Console.WriteLine(scoreDoc.Doc); } indexReader.Dispose(); Assert.AreEqual(failed, false, "Bug in boolean query composed of span queries"); Assert.AreEqual(hits, 1, "Bug in boolean query composed of span queries"); directory.Dispose(); } // LUCENE-5487 [Test] public virtual void TestInOrderWithMinShouldMatch() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); doc.Add(NewTextField("field", "some text here", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.Reader; w.Dispose(); IndexSearcher s = new IndexSearcherAnonymousInnerClassHelper(this, r); BooleanQuery bq = new BooleanQuery(); bq.Add(new TermQuery(new Term("field", "some")), Occur.SHOULD); bq.Add(new TermQuery(new Term("field", "text")), Occur.SHOULD); bq.Add(new TermQuery(new Term("field", "here")), Occur.SHOULD); bq.MinimumNumberShouldMatch = 2; s.Search(bq, 10); r.Dispose(); dir.Dispose(); } private class IndexSearcherAnonymousInnerClassHelper : IndexSearcher { private readonly TestBooleanQuery OuterInstance; public IndexSearcherAnonymousInnerClassHelper(TestBooleanQuery outerInstance, IndexReader r) : base(r) { this.OuterInstance = outerInstance; } protected override void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector) { Assert.AreEqual(-1, collector.GetType().Name.IndexOf("OutOfOrder")); base.Search(leaves, weight, collector); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.Security.Tokens.IssuedSecurityTokenParameters.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.Security.Tokens { public partial class IssuedSecurityTokenParameters : SecurityTokenParameters { #region Methods and constructors protected override SecurityTokenParameters CloneCore() { return default(SecurityTokenParameters); } protected internal override System.IdentityModel.Tokens.SecurityKeyIdentifierClause CreateKeyIdentifierClause(System.IdentityModel.Tokens.SecurityToken token, SecurityTokenReferenceStyle referenceStyle) { return default(System.IdentityModel.Tokens.SecurityKeyIdentifierClause); } public System.Collections.ObjectModel.Collection<System.Xml.XmlElement> CreateRequestParameters(System.ServiceModel.MessageSecurityVersion messageSecurityVersion, System.IdentityModel.Selectors.SecurityTokenSerializer securityTokenSerializer) { Contract.Ensures(Contract.Result<System.Collections.ObjectModel.Collection<System.Xml.XmlElement>>() != null); return default(System.Collections.ObjectModel.Collection<System.Xml.XmlElement>); } protected internal override void InitializeSecurityTokenRequirement(System.IdentityModel.Selectors.SecurityTokenRequirement requirement) { } protected IssuedSecurityTokenParameters(IssuedSecurityTokenParameters other) { Contract.Requires(other != null); } public IssuedSecurityTokenParameters(string tokenType, System.ServiceModel.EndpointAddress issuerAddress) { } public IssuedSecurityTokenParameters(string tokenType) { } public IssuedSecurityTokenParameters() { } public IssuedSecurityTokenParameters(string tokenType, System.ServiceModel.EndpointAddress issuerAddress, System.ServiceModel.Channels.Binding issuerBinding) { } #endregion #region Properties and indexers public System.Collections.ObjectModel.Collection<System.Xml.XmlElement> AdditionalRequestParameters { get { return default(System.Collections.ObjectModel.Collection<System.Xml.XmlElement>); } } public System.Collections.ObjectModel.Collection<ClaimTypeRequirement> ClaimTypeRequirements { get { return default(System.Collections.ObjectModel.Collection<ClaimTypeRequirement>); } } public System.ServiceModel.MessageSecurityVersion DefaultMessageSecurityVersion { get { return default(System.ServiceModel.MessageSecurityVersion); } set { } } internal protected override bool HasAsymmetricKey { get { return default(bool); } } public System.ServiceModel.EndpointAddress IssuerAddress { get { return default(System.ServiceModel.EndpointAddress); } set { } } public System.ServiceModel.Channels.Binding IssuerBinding { get { return default(System.ServiceModel.Channels.Binding); } set { } } public System.ServiceModel.EndpointAddress IssuerMetadataAddress { get { return default(System.ServiceModel.EndpointAddress); } set { } } public int KeySize { get { return default(int); } set { } } public System.IdentityModel.Tokens.SecurityKeyType KeyType { get { return default(System.IdentityModel.Tokens.SecurityKeyType); } set { } } internal protected override bool SupportsClientAuthentication { get { return default(bool); } } internal protected override bool SupportsClientWindowsIdentity { get { return default(bool); } } internal protected override bool SupportsServerAuthentication { get { return default(bool); } } public string TokenType { get { return default(string); } set { } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using AxiomCoders.SharedNet20.Forms; using AxiomCoders.PdfTemplateEditor.EditorStuff; using AxiomCoders.SharedNet20; namespace AxiomCoders.PdfTemplateEditor.Forms { public partial class DataStreamForm : formBase { private List<DataStream> tempDataStreams = new List<DataStream>(); private List<renamedItems> tempRenamed = new List<renamedItems>(); protected override void OnHelpRequested(HelpEventArgs hevent) { } public DataStreamForm() { InitializeComponent(); } private void DataStreamForm_Shown(object sender, EventArgs e) { UpdateToTempData(); RefreshTreeItems(""); } private void UpdateToTempData() { foreach (DataStream tmpData in EditorController.Instance.EditorProject.DataStreams) { DataStream tmpDataStream = new DataStream(); tmpDataStream.Name = tmpData.Name; foreach(Column tmpColumn in tmpData.Columns) { Column tmpColumnData = new Column(); tmpColumnData.Name = tmpColumn.Name; tmpDataStream.Columns.Add(tmpColumnData); } tempDataStreams.Add(tmpDataStream); } } private void UpdateFromTempData() { EditorController.Instance.EditorProject.DataStreams.Clear(); foreach(DataStream tmpData in tempDataStreams) { DataStream tmpDataStream = new DataStream(); tmpDataStream.Name = tmpData.Name; foreach(Column tmpColumn in tmpData.Columns) { Column tmpColumnData = new Column(); tmpColumnData.Name = tmpColumn.Name; tmpDataStream.Columns.Add(tmpColumnData); } EditorController.Instance.EditorProject.DataStreams.Add(tmpDataStream); } foreach(renamedItems renItem in tempRenamed) { foreach(EditorItem item in EditorController.Instance.EditorProject.Children) { RenameDataAndColumn(item, renItem); } } } private void RenameDataAndColumn(EditorItem newItem, renamedItems renItem) { string tmpColumnString; foreach(EditorItem item in newItem.Children) { RenameDataAndColumn(item, renItem); if(item is DynamicEditorItemInterface) { DynamicEditorItemInterface tmp = (DynamicEditorItemInterface)item; if(renItem.type == 0) { if(tmp.SourceDataStream == renItem.befoure) { tmpColumnString = tmp.SourceColumn; tmp.SourceDataStream = renItem.after; tmp.SourceColumn = tmpColumnString; } }else if(renItem.type == 1) { if(tmp.SourceColumn == renItem.befoure) { tmp.SourceColumn = renItem.after; } } } } } private void Add_DataStream(string name) { DataStream tmpDS = new DataStream(); tmpDS.Name = name; //EditorController.Instance.EditorProject.DataStreams.Add(tmpDS); tempDataStreams.Add(tmpDS); RefreshTreeItems(name); } private void Add_Column(string dataStreamParent, string name) { foreach(DataStream tmpParent in tempDataStreams) { if(tmpParent.Name == dataStreamParent) { Column tmpColumn = new Column(); tmpColumn.Name = name; tmpParent.Columns.Add(tmpColumn); RefreshTreeItems(tmpParent.Name); return; } } } private void Remove_DataStream(string name) { foreach(DataStream tmpDS in tempDataStreams) { if (tmpDS.Name == name) { tempDataStreams.Remove(tmpDS); RefreshTreeItems(""); return; } } } private void Remove_Column(string name) { foreach(DataStream tmpDS in tempDataStreams) { foreach (Column tmpCol in tmpDS.Columns) { if (tmpCol.Name == name) { tmpDS.Columns.Remove(tmpCol); RefreshTreeItems(""); return; } } } } private void RefreshTreeItems(string nameToSelect) { DataStreamColections.Nodes.Clear(); foreach(DataStream tmpData in tempDataStreams) { TreeNode parentNode = DataStreamColections.Nodes.Add(tmpData.Name); if (nameToSelect == tmpData.Name) { DataStreamColections.SelectedNode = parentNode; DataStreamColections_AfterSelect(null, null); } foreach (Column tmpCol in tmpData.Columns) { TreeNode tmpNode = parentNode.Nodes.Add(tmpCol.Name); } } DataStreamColections.ExpandAll(); } /// <summary> /// Adds data stream to root tree /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddDataStream_Click(object sender, EventArgs e) { UserTextInput txtInput = new UserTextInput(); txtInput.Text = "Add data stream"; txtInput.TextBoxTitle = "Enter name..."; //txtInput.ShowDialog(); if(txtInput.ShowDialog() == DialogResult.OK) { Add_DataStream(txtInput.ReturnText); } } /// <summary> /// Adds column to specific selected data stream /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddColumn_Click(object sender, EventArgs e) { TreeNode parentNode = DataStreamColections.SelectedNode; if(parentNode.Level != 0) { return; } UserTextInput txtInput = new UserTextInput(); txtInput.Text = "Add column"; txtInput.TextBoxTitle = "Enter name..."; //txtInput.ShowDialog(); if(txtInput.ShowDialog() == DialogResult.OK) { Add_Column(parentNode.Text, txtInput.ReturnText); } } /// <summary> /// Pure visual contest, enables or disables some buttons... /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DataStreamColections_AfterSelect(object sender, TreeViewEventArgs e) { if (DataStreamColections.SelectedNode == null) { RemoveDataStream.Enabled = false; AddColumn.Enabled = false; RemoveColumn.Enabled = false; RenameColumn.Enabled = false; RenameDataStream.Enabled = false; ColumnTypeDrop.Enabled = false; return; } switch (DataStreamColections.SelectedNode.Level) { case 0: AddColumn.Enabled = true; RemoveColumn.Enabled = false; RenameColumn.Enabled = false; ColumnTypeDrop.Enabled = false; RenameDataStream.Enabled = true; RemoveDataStream.Enabled = true; break; case 1: AddColumn.Enabled = false; RemoveColumn.Enabled = true; RenameColumn.Enabled = true; ColumnTypeDrop.Enabled = true; RemoveDataStream.Enabled = false; RenameDataStream.Enabled = false; break; } } /// <summary> /// Removes selected data stream /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RemoveDataStream_Click(object sender, EventArgs e) { if(DataStreamColections.SelectedNode == null) { MessageBox.Show("You must select Data Stream", "Remove Data stream...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if(DataStreamColections.SelectedNode.Level == 0) { if(DialogResult.Yes == MessageBox.Show("You want to delete Data Stream: "+DataStreamColections.SelectedNode.Text,"Remove Data Stream...", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { //DataStreamColections.Nodes.Remove(DataStreamColections.SelectedNode); Remove_DataStream(DataStreamColections.SelectedNode.Text); DataStreamColections_AfterSelect(null, null); } } } /// <summary> /// Removes selected column /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RemoveColumn_Click(object sender, EventArgs e) { if(DataStreamColections.SelectedNode == null) { MessageBox.Show("You must select Column", "Remove Column...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if(DataStreamColections.SelectedNode.Level == 1) { if(DialogResult.Yes == MessageBox.Show("You want to delete Column: " + DataStreamColections.SelectedNode.Text, "Remove Column...", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { //DataStreamColections.Nodes.Remove(DataStreamColections.SelectedNode); Remove_Column(DataStreamColections.SelectedNode.Text); DataStreamColections_AfterSelect(null, null); } } } private void RenameDataStream_Click(object sender, EventArgs e) { UserTextInput tmpTx = new UserTextInput(); renamedItems tmpRenamedItem; tmpTx.Text = "Rename"; tmpTx.TextBoxTitle = "Enter new name..."; foreach(DataStream tmpDS in tempDataStreams) { if(tmpDS.Name == DataStreamColections.SelectedNode.Text) { tmpTx.ReturnText = tmpDS.Name; } } //tmpTx.ShowDialog(); if(tmpTx.ShowDialog() == DialogResult.OK) { foreach(DataStream tmpDS in tempDataStreams) { if(tmpDS.Name == DataStreamColections.SelectedNode.Text) { tmpRenamedItem = new renamedItems(); tmpRenamedItem.befoure = tmpDS.Name; tmpRenamedItem.after = tmpTx.ReturnText; tmpRenamedItem.type = 0; tempRenamed.Add(tmpRenamedItem); tmpDS.Name = tmpTx.ReturnText; RefreshTreeItems(""); return; } } } } private void RenameColumn_Click(object sender, EventArgs e) { renamedItems tmpRenamedItem; UserTextInput tmpTx = new UserTextInput(); tmpTx.ReturnText = DataStreamColections.SelectedNode.Text; tmpTx.Text = "Rename"; tmpTx.TextBoxTitle = "Enter new name..."; foreach(DataStream tmpDS in tempDataStreams) { if(tmpDS.Name == DataStreamColections.SelectedNode.Parent.Text) { foreach(Column tmpCol in tmpDS.Columns) { if(tmpCol.Name == DataStreamColections.SelectedNode.Text) { tmpTx.ReturnText = tmpCol.Name; } } } } //tmpTx.ShowDialog(); if(tmpTx.ShowDialog() == DialogResult.OK) { foreach(DataStream tmpDS in tempDataStreams) { if(tmpDS.Name == DataStreamColections.SelectedNode.Parent.Text) { foreach(Column tmpCol in tmpDS.Columns) { if(tmpCol.Name == DataStreamColections.SelectedNode.Text) { tmpRenamedItem = new renamedItems(); tmpRenamedItem.befoure = tmpCol.Name; tmpRenamedItem.after = tmpTx.ReturnText; tmpRenamedItem.type = 1; tempRenamed.Add(tmpRenamedItem); tmpCol.Name = tmpTx.ReturnText; RefreshTreeItems(""); return; } } } } } } private void StringType_Click(object sender, EventArgs e) { //foreach(DataStream tmpDS in EditorController.Instance.EditorProject.DataStreams) //{ // if(tmpDS.Name == DataStreamColections.SelectedNode.Parent.Text) // { // foreach(Column tmpCol in tmpDS.Columns) // { // if(tmpCol.Name == DataStreamColections.SelectedNode.Text) // { // tmpCol.Type = ""; // return; // } // } // } //} } private void IntType_Click(object sender, EventArgs e) { //foreach(DataStream tmpDS in EditorController.Instance.EditorProject.DataStreams) //{ // if(tmpDS.Name == DataStreamColections.SelectedNode.Parent.Text) // { // foreach(Column tmpCol in tmpDS.Columns) // { // if(tmpCol.Name == DataStreamColections.SelectedNode.Text) // { // tmpCol.Type = "int"; // return; // } // } // } //} } private void FloatType_Click(object sender, EventArgs e) { //foreach(DataStream tmpDS in EditorController.Instance.EditorProject.DataStreams) //{ // if(tmpDS.Name == DataStreamColections.SelectedNode.Parent.Text) // { // foreach(Column tmpCol in tmpDS.Columns) // { // if(tmpCol.Name == DataStreamColections.SelectedNode.Text) // { // tmpCol.Type = "float"; // return; // } // } // } //} } private void btnOk_Click(object sender, EventArgs e) { UpdateFromTempData(); EditorController.Instance.ProjectSaved = false; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void btnHelp_Click(object sender, EventArgs e) { ProductHelp.OpenHelpTopic(this, "PDF%20Reports%20Template%20Editor_Manage%20DataStreams.html"); } } public class renamedItems { public int type; public string befoure; public string after; } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Channels; using System.Text.RegularExpressions; using Sprache; namespace d60.Cirqus.Identity { public class KeyFormat { const string guidPattern = "[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; const string sguidPattern = "[A-Za-z0-9\\-_]{22}"; static readonly IDictionary<Type, KeyFormat> formatByType; static KeyFormat() { formatByType = new ConcurrentDictionary<Type, KeyFormat>(); SeparatorCharacter = '-'; DefaultUniquenessTerm = "guid"; } public static char SeparatorCharacter { get; set; } public static string DefaultUniquenessTerm { get; set; } readonly Regex pattern; public KeyFormat(params Term[] terms) : this((IEnumerable<Term>)terms) { } public KeyFormat(IEnumerable<Term> terms) { Terms = terms.ToList(); pattern = ToRegex(); } public IReadOnlyList<Term> Terms { get; private set; } public static void For<T>(string input) { var format = FromString(input); if (!format.Terms.Any(x => x is LiteralText)) throw new ParseException("Format must contain a unique text identifying the type of id."); formatByType.Add(typeof(T), format); } public static Type GetTypeById(string id) { return formatByType.Single(x => x.Value.Matches(id)).Key; } public static KeyFormat Get<T>() { KeyFormat value; if (!formatByType.TryGetValue(typeof (T), out value)) { return FromString(""); } return value; } public static KeyFormat FromString(string format) { return new KeyFormatParser(SeparatorCharacter, DefaultUniquenessTerm).Execute(format); } public bool Matches(string id) { return pattern.IsMatch(id); } public Id<T> Compile<T>(params object[] args) { var placeholderIndex = 0; return new Id<T>(this, string.Join(SeparatorCharacter.ToString(), Terms.Select(term => new Switch<string>(term) .Match((LiteralText t) => t.Text) .Match((GuidKeyword t) => Guid.NewGuid().ToString()) .Match((SGuidKeyword t) => ToSGuid(Guid.NewGuid())) .Match((Placeholder t) => { if (placeholderIndex >= args.Length) { if (!string.IsNullOrEmpty(t.Property)) { throw new InvalidOperationException(string.Format( "You did not supply a value for the placeholder '{0}' at position {1}", t.Property, placeholderIndex)); } throw new InvalidOperationException(string.Format( "You did not supply a value for the *-placeholder or {{}}-placeholder at position {0}", placeholderIndex)); } return args[placeholderIndex++].ToString(); }) .OrThrow(new ArgumentOutOfRangeException())))); } public string Normalize(string id) { var match = pattern.Match(id); if (!match.Success) { throw new InvalidOperationException(string.Format( "The string '{0}' does not match the expected input '{1}'.", id, ToString())); } return string.Join(SeparatorCharacter.ToString(), Terms.Select((term, i) => { var value = match.Groups[i+1].Value; return new Switch<string>(term) .Match((LiteralText t) => t.Text) .Match((GuidKeyword t) => value) .Match((SGuidKeyword t) => { Guid guid; return Guid.TryParse(value, out guid) ? ToSGuid(guid) : value; }) .Match((Placeholder t) => value) .OrThrow(new ArgumentOutOfRangeException()); })); } public void Apply(object target, string id) { var match = pattern.Match(id); var i = 0; foreach (var term in Terms) { i++; var placeholder = term as Placeholder; if (placeholder == null || string.IsNullOrEmpty(placeholder.Property)) continue; var property = target.GetType().GetProperty(placeholder.Property); var value = match.Groups[i].Value; var convertedValue = new Switch<object>(property.PropertyType) .Match<string>(() => value) .Match<int>(() => int.Parse(value)) .Match<long>(() => long.Parse(value)) .OrThrow(new ArgumentOutOfRangeException()); property.SetValue(target, convertedValue); } } public string Get(string key, string id) { var match = pattern.Match(id); var i = 0; foreach (var term in Terms) { i++; var placeholder = term as Placeholder; if (placeholder == null || string.IsNullOrEmpty(placeholder.Property)) continue; if (placeholder.Property == key) { return match.Groups[i].Value; } } throw new IndexOutOfRangeException(); } public override string ToString() { return string.Join(SeparatorCharacter.ToString(), Terms.Select(term => new Switch<string>(term) .Match((LiteralText t) => t.Text) .Match((GuidKeyword t) => "guid") .Match((SGuidKeyword t) => "sguid") .Match((Placeholder t) => string.IsNullOrEmpty(t.Property) ? "*" : "{" + t.Property + "}") .OrThrow(new ArgumentOutOfRangeException()))); } protected bool Equals(KeyFormat other) { return pattern.ToString().Equals(other.pattern.ToString()); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((KeyFormat) obj); } public override int GetHashCode() { return pattern.ToString().GetHashCode(); } public static string ToSGuid(Guid guid) { return Convert.ToBase64String(guid.ToByteArray()) .Replace("/", "_") .Replace("+", "-") .Substring(0, 22); } public static Guid FromSGuid(string sguid) { return new Guid( Convert.FromBase64String(sguid .Replace("_", "/") .Replace("-", "+") + "==")); } Regex ToRegex() { return new Regex(string.Format("^{0}$", string.Join(SeparatorCharacter.ToString(), Terms.Select(term => new Switch<string>(term) .Match((LiteralText t) => t.Text) .Match((GuidKeyword t) => guidPattern) .Match((SGuidKeyword t) => "(?:" + guidPattern + ")|(?:" + sguidPattern + ")") .Match((Placeholder t) => @"[^/]+") .OrThrow(new ArgumentOutOfRangeException())) .Select(x => string.Format("({0})", x))))); } static KeyFormat InjectGuidsInConstantIds(KeyFormat result) { return result.Terms.All(x => x is LiteralText) ? new KeyFormat(result.Terms.Concat(new[] { new GuidKeyword() })) : result; } public interface Term { } public class LiteralText : Term { public LiteralText(string text) { Text = text; } public string Text { get; private set; } } public class GuidKeyword : Term {} public class SGuidKeyword : Term {} public class Placeholder : Term { public Placeholder(string property) { Property = property; } public string Property { get; private set; } } } }
using UnityEditor; using UnityEngine; using System.Collections.Generic; [CanEditMultipleObjects] [CustomEditor(typeof(tk2dSprite))] class tk2dSpriteEditor : Editor { // Serialized properties are going to be far too much hassle private tk2dBaseSprite[] targetSprites = new tk2dBaseSprite[0]; public override void OnInspectorGUI() { DrawSpriteEditorGUI(); } public void OnSceneGUI() { if (tk2dPreferences.inst.enableSpriteHandles == false) return; tk2dSprite spr = (tk2dSprite)target; var sprite = spr.CurrentSprite; if (sprite == null) { return; } Transform t = spr.transform; Bounds b = spr.GetUntrimmedBounds(); Rect localRect = new Rect(b.min.x, b.min.y, b.size.x, b.size.y); // Draw rect outline Handles.color = new Color(1,1,1,0.5f); tk2dSceneHelper.DrawRect (localRect, t); Handles.BeginGUI (); // Resize handles if (tk2dSceneHelper.RectControlsToggle ()) { EditorGUI.BeginChangeCheck (); Rect resizeRect = tk2dSceneHelper.RectControl (999888, localRect, t); if (EditorGUI.EndChangeCheck ()) { Undo.RegisterUndo (new Object[] {t, spr}, "Resize"); spr.ReshapeBounds(new Vector3(resizeRect.xMin, resizeRect.yMin) - new Vector3(localRect.xMin, localRect.yMin), new Vector3(resizeRect.xMax, resizeRect.yMax) - new Vector3(localRect.xMax, localRect.yMax)); EditorUtility.SetDirty(spr); } } // Rotate handles if (!tk2dSceneHelper.RectControlsToggle ()) { EditorGUI.BeginChangeCheck(); float theta = tk2dSceneHelper.RectRotateControl (888999, localRect, t, new List<int>()); if (EditorGUI.EndChangeCheck()) { Undo.RegisterUndo (t, "Rotate"); if (Mathf.Abs(theta) > Mathf.Epsilon) { t.Rotate(t.forward, theta, Space.World); } } } Handles.EndGUI (); // Sprite selecting tk2dSceneHelper.HandleSelectSprites(); // Move targeted sprites tk2dSceneHelper.HandleMoveSprites(t, localRect); if (GUI.changed) { EditorUtility.SetDirty(target); } } protected T[] GetTargetsOfType<T>( Object[] objects ) where T : UnityEngine.Object { List<T> ts = new List<T>(); foreach (Object o in objects) { T s = o as T; if (s != null) ts.Add(s); } return ts.ToArray(); } protected void OnEnable() { targetSprites = GetTargetsOfType<tk2dBaseSprite>( targets ); } void OnDestroy() { targetSprites = new tk2dBaseSprite[0]; tk2dSpriteThumbnailCache.Done(); tk2dGrid.Done(); tk2dEditorSkin.Done(); } // Callback and delegate void SpriteChangedCallbackImpl(tk2dSpriteCollectionData spriteCollection, int spriteId, object data) { Undo.RegisterUndo(targetSprites, "Sprite Change"); foreach (tk2dBaseSprite s in targetSprites) { s.SetSprite(spriteCollection, spriteId); s.EditMode__CreateCollider(); EditorUtility.SetDirty(s); } } tk2dSpriteGuiUtility.SpriteChangedCallback _spriteChangedCallbackInstance = null; tk2dSpriteGuiUtility.SpriteChangedCallback spriteChangedCallbackInstance { get { if (_spriteChangedCallbackInstance == null) { _spriteChangedCallbackInstance = new tk2dSpriteGuiUtility.SpriteChangedCallback( SpriteChangedCallbackImpl ); } return _spriteChangedCallbackInstance; } } protected void DrawSpriteEditorGUI() { Event ev = Event.current; tk2dSpriteGuiUtility.SpriteSelector( targetSprites[0].Collection, targetSprites[0].spriteId, spriteChangedCallbackInstance, null ); if (targetSprites[0].Collection != null) { if (tk2dPreferences.inst.displayTextureThumbs) { tk2dBaseSprite sprite = targetSprites[0]; tk2dSpriteDefinition def = sprite.GetCurrentSpriteDef(); if (sprite.Collection.version < 1 || def.texelSize == Vector2.zero) { string message = ""; message = "No thumbnail data."; if (sprite.Collection.version < 1) message += "\nPlease rebuild Sprite Collection."; tk2dGuiUtility.InfoBox(message, tk2dGuiUtility.WarningLevel.Info); } else { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); int tileSize = 128; Rect r = GUILayoutUtility.GetRect(tileSize, tileSize, GUILayout.ExpandWidth(false)); tk2dGrid.Draw(r); tk2dSpriteThumbnailCache.DrawSpriteTextureInRect(r, def, Color.white); GUILayout.EndHorizontal(); r = GUILayoutUtility.GetLastRect(); if (ev.type == EventType.MouseDown && ev.button == 0 && r.Contains(ev.mousePosition)) { tk2dSpriteGuiUtility.SpriteSelectorPopup( sprite.Collection, sprite.spriteId, spriteChangedCallbackInstance, null ); } } } Color newColor = EditorGUILayout.ColorField("Color", targetSprites[0].color); if (newColor != targetSprites[0].color) { Undo.RegisterUndo(targetSprites, "Sprite Color"); foreach (tk2dBaseSprite s in targetSprites) { s.color = newColor; } } int sortingOrder = EditorGUILayout.IntField("Sorting Order In Layer", targetSprites[0].SortingOrder); if (sortingOrder != targetSprites[0].SortingOrder) { Undo.RegisterUndo(targetSprites, "Sorting Order In Layer"); foreach (tk2dBaseSprite s in targetSprites) { s.SortingOrder = sortingOrder; } } Vector3 newScale = EditorGUILayout.Vector3Field("Scale", targetSprites[0].scale); if (newScale != targetSprites[0].scale) { Undo.RegisterUndo(targetSprites, "Sprite Scale"); foreach (tk2dBaseSprite s in targetSprites) { s.scale = newScale; s.EditMode__CreateCollider(); } } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("HFlip", EditorStyles.miniButton)) { Undo.RegisterUndo(targetSprites, "Sprite HFlip"); foreach (tk2dBaseSprite sprite in targetSprites) { sprite.EditMode__CreateCollider(); Vector3 scale = sprite.scale; scale.x *= -1.0f; sprite.scale = scale; } GUI.changed = true; } if (GUILayout.Button("VFlip", EditorStyles.miniButton)) { Undo.RegisterUndo(targetSprites, "Sprite VFlip"); foreach (tk2dBaseSprite sprite in targetSprites) { Vector3 s = sprite.scale; s.y *= -1.0f; sprite.scale = s; GUI.changed = true; } } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Reset Scale", "Set scale to 1"), EditorStyles.miniButton)) { Undo.RegisterUndo(targetSprites, "Sprite Reset Scale"); foreach (tk2dBaseSprite sprite in targetSprites) { Vector3 s = sprite.scale; s.x = Mathf.Sign(s.x); s.y = Mathf.Sign(s.y); s.z = Mathf.Sign(s.z); sprite.scale = s; GUI.changed = true; } } if (GUILayout.Button(new GUIContent("Bake Scale", "Transfer scale from transform.scale -> sprite"), EditorStyles.miniButton)) { Undo.RegisterSceneUndo("Bake Scale"); foreach (tk2dBaseSprite sprite in targetSprites) { tk2dScaleUtility.Bake(sprite.transform); } GUI.changed = true; } GUIContent pixelPerfectButton = new GUIContent("1:1", "Make Pixel Perfect for camera"); if ( GUILayout.Button(pixelPerfectButton, EditorStyles.miniButton )) { if (tk2dPixelPerfectHelper.inst) tk2dPixelPerfectHelper.inst.Setup(); Undo.RegisterUndo(targetSprites, "Sprite Pixel Perfect"); foreach (tk2dBaseSprite sprite in targetSprites) { sprite.MakePixelPerfect(); } GUI.changed = true; } EditorGUILayout.EndHorizontal(); } else { tk2dGuiUtility.InfoBox("Please select a sprite collection.", tk2dGuiUtility.WarningLevel.Error); } bool needUpdatePrefabs = false; if (GUI.changed) { foreach (tk2dBaseSprite sprite in targetSprites) { #if !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4) if (PrefabUtility.GetPrefabType(sprite) == PrefabType.Prefab) needUpdatePrefabs = true; #endif EditorUtility.SetDirty(sprite); } } // This is a prefab, and changes need to be propagated. This isn't supported in Unity 3.4 if (needUpdatePrefabs) { #if !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4) // Rebuild prefab instances tk2dBaseSprite[] allSprites = Resources.FindObjectsOfTypeAll(typeof(tk2dBaseSprite)) as tk2dBaseSprite[]; foreach (var spr in allSprites) { if (PrefabUtility.GetPrefabType(spr) == PrefabType.PrefabInstance) { Object parent = PrefabUtility.GetPrefabParent(spr.gameObject); bool found = false; foreach (tk2dBaseSprite sprite in targetSprites) { if (sprite.gameObject == parent) { found = true; break; } } if (found) { // Reset all prefab states var propMod = PrefabUtility.GetPropertyModifications(spr); PrefabUtility.ResetToPrefabState(spr); PrefabUtility.SetPropertyModifications(spr, propMod); spr.ForceBuild(); } } } #endif } } void PerformActionOnSelection(string actionName, System.Action<GameObject> action) { Undo.RegisterSceneUndo(actionName); foreach (tk2dBaseSprite sprite in targetSprites) { action(sprite.gameObject); } } static void PerformActionOnGlobalSelection(string actionName, System.Action<GameObject> action) { Undo.RegisterSceneUndo(actionName); foreach (GameObject go in Selection.gameObjects) { if (go.GetComponent<tk2dBaseSprite>() != null) { action(go); } } } static void ConvertSpriteType(GameObject go, System.Type targetType) { tk2dBaseSprite spr = go.GetComponent<tk2dBaseSprite>(); System.Type sourceType = spr.GetType(); if (sourceType != targetType) { tk2dBatchedSprite batchedSprite = new tk2dBatchedSprite(); tk2dStaticSpriteBatcherEditor.FillBatchedSprite(batchedSprite, go); if (targetType == typeof(tk2dSprite)) batchedSprite.type = tk2dBatchedSprite.Type.Sprite; else if (targetType == typeof(tk2dTiledSprite)) batchedSprite.type = tk2dBatchedSprite.Type.TiledSprite; else if (targetType == typeof(tk2dSlicedSprite)) batchedSprite.type = tk2dBatchedSprite.Type.SlicedSprite; else if (targetType == typeof(tk2dClippedSprite)) batchedSprite.type = tk2dBatchedSprite.Type.ClippedSprite; Object.DestroyImmediate(spr, true); bool sourceHasDimensions = sourceType == typeof(tk2dSlicedSprite) || sourceType == typeof(tk2dTiledSprite); bool targetHasDimensions = targetType == typeof(tk2dSlicedSprite) || targetType == typeof(tk2dTiledSprite); // Some minor fixups if (!sourceHasDimensions && targetHasDimensions) { batchedSprite.Dimensions = new Vector2(100, 100); } if (targetType == typeof(tk2dClippedSprite)) { batchedSprite.ClippedSpriteRegionBottomLeft = Vector2.zero; batchedSprite.ClippedSpriteRegionTopRight = Vector2.one; } if (targetType == typeof(tk2dSlicedSprite)) { batchedSprite.SlicedSpriteBorderBottomLeft = new Vector2(0.1f, 0.1f); batchedSprite.SlicedSpriteBorderTopRight = new Vector2(0.1f, 0.1f); } tk2dStaticSpriteBatcherEditor.RestoreBatchedSprite(go, batchedSprite); } } [MenuItem("CONTEXT/tk2dBaseSprite/Convert to Sprite")] static void DoConvertSprite() { PerformActionOnGlobalSelection( "Convert to Sprite", (go) => ConvertSpriteType(go, typeof(tk2dSprite)) ); } [MenuItem("CONTEXT/tk2dBaseSprite/Convert to Sliced Sprite")] static void DoConvertSlicedSprite() { PerformActionOnGlobalSelection( "Convert to Sliced Sprite", (go) => ConvertSpriteType(go, typeof(tk2dSlicedSprite)) ); } [MenuItem("CONTEXT/tk2dBaseSprite/Convert to Tiled Sprite")] static void DoConvertTiledSprite() { PerformActionOnGlobalSelection( "Convert to Tiled Sprite", (go) => ConvertSpriteType(go, typeof(tk2dTiledSprite)) ); } [MenuItem("CONTEXT/tk2dBaseSprite/Convert to Clipped Sprite")] static void DoConvertClippedSprite() { PerformActionOnGlobalSelection( "Convert to Clipped Sprite", (go) => ConvertSpriteType(go, typeof(tk2dClippedSprite)) ); } [MenuItem("CONTEXT/tk2dBaseSprite/Add animator", true, 10000)] static bool ValidateAddAnimator() { if (Selection.activeGameObject == null) return false; return Selection.activeGameObject.GetComponent<tk2dSpriteAnimator>() == null; } [MenuItem("CONTEXT/tk2dBaseSprite/Add animator", false, 10000)] static void DoAddAnimator() { tk2dSpriteAnimation anim = null; int clipId = -1; if (!tk2dSpriteAnimatorEditor.GetDefaultSpriteAnimation(out anim, out clipId)) { EditorUtility.DisplayDialog("Create Sprite Animation", "Unable to create animated sprite as no SpriteAnimations have been found.", "Ok"); return; } else { PerformActionOnGlobalSelection("Add animator", delegate(GameObject go) { tk2dSpriteAnimator animator = go.GetComponent<tk2dSpriteAnimator>(); if (animator == null) { animator = go.AddComponent<tk2dSpriteAnimator>(); animator.Library = anim; animator.DefaultClipId = clipId; tk2dSpriteAnimationClip clip = anim.GetClipById(clipId); animator.SetSprite( clip.frames[0].spriteCollection, clip.frames[0].spriteId ); } }); } } [MenuItem("CONTEXT/tk2dBaseSprite/Add AttachPoint", false, 10002)] static void DoRemoveAnimator() { PerformActionOnGlobalSelection("Add AttachPoint", delegate(GameObject go) { tk2dSpriteAttachPoint ap = go.GetComponent<tk2dSpriteAttachPoint>(); if (ap == null) { go.AddComponent<tk2dSpriteAttachPoint>(); } }); } [MenuItem("GameObject/Create Other/tk2d/Sprite", false, 12900)] static void DoCreateSpriteObject() { tk2dSpriteGuiUtility.GetSpriteCollectionAndCreate( (sprColl) => { GameObject go = tk2dEditorUtility.CreateGameObjectInScene("Sprite"); tk2dSprite sprite = go.AddComponent<tk2dSprite>(); sprite.SetSprite(sprColl, sprColl.FirstValidDefinitionIndex); sprite.renderer.material = sprColl.FirstValidDefinition.material; sprite.Build(); Selection.activeGameObject = go; Undo.RegisterCreatedObjectUndo(go, "Create Sprite"); } ); } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Management.Automation.Language; using System.Reflection; using Microsoft.PowerShell; using Dbg = System.Diagnostics.Debug; namespace System.Management.Automation { /// <summary> /// This class represents the compiled metadata for a parameter set. /// </summary> public sealed class ParameterSetMetadata { #region Private Data private bool _isMandatory; private int _position; private bool _valueFromPipeline; private bool _valueFromPipelineByPropertyName; private bool _valueFromRemainingArguments; private string _helpMessage; private string _helpMessageBaseName; private string _helpMessageResourceId; #endregion #region Constructor /// <summary> /// </summary> /// <param name="psMD"></param> internal ParameterSetMetadata(ParameterSetSpecificMetadata psMD) { Dbg.Assert(psMD != null, "ParameterSetSpecificMetadata cannot be null"); Initialize(psMD); } /// <summary> /// A copy constructor that creates a deep copy of the <paramref name="other"/> ParameterSetMetadata object. /// </summary> /// <param name="other">Object to copy.</param> internal ParameterSetMetadata(ParameterSetMetadata other) { if (other == null) { throw PSTraceSource.NewArgumentNullException(nameof(other)); } _helpMessage = other._helpMessage; _helpMessageBaseName = other._helpMessageBaseName; _helpMessageResourceId = other._helpMessageResourceId; _isMandatory = other._isMandatory; _position = other._position; _valueFromPipeline = other._valueFromPipeline; _valueFromPipelineByPropertyName = other._valueFromPipelineByPropertyName; _valueFromRemainingArguments = other._valueFromRemainingArguments; } #endregion #region Public Properties /// <summary> /// Returns true if the parameter is mandatory for this parameterset, false otherwise. /// </summary> /// <value></value> public bool IsMandatory { get { return _isMandatory; } set { _isMandatory = value; } } /// <summary> /// If the parameter is allowed to be positional for this parameter set, this returns /// the position it is allowed to be in. If it is not positional, this returns int.MinValue. /// </summary> /// <value></value> public int Position { get { return _position; } set { _position = value; } } /// <summary> /// Specifies that this parameter can take values from the incoming pipeline object. /// </summary> public bool ValueFromPipeline { get { return _valueFromPipeline; } set { _valueFromPipeline = value; } } /// <summary> /// Specifies that this parameter can take values from a property from the incoming /// pipeline object with the same name as the parameter. /// </summary> public bool ValueFromPipelineByPropertyName { get { return _valueFromPipelineByPropertyName; } set { _valueFromPipelineByPropertyName = value; } } /// <summary> /// Specifies if this parameter takes all the remaining unbound /// arguments that were specified. /// </summary> /// <value></value> public bool ValueFromRemainingArguments { get { return _valueFromRemainingArguments; } set { _valueFromRemainingArguments = value; } } /// <summary> /// A short description for this parameter, suitable for presentation as a tool tip. /// </summary> public string HelpMessage { get { return _helpMessage; } set { _helpMessage = value; } } /// <summary> /// The base name of the resource for a help message. /// </summary> public string HelpMessageBaseName { get { return _helpMessageBaseName; } set { _helpMessageBaseName = value; } } /// <summary> /// The Id of the resource for a help message. /// </summary> public string HelpMessageResourceId { get { return _helpMessageResourceId; } set { _helpMessageResourceId = value; } } #endregion #region Private / Internal Methods & Properties /// <summary> /// </summary> /// <param name="psMD"></param> internal void Initialize(ParameterSetSpecificMetadata psMD) { _isMandatory = psMD.IsMandatory; _position = psMD.Position; _valueFromPipeline = psMD.ValueFromPipeline; _valueFromPipelineByPropertyName = psMD.ValueFromPipelineByPropertyName; _valueFromRemainingArguments = psMD.ValueFromRemainingArguments; _helpMessage = psMD.HelpMessage; _helpMessageBaseName = psMD.HelpMessageBaseName; _helpMessageResourceId = psMD.HelpMessageResourceId; } /// <summary> /// Compares this instance with the supplied <paramref name="second"/>. /// </summary> /// <param name="second"> /// An object to compare this instance with /// </param> /// <returns> /// true if the metadata is same. false otherwise. /// </returns> internal bool Equals(ParameterSetMetadata second) { if ((_isMandatory != second._isMandatory) || (_position != second._position) || (_valueFromPipeline != second._valueFromPipeline) || (_valueFromPipelineByPropertyName != second._valueFromPipelineByPropertyName) || (_valueFromRemainingArguments != second._valueFromRemainingArguments) || (_helpMessage != second._helpMessage) || (_helpMessageBaseName != second._helpMessageBaseName) || (_helpMessageResourceId != second._helpMessageResourceId)) { return false; } return true; } #endregion #region Efficient serialization + rehydration logic [Flags] internal enum ParameterFlags : uint { Mandatory = 0x01, ValueFromPipeline = 0x02, ValueFromPipelineByPropertyName = 0x04, ValueFromRemainingArguments = 0x08, } internal ParameterFlags Flags { get { ParameterFlags flags = 0; if (IsMandatory) { flags |= ParameterFlags.Mandatory; } if (ValueFromPipeline) { flags |= ParameterFlags.ValueFromPipeline; } if (ValueFromPipelineByPropertyName) { flags |= ParameterFlags.ValueFromPipelineByPropertyName; } if (ValueFromRemainingArguments) { flags |= ParameterFlags.ValueFromRemainingArguments; } return flags; } set { this.IsMandatory = ((value & ParameterFlags.Mandatory) == ParameterFlags.Mandatory); this.ValueFromPipeline = ((value & ParameterFlags.ValueFromPipeline) == ParameterFlags.ValueFromPipeline); this.ValueFromPipelineByPropertyName = ((value & ParameterFlags.ValueFromPipelineByPropertyName) == ParameterFlags.ValueFromPipelineByPropertyName); this.ValueFromRemainingArguments = ((value & ParameterFlags.ValueFromRemainingArguments) == ParameterFlags.ValueFromRemainingArguments); } } /// <summary> /// Constructor used by rehydration. /// </summary> internal ParameterSetMetadata( int position, ParameterFlags flags, string helpMessage) { this.Position = position; this.Flags = flags; this.HelpMessage = helpMessage; } #endregion #region Proxy Parameter Generation private const string MandatoryFormat = @"{0}Mandatory=$true"; private const string PositionFormat = @"{0}Position={1}"; private const string ValueFromPipelineFormat = @"{0}ValueFromPipeline=$true"; private const string ValueFromPipelineByPropertyNameFormat = @"{0}ValueFromPipelineByPropertyName=$true"; private const string ValueFromRemainingArgumentsFormat = @"{0}ValueFromRemainingArguments=$true"; private const string HelpMessageFormat = @"{0}HelpMessage='{1}'"; /// <summary> /// </summary> /// <returns></returns> internal string GetProxyParameterData() { Text.StringBuilder result = new System.Text.StringBuilder(); string prefix = string.Empty; if (_isMandatory) { result.AppendFormat(CultureInfo.InvariantCulture, MandatoryFormat, prefix); prefix = ", "; } if (_position != Int32.MinValue) { result.AppendFormat(CultureInfo.InvariantCulture, PositionFormat, prefix, _position); prefix = ", "; } if (_valueFromPipeline) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineFormat, prefix); prefix = ", "; } if (_valueFromPipelineByPropertyName) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineByPropertyNameFormat, prefix); prefix = ", "; } if (_valueFromRemainingArguments) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromRemainingArgumentsFormat, prefix); prefix = ", "; } if (!string.IsNullOrEmpty(_helpMessage)) { result.AppendFormat( CultureInfo.InvariantCulture, HelpMessageFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(_helpMessage)); prefix = ", "; } return result.ToString(); } #endregion } /// <summary> /// This class represents the compiled metadata for a parameter. /// </summary> public sealed class ParameterMetadata { #region Private Data private string _name; private Type _parameterType; private bool _isDynamic; private Dictionary<string, ParameterSetMetadata> _parameterSets; private Collection<string> _aliases; private Collection<Attribute> _attributes; #endregion #region Constructor /// <summary> /// Constructs a ParameterMetadata instance. /// </summary> /// <param name="name"> /// Name of the parameter. /// </param> /// <exception cref="ArgumentNullException"> /// name is null. /// </exception> public ParameterMetadata(string name) : this(name, null) { } /// <summary> /// Constructs a ParameterMetadata instance. /// </summary> /// <param name="name"> /// Name of the parameter. /// </param> /// <param name="parameterType"> /// Type of the parameter. /// </param> /// <exception cref="ArgumentNullException"> /// name is null. /// </exception> public ParameterMetadata(string name, Type parameterType) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } _name = name; _parameterType = parameterType; _attributes = new Collection<Attribute>(); _aliases = new Collection<string>(); _parameterSets = new Dictionary<string, ParameterSetMetadata>(); } /// <summary> /// A copy constructor that creates a deep copy of the <paramref name="other"/> ParameterMetadata object. /// Instances of Attribute and Type classes are copied by reference. /// </summary> /// <param name="other">Object to copy.</param> public ParameterMetadata(ParameterMetadata other) { if (other == null) { throw PSTraceSource.NewArgumentNullException(nameof(other)); } _isDynamic = other._isDynamic; _name = other._name; _parameterType = other._parameterType; // deep copy _aliases = new Collection<string>(new List<string>(other._aliases.Count)); foreach (string alias in other._aliases) { _aliases.Add(alias); } // deep copy of the collection, collection items (Attributes) copied by reference if (other._attributes == null) { _attributes = null; } else { _attributes = new Collection<Attribute>(new List<Attribute>(other._attributes.Count)); foreach (Attribute attribute in other._attributes) { _attributes.Add(attribute); } } // deep copy _parameterSets = null; if (other._parameterSets == null) { _parameterSets = null; } else { _parameterSets = new Dictionary<string, ParameterSetMetadata>(other._parameterSets.Count); foreach (KeyValuePair<string, ParameterSetMetadata> entry in other._parameterSets) { _parameterSets.Add(entry.Key, new ParameterSetMetadata(entry.Value)); } } } /// <summary> /// An internal constructor which constructs a ParameterMetadata object /// from compiled command parameter metadata. ParameterMetadata /// is a proxy written on top of CompiledCommandParameter. /// </summary> /// <param name="cmdParameterMD"> /// Internal CompiledCommandParameter metadata /// </param> internal ParameterMetadata(CompiledCommandParameter cmdParameterMD) { Dbg.Assert(cmdParameterMD != null, "CompiledCommandParameter cannot be null"); Initialize(cmdParameterMD); } /// <summary> /// Constructor used by implicit remoting. /// </summary> internal ParameterMetadata( Collection<string> aliases, bool isDynamic, string name, Dictionary<string, ParameterSetMetadata> parameterSets, Type parameterType) { _aliases = aliases; _isDynamic = isDynamic; _name = name; _parameterSets = parameterSets; _parameterType = parameterType; _attributes = new Collection<Attribute>(); } #endregion #region Public Methods/Properties /// <summary> /// Gets the name of the parameter. /// </summary> public string Name { get { return _name; } set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentNullException("Name"); } _name = value; } } /// <summary> /// Gets the Type information of the Parameter. /// </summary> public Type ParameterType { get { return _parameterType; } set { _parameterType = value; } } /// <summary> /// Gets the ParameterSets metadata that this parameter belongs to. /// </summary> public Dictionary<string, ParameterSetMetadata> ParameterSets { get { return _parameterSets; } } /// <summary> /// Specifies if the parameter is Dynamic. /// </summary> public bool IsDynamic { get { return _isDynamic; } set { _isDynamic = value; } } /// <summary> /// Specifies the alias names for this parameter. /// </summary> public Collection<string> Aliases { get { return _aliases; } } /// <summary> /// A collection of the attributes found on the member. /// </summary> public Collection<Attribute> Attributes { get { return _attributes; } } /// <summary> /// Specifies if the parameter is a SwitchParameter. /// </summary> public bool SwitchParameter { get { if (_parameterType != null) { return _parameterType.Equals(typeof(SwitchParameter)); } return false; } } /// <summary> /// Gets a dictionary of parameter metadata for the supplied <paramref name="type"/>. /// </summary> /// <param name="type"> /// CLR Type for which the parameter metadata is constructed. /// </param> /// <returns> /// A Dictionary of ParameterMetadata keyed by parameter name. /// null if no parameter metadata is found. /// </returns> /// <exception cref="ArgumentNullException"> /// type is null. /// </exception> public static Dictionary<string, ParameterMetadata> GetParameterMetadata(Type type) { if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } CommandMetadata cmdMetaData = new CommandMetadata(type); Dictionary<string, ParameterMetadata> result = cmdMetaData.Parameters; // early GC. cmdMetaData = null; return result; } #endregion #region Internal Methods/Properties /// <summary> /// </summary> /// <param name="compiledParameterMD"></param> internal void Initialize(CompiledCommandParameter compiledParameterMD) { _name = compiledParameterMD.Name; _parameterType = compiledParameterMD.Type; _isDynamic = compiledParameterMD.IsDynamic; // Create parameter set metadata _parameterSets = new Dictionary<string, ParameterSetMetadata>(StringComparer.OrdinalIgnoreCase); foreach (string key in compiledParameterMD.ParameterSetData.Keys) { ParameterSetSpecificMetadata pMD = compiledParameterMD.ParameterSetData[key]; _parameterSets.Add(key, new ParameterSetMetadata(pMD)); } // Create aliases for this parameter _aliases = new Collection<string>(); foreach (string alias in compiledParameterMD.Aliases) { _aliases.Add(alias); } // Create attributes for this parameter _attributes = new Collection<Attribute>(); foreach (var attrib in compiledParameterMD.CompiledAttributes) { _attributes.Add(attrib); } } /// <summary> /// </summary> /// <param name="cmdParameterMetadata"></param> /// <returns></returns> internal static Dictionary<string, ParameterMetadata> GetParameterMetadata(MergedCommandParameterMetadata cmdParameterMetadata) { Dbg.Assert(cmdParameterMetadata != null, "cmdParameterMetadata cannot be null"); Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase); foreach (var keyValuePair in cmdParameterMetadata.BindableParameters) { var key = keyValuePair.Key; var mergedCompiledPMD = keyValuePair.Value; ParameterMetadata parameterMetaData = new ParameterMetadata(mergedCompiledPMD.Parameter); result.Add(key, parameterMetaData); } return result; } internal bool IsMatchingType(PSTypeName psTypeName) { Type dotNetType = psTypeName.Type; if (dotNetType != null) { // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. bool parameterAcceptsObjects = ((int)(LanguagePrimitives.FigureConversion(typeof(object), this.ParameterType).Rank)) >= (int)(ConversionRank.AssignableS2A); if (dotNetType.Equals(typeof(object))) { return parameterAcceptsObjects; } if (parameterAcceptsObjects) { return (psTypeName.Type != null) && (psTypeName.Type.Equals(typeof(object))); } // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. var conversionData = LanguagePrimitives.FigureConversion(dotNetType, this.ParameterType); if (conversionData != null) { if ((int)(conversionData.Rank) >= (int)(ConversionRank.NumericImplicitS2A)) { return true; } } return false; } var wildcardPattern = WildcardPattern.Get( "*" + (psTypeName.Name ?? string.Empty), WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); if (wildcardPattern.IsMatch(this.ParameterType.FullName)) { return true; } if (this.ParameterType.IsArray && wildcardPattern.IsMatch((this.ParameterType.GetElementType().FullName))) { return true; } if (this.Attributes != null) { PSTypeNameAttribute typeNameAttribute = this.Attributes.OfType<PSTypeNameAttribute>().FirstOrDefault(); if (typeNameAttribute != null && wildcardPattern.IsMatch(typeNameAttribute.PSTypeName)) { return true; } } return false; } #endregion #region Proxy Parameter generation // The formats are prefixed with {0} to enable easy formatting. private const string ParameterNameFormat = @"{0}${{{1}}}"; private const string ParameterTypeFormat = @"{0}[{1}]"; private const string ParameterSetNameFormat = "ParameterSetName='{0}'"; private const string AliasesFormat = @"{0}[Alias({1})]"; private const string ValidateLengthFormat = @"{0}[ValidateLength({1}, {2})]"; private const string ValidateRangeRangeKindFormat = @"{0}[ValidateRange([System.Management.Automation.ValidateRangeKind]::{1})]"; private const string ValidateRangeFloatFormat = @"{0}[ValidateRange({1:R}, {2:R})]"; private const string ValidateRangeFormat = @"{0}[ValidateRange({1}, {2})]"; private const string ValidatePatternFormat = "{0}[ValidatePattern('{1}')]"; private const string ValidateScriptFormat = @"{0}[ValidateScript({{ {1} }})]"; private const string ValidateCountFormat = @"{0}[ValidateCount({1}, {2})]"; private const string ValidateSetFormat = @"{0}[ValidateSet({1})]"; private const string ValidateNotNullFormat = @"{0}[ValidateNotNull()]"; private const string ValidateNotNullOrEmptyFormat = @"{0}[ValidateNotNullOrEmpty()]"; private const string AllowNullFormat = @"{0}[AllowNull()]"; private const string AllowEmptyStringFormat = @"{0}[AllowEmptyString()]"; private const string AllowEmptyCollectionFormat = @"{0}[AllowEmptyCollection()]"; private const string PSTypeNameFormat = @"{0}[PSTypeName('{1}')]"; private const string ObsoleteFormat = @"{0}[Obsolete({1})]"; private const string CredentialAttributeFormat = @"{0}[System.Management.Automation.CredentialAttribute()]"; /// <summary> /// </summary> /// <param name="prefix"> /// prefix that is added to every new-line. Used for tabbing content. /// </param> /// <param name="paramNameOverride"> /// The paramNameOverride is used as the parameter name if it is not null or empty. /// </param> /// <param name="isProxyForCmdlet"> /// The parameter is for a cmdlet and requires a Parameter attribute. /// </param> /// <returns></returns> internal string GetProxyParameterData(string prefix, string paramNameOverride, bool isProxyForCmdlet) { Text.StringBuilder result = new System.Text.StringBuilder(); if (_parameterSets != null && isProxyForCmdlet) { foreach (var pair in _parameterSets) { string parameterSetName = pair.Key; ParameterSetMetadata parameterSet = pair.Value; string paramSetData = parameterSet.GetProxyParameterData(); if (!string.IsNullOrEmpty(paramSetData) || !parameterSetName.Equals(ParameterAttribute.AllParameterSets)) { string separator = string.Empty; result.Append(prefix); result.Append("[Parameter("); if (!parameterSetName.Equals(ParameterAttribute.AllParameterSets)) { result.AppendFormat( CultureInfo.InvariantCulture, ParameterSetNameFormat, CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); separator = ", "; } if (!string.IsNullOrEmpty(paramSetData)) { result.Append(separator); result.Append(paramSetData); } result.Append(")]"); } } } if ((_aliases != null) && (_aliases.Count > 0)) { Text.StringBuilder aliasesData = new System.Text.StringBuilder(); string comma = string.Empty; // comma is not need for the first element foreach (string alias in _aliases) { aliasesData.AppendFormat( CultureInfo.InvariantCulture, "{0}'{1}'", comma, CodeGeneration.EscapeSingleQuotedStringContent(alias)); comma = ","; } result.AppendFormat(CultureInfo.InvariantCulture, AliasesFormat, prefix, aliasesData.ToString()); } if ((_attributes != null) && (_attributes.Count > 0)) { foreach (Attribute attrib in _attributes) { string attribData = GetProxyAttributeData(attrib, prefix); if (!string.IsNullOrEmpty(attribData)) { result.Append(attribData); } } } if (SwitchParameter) { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, "switch"); } else if (_parameterType != null) { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, ToStringCodeMethods.Type(_parameterType)); } /* 1. CredentialAttribute needs to go after the type * 2. To avoid risk, I don't want to move other attributes to go here / after the type */ CredentialAttribute credentialAttrib = _attributes.OfType<CredentialAttribute>().FirstOrDefault(); if (credentialAttrib != null) { string attribData = string.Format(CultureInfo.InvariantCulture, CredentialAttributeFormat, prefix); if (!string.IsNullOrEmpty(attribData)) { result.Append(attribData); } } result.AppendFormat( CultureInfo.InvariantCulture, ParameterNameFormat, prefix, CodeGeneration.EscapeVariableName(string.IsNullOrEmpty(paramNameOverride) ? _name : paramNameOverride)); return result.ToString(); } /// <summary> /// Generates proxy data for attributes like ValidateLength, ValidateRange etc. /// </summary> /// <param name="attrib"> /// Attribute to process. /// </param> /// <param name="prefix"> /// Prefix string to add. /// </param> /// <returns> /// Attribute's proxy string. /// </returns> private static string GetProxyAttributeData(Attribute attrib, string prefix) { string result; ValidateLengthAttribute validLengthAttrib = attrib as ValidateLengthAttribute; if (validLengthAttrib != null) { result = string.Format( CultureInfo.InvariantCulture, ValidateLengthFormat, prefix, validLengthAttrib.MinLength, validLengthAttrib.MaxLength); return result; } ValidateRangeAttribute validRangeAttrib = attrib as ValidateRangeAttribute; if (validRangeAttrib != null) { if (validRangeAttrib.RangeKind.HasValue) { result = string.Format( CultureInfo.InvariantCulture, ValidateRangeRangeKindFormat, prefix, validRangeAttrib.RangeKind.ToString()); return result; } else { Type rangeType = validRangeAttrib.MinRange.GetType(); string format; if (rangeType == typeof(float) || rangeType == typeof(double)) { format = ValidateRangeFloatFormat; } else { format = ValidateRangeFormat; } result = string.Format( CultureInfo.InvariantCulture, format, prefix, validRangeAttrib.MinRange, validRangeAttrib.MaxRange); return result; } } AllowNullAttribute allowNullAttrib = attrib as AllowNullAttribute; if (allowNullAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowNullFormat, prefix); return result; } AllowEmptyStringAttribute allowEmptyStringAttrib = attrib as AllowEmptyStringAttribute; if (allowEmptyStringAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyStringFormat, prefix); return result; } AllowEmptyCollectionAttribute allowEmptyColAttrib = attrib as AllowEmptyCollectionAttribute; if (allowEmptyColAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyCollectionFormat, prefix); return result; } ValidatePatternAttribute patternAttrib = attrib as ValidatePatternAttribute; if (patternAttrib != null) { /* TODO: Validate Pattern dont support Options in ScriptCmdletText. StringBuilder regexOps = new System.Text.StringBuilder(); string or = string.Empty; string[] regexOptionEnumValues = Enum.GetNames(typeof(System.Text.RegularExpressions.RegexOptions)); foreach (string regexOption in regexOptionEnumValues) { System.Text.RegularExpressions.RegexOptions option = (System.Text.RegularExpressions.RegexOptions) Enum.Parse( typeof(System.Text.RegularExpressions.RegexOptions), regexOption, true); if ((option & patternAttrib.Options) == option) { tracer.WriteLine("Regex option {0} found", regexOption); regexOps.AppendFormat(CultureInfo.InvariantCulture, "{0}[System.Text.RegularExpressions.RegexOptions]::{1}", or, option.ToString() ); or = "|"; } }*/ result = string.Format(CultureInfo.InvariantCulture, ValidatePatternFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(patternAttrib.RegexPattern) /*,regexOps.ToString()*/); return result; } ValidateCountAttribute countAttrib = attrib as ValidateCountAttribute; if (countAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateCountFormat, prefix, countAttrib.MinLength, countAttrib.MaxLength); return result; } ValidateNotNullAttribute notNullAttrib = attrib as ValidateNotNullAttribute; if (notNullAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullFormat, prefix); return result; } ValidateNotNullOrEmptyAttribute notNullEmptyAttrib = attrib as ValidateNotNullOrEmptyAttribute; if (notNullEmptyAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullOrEmptyFormat, prefix); return result; } ValidateSetAttribute setAttrib = attrib as ValidateSetAttribute; if (setAttrib != null) { Text.StringBuilder values = new System.Text.StringBuilder(); string comma = string.Empty; foreach (string validValue in setAttrib.ValidValues) { values.AppendFormat( CultureInfo.InvariantCulture, "{0}'{1}'", comma, CodeGeneration.EscapeSingleQuotedStringContent(validValue)); comma = ","; } result = string.Format(CultureInfo.InvariantCulture, ValidateSetFormat, prefix, values.ToString()/*, setAttrib.IgnoreCase*/); return result; } ValidateScriptAttribute scriptAttrib = attrib as ValidateScriptAttribute; if (scriptAttrib != null) { // Talked with others and I think it is okay to use *unescaped* value from sb.ToString() // 1. implicit remoting is not bringing validation scripts across // 2. other places in code also assume that contents of a script block can be parsed // without escaping result = string.Format(CultureInfo.InvariantCulture, ValidateScriptFormat, prefix, scriptAttrib.ScriptBlock.ToString()); return result; } PSTypeNameAttribute psTypeNameAttrib = attrib as PSTypeNameAttribute; if (psTypeNameAttrib != null) { result = string.Format( CultureInfo.InvariantCulture, PSTypeNameFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(psTypeNameAttrib.PSTypeName)); return result; } ObsoleteAttribute obsoleteAttrib = attrib as ObsoleteAttribute; if (obsoleteAttrib != null) { string parameters = string.Empty; if (obsoleteAttrib.IsError) { string message = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'"; parameters = message + ", $true"; } else if (obsoleteAttrib.Message != null) { parameters = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'"; } result = string.Format( CultureInfo.InvariantCulture, ObsoleteFormat, prefix, parameters); return result; } return null; } #endregion } /// <summary> /// The metadata associated with a bindable type. /// </summary> internal class InternalParameterMetadata { #region ctor /// <summary> /// Gets or constructs an instance of the InternalParameterMetadata for the specified runtime-defined parameters. /// </summary> /// <param name="runtimeDefinedParameters"> /// The runtime-defined parameter collection that describes the parameters and their metadata. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <param name="checkNames"> /// Check for reserved parameter names. /// </param> /// <returns> /// An instance of the TypeMetadata for the specified runtime-defined parameters. The metadata /// is always constructed on demand and never cached. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="runtimeDefinedParameters"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal static InternalParameterMetadata Get(RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { if (runtimeDefinedParameters == null) { throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter"); } return new InternalParameterMetadata(runtimeDefinedParameters, processingDynamicParameters, checkNames); } /// <summary> /// Gets or constructs an instance of the InternalParameterMetadata for the specified type. /// </summary> /// <param name="type"> /// The type to get the metadata for. /// </param> /// <param name="context"> /// The current engine context. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <returns> /// An instance of the TypeMetadata for the specified type. The metadata may get /// constructed on-demand or may be retrieved from the cache. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal static InternalParameterMetadata Get(Type type, ExecutionContext context, bool processingDynamicParameters) { if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } InternalParameterMetadata result; if (context == null || !s_parameterMetadataCache.TryGetValue(type.AssemblyQualifiedName, out result)) { result = new InternalParameterMetadata(type, processingDynamicParameters); if (context != null) { s_parameterMetadataCache.TryAdd(type.AssemblyQualifiedName, result); } } return result; } // /// <summary> /// Constructs an instance of the InternalParameterMetadata using the metadata in the /// runtime-defined parameter collection. /// </summary> /// <param name="runtimeDefinedParameters"> /// The collection of runtime-defined parameters that declare the parameters and their /// metadata. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <param name="checkNames"> /// Check if the parameter name has been reserved. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="runtimeDefinedParameters"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal InternalParameterMetadata(RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { if (runtimeDefinedParameters == null) { throw PSTraceSource.NewArgumentNullException(nameof(runtimeDefinedParameters)); } ConstructCompiledParametersUsingRuntimeDefinedParameters(runtimeDefinedParameters, processingDynamicParameters, checkNames); } // /// <summary> /// Constructs an instance of the InternalParameterMetadata using the reflection information retrieved /// from the enclosing bindable object type. /// </summary> /// <param name="type"> /// The type information for the bindable object /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal InternalParameterMetadata(Type type, bool processingDynamicParameters) { if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } _type = type; TypeName = type.Name; ConstructCompiledParametersUsingReflection(processingDynamicParameters); } #endregion ctor /// <summary> /// Gets the type name of the bindable type. /// </summary> internal string TypeName { get; } = string.Empty; /// <summary> /// Gets a dictionary of the compiled parameter metadata for this Type. /// The dictionary keys are the names of the parameters (or aliases) and /// the values are the compiled parameter metadata. /// </summary> internal Dictionary<string, CompiledCommandParameter> BindableParameters { get; } = new Dictionary<string, CompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets a dictionary of the parameters that have been aliased to other names. The key is /// the alias name and the value is the CompiledCommandParameter metadata. /// </summary> internal Dictionary<string, CompiledCommandParameter> AliasedParameters { get; } = new Dictionary<string, CompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The type information for the class that implements the bindable object. /// This member is null in all cases except when constructed with using reflection /// against the Type. /// </summary> private readonly Type _type; /// <summary> /// The flags used when reflecting against the object to create the metadata. /// </summary> internal static readonly BindingFlags metaDataBindingFlags = (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); #region helper methods /// <summary> /// Fills in the data for an instance of this class using the specified runtime-defined parameters. /// </summary> /// <param name="runtimeDefinedParameters"> /// A description of the parameters and their metadata. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <param name="checkNames"> /// Check if the parameter name has been reserved. /// </param> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> private void ConstructCompiledParametersUsingRuntimeDefinedParameters( RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { Diagnostics.Assert( runtimeDefinedParameters != null, "This method should only be called when constructed with a valid runtime-defined parameter collection"); foreach (RuntimeDefinedParameter parameterDefinition in runtimeDefinedParameters.Values) { // Create the compiled parameter and add it to the bindable parameters collection if (processingDynamicParameters) { // When processing dynamic parameters, parameter definitions come from the user, // Invalid data could be passed in, or the parameter could be actually disabled. if (parameterDefinition == null || parameterDefinition.IsDisabled()) { continue; } } CompiledCommandParameter parameter = new CompiledCommandParameter(parameterDefinition, processingDynamicParameters); AddParameter(parameter, checkNames); } } /// <summary> /// Compiles the parameter using reflection against the CLR type. /// </summary> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> private void ConstructCompiledParametersUsingReflection(bool processingDynamicParameters) { Diagnostics.Assert( _type != null, "This method should only be called when constructed with the Type"); // Get the property and field info PropertyInfo[] properties = _type.GetProperties(metaDataBindingFlags); FieldInfo[] fields = _type.GetFields(metaDataBindingFlags); foreach (PropertyInfo property in properties) { // Check whether the property is a parameter if (!IsMemberAParameter(property)) { continue; } AddParameter(property, processingDynamicParameters); } foreach (FieldInfo field in fields) { // Check whether the field is a parameter if (!IsMemberAParameter(field)) { continue; } AddParameter(field, processingDynamicParameters); } } private static void CheckForReservedParameter(string name) { if (name.Equals("SelectProperty", StringComparison.OrdinalIgnoreCase) || name.Equals("SelectObject", StringComparison.OrdinalIgnoreCase)) { throw new MetadataException( "ReservedParameterName", null, DiscoveryExceptions.ReservedParameterName, name); } } // This call verifies that the parameter is unique or // can be deemed unique. If not, an exception is thrown. // If it is unique (or deemed unique), then it is added // to the bindableParameters collection // private void AddParameter(MemberInfo member, bool processingDynamicParameters) { bool error = false; bool useExisting = false; CheckForReservedParameter(member.Name); do // false loop { CompiledCommandParameter existingParameter; if (!BindableParameters.TryGetValue(member.Name, out existingParameter)) { break; } Type existingParamDeclaringType = existingParameter.DeclaringType; if (existingParamDeclaringType == null) { error = true; break; } if (existingParamDeclaringType.IsSubclassOf(member.DeclaringType)) { useExisting = true; break; } if (member.DeclaringType.IsSubclassOf(existingParamDeclaringType)) { // Need to swap out the new member for the parameter definition // that is already defined. RemoveParameter(existingParameter); break; } error = true; } while (false); if (error) { // A duplicate parameter was found and could not be deemed unique // through inheritance. throw new MetadataException( "DuplicateParameterDefinition", null, ParameterBinderStrings.DuplicateParameterDefinition, member.Name); } if (!useExisting) { CompiledCommandParameter parameter = new CompiledCommandParameter(member, processingDynamicParameters); AddParameter(parameter, true); } } private void AddParameter(CompiledCommandParameter parameter, bool checkNames) { if (checkNames) { CheckForReservedParameter(parameter.Name); } BindableParameters.Add(parameter.Name, parameter); // Now add entries in the parameter aliases collection for any aliases. foreach (string alias in parameter.Aliases) { if (AliasedParameters.ContainsKey(alias)) { throw new MetadataException( "AliasDeclaredMultipleTimes", null, DiscoveryExceptions.AliasDeclaredMultipleTimes, alias); } AliasedParameters.Add(alias, parameter); } } private void RemoveParameter(CompiledCommandParameter parameter) { BindableParameters.Remove(parameter.Name); // Now add entries in the parameter aliases collection for any aliases. foreach (string alias in parameter.Aliases) { AliasedParameters.Remove(alias); } } /// <summary> /// Determines if the specified member represents a parameter based on its attributes. /// </summary> /// <param name="member"> /// The member to check to see if it is a parameter. /// </param> /// <returns> /// True if at least one ParameterAttribute is declared on the member, or false otherwise. /// </returns> /// <exception cref="MetadataException"> /// If GetCustomAttributes fails on <paramref name="member"/>. /// </exception> private static bool IsMemberAParameter(MemberInfo member) { try { var expAttribute = member.GetCustomAttributes<ExperimentalAttribute>(inherit: false).FirstOrDefault(); if (expAttribute != null && expAttribute.ToHide) { return false; } var hasAnyVisibleParamAttributes = false; var paramAttributes = member.GetCustomAttributes<ParameterAttribute>(inherit: false); foreach (var paramAttribute in paramAttributes) { if (!paramAttribute.ToHide) { hasAnyVisibleParamAttributes = true; break; } } return hasAnyVisibleParamAttributes; } catch (MetadataException metadataException) { throw new MetadataException( "GetCustomAttributesMetadataException", metadataException, Metadata.MetadataMemberInitialization, member.Name, metadataException.Message); } catch (ArgumentException argumentException) { throw new MetadataException( "GetCustomAttributesArgumentException", argumentException, Metadata.MetadataMemberInitialization, member.Name, argumentException.Message); } } #endregion helper methods #region Metadata cache /// <summary> /// The cache of the type metadata. The key for the cache is the Type.FullName. /// Note, this is a case-sensitive dictionary because Type names are case sensitive. /// </summary> private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, InternalParameterMetadata> s_parameterMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary<string, InternalParameterMetadata>(StringComparer.Ordinal); #endregion Metadata cache } }
// 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.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class SymbolEquivalenceComparerTests { public static readonly CS.CSharpCompilationOptions CSharpDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); public static readonly CS.CSharpCompilationOptions CSharpSignedDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithCryptoKeyFile(SigningTestHelpers.KeyPairFile). WithStrongNameProvider(new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create<string>())); [Fact] public void TestArraysAreEquivalent() { var csharpCode = @"class C { int intField1; int[] intArrayField1; string[] stringArrayField1; int[][] intArrayArrayField1; int[,] intArrayRank2Field1; System.Int32 int32Field1; int intField2; int[] intArrayField2; string[] stringArrayField2; int[][] intArrayArrayField2; int[,] intArrayRank2Field2; System.Int32 int32Field2; }"; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode)) { var type = (ITypeSymbol)workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single(); var intField1 = (IFieldSymbol)type.GetMembers("intField1").Single(); var intArrayField1 = (IFieldSymbol)type.GetMembers("intArrayField1").Single(); var stringArrayField1 = (IFieldSymbol)type.GetMembers("stringArrayField1").Single(); var intArrayArrayField1 = (IFieldSymbol)type.GetMembers("intArrayArrayField1").Single(); var intArrayRank2Field1 = (IFieldSymbol)type.GetMembers("intArrayRank2Field1").Single(); var int32Field1 = (IFieldSymbol)type.GetMembers("int32Field1").Single(); var intField2 = (IFieldSymbol)type.GetMembers("intField2").Single(); var intArrayField2 = (IFieldSymbol)type.GetMembers("intArrayField2").Single(); var stringArrayField2 = (IFieldSymbol)type.GetMembers("stringArrayField2").Single(); var intArrayArrayField2 = (IFieldSymbol)type.GetMembers("intArrayArrayField2").Single(); var intArrayRank2Field2 = (IFieldSymbol)type.GetMembers("intArrayRank2Field2").Single(); var int32Field2 = (IFieldSymbol)type.GetMembers("int32Field2").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField2.Type)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intField1.Type), SymbolEquivalenceComparer.Instance.GetHashCode(intField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField2.Type)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField1.Type), SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field2.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, stringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, intArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, int32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, intField1.Type)); } } [Fact] public void TestArraysInDifferentLanguagesAreEquivalent() { var csharpCode = @"class C { int intField1; int[] intArrayField1; string[] stringArrayField1; int[][] intArrayArrayField1; int[,] intArrayRank2Field1; System.Int32 int32Field1; }"; var vbCode = @"class C dim intField1 as Integer; dim intArrayField1 as Integer() dim stringArrayField1 as String() dim intArrayArrayField1 as Integer()() dim intArrayRank2Field1 as Integer(,) dim int32Field1 as System.Int32 end class"; using (var csharpWorkspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode)) using (var vbWorkspace = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode)) { var csharpType = (ITypeSymbol)csharpWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single(); var vbType = vbWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single(); var csharpIntField1 = (IFieldSymbol)csharpType.GetMembers("intField1").Single(); var csharpIntArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayField1").Single(); var csharpStringArrayField1 = (IFieldSymbol)csharpType.GetMembers("stringArrayField1").Single(); var csharpIntArrayArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayArrayField1").Single(); var csharpIntArrayRank2Field1 = (IFieldSymbol)csharpType.GetMembers("intArrayRank2Field1").Single(); var csharpInt32Field1 = (IFieldSymbol)csharpType.GetMembers("int32Field1").Single(); var vbIntField1 = (IFieldSymbol)vbType.GetMembers("intField1").Single(); var vbIntArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayField1").Single(); var vbStringArrayField1 = (IFieldSymbol)vbType.GetMembers("stringArrayField1").Single(); var vbIntArrayArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayArrayField1").Single(); var vbIntArrayRank2Field1 = (IFieldSymbol)vbType.GetMembers("intArrayRank2Field1").Single(); var vbInt32Field1 = (IFieldSymbol)vbType.GetMembers("int32Field1").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbIntArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbStringArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbInt32Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayField1.Type, csharpStringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbIntArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayArrayField1.Type, csharpIntArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayRank2Field1.Type, vbInt32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbIntField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntField1.Type, csharpIntArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbStringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbStringArrayField1.Type, csharpIntArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayRank2Field1.Type, csharpInt32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(vbInt32Field1.Type, csharpIntField1.Type)); } } [Fact] public void TestFields() { var csharpCode1 = @"class Type1 { int field1; string field2; } class Type2 { bool field3; short field4; }"; var csharpCode2 = @"class Type1 { int field1; short field4; } class Type2 { bool field3; string field2; }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field1_v2 = type1_v2.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); var field2_v2 = type2_v2.GetMembers("field2").Single(); var field3_v1 = type2_v1.GetMembers("field3").Single(); var field3_v2 = type2_v2.GetMembers("field3").Single(); var field4_v1 = type2_v1.GetMembers("field4").Single(); var field4_v2 = type1_v2.GetMembers("field4").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(field1_v1), SymbolEquivalenceComparer.Instance.GetHashCode(field1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2)); } } [WorkItem(538124)] [Fact] public void TestFieldsAcrossLanguages() { var csharpCode1 = @"class Type1 { int field1; string field2; } class Type2 { bool field3; short field4; }"; var vbCode1 = @"class Type1 dim field1 as Integer; dim field4 as Short; end class class Type2 dim field3 as Boolean; dim field2 as String; end class"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field1_v2 = type1_v2.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); var field2_v2 = type2_v2.GetMembers("field2").Single(); var field3_v1 = type2_v1.GetMembers("field3").Single(); var field3_v2 = type2_v2.GetMembers("field3").Single(); var field4_v1 = type2_v1.GetMembers("field4").Single(); var field4_v2 = type1_v2.GetMembers("field4").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2)); } } [Fact] public void TestFieldsInGenericTypes() { var code = @"class C<T> { int foo; C<int> intInstantiation1; C<string> stringInstantiation; C<T> instanceInstantiation; } class D { C<int> intInstantiation2; } "; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code)) { var typeC = workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single(); var typeD = workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("D").Single(); var intInstantiation1 = (IFieldSymbol)typeC.GetMembers("intInstantiation1").Single(); var stringInstantiation = (IFieldSymbol)typeC.GetMembers("stringInstantiation").Single(); var instanceInstantiation = (IFieldSymbol)typeC.GetMembers("instanceInstantiation").Single(); var intInstantiation2 = (IFieldSymbol)typeD.GetMembers("intInstantiation2").Single(); var foo = typeC.GetMembers("foo").Single(); var foo_intInstantiation1 = intInstantiation1.Type.GetMembers("foo").Single(); var foo_stringInstantiation = stringInstantiation.Type.GetMembers("foo").Single(); var foo_instanceInstantiation = instanceInstantiation.Type.GetMembers("foo").Single(); var foo_intInstantiation2 = intInstantiation2.Type.GetMembers("foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_stringInstantiation)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_stringInstantiation)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo, foo_instanceInstantiation)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo), SymbolEquivalenceComparer.Instance.GetHashCode(foo_instanceInstantiation)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_intInstantiation2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation1), SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation2)); } } [Fact] public void TestMethodsWithDifferentReturnTypeNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { int Foo() {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public void TestMethodsWithDifferentNamesAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo1() {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public void TestMethodsWithDifferentAritiesAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo<T>() {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public void TestMethodsWithDifferentParametersAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public void TestMethodsWithDifferentTypeParameters() { var csharpCode1 = @"class Type1 { void Foo<A>(A a) {} }"; var csharpCode2 = @"class Type1 { void Foo<B>(B a) {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public void TestMethodsWithSameParameters() { var csharpCode1 = @"class Type1 { void Foo(int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public void TestMethodsWithDifferentParameterNames() { var csharpCode1 = @"class Type1 { void Foo(int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int b) {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public void TestMethodsAreNotEquivalentOutToRef() { var csharpCode1 = @"class Type1 { void Foo(out int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(ref int a) {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public void TestMethodsNotEquivalentRemoveOut() { var csharpCode1 = @"class Type1 { void Foo(out int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public void TestMethodsAreEquivalentIgnoreParams() { var csharpCode1 = @"class Type1 { void Foo(params int[] a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int[] a) {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public void TestMethodsNotEquivalentDifferentParameterTypes() { var csharpCode1 = @"class Type1 { void Foo(int[] a) {} }"; var csharpCode2 = @"class Type1 { void Foo(string[] a) {} }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public void TestMethodsAcrossLanguages() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { T Foo<T>(IList<T> list, int a) {} void Bar() { } }"; var vbCode1 = @" Imports System.Collections.Generic class Type1 function Foo(of U)(list as IList(of U), a as Integer) as U end function sub Quux() end sub end class"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1)) { var csharpType1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var vbType1 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var csharpFooMethod = csharpType1.GetMembers("Foo").Single(); var csharpBarMethod = csharpType1.GetMembers("Bar").Single(); var vbFooMethod = vbType1.GetMembers("Foo").Single(); var vbQuuxMethod = vbType1.GetMembers("Quux").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod), SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbQuuxMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbQuuxMethod)); } } [Fact] public void TestMethodsInGenericTypesAcrossLanguages() { var csharpCode1 = @" using System.Collections.Generic; class Type1<X> { T Foo<T>(IList<T> list, X a) {} void Bar(X x) { } }"; var vbCode1 = @" Imports System.Collections.Generic class Type1(of M) function Foo(of U)(list as IList(of U), a as M) as U end function sub Bar(x as Object) end sub end class"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1)) { var csharpType1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var vbType1 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var csharpFooMethod = csharpType1.GetMembers("Foo").Single(); var csharpBarMethod = csharpType1.GetMembers("Bar").Single(); var vbFooMethod = vbType1.GetMembers("Foo").Single(); var vbBarMethod = vbType1.GetMembers("Bar").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod), SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbBarMethod)); } } [Fact] public void TestObjectAndDynamicAreNotEqualNormally() { var csharpCode1 = @"class Type1 { object field1; dynamic field2; }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field2_v1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field1_v1)); } } [Fact] public void TestObjectAndDynamicAreEqualInSignatures() { var csharpCode1 = @"class Type1 { void Foo(object o1) { } }"; var csharpCode2 = @"class Type1 { void Foo(dynamic o1) { } }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public void TestUnequalGenericsInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(IList<int> o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(IList<string> o1) { } }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); } } [Fact] public void TestGenericsWithDynamicAndObjectInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(IList<object> o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(IList<dynamic> o1) { } }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public void TestDynamicAndUnrelatedTypeInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(dynamic o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(string o1) { } }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); } } [Fact] public void TestNamespaces() { var csharpCode1 = @"namespace Outer { namespace Inner { class Type { } } class Type { } } "; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) { var outer1 = (INamespaceSymbol)workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetMembers("Outer").Single(); var outer2 = (INamespaceSymbol)workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetMembers("Outer").Single(); var inner1 = (INamespaceSymbol)outer1.GetMembers("Inner").Single(); var inner2 = (INamespaceSymbol)outer2.GetMembers("Inner").Single(); var outerType1 = outer1.GetTypeMembers("Type").Single(); var outerType2 = outer2.GetTypeMembers("Type").Single(); var innerType1 = inner1.GetTypeMembers("Type").Single(); var innerType2 = inner2.GetTypeMembers("Type").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outer2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(outer2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, inner2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1), SymbolEquivalenceComparer.Instance.GetHashCode(inner2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outerType1, outerType2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outerType1), SymbolEquivalenceComparer.Instance.GetHashCode(outerType2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(innerType1, innerType2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(innerType1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(inner1, outerType1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(outerType1, innerType1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(innerType1, outer1)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(inner1.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, innerType1.ContainingSymbol.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, innerType1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outerType1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(outerType1.ContainingSymbol)); } } [Fact] public void TestNamedTypesEquivalent() { var csharpCode1 = @" class Type1 { } class Type2<X> { } "; var csharpCode2 = @" class Type1 { void Foo(); } class Type2<Y> { }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single(); var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type1_v1), SymbolEquivalenceComparer.Instance.GetHashCode(type1_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v2, type2_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type2_v1), SymbolEquivalenceComparer.Instance.GetHashCode(type2_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type2_v1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type1_v1)); } } [Fact] public void TestNamedTypesDifferentIfNameChanges() { var csharpCode1 = @" class Type1 { }"; var csharpCode2 = @" class Type2 { void Foo(); }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [Fact] public void TestNamedTypesDifferentIfTypeKindChanges() { var csharpCode1 = @" struct Type1 { }"; var csharpCode2 = @" class Type1 { void Foo(); }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [Fact] public void TestNamedTypesDifferentIfArityChanges() { var csharpCode1 = @" class Type1 { }"; var csharpCode2 = @" class Type1<T> { void Foo(); }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [Fact] public void TestNamedTypesDifferentIfContainerDifferent() { var csharpCode1 = @" class Outer { class Type1 { } }"; var csharpCode2 = @" class Other { class Type1 { void Foo(); } }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var outer = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Outer").Single(); var other = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Other").Single(); var type1_v1 = outer.GetTypeMembers("Type1").Single(); var type1_v2 = other.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [Fact] public void TestAliasedTypes1() { var csharpCode1 = @" using i = System.Int32; class Type1 { void Foo(i o1) { } }"; var csharpCode2 = @" class Type1 { void Foo(int o1) { } }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2)) { var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public void TestCSharpReducedExtensionMethodsAreEquivalent() { var code = @" class Zed {} public static class Extensions { public static void NotGeneric(this Zed z, int data) { } public static void GenericThis<T>(this T me, int data) where T : Zed { } public static void GenericNotThis<T>(this Zed z, T data) { } public static void GenericThisAndMore<T,S>(this T me, S data) where T : Zed { } public static void GenericThisAndOther<T>(this T me, T data) where T : Zed { } } class Test { void NotGeneric() { Zed z; int n; z.NotGeneric(n); } void GenericThis() { Zed z; int n; z.GenericThis(n); } void GenericNotThis() { Zed z; int n; z.GenericNotThis(n); } void GenericThisAndMore() { Zed z; int n; z.GenericThisAndMore(n); } void GenericThisAndOther() { Zed z; z.GenericThisAndOther(z); } } "; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code)) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code)) { var comp1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result; var comp2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result; TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther"); } } [Fact] public void TestVisualBasicReducedExtensionMethodsAreEquivalent() { var code = @" Imports System.Runtime.CompilerServices Class Zed End Class Module Extensions <Extension> Public Sub NotGeneric(z As Zed, data As Integer) End Sub <Extension> Public Sub GenericThis(Of T As Zed)(m As T, data as Integer) End Sub <Extension> Public Sub GenericNotThis(Of T)(z As Zed, data As T) End Sub <Extension> Public Sub GenericThisAndMore(Of T As Zed, S)(m As T, data As S) End Sub <Extension> Public Sub GenericThisAndOther(Of T As Zed)(m As T, data As T) End Sub End Module Class Test Sub NotGeneric() Dim z As Zed Dim n As Integer z.NotGeneric(n) End Sub Sub GenericThis() Dim z As Zed Dim n As Integer z.GenericThis(n) End Sub Sub GenericNotThis() Dim z As Zed Dim n As Integer z.GenericNotThis(n) End Sub Sub GenericThisAndMore() Dim z As Zed Dim n As Integer z.GenericThisAndMore(n) End Sub Sub GenericThisAndOther() Dim z As Zed z.GenericThisAndOther(z) End Sub End Class "; using (var workspace1 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code)) using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code)) { var comp1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result; var comp2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result; TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther"); } } [Fact] public void TestDifferentModules() { var csharpCode = @"namespace N { namespace M { } }"; using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "FooModule"))) using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "BarModule"))) { var namespace1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M"); var namespace2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M"); Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(namespace1, namespace2)); Assert.Equal(SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace1), SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(namespace1, namespace2)); Assert.NotEqual(SymbolEquivalenceComparer.Instance.GetHashCode(namespace1), SymbolEquivalenceComparer.Instance.GetHashCode(namespace2)); } } [Fact] public void AssemblyComparer1() { var references = new[] { TestReferences.NetFx.v4_0_30319.mscorlib }; string source = "public class T {}"; string sourceV1 = "[assembly: System.Reflection.AssemblyVersion(\"1.0.0.0\")] public class T {}"; string sourceV2 = "[assembly: System.Reflection.AssemblyVersion(\"2.0.0.0\")] public class T {}"; var a1 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions); var a2 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions); var b1 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV1) }, references, CSharpSignedDllOptions); var b2 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions); var b3 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions); var ta1 = (ITypeSymbol)a1.GlobalNamespace.GetMembers("T").Single(); var ta2 = (ITypeSymbol)a2.GlobalNamespace.GetMembers("T").Single(); var tb1 = (ITypeSymbol)b1.GlobalNamespace.GetMembers("T").Single(); var tb2 = (ITypeSymbol)b2.GlobalNamespace.GetMembers("T").Single(); var tb3 = (ITypeSymbol)b3.GlobalNamespace.GetMembers("T").Single(); var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance); // same name: Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, ta2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(ta1, ta2)); Assert.True(identityComparer.Equals(ta1, ta2)); // different name: Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, tb1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(ta1, tb1)); Assert.False(identityComparer.Equals(ta1, tb1)); // different identity Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb1, tb2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb1, tb2)); Assert.False(identityComparer.Equals(tb1, tb2)); // same identity Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb2, tb3)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb2, tb3)); Assert.True(identityComparer.Equals(tb2, tb3)); } private sealed class AssemblySymbolIdentityComparer : IEqualityComparer<IAssemblySymbol> { public static readonly IEqualityComparer<IAssemblySymbol> Instance = new AssemblySymbolIdentityComparer(); public bool Equals(IAssemblySymbol x, IAssemblySymbol y) { return x.Identity.Equals(y.Identity); } public int GetHashCode(IAssemblySymbol obj) { return obj.Identity.GetHashCode(); } } [Fact] public void CustomModifiers_Methods1() { const string ilSource = @" .class public C { .method public instance int32 [] modopt([mscorlib]System.Int64) F( // 0 int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32 [] modopt([mscorlib]System.Boolean) F( // 1 int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32[] F( // 2 int32 a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32[] F( // 3 int32 a, int32 b) { ldnull throw } } "; MetadataReference r1, r2; using (var tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource)) { byte[] bytes = File.ReadAllBytes(tempAssembly.Path); r1 = MetadataReference.CreateFromImage(bytes); r2 = MetadataReference.CreateFromImage(bytes); } var c1 = CS.CSharpCompilation.Create("comp1", new SyntaxTree[0], new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r1 }); var c2 = CS.CSharpCompilation.Create("comp2", new SyntaxTree[0], new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r2 }); var type1 = (ITypeSymbol)c1.GlobalNamespace.GetMembers("C").Single(); var type2 = (ITypeSymbol)c2.GlobalNamespace.GetMembers("C").Single(); var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance); var f1 = type1.GetMembers("F"); var f2 = type2.GetMembers("F"); Assert.True(identityComparer.Equals(f1[0], f2[0])); Assert.False(identityComparer.Equals(f1[0], f2[1])); Assert.False(identityComparer.Equals(f1[0], f2[2])); Assert.False(identityComparer.Equals(f1[0], f2[3])); Assert.False(identityComparer.Equals(f1[1], f2[0])); Assert.True(identityComparer.Equals(f1[1], f2[1])); Assert.False(identityComparer.Equals(f1[1], f2[2])); Assert.False(identityComparer.Equals(f1[1], f2[3])); Assert.False(identityComparer.Equals(f1[2], f2[0])); Assert.False(identityComparer.Equals(f1[2], f2[1])); Assert.True(identityComparer.Equals(f1[2], f2[2])); Assert.False(identityComparer.Equals(f1[2], f2[3])); Assert.False(identityComparer.Equals(f1[3], f2[0])); Assert.False(identityComparer.Equals(f1[3], f2[1])); Assert.False(identityComparer.Equals(f1[3], f2[2])); Assert.True(identityComparer.Equals(f1[3], f2[3])); } private void TestReducedExtension<TInvocation>(Compilation comp1, Compilation comp2, string typeName, string methodName) where TInvocation : SyntaxNode { var method1 = GetInvokedSymbol<TInvocation>(comp1, typeName, methodName); var method2 = GetInvokedSymbol<TInvocation>(comp2, typeName, methodName); Assert.NotNull(method1); Assert.Equal(method1.MethodKind, MethodKind.ReducedExtension); Assert.NotNull(method2); Assert.Equal(method2.MethodKind, MethodKind.ReducedExtension); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method1, method2)); var cfmethod1 = method1.ConstructedFrom; var cfmethod2 = method2.ConstructedFrom; Assert.True(SymbolEquivalenceComparer.Instance.Equals(cfmethod1, cfmethod2)); } private IMethodSymbol GetInvokedSymbol<TInvocation>(Compilation compilation, string typeName, string methodName) where TInvocation : SyntaxNode { var type1 = compilation.GlobalNamespace.GetTypeMembers(typeName).Single(); var method = type1.GetMembers(methodName).Single(); var method_root = method.DeclaringSyntaxReferences[0].GetSyntax(); var invocation = method_root.DescendantNodes().OfType<TInvocation>().FirstOrDefault(); if (invocation == null) { // vb method root is statement, but we need block to find body with invocation invocation = method_root.Parent.DescendantNodes().OfType<TInvocation>().First(); } var model = compilation.GetSemanticModel(invocation.SyntaxTree); var info = model.GetSymbolInfo(invocation); return info.Symbol as IMethodSymbol; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Sql.LegacySdk; using Microsoft.Azure.Management.Sql.LegacySdk.Models; namespace Microsoft.Azure.Management.Sql.LegacySdk { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class ElasticPoolRecommendedActionOperationsExtensions { /// <summary> /// Returns details of a recommended action. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IElasticPoolRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='elasticPoolName'> /// Required. The name of the Azure SQL elastic pool. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL elastic pool advisor. /// </param> /// <param name='recommendedActionName'> /// Required. The name of the Azure SQL elastic pool recommended action. /// </param> /// <returns> /// Represents the response to a get recommended action request. /// </returns> public static RecommendedActionGetResponse Get(this IElasticPoolRecommendedActionOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string advisorName, string recommendedActionName) { return Task.Factory.StartNew((object s) => { return ((IElasticPoolRecommendedActionOperations)s).GetAsync(resourceGroupName, serverName, elasticPoolName, advisorName, recommendedActionName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns details of a recommended action. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IElasticPoolRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='elasticPoolName'> /// Required. The name of the Azure SQL elastic pool. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL elastic pool advisor. /// </param> /// <param name='recommendedActionName'> /// Required. The name of the Azure SQL elastic pool recommended action. /// </param> /// <returns> /// Represents the response to a get recommended action request. /// </returns> public static Task<RecommendedActionGetResponse> GetAsync(this IElasticPoolRecommendedActionOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string advisorName, string recommendedActionName) { return operations.GetAsync(resourceGroupName, serverName, elasticPoolName, advisorName, recommendedActionName, CancellationToken.None); } /// <summary> /// Returns list of recommended actions for this advisor. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IElasticPoolRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='elasticPoolName'> /// Required. The name of the Azure SQL elastic pool. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL elastic pool advisor. /// </param> /// <returns> /// Represents the response to a list recommended actions request. /// </returns> public static RecommendedActionListResponse List(this IElasticPoolRecommendedActionOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string advisorName) { return Task.Factory.StartNew((object s) => { return ((IElasticPoolRecommendedActionOperations)s).ListAsync(resourceGroupName, serverName, elasticPoolName, advisorName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns list of recommended actions for this advisor. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IElasticPoolRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='elasticPoolName'> /// Required. The name of the Azure SQL elastic pool. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL elastic pool advisor. /// </param> /// <returns> /// Represents the response to a list recommended actions request. /// </returns> public static Task<RecommendedActionListResponse> ListAsync(this IElasticPoolRecommendedActionOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string advisorName) { return operations.ListAsync(resourceGroupName, serverName, elasticPoolName, advisorName, CancellationToken.None); } /// <summary> /// Updates recommended action state. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IElasticPoolRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='elasticPoolName'> /// Required. The name of the Azure SQL elastic pool. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL elastic pool advisor. /// </param> /// <param name='recommendedActionName'> /// Required. The name of the Azure SQL elastic pool recommended action. /// </param> /// <param name='parameters'> /// Required. The required parameters for updating recommended action /// state. /// </param> /// <returns> /// Represents the response to an update recommended action request. /// </returns> public static RecommendedActionUpdateResponse Update(this IElasticPoolRecommendedActionOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string advisorName, string recommendedActionName, RecommendedActionUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IElasticPoolRecommendedActionOperations)s).UpdateAsync(resourceGroupName, serverName, elasticPoolName, advisorName, recommendedActionName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates recommended action state. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IElasticPoolRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='elasticPoolName'> /// Required. The name of the Azure SQL elastic pool. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL elastic pool advisor. /// </param> /// <param name='recommendedActionName'> /// Required. The name of the Azure SQL elastic pool recommended action. /// </param> /// <param name='parameters'> /// Required. The required parameters for updating recommended action /// state. /// </param> /// <returns> /// Represents the response to an update recommended action request. /// </returns> public static Task<RecommendedActionUpdateResponse> UpdateAsync(this IElasticPoolRecommendedActionOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string advisorName, string recommendedActionName, RecommendedActionUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, serverName, elasticPoolName, advisorName, recommendedActionName, parameters, CancellationToken.None); } } }
// 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.IO; using System.Collections.Generic; using Microsoft.Build.BuildEngine.Shared; using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities; namespace Microsoft.Build.BuildEngine { internal class PropertyDefinition { private string name = null; private string value = null; private string source = null; public PropertyDefinition(string name, string value, string source) { error.VerifyThrowArgumentLength(name, nameof(name)); error.VerifyThrowArgumentLength(source, nameof(source)); // value can be the empty string but not null error.VerifyThrowArgumentNull(value, nameof(value)); this.name = name; this.value = value; this.source = source; } /// <summary> /// The name of the property /// </summary> public string Name { get { return name; } } /// <summary> /// The value of the property /// </summary> public string Value { get { return value; } } /// <summary> /// A description of the location where the property was defined, /// such as a registry key path or a path to a config file and /// line number. /// </summary> public string Source { get { return source; } } } internal abstract class ToolsetReader { /// <summary> /// Gathers toolset data from both the registry and configuration file, if any /// </summary> /// <param name="toolsets"></param> /// <param name="globalProperties"></param> /// <param name="initialProperties"></param> /// <returns></returns> internal static string ReadAllToolsets(ToolsetCollection toolsets, BuildPropertyGroup globalProperties, BuildPropertyGroup initialProperties) { return ReadAllToolsets(toolsets, null, null, globalProperties, initialProperties, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry); } /// <summary> /// Gathers toolset data from the registry and configuration file, if any: /// allows you to specify which of the registry and configuration file to /// read from by providing ToolsetInitialization /// </summary> /// <param name="toolsets"></param> /// <param name="globalProperties"></param> /// <param name="initialProperties"></param> /// <param name="locations"></param> /// <returns></returns> internal static string ReadAllToolsets(ToolsetCollection toolsets, BuildPropertyGroup globalProperties, BuildPropertyGroup initialProperties, ToolsetDefinitionLocations locations) { return ReadAllToolsets(toolsets, null, null, globalProperties, initialProperties, locations); } /// <summary> /// Gathers toolset data from the registry and configuration file, if any. /// NOTE: this method is internal for unit testing purposes only. /// </summary> /// <param name="toolsets"></param> /// <param name="registryReader"></param> /// <param name="configurationReader"></param> /// <param name="globalProperties"></param> /// <param name="initialProperties"></param> /// <param name="locations"></param> /// <returns></returns> internal static string ReadAllToolsets(ToolsetCollection toolsets, ToolsetRegistryReader registryReader, ToolsetConfigurationReader configurationReader, BuildPropertyGroup globalProperties, BuildPropertyGroup initialProperties, ToolsetDefinitionLocations locations) { // The 2.0 .NET Framework installer did not write a ToolsVersion key for itself in the registry. // The 3.5 installer writes one for 2.0, but 3.5 might not be installed. // The 4.0 and subsequent installers can't keep writing the 2.0 one, because (a) it causes SxS issues and (b) we // don't want it unless 2.0 is installed. // So if the 2.0 framework is actually installed, and we're reading the registry, create a toolset for it. // The registry and config file can overwrite it. if ( ((locations & ToolsetDefinitionLocations.Registry) != 0) && !toolsets.Contains("2.0") && FrameworkLocationHelper.PathToDotNetFrameworkV20 != null ) { Toolset synthetic20Toolset = new Toolset("2.0", FrameworkLocationHelper.PathToDotNetFrameworkV20, initialProperties); toolsets.Add(synthetic20Toolset); } // The ordering here is important because the configuration file should have greater precedence // than the registry string defaultToolsVersionFromRegistry = null; if ((locations & ToolsetDefinitionLocations.Registry) == ToolsetDefinitionLocations.Registry) { ToolsetRegistryReader registryReaderToUse = registryReader ?? new ToolsetRegistryReader(); // We do not accumulate properties when reading them from the registry, because the order // in which values are returned to us is essentially random: so we disallow one property // in the registry to refer to another also in the registry defaultToolsVersionFromRegistry = registryReaderToUse.ReadToolsets(toolsets, globalProperties, initialProperties, false /* do not accumulate properties */); } string defaultToolsVersionFromConfiguration = null; if ((locations & ToolsetDefinitionLocations.ConfigurationFile) == ToolsetDefinitionLocations.ConfigurationFile) { if (configurationReader == null && ConfigurationFileMayHaveToolsets()) { // We haven't been passed in a fake configuration reader by a unit test, // and it looks like we have a .config file to read, so create a real // configuration reader configurationReader = new ToolsetConfigurationReader(); } if (configurationReader != null) { ToolsetConfigurationReader configurationReaderToUse = configurationReader ?? new ToolsetConfigurationReader(); // Accumulation of properties is okay in the config file because it's deterministically ordered defaultToolsVersionFromConfiguration = configurationReaderToUse.ReadToolsets(toolsets, globalProperties, initialProperties, true /* accumulate properties */); } } // We'll use the default from the configuration file if it was specified, otherwise we'll try // the one from the registry. It's possible (and valid) that neither the configuration file // nor the registry specify a default, in which case we'll just return null. string defaultToolsVersion = defaultToolsVersionFromConfiguration ?? defaultToolsVersionFromRegistry; // If we got a default version from the registry or config file, and it // actually exists, fine. // Otherwise we have to come up with one. if (defaultToolsVersion == null || !toolsets.Contains(defaultToolsVersion)) { // We're going to choose a hard coded default tools version of 2.0. defaultToolsVersion = Constants.defaultToolsVersion; // But don't overwrite any existing tools path for this default we're choosing. if (!toolsets.Contains(Constants.defaultToolsVersion)) { // There's no tools path already for 2.0, so use the path to the v2.0 .NET Framework. // If an old-fashioned caller sets BinPath property, or passed a BinPath to the constructor, // that will overwrite what we're setting here. ErrorUtilities.VerifyThrow(Constants.defaultToolsVersion == "2.0", "Getting 2.0 FX path so default should be 2.0"); string pathToFramework = FrameworkLocationHelper.PathToDotNetFrameworkV20; // We could not find the default toolsversion because it was not installed on the machine. Fallback to the // one we expect to always be there when running msbuild 4.0. if (pathToFramework == null) { pathToFramework = FrameworkLocationHelper.PathToDotNetFrameworkV40; defaultToolsVersion = Constants.defaultFallbackToolsVersion; } // Again don't overwrite any existing tools path for this default we're choosing. if (!toolsets.Contains(defaultToolsVersion)) { Toolset defaultToolset = new Toolset(defaultToolsVersion, pathToFramework, initialProperties); toolsets.Add(defaultToolset); } } } return defaultToolsVersion; } /// <summary> /// Creating a ToolsetConfigurationReader, and also reading toolsets from the /// configuration file, are a little expensive. To try to avoid this cost if it's /// not necessary, we'll check if the file exists first. If it exists, we'll scan for /// the string "toolsVersion" to see if it might actually have any tools versions /// defined in it. /// </summary> /// <returns>True if there may be toolset definitions, otherwise false</returns> private static bool ConfigurationFileMayHaveToolsets() { bool result; try { result = (File.Exists(FileUtilities.CurrentExecutableConfigurationFilePath) && File.ReadAllText(FileUtilities.CurrentExecutableConfigurationFilePath).Contains("toolsVersion")); } catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception. { if (ExceptionHandling.NotExpectedException(e)) throw; // There was some problem reading the config file: let the configuration reader // encounter it result = true; } return result; } /// <summary> /// Populates the toolset collection passed in with the toolsets read from some location. /// </summary> /// <remarks>Internal for unit testing only</remarks> /// <param name="toolsets"></param> /// <param name="globalProperties"></param> /// <param name="initialProperties"></param> /// <param name="accumulateProperties"></param> /// <returns>the default tools version if available, or null otherwise</returns> internal string ReadToolsets(ToolsetCollection toolsets, BuildPropertyGroup globalProperties, BuildPropertyGroup initialProperties, bool accumulateProperties) { error.VerifyThrowArgumentNull(toolsets, nameof(toolsets)); ReadEachToolset(toolsets, globalProperties, initialProperties, accumulateProperties); string defaultToolsVersion = DefaultToolsVersion; // We don't check whether the default tools version actually // corresponds to a toolset definition. That's because our default for // the indefinite future is 2.0, and 2.0 might not be installed, which is fine. // If a project tries to use 2.0 (or whatever the default is) in these circumstances // they'll get a nice error saying that toolset isn't available and listing those that are. return defaultToolsVersion; } /// <summary> /// Reads all the toolsets and populates the given ToolsetCollection with them /// </summary> /// <param name="toolsets"></param> /// <param name="globalProperties"></param> /// <param name="initialProperties"></param> /// <param name="accumulateProperties"></param> private void ReadEachToolset(ToolsetCollection toolsets, BuildPropertyGroup globalProperties, BuildPropertyGroup initialProperties, bool accumulateProperties) { foreach (PropertyDefinition toolsVersion in ToolsVersions) { // We clone here because we don't want to interfere with the evaluation // of subsequent Toolsets; otherwise, properties found during the evaluation // of this Toolset would be persisted in initialProperties and appear // to later Toolsets as Global or Environment properties from the Engine. BuildPropertyGroup initialPropertiesClone = initialProperties.Clone(true /* deep clone */); Toolset toolset = ReadToolset(toolsVersion, globalProperties, initialPropertiesClone, accumulateProperties); if (toolset != null) { toolsets.Add(toolset); } } } /// <summary> /// Reads the settings for a specified tools version /// </summary> /// <param name="toolsVersion"></param> /// <param name="globalProperties"></param> /// <param name="initialProperties"></param> /// <param name="accumulateProperties"></param> /// <returns></returns> private Toolset ReadToolset(PropertyDefinition toolsVersion, BuildPropertyGroup globalProperties, BuildPropertyGroup initialProperties, bool accumulateProperties) { // Initial properties is the set of properties we're going to use to expand property expressions like $(foo) // in the values we read out of the registry or config file. We'll add to it as we pick up properties (including binpath) // from the registry or config file, so that properties there can be referenced in values below them. // After processing all the properties, we don't need initialProperties anymore. string toolsPath = null; string binPath = null; BuildPropertyGroup properties = new BuildPropertyGroup(); IEnumerable<PropertyDefinition> rawProperties = GetPropertyDefinitions(toolsVersion.Name); Expander expander = new Expander(initialProperties); foreach (PropertyDefinition property in rawProperties) { if (String.Equals(property.Name, ReservedPropertyNames.toolsPath, StringComparison.OrdinalIgnoreCase)) { toolsPath = ExpandProperty(property, expander); toolsPath = ExpandRelativePathsRelativeToExeLocation(toolsPath); if (accumulateProperties) { SetProperty ( new PropertyDefinition(ReservedPropertyNames.toolsPath, toolsPath, property.Source), initialProperties, globalProperties ); } } else if (String.Equals(property.Name, ReservedPropertyNames.binPath, StringComparison.OrdinalIgnoreCase)) { binPath = ExpandProperty(property, expander); binPath = ExpandRelativePathsRelativeToExeLocation(binPath); if (accumulateProperties) { SetProperty ( new PropertyDefinition(ReservedPropertyNames.binPath, binPath, property.Source), initialProperties, globalProperties ); } } else if(ReservedPropertyNames.IsReservedProperty(property.Name)) { // We don't allow toolsets to define reserved properties string baseMessage = ResourceUtilities.FormatResourceString("CannotModifyReservedProperty", property.Name); InvalidToolsetDefinitionException.Throw("InvalidPropertyNameInToolset", property.Name, property.Source, baseMessage); } else { // It's an arbitrary property string propertyValue = ExpandProperty(property, expander); PropertyDefinition expandedProperty = new PropertyDefinition(property.Name, propertyValue, property.Source); SetProperty(expandedProperty, properties, globalProperties); if (accumulateProperties) { SetProperty(expandedProperty, initialProperties, globalProperties); } } if (accumulateProperties) { expander = new Expander(initialProperties); } } // All tools versions must specify a value for MSBuildToolsPath (or MSBuildBinPath) if (String.IsNullOrEmpty(toolsPath) && String.IsNullOrEmpty(binPath)) { InvalidToolsetDefinitionException.Throw("MSBuildToolsPathIsNotSpecified", toolsVersion.Name, toolsVersion.Source); } // If both MSBuildBinPath and MSBuildToolsPath are present, they must be the same if (toolsPath != null && binPath != null && !toolsPath.Equals(binPath, StringComparison.OrdinalIgnoreCase)) { return null; } Toolset toolset = null; try { toolset = new Toolset(toolsVersion.Name, toolsPath ?? binPath, properties); } catch (ArgumentException e) { InvalidToolsetDefinitionException.Throw("ErrorCreatingToolset", toolsVersion.Name, e.Message); } return toolset; } /// <summary> /// Expands the given unexpanded property expression using the properties in the /// given BuildPropertyGroup. /// </summary> /// <param name="unexpandedProperty"></param> /// <param name="properties"></param> /// <returns></returns> private string ExpandProperty(PropertyDefinition property, Expander expander) { try { return expander.ExpandAllIntoStringLeaveEscaped(property.Value, null); } catch (InvalidProjectFileException ex) { InvalidToolsetDefinitionException.Throw(ex, "ErrorEvaluatingToolsetPropertyExpression", property.Value, property.Source, ex.Message); } return string.Empty; } /// <summary> /// Sets the given property in the given property group. /// </summary> /// <param name="property"></param> /// <param name="propertyGroup"></param> /// <param name="globalProperties"></param> private void SetProperty(PropertyDefinition property, BuildPropertyGroup propertyGroup, BuildPropertyGroup globalProperties) { try { // Global properties cannot be overwritten if (globalProperties[property.Name] == null) { propertyGroup.SetProperty(property.Name, property.Value); } } catch (ArgumentException ex) { InvalidToolsetDefinitionException.Throw(ex, "InvalidPropertyNameInToolset", property.Name, property.Source, ex.Message); } } /// <summary> /// Given a path, de-relativizes it using the location of the currently /// executing .exe as the base directory. For example, the path "..\foo" /// becomes "c:\windows\microsoft.net\framework\foo" if the current exe is /// "c:\windows\microsoft.net\framework\v3.5.1234\msbuild.exe". /// If the path is not relative, it is returned without modification. /// If the path is invalid, it is returned without modification. /// </summary> /// <param name="path"></param> /// <returns></returns> private string ExpandRelativePathsRelativeToExeLocation(string path) { try { // Trim, because we don't want to do anything with empty values // (those should cause an error) string trimmedValue = path.Trim(); if (trimmedValue.Length > 0 && !Path.IsPathRooted(trimmedValue)) { path = Path.GetFullPath( Path.Combine(FileUtilities.CurrentExecutableDirectory, trimmedValue)); } } catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception. { if (ExceptionHandling.NotExpectedException(e)) throw; // This means that the path looked relative, but was an invalid path. In this case, we'll // just not expand it, and carry on - to be consistent with what happens when there's a // non-relative bin path with invalid characters. The problem will be detected later when // it's used in a project file. } return path; } /// <summary> /// Returns the list of tools versions /// </summary> protected abstract IEnumerable<PropertyDefinition> ToolsVersions { get; } /// <summary> /// Returns the default tools version, or null if none was specified /// </summary> protected abstract string DefaultToolsVersion { get; } /// <summary> /// Provides an enumerator over property definitions for a specified tools version /// </summary> /// <param name="toolsVersion"></param> /// <returns></returns> protected abstract IEnumerable<PropertyDefinition> GetPropertyDefinitions(string toolsVersion); } }
using System.Linq; using Robust.Shared.GameStates; using Robust.Shared.Prototypes; namespace Content.Shared.Tag; public sealed class TagSystem : EntitySystem { [Dependency] private readonly IPrototypeManager _proto = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<TagComponent, ComponentInit>(OnTagInit); SubscribeLocalEvent<TagComponent, ComponentGetState>(OnTagGetState); SubscribeLocalEvent<TagComponent, ComponentHandleState>(OnTagHandleState); } private void OnTagHandleState(EntityUid uid, TagComponent component, ref ComponentHandleState args) { if (args.Current is not TagComponentState state) return; component.Tags.Clear(); foreach (var tag in state.Tags) { GetTagOrThrow(tag); component.Tags.Add(tag); } } private static void OnTagGetState(EntityUid uid, TagComponent component, ref ComponentGetState args) { var tags = new string[component.Tags.Count]; var i = 0; foreach (var tag in component.Tags) { tags[i] = tag; i++; } args.State = new TagComponentState(tags); } private void OnTagInit(EntityUid uid, TagComponent component, ComponentInit args) { foreach (var tag in component.Tags) { GetTagOrThrow(tag); } } private TagPrototype GetTagOrThrow(string id) { return _proto.Index<TagPrototype>(id); } /// <summary> /// Tries to add a tag to an entity if the tag doesn't already exist. /// </summary> /// <param name="entity">The entity to add the tag to.</param> /// <param name="id">The tag to add.</param> /// <returns> /// true if it was added, false otherwise even if it already existed. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if no <see cref="TagPrototype"/> exists with the given id. /// </exception> public bool AddTag(EntityUid entity, string id) { return EntityManager.EnsureComponent<TagComponent>(entity, out var component) && AddTag(component, id); } /// <summary> /// Tries to add the given tags to an entity if the tags don't already exist. /// </summary> /// <param name="entity">The entity to add the tag to.</param> /// <param name="ids">The tags to add.</param> /// <returns> /// true if any tags were added, false otherwise even if they all already existed. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool AddTags(EntityUid entity, params string[] ids) { return EntityManager.EnsureComponent<TagComponent>(entity, out var component) && AddTags(component, ids); } /// <summary> /// Tries to add the given tags to an entity if the tags don't already exist. /// </summary> /// <param name="entity">The entity to add the tag to.</param> /// <param name="ids">The tags to add.</param> /// <returns> /// true if any tags were added, false otherwise even if they all already existed. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool AddTags(EntityUid entity, IEnumerable<string> ids) { return EntityManager.EnsureComponent<TagComponent>(entity, out var component) && AddTags(component, ids); } /// <summary> /// Tries to add a tag to an entity if it has a <see cref="TagComponent"/> /// and the tag doesn't already exist. /// </summary> /// <param name="entity">The entity to add the tag to.</param> /// <param name="id">The tag to add.</param> /// <returns> /// true if it was added, false otherwise even if it already existed. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if no <see cref="TagPrototype"/> exists with the given id. /// </exception> public bool TryAddTag(EntityUid entity, string id) { return TryComp<TagComponent>(entity, out var component) && AddTag(component, id); } /// <summary> /// Tries to add the given tags to an entity if it has a /// <see cref="TagComponent"/> and the tags don't already exist. /// </summary> /// <param name="entity">The entity to add the tag to.</param> /// <param name="ids">The tags to add.</param> /// <returns> /// true if any tags were added, false otherwise even if they all already existed. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool TryAddTags(EntityUid entity, params string[] ids) { return TryComp<TagComponent>(entity, out var component) && AddTags(component, ids); } /// <summary> /// Tries to add the given tags to an entity if it has a /// <see cref="TagComponent"/> and the tags don't already exist. /// </summary> /// <param name="entity">The entity to add the tag to.</param> /// <param name="ids">The tags to add.</param> /// <returns> /// true if any tags were added, false otherwise even if they all already existed. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool TryAddTags(EntityUid entity, IEnumerable<string> ids) { return TryComp<TagComponent>(entity, out var component) && AddTags(component, ids); } /// <summary> /// Checks if a tag has been added to an entity. /// </summary> /// <param name="entity">The entity to check.</param> /// <param name="id">The tag to check for.</param> /// <returns>true if it exists, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if no <see cref="TagPrototype"/> exists with the given id. /// </exception> public bool HasTag(EntityUid entity, string id) { return TryComp<TagComponent>(entity, out var component) && HasTag(component, id); } /// <summary> /// Checks if all of the given tags have been added to an entity. /// </summary> /// <param name="entity">The entity to check.</param> /// <param name="ids">The tags to check for.</param> /// <returns>true if they all exist, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool HasAllTags(EntityUid entity, params string[] ids) { return TryComp<TagComponent>(entity, out var component) && HasAllTags(component, ids); } /// <summary> /// Checks if all of the given tags have been added to an entity. /// </summary> /// <param name="entity">The entity to check.</param> /// <param name="ids">The tags to check for.</param> /// <returns>true if they all exist, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool HasAllTags(EntityUid entity, IEnumerable<string> ids) { return TryComp<TagComponent>(entity, out var component) && HasAllTags(component, ids); } /// <summary> /// Checks if all of the given tags have been added to an entity. /// </summary> /// <param name="entity">The entity to check.</param> /// <param name="ids">The tags to check for.</param> /// <returns>true if any of them exist, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool HasAnyTag(EntityUid entity, params string[] ids) { return TryComp<TagComponent>(entity, out var component) && HasAnyTag(component, ids); } /// <summary> /// Checks if all of the given tags have been added to an entity. /// </summary> /// <param name="entity">The entity to check.</param> /// <param name="ids">The tags to check for.</param> /// <returns>true if any of them exist, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool HasAnyTag(EntityUid entity, IEnumerable<string> ids) { return TryComp<TagComponent>(entity, out var component) && HasAnyTag(component, ids); } /// <summary> /// Tries to remove a tag from an entity if it exists. /// </summary> /// <param name="entity">The entity to remove the tag from.</param> /// <param name="id">The tag to remove.</param> /// <returns> /// true if it was removed, false otherwise even if it didn't exist. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if no <see cref="TagPrototype"/> exists with the given id. /// </exception> public bool RemoveTag(EntityUid entity, string id) { return TryComp<TagComponent>(entity, out var component) && RemoveTag(component, id); } /// <summary> /// Tries to remove a tag from an entity if it exists. /// </summary> /// <param name="entity">The entity to remove the tag from.</param> /// <param name="ids">The tag to remove.</param> /// <returns> /// true if it was removed, false otherwise even if it didn't exist. /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> /// </returns> public bool RemoveTags(EntityUid entity, params string[] ids) { return TryComp<TagComponent>(entity, out var component) && RemoveTags(component, ids); } /// <summary> /// Tries to remove a tag from an entity if it exists. /// </summary> /// <param name="entity">The entity to remove the tag from.</param> /// <param name="ids">The tag to remove.</param> /// <returns> /// true if it was removed, false otherwise even if it didn't exist. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool RemoveTags(EntityUid entity, IEnumerable<string> ids) { return TryComp<TagComponent>(entity, out var component) && RemoveTags(component, ids); } /// <summary> /// Tries to add a tag if it doesn't already exist. /// </summary> /// <param name="id">The tag to add.</param> /// <returns>true if it was added, false if it already existed.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if no <see cref="TagPrototype"/> exists with the given id. /// </exception> public bool AddTag(TagComponent component, string id) { GetTagOrThrow(id); var added = component.Tags.Add(id); if (added) { Dirty(component); return true; } return false; } /// <summary> /// Tries to add the given tags if they don't already exist. /// </summary> /// <param name="ids">The tags to add.</param> /// <returns>true if any tags were added, false if they all already existed.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool AddTags(TagComponent component, params string[] ids) { return AddTags(component, ids.AsEnumerable()); } /// <summary> /// Tries to add the given tags if they don't already exist. /// </summary> /// <param name="ids">The tags to add.</param> /// <returns>true if any tags were added, false if they all already existed.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool AddTags(TagComponent component, IEnumerable<string> ids) { var count = component.Tags.Count; foreach (var id in ids) { GetTagOrThrow(id); component.Tags.Add(id); } if (component.Tags.Count > count) { Dirty(component); return true; } return false; } /// <summary> /// Checks if a tag has been added. /// </summary> /// <param name="id">The tag to check for.</param> /// <returns>true if it exists, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if no <see cref="TagPrototype"/> exists with the given id. /// </exception> public bool HasTag(TagComponent component, string id) { GetTagOrThrow(id); return component.Tags.Contains(id); } /// <summary> /// Checks if all of the given tags have been added. /// </summary> /// <param name="ids">The tags to check for.</param> /// <returns>true if they all exist, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool HasAllTags(TagComponent component, params string[] ids) { return HasAllTags(component, ids.AsEnumerable()); } /// <summary> /// Checks if all of the given tags have been added. /// </summary> /// <param name="ids">The tags to check for.</param> /// <returns>true if they all exist, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool HasAllTags(TagComponent component, IEnumerable<string> ids) { foreach (var id in ids) { GetTagOrThrow(id); if (!component.Tags.Contains(id)) return false; } return true; } /// <summary> /// Checks if any of the given tags have been added. /// </summary> /// <param name="ids">The tags to check for.</param> /// <returns>true if any of them exist, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool HasAnyTag(TagComponent component, params string[] ids) { return HasAnyTag(component, ids.AsEnumerable()); } /// <summary> /// Checks if any of the given tags have been added. /// </summary> /// <param name="ids">The tags to check for.</param> /// <returns>true if any of them exist, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool HasAnyTag(TagComponent component, IEnumerable<string> ids) { foreach (var id in ids) { GetTagOrThrow(id); if (component.Tags.Contains(id)) { return true; } } return false; } /// <summary> /// Tries to remove a tag if it exists. /// </summary> /// <returns> /// true if it was removed, false otherwise even if it didn't exist. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if no <see cref="TagPrototype"/> exists with the given id. /// </exception> public bool RemoveTag(TagComponent component, string id) { GetTagOrThrow(id); if (component.Tags.Remove(id)) { Dirty(component); return true; } return false; } /// <summary> /// Tries to remove all of the given tags if they exist. /// </summary> /// <param name="ids">The tags to remove.</param> /// <returns> /// true if it was removed, false otherwise even if they didn't exist. /// </returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool RemoveTags(TagComponent component, params string[] ids) { return RemoveTags(component, ids.AsEnumerable()); } /// <summary> /// Tries to remove all of the given tags if they exist. /// </summary> /// <param name="ids">The tags to remove.</param> /// <returns>true if any tag was removed, false otherwise.</returns> /// <exception cref="UnknownPrototypeException"> /// Thrown if one of the ids represents an unregistered <see cref="TagPrototype"/>. /// </exception> public bool RemoveTags(TagComponent component, IEnumerable<string> ids) { var count = component.Tags.Count; foreach (var id in ids) { GetTagOrThrow(id); component.Tags.Remove(id); } if (component.Tags.Count < count) { Dirty(component); return true; } return false; } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <[email protected]> // // Custom Node Swizzle // Donated by Tobias Pott - @ Tobias Pott // www.tobiaspott.de using System; using UnityEditor; using UnityEngine; namespace AmplifyShaderEditor { [Serializable] [NodeAttributes( "Swizzle", "Misc", "swizzle components of vector types " )] public sealed class SwizzleNode : SingleInputOp { private const string OutputTypeStr = "Output type"; [SerializeField] private WirePortDataType _selectedOutputType = WirePortDataType.FLOAT4; [SerializeField] private int _selectedOutputTypeInt = 4; [SerializeField] private int[] _selectedOutputSwizzleTypes = new int[] { 0, 1, 2, 3 }; private readonly string[] SwizzleVectorChannels = { "x", "y", "z", "w" }; private readonly string[] SwizzleColorChannels = { "r", "g", "b", "a" }; private readonly string[] SwizzleChannelLabels = { "Channel 0", "Channel 1", "Channel 2", "Channel 3" }; private readonly string[] _outputValueTypes ={ "Float", "Vector2", "Vector3", "Vector4"}; protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); m_inputPorts[ 0 ].CreatePortRestrictions( WirePortDataType.FLOAT, WirePortDataType.FLOAT2, WirePortDataType.FLOAT3, WirePortDataType.FLOAT4, WirePortDataType.COLOR, WirePortDataType.INT ); m_inputPorts[ 0 ].DataType = WirePortDataType.FLOAT4; m_outputPorts[ 0 ].DataType = _selectedOutputType; m_textLabelWidth = 90; m_autoWrapProperties = true; m_autoUpdateOutputPort = false; } public override void DrawProperties() { EditorGUILayout.BeginVertical(); EditorGUI.BeginChangeCheck(); _selectedOutputTypeInt = EditorGUILayoutPopup( OutputTypeStr, _selectedOutputTypeInt, _outputValueTypes ); if ( EditorGUI.EndChangeCheck() ) { switch ( _selectedOutputTypeInt ) { case 0: _selectedOutputType = WirePortDataType.FLOAT; break; case 1: _selectedOutputType = WirePortDataType.FLOAT2; break; case 2: _selectedOutputType = WirePortDataType.FLOAT3; break; case 3: _selectedOutputType = WirePortDataType.FLOAT4; break; } UpdatePorts(); } EditorGUILayout.EndVertical(); // Draw base properties base.DrawProperties(); EditorGUILayout.BeginVertical(); int count = 0; switch ( _selectedOutputType ) { case WirePortDataType.FLOAT4: case WirePortDataType.COLOR: count = 4; break; case WirePortDataType.FLOAT3: count = 3; break; case WirePortDataType.FLOAT2: count = 2; break; case WirePortDataType.INT: case WirePortDataType.FLOAT: count = 1; break; case WirePortDataType.OBJECT: case WirePortDataType.FLOAT3x3: case WirePortDataType.FLOAT4x4: break; } int inputMaxChannelId = 0; switch ( m_inputPorts[ 0 ].DataType ) { case WirePortDataType.FLOAT4: case WirePortDataType.COLOR: inputMaxChannelId = 3; break; case WirePortDataType.FLOAT3: inputMaxChannelId = 2; break; case WirePortDataType.FLOAT2: inputMaxChannelId = 1; break; case WirePortDataType.INT: case WirePortDataType.FLOAT: inputMaxChannelId = 0; break; case WirePortDataType.OBJECT: case WirePortDataType.FLOAT3x3: case WirePortDataType.FLOAT4x4: break; } EditorGUI.BeginChangeCheck(); if ( m_inputPorts[ 0 ].DataType == WirePortDataType.COLOR ) { for ( int i = 0; i < count; i++ ) { _selectedOutputSwizzleTypes[ i ] = Mathf.Clamp( EditorGUILayoutPopup( SwizzleChannelLabels[ i ], _selectedOutputSwizzleTypes[ i ], SwizzleColorChannels ), 0, inputMaxChannelId ); } } else { for ( int i = 0; i < count; i++ ) { _selectedOutputSwizzleTypes[ i ] = Mathf.Clamp( EditorGUILayoutPopup( SwizzleChannelLabels[ i ], _selectedOutputSwizzleTypes[ i ], SwizzleVectorChannels ), 0, inputMaxChannelId ); } } if ( EditorGUI.EndChangeCheck() ) { UpdatePorts(); } EditorGUILayout.EndVertical(); } void UpdatePorts() { m_sizeIsDirty = true; ChangeOutputType( _selectedOutputType, false ); } public string GetSwizzleComponentForChannel( int channel ) { if ( m_inputPorts[ 0 ].DataType == WirePortDataType.COLOR ) { return SwizzleColorChannels[ channel ]; } else { return SwizzleVectorChannels[ channel ]; } } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar ) { if ( m_outputPorts[ 0 ].IsLocalValue ) return m_outputPorts[ 0 ].LocalValue; string value = string.Format( "({0}).", m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector ) ); int count = 0; switch ( _selectedOutputType ) { case WirePortDataType.FLOAT4: case WirePortDataType.COLOR: count = 4; break; case WirePortDataType.FLOAT3: count = 3; break; case WirePortDataType.FLOAT2: count = 2; break; case WirePortDataType.INT: case WirePortDataType.FLOAT: count = 1; break; case WirePortDataType.OBJECT: case WirePortDataType.FLOAT3x3: case WirePortDataType.FLOAT4x4: break; } for ( int i = 0; i < count; i++ ) { value += GetSwizzleComponentForChannel( _selectedOutputSwizzleTypes[ i ] ); } return CreateOutputLocalVariable( 0, value, ref dataCollector ); } public override void ReadFromString( ref string[] nodeParams ) { base.ReadFromString( ref nodeParams ); _selectedOutputType = ( WirePortDataType ) Enum.Parse( typeof( WirePortDataType ), GetCurrentParam( ref nodeParams ) ); switch ( _selectedOutputType ) { case WirePortDataType.FLOAT: _selectedOutputTypeInt = 0; break; case WirePortDataType.FLOAT2: _selectedOutputTypeInt = 1; break; case WirePortDataType.FLOAT3: _selectedOutputTypeInt = 2; break; case WirePortDataType.COLOR: case WirePortDataType.FLOAT4: _selectedOutputTypeInt = 3; break; } for ( int i = 0; i < _selectedOutputSwizzleTypes.Length; i++ ) { _selectedOutputSwizzleTypes[ i ] = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); } UpdatePorts(); } public override void WriteToString( ref string nodeInfo, ref string connectionsInfo ) { base.WriteToString( ref nodeInfo, ref connectionsInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, _selectedOutputType ); for ( int i = 0; i < _selectedOutputSwizzleTypes.Length; i++ ) { IOUtils.AddFieldValueToString( ref nodeInfo, _selectedOutputSwizzleTypes[ i ] ); } } } }
// jQueryDeferred.cs // Script#/Libraries/jQuery/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace jQueryApi { /// <summary> /// Represents a deferred value. /// </summary> [Imported] [IgnoreNamespace] [ScriptName("Object")] public sealed class jQueryDeferred : IDeferred { private jQueryDeferred() { } /// <summary> /// Add handlers to be called when the deferred object is resolved or /// rejected. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Always(params Action[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or /// rejected. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Always(params Callback[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Done(params Action[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Done(params Callback[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is rejected. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Fail(params Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is rejected. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Fail(params Callback[] failCallbacks) { return null; } /// <summary> /// Determines whether the deferred object has been rejected. /// </summary> /// <returns>true if it has been rejected; false otherwise.</returns> public bool IsRejected() { return false; } /// <summary> /// Determines whether the deferred object has been resolved. /// </summary> /// <returns>true if it has been resolved; false otherwise.</returns> public bool IsResolved() { return false; } /// <summary> /// Returns a deferred object that can be further composed. /// </summary> /// <returns>A deferred object.</returns> public IDeferred Promise() { return null; } /// <summary> /// Rejects the deferred object and call any failure callbacks with the specified arguments. /// </summary> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred Reject(params object[] args) { return null; } /// <summary> /// Rejects the deferred object and call any failure callbacks with the specified arguments /// using the specified context as the this parameter. /// </summary> /// <param name="context">The context in which the callback is invoked.</param> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred RejectWith(object context, params object[] args) { return null; } /// <summary> /// Resolves the deferred object and call any done callbacks with the specified arguments. /// </summary> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred Resolve(params object[] args) { return null; } /// <summary> /// Resolves the deferred object and call any failure callbacks with the specified arguments /// using the specified context as the this parameter. /// </summary> /// <param name="context">The context in which the callback is invoked.</param> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred ResolveWith(object context, params object[] args) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the object is resolved.</param> /// <param name="failCallback">The callback to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Then(Action doneCallback, Action failCallback) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the object is resolved.</param> /// <param name="failCallback">The callback to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Then(Callback doneCallback, Callback failCallback) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the object is resolved.</param> /// <param name="failCallbacks">The callbacks to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the object is resolved.</param> /// <param name="failCallbacks">The callbacks to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Then(Callback[] doneCallbacks, Callback[] failCallbacks) { return null; } #region Implementation of IDeferred void IPromise.Then(Delegate fulfilledHandler) { } void IPromise.Then(Delegate fulfilledHandler, Delegate errorHandler) { } void IPromise.Then(Delegate fulfilledHandler, Delegate errorHandler, Delegate progressHandler) { } IDeferred IDeferred.Always(params Action[] callbacks) { return null; } IDeferred IDeferred.Always(params Callback[] callbacks) { return null; } IDeferred IDeferred.Done(params Action[] doneCallbacks) { return null; } IDeferred IDeferred.Done(params Callback[] doneCallbacks) { return null; } IDeferred IDeferred.Fail(params Action[] failCallbacks) { return null; } IDeferred IDeferred.Fail(params Callback[] failCallbacks) { return null; } bool IDeferred.IsRejected() { return false; } bool IDeferred.IsResolved() { return false; } IDeferred IDeferred.Pipe(jQueryDeferredFilter successFilter) { return null; } IDeferred IDeferred.Pipe(jQueryDeferredFilter successFilter, jQueryDeferredFilter failFilter) { return null; } IDeferred IDeferred.Then(Action doneCallback, Action failCallback) { return null; } IDeferred IDeferred.Then(Callback doneCallback, Callback failCallback) { return null; } IDeferred IDeferred.Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } IDeferred IDeferred.Then(Callback[] doneCallbacks, Callback[] failCallbacks) { return null; } #endregion } /// <summary> /// Represents a deferred value. /// </summary> [Imported] [IgnoreNamespace] [ScriptName("Object")] public sealed class jQueryDeferred<TData> : IDeferred<TData> { private jQueryDeferred() { } /// <summary> /// Add handlers to be called when the deferred object is resolved or /// rejected. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred<TData> Always(params Action[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or /// rejected. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred<TData> Always(params Action<TData>[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred<TData> Done(params Action[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred<TData> Done(params Action<TData>[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is rejected. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred<TData> Fail(params Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is rejected. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred<TData> Fail(params Action<TData>[] failCallbacks) { return null; } /// <summary> /// Determines whether the deferred object has been rejected. /// </summary> /// <returns>true if it has been rejected; false otherwise.</returns> public bool IsRejected() { return false; } /// <summary> /// Determines whether the deferred object has been resolved. /// </summary> /// <returns>true if it has been resolved; false otherwise.</returns> public bool IsResolved() { return false; } /// <summary> /// Returns a deferred object that can be further composed. /// </summary> /// <returns>A deferred object.</returns> public IDeferred<TData> Promise() { return null; } /// <summary> /// Rejects the deferred object and call any failure callbacks with the specified arguments. /// </summary> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred<TData> Reject(params TData[] args) { return null; } /// <summary> /// Rejects the deferred object and call any failure callbacks with the specified arguments /// using the specified context as the this parameter. /// </summary> /// <param name="context">The context in which the callback is invoked.</param> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> RejectWith(object context, params TData[] args) { return null; } /// <summary> /// Resolves the deferred object and call any done callbacks with the specified arguments. /// </summary> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> [ExpandParams] public jQueryDeferred<TData> Resolve(params TData[] args) { return null; } /// <summary> /// Resolves the deferred object and call any failure callbacks with the specified arguments /// using the specified context as the this parameter. /// </summary> /// <param name="context">The context in which the callback is invoked.</param> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> ResolveWith(object context, params TData[] args) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the object is resolved.</param> /// <param name="failCallback">The callback to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Then(Action doneCallback, Action failCallback) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the object is resolved.</param> /// <param name="failCallback">The callback to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Then(Action<TData> doneCallback, Action<TData> failCallback) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the object is resolved.</param> /// <param name="failCallbacks">The callbacks to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the object is resolved.</param> /// <param name="failCallbacks">The callbacks to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Then(Action<TData>[] doneCallbacks, Action<TData>[] failCallbacks) { return null; } #region Implementation of IDeferred void IPromise.Then(Delegate fulfilledHandler) { } void IPromise.Then(Delegate fulfilledHandler, Delegate errorHandler) { } void IPromise.Then(Delegate fulfilledHandler, Delegate errorHandler, Delegate progressHandler) { } IDeferred<TData> IDeferred<TData>.Always(params Action[] callbacks) { return null; } IDeferred<TData> IDeferred<TData>.Always(params Action<TData>[] callbacks) { return null; } IDeferred<TData> IDeferred<TData>.Done(params Action[] doneCallbacks) { return null; } IDeferred<TData> IDeferred<TData>.Done(params Action<TData>[] doneCallbacks) { return null; } IDeferred<TData> IDeferred<TData>.Fail(params Action[] failCallbacks) { return null; } IDeferred<TData> IDeferred<TData>.Fail(params Action<TData>[] failCallbacks) { return null; } bool IDeferred<TData>.IsRejected() { return false; } bool IDeferred<TData>.IsResolved() { return false; } IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(Func<TData, IDeferred<TTargetData>> successChain) { return null; } IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter) { return null; } IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter, jQueryDeferredFilter<TTargetData> failFilter) { return null; } IDeferred<TData> IDeferred<TData>.Then(Action doneCallback, Action failCallback) { return null; } IDeferred<TData> IDeferred<TData>.Then(Action<TData> doneCallback, Action<TData> failCallback) { return null; } IDeferred<TData> IDeferred<TData>.Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } IDeferred<TData> IDeferred<TData>.Then(Action<TData>[] doneCallbacks, Action<TData>[] failCallbacks) { return null; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.Net.WebSockets; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace System.Net { public sealed unsafe partial class HttpListenerRequest { private string[] _acceptTypes; private string[] _userLanguages; private CookieCollection _cookies; private bool? _keepAlive; private string _rawUrl; private Uri _requestUri; private Version _version; public string[] AcceptTypes { get { if (_acceptTypes == null) { _acceptTypes = Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]); } return _acceptTypes; } } public string[] UserLanguages { get { if (_userLanguages == null) { _userLanguages = Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]); } return _userLanguages; } } private static Func<CookieCollection, Cookie, bool, int> s_internalAddMethod = null; private static Func<CookieCollection, Cookie, bool, int> InternalAddMethod { get { if (s_internalAddMethod == null) { // We need to use CookieCollection.InternalAdd, as this method performs no validation on the Cookies. // Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons. MethodInfo method = typeof(CookieCollection).GetMethod("InternalAdd", BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(method != null, "We need to use an internal method named InternalAdd that is declared on Cookie."); s_internalAddMethod = (Func<CookieCollection, Cookie, bool, int>)Delegate.CreateDelegate(typeof(Func<CookieCollection, Cookie, bool, int>), method); } return s_internalAddMethod; } } private CookieCollection ParseCookies(Uri uri, string setCookieHeader) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "uri:" + uri + " setCookieHeader:" + setCookieHeader); CookieCollection cookies = new CookieCollection(); CookieParser parser = new CookieParser(setCookieHeader); while (true) { Cookie cookie = parser.GetServer(); if (cookie == null) { // EOF, done. break; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "CookieParser returned cookie: " + cookie.ToString()); if (cookie.Name.Length == 0) { continue; } InternalAddMethod(cookies, cookie, true); } return cookies; } public CookieCollection Cookies { get { if (_cookies == null) { string cookieString = Headers[HttpKnownHeaderNames.Cookie]; if (!string.IsNullOrEmpty(cookieString)) { _cookies = ParseCookies(RequestUri, cookieString); } if (_cookies == null) { _cookies = new CookieCollection(); } } return _cookies; } } public Encoding ContentEncoding { get { if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) { string postDataCharset = Headers["x-up-devcap-post-charset"]; if (postDataCharset != null && postDataCharset.Length > 0) { try { return Encoding.GetEncoding(postDataCharset); } catch (ArgumentException) { } } } if (HasEntityBody) { if (ContentType != null) { string charSet = Helpers.GetAttributeFromHeader(ContentType, "charset"); if (charSet != null) { try { return Encoding.GetEncoding(charSet); } catch (ArgumentException) { } } } } return Encoding.Default; } } public string ContentType => Headers[HttpKnownHeaderNames.ContentType]; public bool IsLocal => LocalEndPoint.Address.Equals(RemoteEndPoint.Address); public bool IsWebSocketRequest { get { if (!SupportsWebSockets) { return false; } bool foundConnectionUpgradeHeader = false; if (string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Upgrade])) { return false; } foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection)) { if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase)) { foundConnectionUpgradeHeader = true; break; } } if (!foundConnectionUpgradeHeader) { return false; } foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade)) { if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } } public bool KeepAlive { get { if (!_keepAlive.HasValue) { string header = Headers[HttpKnownHeaderNames.ProxyConnection]; if (string.IsNullOrEmpty(header)) { header = Headers[HttpKnownHeaderNames.Connection]; } if (string.IsNullOrEmpty(header)) { if (ProtocolVersion >= HttpVersion.Version11) { _keepAlive = true; } else { header = Headers[HttpKnownHeaderNames.KeepAlive]; _keepAlive = !string.IsNullOrEmpty(header); } } else { header = header.ToLower(CultureInfo.InvariantCulture); _keepAlive = header.IndexOf("close", StringComparison.InvariantCultureIgnoreCase) < 0 || header.IndexOf("keep-alive", StringComparison.InvariantCultureIgnoreCase) >= 0; } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_keepAlive=" + _keepAlive); return _keepAlive.Value; } } public NameValueCollection QueryString { get { NameValueCollection queryString = new NameValueCollection(); Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding); return queryString; } } public string RawUrl => _rawUrl; private string RequestScheme => IsSecureConnection ? UriScheme.Https : UriScheme.Http; public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent]; public string UserHostAddress => LocalEndPoint.ToString(); public string UserHostName => Headers[HttpKnownHeaderNames.Host]; public Uri UrlReferrer { get { string referrer = Headers[HttpKnownHeaderNames.Referer]; if (referrer == null) { return null; } bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out Uri urlReferrer); return success ? urlReferrer : null; } } public Uri Url => RequestUri; public Version ProtocolVersion => _version; public X509Certificate2 GetClientCertificate() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { if (ClientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, $"{nameof(GetClientCertificate)}()/{nameof(BeginGetClientCertificate)}()")); ClientCertState = ListenerClientCertState.InProgress; GetClientCertificateCore(); ClientCertState = ListenerClientCertState.Completed; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}"); } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return ClientCertificate; } public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); if (ClientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, $"{nameof(GetClientCertificate)}()/{nameof(BeginGetClientCertificate)}()")); ClientCertState = ListenerClientCertState.InProgress; return BeginGetClientCertificateCore(requestCallback, state); } public Task<X509Certificate2> GetClientCertificateAsync() { return Task.Factory.FromAsync( (callback, state) => ((HttpListenerRequest)state).BeginGetClientCertificate(callback, state), iar => ((HttpListenerRequest)iar.AsyncState).EndGetClientCertificate(iar), this); } internal ListenerClientCertState ClientCertState { get; set; } = ListenerClientCertState.NotInitialized; internal X509Certificate2 ClientCertificate { get; set; } public int ClientCertificateError { get { if (ClientCertState == ListenerClientCertState.NotInitialized) throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "GetClientCertificate()/BeginGetClientCertificate()")); else if (ClientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_mustcompletecall, "GetClientCertificate()/BeginGetClientCertificate()")); return GetClientCertificateErrorCore(); } } private static class Helpers { // // Get attribute off header value // internal static string GetAttributeFromHeader(string headerValue, string attrName) { if (headerValue == null) return null; int l = headerValue.Length; int k = attrName.Length; // find properly separated attribute name int i = 1; // start searching from 1 while (i < l) { i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, attrName, i, CompareOptions.IgnoreCase); if (i < 0) break; if (i + k >= l) break; char chPrev = headerValue[i - 1]; char chNext = headerValue[i + k]; if ((chPrev == ';' || chPrev == ',' || char.IsWhiteSpace(chPrev)) && (chNext == '=' || char.IsWhiteSpace(chNext))) break; i += k; } if (i < 0 || i >= l) return null; // skip to '=' and the following whitespace i += k; while (i < l && char.IsWhiteSpace(headerValue[i])) i++; if (i >= l || headerValue[i] != '=') return null; i++; while (i < l && char.IsWhiteSpace(headerValue[i])) i++; if (i >= l) return null; // parse the value string attrValue = null; int j; if (i < l && headerValue[i] == '"') { if (i == l - 1) return null; j = headerValue.IndexOf('"', i + 1); if (j < 0 || j == i + 1) return null; attrValue = headerValue.Substring(i + 1, j - i - 1).Trim(); } else { for (j = i; j < l; j++) { if (headerValue[j] == ' ' || headerValue[j] == ',') break; } if (j == i) return null; attrValue = headerValue.Substring(i, j - i).Trim(); } return attrValue; } internal static string[] ParseMultivalueHeader(string s) { if (s == null) return null; int l = s.Length; // collect comma-separated values into list List<string> values = new List<string>(); int i = 0; while (i < l) { // find next , int ci = s.IndexOf(',', i); if (ci < 0) ci = l; // append corresponding server value values.Add(s.Substring(i, ci - i)); // move to next i = ci + 1; // skip leading space if (i < l && s[i] == ' ') i++; } // return list as array of strings int n = values.Count; string[] strings; // if n is 0 that means s was empty string if (n == 0) { strings = new string[1]; strings[0] = string.Empty; } else { strings = new string[n]; values.CopyTo(0, strings, 0, n); } return strings; } private static string UrlDecodeStringFromStringInternal(string s, Encoding e) { int count = s.Length; UrlDecoder helper = new UrlDecoder(count, e); // go through the string's chars collapsing %XX and %uXXXX and // appending each char as char, with exception of %XX constructs // that are appended as bytes for (int pos = 0; pos < count; pos++) { char ch = s[pos]; if (ch == '+') { ch = ' '; } else if (ch == '%' && pos < count - 2) { if (s[pos + 1] == 'u' && pos < count - 5) { int h1 = HexToInt(s[pos + 2]); int h2 = HexToInt(s[pos + 3]); int h3 = HexToInt(s[pos + 4]); int h4 = HexToInt(s[pos + 5]); if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0) { // valid 4 hex chars ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4); pos += 5; // only add as char helper.AddChar(ch); continue; } } else { int h1 = HexToInt(s[pos + 1]); int h2 = HexToInt(s[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars byte b = (byte)((h1 << 4) | h2); pos += 2; // don't add as char helper.AddByte(b); continue; } } } if ((ch & 0xFF80) == 0) helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode else helper.AddChar(ch); } return helper.GetString(); } private static int HexToInt(char h) { return (h >= '0' && h <= '9') ? h - '0' : (h >= 'a' && h <= 'f') ? h - 'a' + 10 : (h >= 'A' && h <= 'F') ? h - 'A' + 10 : -1; } private class UrlDecoder { private int _bufferSize; // Accumulate characters in a special array private int _numChars; private char[] _charBuffer; // Accumulate bytes for decoding into characters in a special array private int _numBytes; private byte[] _byteBuffer; // Encoding to convert chars to bytes private Encoding _encoding; private void FlushBytes() { if (_numBytes > 0) { _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = new char[bufferSize]; // byte buffer created on demand } internal void AddChar(char ch) { if (_numBytes > 0) FlushBytes(); _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { { if (_byteBuffer == null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } } internal string GetString() { if (_numBytes > 0) FlushBytes(); if (_numChars > 0) return new string(_charBuffer, 0, _numChars); else return string.Empty; } } internal static void FillFromString(NameValueCollection nvc, string s, bool urlencoded, Encoding encoding) { int l = (s != null) ? s.Length : 0; int i = (s.Length > 0 && s[0] == '?') ? 1 : 0; while (i < l) { // find next & while noting first = on the way (and if there are more) int si = i; int ti = -1; while (i < l) { char ch = s[i]; if (ch == '=') { if (ti < 0) ti = i; } else if (ch == '&') { break; } i++; } // extract the name / value pair string name = null; string value = null; if (ti >= 0) { name = s.Substring(si, ti - si); value = s.Substring(ti + 1, i - ti - 1); } else { value = s.Substring(si, i - si); } // add name / value pair to the collection if (urlencoded) nvc.Add( name == null ? null : UrlDecodeStringFromStringInternal(name, encoding), UrlDecodeStringFromStringInternal(value, encoding)); else nvc.Add(name, value); // trailing '&' if (i == l - 1 && s[i] == '&') nvc.Add(null, ""); i++; } } } } }
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 Manufacturing.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.IO; using NUnit.Framework.Constraints; using NUnit.TestUtilities.Comparers; namespace NUnit.Framework.Syntax { [Obsolete("Test of Obsolete AssertionHelper class")] class AssertionHelperTests : AssertionHelper { private static readonly string DEFAULT_PATH_CASE = Path.DirectorySeparatorChar == '\\' ? "ignorecase" : "respectcase"; #region Not [Test] public void NotNull() { var expression = Not.Null; Expect(expression, TypeOf<NullConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<NotConstraint>()); Expect(constraint.ToString(), EqualTo("<not <null>>")); } [Test] public void NotNotNotNull() { var expression = Not.Not.Not.Null; Expect(expression, TypeOf<NullConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<NotConstraint>()); Expect(constraint.ToString(), EqualTo("<not <not <not <null>>>>")); } #endregion #region All [Test] public void AllItems() { var expression = All.GreaterThan(0); Expect(expression, TypeOf<GreaterThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AllItemsConstraint>()); Expect(constraint.ToString(), EqualTo("<all <greaterthan 0>>")); } #endregion #region Some [Test] public void Some_EqualTo() { var expression = Some.EqualTo(3); Expect(expression, TypeOf<EqualConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<SomeItemsConstraint>()); Expect(constraint.ToString(), EqualTo("<some <equal 3>>")); } [Test] public void Some_BeforeBinaryOperators() { var expression = Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999); Expect(expression, TypeOf<EqualConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<SomeItemsConstraint>()); Expect(constraint.ToString(), EqualTo("<some <or <and <greaterthan 0> <lessthan 100>> <equal 999>>>")); } [Test] public void Some_Nested() { var expression = Some.With.Some.LessThan(100); Expect(expression, TypeOf<LessThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<SomeItemsConstraint>()); Expect(constraint.ToString(), EqualTo("<some <some <lessthan 100>>>")); } [Test] public void Some_AndSome() { var expression = Some.GreaterThan(0).And.Some.LessThan(100); Expect(expression, TypeOf<LessThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AndConstraint>()); Expect(constraint.ToString(), EqualTo("<and <some <greaterthan 0>> <some <lessthan 100>>>")); } #endregion #region None [Test] public void NoItems() { var expression = None.LessThan(0); Expect(expression, TypeOf<LessThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<NoItemConstraint>()); Expect(constraint.ToString(), EqualTo("<none <lessthan 0>>")); } #endregion #region Property [Test] public void Property() { var expression = Property("X"); Expect(expression, TypeOf<ResolvableConstraintExpression>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<PropertyExistsConstraint>()); Expect(constraint.ToString(), EqualTo("<propertyexists X>")); } [Test] public void Property_FollowedByAnd() { var expression = Property("X").And.EqualTo(7); Expect(expression, TypeOf<EqualConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AndConstraint>()); Expect(constraint.ToString(), EqualTo("<and <propertyexists X> <equal 7>>")); } [Test] public void Property_FollowedByConstraint() { var expression = Property("X").GreaterThan(5); Expect(expression, TypeOf<GreaterThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<PropertyConstraint>()); Expect(constraint.ToString(), EqualTo("<property X <greaterthan 5>>")); } [Test] public void Property_FollowedByNot() { var expression = Property("X").Not.GreaterThan(5); Expect(expression, TypeOf<GreaterThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<PropertyConstraint>()); Expect(constraint.ToString(), EqualTo("<property X <not <greaterthan 5>>>")); } [Test] public void LengthProperty() { var expression = Length.GreaterThan(5); Expect(expression, TypeOf<GreaterThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<PropertyConstraint>()); Expect(constraint.ToString(), EqualTo("<property Length <greaterthan 5>>")); } [Test] public void CountProperty() { var expression = Count.EqualTo(5); Expect(expression, TypeOf<EqualConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<PropertyConstraint>()); Expect(constraint.ToString(), EqualTo("<property Count <equal 5>>")); } [Test] public void MessageProperty() { var expression = Message.StartsWith("Expected"); Expect(expression, TypeOf<StartsWithConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<PropertyConstraint>()); Expect(constraint.ToString(), EqualTo(@"<property Message <startswith ""Expected"">>")); } #endregion #region Attribute [Test] public void AttributeExistsTest() { var expression = Attribute(typeof(TestFixtureAttribute)); Expect(expression, TypeOf<ResolvableConstraintExpression>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AttributeExistsConstraint>()); Expect(constraint.ToString(), EqualTo("<attributeexists NUnit.Framework.TestFixtureAttribute>")); } [Test] public void AttributeTest_FollowedByConstraint() { var expression = Attribute(typeof(TestFixtureAttribute)).Property("Description").Not.Null; Expect(expression, TypeOf<NullConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AttributeConstraint>()); Expect(constraint.ToString(), EqualTo("<attribute NUnit.Framework.TestFixtureAttribute <property Description <not <null>>>>")); } [Test] public void AttributeExistsTest_Generic() { var expression = Attribute<TestFixtureAttribute>(); Expect(expression, TypeOf<ResolvableConstraintExpression>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AttributeExistsConstraint>()); Expect(constraint.ToString(), EqualTo("<attributeexists NUnit.Framework.TestFixtureAttribute>")); } [Test] public void AttributeTest_FollowedByConstraint_Generic() { var expression = Attribute<TestFixtureAttribute>().Property("Description").Not.Null; Expect(expression, TypeOf<NullConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AttributeConstraint>()); Expect(constraint.ToString(), EqualTo("<attribute NUnit.Framework.TestFixtureAttribute <property Description <not <null>>>>")); } #endregion #region Null [Test] public void NullTest() { var constraint = Null; Expect(constraint, TypeOf<NullConstraint>()); Expect(constraint.ToString(), EqualTo("<null>")); } #endregion #region True [Test] public void TrueTest() { var constraint = True; Expect(constraint, TypeOf<TrueConstraint>()); Expect(constraint.ToString(), EqualTo("<true>")); } #endregion #region False [Test] public void FalseTest() { var constraint = False; Expect(constraint, TypeOf<FalseConstraint>()); Expect(constraint.ToString(), EqualTo("<false>")); } #endregion #region Positive [Test] public void PositiveTest() { var constraint = Positive; Expect(constraint, TypeOf<GreaterThanConstraint>()); Expect(constraint.ToString(), EqualTo("<greaterthan 0>")); } #endregion #region Negative [Test] public void NegativeTest() { var constraint = Negative; Expect(constraint, TypeOf<LessThanConstraint>()); Expect(constraint.ToString(), EqualTo("<lessthan 0>")); } #endregion #region Zero [Test] public void ZeroTest() { var constraint = Zero; Expect(constraint, TypeOf<EqualConstraint>()); Expect(constraint.ToString(), EqualTo("<equal 0>")); } #endregion #region NaN [Test] public void NaNTest() { var constraint = NaN; Expect(constraint, TypeOf<NaNConstraint>()); Expect(constraint.ToString(), EqualTo("<nan>")); } #endregion #region After [Test] public void After() { var constraint = EqualTo(10).After(1000); Expect(constraint, TypeOf<DelayedConstraint.WithRawDelayInterval>()); Expect(constraint.ToString(), EqualTo("<after 1000 <equal 10>>")); } [Test] public void After_Property() { var constraint = Property("X").EqualTo(10).After(1000); Expect(constraint, TypeOf<DelayedConstraint.WithRawDelayInterval>()); Expect(constraint.ToString(), EqualTo("<after 1000 <property X <equal 10>>>")); } [Test] public void After_And() { var constraint = GreaterThan(0).And.LessThan(10).After(1000); Expect(constraint, TypeOf<DelayedConstraint.WithRawDelayInterval>()); Expect(constraint.ToString(), EqualTo("<after 1000 <and <greaterthan 0> <lessthan 10>>>")); } #endregion #region Unique [Test] public void UniqueItems() { var constraint = Unique; Expect(constraint, TypeOf<UniqueItemsConstraint>()); Expect(constraint.ToString(), EqualTo("<uniqueitems>")); } #endregion #region Ordered [Test] public void CollectionOrdered() { var constraint = Ordered; Expect(constraint, TypeOf<CollectionOrderedConstraint>()); Expect(constraint.ToString(), EqualTo("<ordered>")); } [Test] public void CollectionOrdered_Descending() { var constraint = Ordered.Descending; Expect(constraint, TypeOf<CollectionOrderedConstraint>()); Expect(constraint.ToString(), EqualTo("<ordered descending>")); } [Test] public void CollectionOrdered_Comparer() { var constraint = Ordered.Using(ObjectComparer.Default); Expect(constraint, TypeOf<CollectionOrderedConstraint>()); Expect(constraint.ToString(), EqualTo("<ordered NUnit.TestUtilities.Comparers.ObjectComparer>")); } [Test] public void CollectionOrdered_Comparer_Descending() { var constraint = Ordered.Using(ObjectComparer.Default).Descending; Expect(constraint, TypeOf<CollectionOrderedConstraint>()); Expect(constraint.ToString(), EqualTo("<ordered descending NUnit.TestUtilities.Comparers.ObjectComparer>")); } #endregion #region OrderedBy [Test] public void CollectionOrderedBy() { var constraint = Ordered.By("SomePropertyName"); Expect(constraint, TypeOf<CollectionOrderedConstraint>()); Expect(constraint.ToString(), EqualTo("<orderedby SomePropertyName>")); } [Test] public void CollectionOrderedBy_Descending() { var constraint = Ordered.By("SomePropertyName").Descending; Expect(constraint, TypeOf<CollectionOrderedConstraint>()); Expect(constraint.ToString(), EqualTo("<orderedby SomePropertyName descending>")); } [Test] public void CollectionOrderedBy_Comparer() { var constraint = Ordered.By("SomePropertyName").Using(ObjectComparer.Default); Expect(constraint, TypeOf<CollectionOrderedConstraint>()); Expect(constraint.ToString(), EqualTo("<orderedby SomePropertyName NUnit.TestUtilities.Comparers.ObjectComparer>")); } [Test] public void CollectionOrderedBy_Comparer_Descending() { var constraint = Ordered.By("SomePropertyName").Using(ObjectComparer.Default).Descending; Expect(constraint, TypeOf<CollectionOrderedConstraint>()); Expect(constraint.ToString(), EqualTo("<orderedby SomePropertyName descending NUnit.TestUtilities.Comparers.ObjectComparer>")); } #endregion #region Contains [Test] public void ContainsConstraint() { var constraint = Contains(42); Expect(constraint, TypeOf<SomeItemsConstraint>()); Expect(constraint.ToString(), EqualTo("<some <equal 42>>")); } [Test] public void ContainsConstraintWithOr() { var constraint = Contains(5).Or.Contains(7); var collection1 = new[] { 3, 5, 1, 8 }; var collection2 = new[] { 2, 7, 9, 2 }; Assert.That(collection1, constraint); Assert.That(collection2, constraint); } [Test] public void ContainsConstraintWithUsing() { Func<int, int, bool> myIntComparer = (x, y) => x == y; var constraint = Contains(5).Using(myIntComparer); var collection = new[] { 3, 5, 1, 8 }; Assert.That(collection, constraint); } #endregion #region Member [Test] public void MemberConstraintWithAnd() { var constraint = Member(1).And.Member(7); var collection = new[] { 2, 1, 7, 4 }; Assert.That(collection, constraint); } [Test] public void MemberConstraintWithUsing() { Func<int, int, bool> myIntComparer = (x, y) => x == y; var constraint = Member(1).Using(myIntComparer); var collection = new[] { 2, 1, 7, 4 }; Assert.That(collection, constraint); } #endregion #region SubsetOf [Test] public void SubsetOfConstraint() { var constraint = SubsetOf(new int[] { 1, 2, 3 }); Expect(constraint, TypeOf<CollectionSubsetConstraint>()); Expect(constraint.ToString(), EqualTo("<subsetof System.Int32[]>")); } #endregion #region EquivalentTo [Test] public void EquivalentConstraint() { var constraint = EquivalentTo(new int[] { 1, 2, 3 }); Expect(constraint, TypeOf<CollectionEquivalentConstraint>()); Expect(constraint.ToString(), EqualTo("<equivalent System.Int32[]>")); } #endregion #region ComparisonConstraints [Test] public void GreaterThan() { var constraint = GreaterThan(7); Expect(constraint, TypeOf<GreaterThanConstraint>()); Expect(constraint.ToString(), EqualTo("<greaterthan 7>")); } [Test] public void GreaterThanOrEqual() { var constraint = GreaterThanOrEqualTo(7); Expect(constraint, TypeOf<GreaterThanOrEqualConstraint>()); Expect(constraint.ToString(), EqualTo("<greaterthanorequal 7>")); } [Test] public void AtLeast() { var constraint = AtLeast(7); Expect(constraint, TypeOf<GreaterThanOrEqualConstraint>()); Expect(constraint.ToString(), EqualTo("<greaterthanorequal 7>")); } [Test] public void LessThan() { var constraint = LessThan(7); Expect(constraint, TypeOf<LessThanConstraint>()); Expect(constraint.ToString(), EqualTo("<lessthan 7>")); } [Test] public void LessThanOrEqual() { var constraint = LessThanOrEqualTo(7); Expect(constraint, TypeOf<LessThanOrEqualConstraint>()); Expect(constraint.ToString(), EqualTo("<lessthanorequal 7>")); } [Test] public void AtMost() { var constraint = AtMost(7); Expect(constraint, TypeOf<LessThanOrEqualConstraint>()); Expect(constraint.ToString(), EqualTo("<lessthanorequal 7>")); } #endregion #region EqualTo [Test] public void EqualConstraint() { var constraint = EqualTo(999); Expect(constraint, TypeOf<EqualConstraint>()); Expect(constraint.ToString(), EqualTo("<equal 999>")); } [Test] public void Equal_IgnoreCase() { var constraint = EqualTo("X").IgnoreCase; Expect(constraint, TypeOf<EqualConstraint>()); Expect(constraint.ToString(), EqualTo(@"<equal ""X"">")); } [Test] public void Equal_WithinTolerance() { var constraint = EqualTo(0.7).Within(.005); Expect(constraint, TypeOf<EqualConstraint>()); Expect(constraint.ToString(), EqualTo("<equal 0.7>")); } #endregion #region And [Test] public void AndConstraint() { var expression = GreaterThan(5).And.LessThan(10); Expect(expression, TypeOf<LessThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AndConstraint>()); Expect(constraint.ToString(), EqualTo("<and <greaterthan 5> <lessthan 10>>")); } [Test] public void AndConstraint_ThreeAndsWithNot() { var expression = Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10); Expect(expression, TypeOf<GreaterThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<AndConstraint>()); Expect(constraint.ToString(), EqualTo("<and <not <null>> <and <not <lessthan 5>> <not <greaterthan 10>>>>")); } #endregion #region Or [Test] public void OrConstraint() { var expression = LessThan(5).Or.GreaterThan(10); Expect(expression, TypeOf<GreaterThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<OrConstraint>()); Expect(constraint.ToString(), EqualTo("<or <lessthan 5> <greaterthan 10>>")); } [Test] public void OrConstraint_ThreeOrs() { var expression = LessThan(5).Or.GreaterThan(10).Or.EqualTo(7); Expect(expression, TypeOf<EqualConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<OrConstraint>()); Expect(constraint.ToString(), EqualTo("<or <lessthan 5> <or <greaterthan 10> <equal 7>>>")); } [Test] public void OrConstraint_PrecededByAnd() { var expression = LessThan(100).And.GreaterThan(0).Or.EqualTo(999); Expect(expression, TypeOf<EqualConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<OrConstraint>()); Expect(constraint.ToString(), EqualTo("<or <and <lessthan 100> <greaterthan 0>> <equal 999>>")); } [Test] public void OrConstraint_FollowedByAnd() { var expression = EqualTo(999).Or.GreaterThan(0).And.LessThan(100); Expect(expression, TypeOf<LessThanConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<OrConstraint>()); Expect(constraint.ToString(), Is.EqualTo("<or <equal 999> <and <greaterthan 0> <lessthan 100>>>")); } #endregion #region SamePath [Test] public void SamePath() { var constraint = SamePath("/path/to/match"); Expect(constraint, TypeOf<SamePathConstraint>()); Expect(constraint.ToString(), EqualTo( string.Format(@"<samepath ""/path/to/match"" {0}>", DEFAULT_PATH_CASE))); } [Test] public void SamePath_IgnoreCase() { var constraint = SamePath("/path/to/match").IgnoreCase; Expect(constraint, TypeOf<SamePathConstraint>()); Expect(constraint.ToString(), EqualTo(@"<samepath ""/path/to/match"" ignorecase>")); } [Test] public void NotSamePath_IgnoreCase() { var expression = Not.SamePath("/path/to/match").IgnoreCase; Expect(expression, TypeOf<SamePathConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<NotConstraint>()); Expect(constraint.ToString(), EqualTo(@"<not <samepath ""/path/to/match"" ignorecase>>")); } [Test] public void SamePath_RespectCase() { var constraint = SamePath("/path/to/match").RespectCase; Expect(constraint, TypeOf<SamePathConstraint>()); Expect(constraint.ToString(), EqualTo(@"<samepath ""/path/to/match"" respectcase>")); } [Test] public void NotSamePath_RespectCase() { var expression = Not.SamePath("/path/to/match").RespectCase; Expect(expression, TypeOf<SamePathConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<NotConstraint>()); Expect(constraint.ToString(), EqualTo(@"<not <samepath ""/path/to/match"" respectcase>>")); } #endregion #region SamePathOrUnder [Test] public void SamePathOrUnder() { var constraint = SamePathOrUnder("/path/to/match"); Expect(constraint, TypeOf<SamePathOrUnderConstraint>()); Expect(constraint.ToString(), EqualTo( string.Format(@"<samepathorunder ""/path/to/match"" {0}>", DEFAULT_PATH_CASE))); } [Test] public void SamePathOrUnder_IgnoreCase() { var constraint = SamePathOrUnder("/path/to/match").IgnoreCase; Expect(constraint, TypeOf<SamePathOrUnderConstraint>()); Expect(constraint.ToString(), EqualTo(@"<samepathorunder ""/path/to/match"" ignorecase>")); } [Test] public void NotSamePathOrUnder_IgnoreCase() { var expression = Not.SamePathOrUnder("/path/to/match").IgnoreCase; Expect(expression, TypeOf<SamePathOrUnderConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<NotConstraint>()); Expect(constraint.ToString(), EqualTo(@"<not <samepathorunder ""/path/to/match"" ignorecase>>")); } [Test] public void SamePathOrUnder_RespectCase() { var constraint = SamePathOrUnder("/path/to/match").RespectCase; Expect(constraint, TypeOf<SamePathOrUnderConstraint>()); Expect(constraint.ToString(), EqualTo(@"<samepathorunder ""/path/to/match"" respectcase>")); } [Test] public void NotSamePathOrUnder_RespectCase() { var expression = Not.SamePathOrUnder("/path/to/match").RespectCase; Expect(expression, TypeOf<SamePathOrUnderConstraint>()); var constraint = Resolve(expression); Expect(constraint, TypeOf<NotConstraint>()); Expect(constraint.ToString(), EqualTo(@"<not <samepathorunder ""/path/to/match"" respectcase>>")); } #endregion #region BinarySerializable #if !NETCOREAPP1_1 [Test] public void BinarySerializableConstraint() { var constraint = BinarySerializable; Expect(constraint, TypeOf<BinarySerializableConstraint>()); Expect(constraint.ToString(), EqualTo("<binaryserializable>")); } #endif #endregion #region XmlSerializable #if !NETCOREAPP1_1 [Test] public void XmlSerializableConstraint() { var constraint = XmlSerializable; Expect(constraint, TypeOf<XmlSerializableConstraint>()); Expect(constraint.ToString(), EqualTo("<xmlserializable>")); } #endif #endregion #region Contains [Test] public void ContainsTest() { var constraint = Contains("X"); Expect(constraint, TypeOf<ContainsConstraint>()); Expect(constraint.ToString(), EqualTo("<contains>")); } [Test] public void ContainsTest_IgnoreCase() { var constraint = Contains("X").IgnoreCase; Expect(constraint, TypeOf<ContainsConstraint>()); Expect(constraint.ToString(), EqualTo("<contains>")); } #endregion #region StartsWith [Test] public void StartsWithTest() { var constraint = StartsWith("X"); Expect(constraint, TypeOf<StartsWithConstraint>()); Expect(constraint.ToString(), EqualTo(@"<startswith ""X"">")); } [Test] public void StartsWithTest_IgnoreCase() { var constraint = StartsWith("X").IgnoreCase; Expect(constraint, TypeOf<StartsWithConstraint>()); Expect(constraint.ToString(), EqualTo(@"<startswith ""X"">")); } #endregion #region EndsWith [Test] public void EndsWithTest() { var constraint = EndsWith("X"); Expect(constraint, TypeOf<EndsWithConstraint>()); Expect(constraint.ToString(), EqualTo(@"<endswith ""X"">")); } [Test] public void EndsWithTest_IgnoreCase() { var constraint = EndsWith("X").IgnoreCase; Expect(constraint, TypeOf<EndsWithConstraint>()); Expect(constraint.ToString(), EqualTo(@"<endswith ""X"">")); } #endregion #region Matches [Test] public void MatchesTest() { var constraint = Matches("X"); Expect(constraint, TypeOf<RegexConstraint>()); Expect(constraint.ToString(), EqualTo(@"<regex ""X"">")); } [Test] public void MatchesTest_IgnoreCase() { var constraint = Matches("X").IgnoreCase; Expect(constraint, TypeOf<RegexConstraint>()); Expect(constraint.ToString(), EqualTo(@"<regex ""X"">")); } #endregion #region TypeOf [Test] public void TypeOfTest() { var constraint = TypeOf(typeof(string)); Expect(constraint, TypeOf<ExactTypeConstraint>()); Expect(constraint.ToString(), EqualTo("<typeof System.String>")); } [Test] public void TypeOfTest_Generic() { var constraint = TypeOf<string>(); Expect(constraint, TypeOf<ExactTypeConstraint>()); Expect(constraint.ToString(), EqualTo("<typeof System.String>")); } #endregion #region InstanceOf [Test] public void InstanceOfTest() { var constraint = InstanceOf(typeof(string)); Expect(constraint, TypeOf<InstanceOfTypeConstraint>()); Expect(constraint.ToString(), EqualTo("<instanceof System.String>")); } [Test] public void InstanceOfTest_Generic() { var constraint = InstanceOf<string>(); Expect(constraint, TypeOf<InstanceOfTypeConstraint>()); Expect(constraint.ToString(), EqualTo("<instanceof System.String>")); } #endregion #region AssignableFrom [Test] public void AssignableFromTest() { var constraint = AssignableFrom(typeof(string)); Expect(constraint, TypeOf<AssignableFromConstraint>()); Expect(constraint.ToString(), EqualTo("<assignablefrom System.String>")); } [Test] public void AssignableFromTest_Generic() { var constraint = AssignableFrom<string>(); Expect(constraint, TypeOf<AssignableFromConstraint>()); Expect(constraint.ToString(), EqualTo("<assignablefrom System.String>")); } #endregion #region AssignableTo [Test] public void AssignableToTest() { var constraint = AssignableTo(typeof(string)); Expect(constraint, TypeOf<AssignableToConstraint>()); Expect(constraint.ToString(), EqualTo("<assignableto System.String>")); } [Test] public void AssignableToTest_Generic() { var constraint = AssignableTo<string>(); Expect(constraint, TypeOf<AssignableToConstraint>()); Expect(constraint.ToString(), EqualTo("<assignableto System.String>")); } #endregion #region Operator Overrides [Test] public void NotOperator() { var constraint = !Null; Expect(constraint, TypeOf<NotConstraint>()); Expect(constraint.ToString(), EqualTo("<not <null>>")); } [Test] public void AndOperator() { var constraint = GreaterThan(5) & LessThan(10); Expect(constraint, TypeOf<AndConstraint>()); Expect(constraint.ToString(), EqualTo("<and <greaterthan 5> <lessthan 10>>")); } [Test] public void OrOperator() { var constraint = LessThan(5) | GreaterThan(10); Expect(constraint, TypeOf<OrConstraint>()); Expect(constraint.ToString(), EqualTo("<or <lessthan 5> <greaterthan 10>>")); } #endregion #region Helper Methods private static IConstraint Resolve(IResolveConstraint expression) { return ((IResolveConstraint)expression).Resolve(); } #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Sql.Database.Model; using Microsoft.Azure.Commands.Sql.Database.Services; using Microsoft.Azure.Commands.Sql.ElasticPool.Model; using Microsoft.Azure.Commands.Sql.Server.Adapter; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.Management.Sql.Models; using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using DatabaseEdition = Microsoft.Azure.Commands.Sql.Database.Model.DatabaseEdition; namespace Microsoft.Azure.Commands.Sql.ElasticPool.Services { /// <summary> /// Adapter for ElasticPool operations /// </summary> public class AzureSqlElasticPoolAdapter { /// <summary> /// Gets or sets the AzureEndpointsCommunicator which has all the needed management clients /// </summary> private AzureSqlElasticPoolCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public AzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private AzureSubscription _subscription { get; set; } /// <summary> /// Constructs a database adapter /// </summary> /// <param name="profile">The current azure profile</param> /// <param name="subscription">The current azure subscription</param> public AzureSqlElasticPoolAdapter(AzureContext context) { _subscription = context.Subscription; Context = context; Communicator = new AzureSqlElasticPoolCommunicator(Context); } /// <summary> /// Gets an Azure Sql Database ElasticPool by name. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the Azure Sql Database ElasticPool</param> /// <returns>The Azure Sql Database ElasticPool object</returns> internal AzureSqlElasticPoolModel GetElasticPool(string resourceGroupName, string serverName, string poolName) { var resp = Communicator.Get(resourceGroupName, serverName, poolName, Util.GenerateTracingId()); return CreateElasticPoolModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets a list of Azure Sql Databases ElasticPool. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlElasticPoolModel> ListElasticPools(string resourceGroupName, string serverName) { var resp = Communicator.List(resourceGroupName, serverName, Util.GenerateTracingId()); return resp.Select((db) => { return CreateElasticPoolModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Creates or updates an Azure Sql Database ElasticPool. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database ElasticPool</returns> internal AzureSqlElasticPoolModel UpsertElasticPool(AzureSqlElasticPoolModel model) { var resp = Communicator.CreateOrUpdate(model.ResourceGroupName, model.ServerName, model.ElasticPoolName, Util.GenerateTracingId(), new Management.Sql.Models.ElasticPool { Location = model.Location, Tags = model.Tags, DatabaseDtuMax = model.DatabaseDtuMax, DatabaseDtuMin = model.DatabaseDtuMin, Edition = model.Edition.ToString(), Dtu = model.Dtu, StorageMB = model.StorageMB }); return CreateElasticPoolModelFromResponse(model.ResourceGroupName, model.ServerName, resp); } /// <summary> /// Deletes a database /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database to delete</param> public void RemoveElasticPool(string resourceGroupName, string serverName, string databaseName) { Communicator.Remove(resourceGroupName, serverName, databaseName, Util.GenerateTracingId()); } /// <summary> /// Gets a database in an elastic pool /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the Azure Sql Database ElasticPool</param> /// <param name="databaseName">The name of the database</param> /// <returns></returns> public AzureSqlDatabaseModel GetElasticPoolDatabase(string resourceGroupName, string serverName, string poolName, string databaseName) { var resp = Communicator.GetDatabase(resourceGroupName, serverName, poolName, databaseName, Util.GenerateTracingId()); return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets a list of Azure Sql Databases in an ElasticPool. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the elastic pool the database are in</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModel> ListElasticPoolDatabases(string resourceGroupName, string serverName, string poolName) { var resp = Communicator.ListDatabases(resourceGroupName, serverName, poolName, Util.GenerateTracingId()); return resp.Select((db) => { return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Gets a list of Elastic Pool Activity /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the elastic pool</param> /// <returns>A list of Elastic Pool Activities</returns> internal IList<AzureSqlElasticPoolActivityModel> GetElasticPoolActivity(string resourceGroupName, string serverName, string poolName) { var resp = Communicator.ListActivity(resourceGroupName, serverName, poolName, Util.GenerateTracingId()); return resp.Select((activity) => { return CreateActivityModelFromResponse(activity); }).ToList(); } /// <summary> /// Gets a list of Elastic Pool Database Activity /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the elastic pool</param> /// <returns>A list of Elastic Pool Database Activities</returns> internal IList<AzureSqlDatabaseActivityModel> ListElasticPoolDatabaseActivity(string resourceGroupName, string serverName, string poolName) { var resp = Communicator.ListDatabaseActivity(resourceGroupName, serverName, poolName, Util.GenerateTracingId()); return resp.Select((activity) => { return CreateDatabaseActivityModelFromResponse(activity); }).ToList(); } /// <summary> /// Converts a model received from the server to a powershell model /// </summary> /// <param name="model">The model to transform</param> /// <returns>The transformed model</returns> private AzureSqlDatabaseActivityModel CreateDatabaseActivityModelFromResponse(ElasticPoolDatabaseActivity model) { AzureSqlDatabaseActivityModel activity = new AzureSqlDatabaseActivityModel(); //activity.CurrentElasticPoolName = model.Properties.CurrentElasticPoolName; //activity.CurrentServiceObjectiveName = model.Properties.CurrentServiceObjectiveName; //activity.DatabaseName = model.Properties.DatabaseName; //activity.EndTime = model.Properties.EndTime; //activity.ErrorCode = model.Properties.ErrorCode; //activity.ErrorMessage = model.Properties.ErrorMessage; //activity.ErrorSeverity = model.Properties.ErrorSeverity; //activity.Operation = model.Properties.Operation; //activity.OperationId = model.Properties.OperationId; //activity.PercentComplete = model.Properties.PercentComplete; //activity.RequestedElasticPoolName = model.Properties.RequestedElasticPoolName; //activity.RequestedServiceObjectiveName = model.Properties.RequestedServiceObjectiveName; //activity.ServerName = model.Properties.ServerName; //activity.StartTime = model.Properties.StartTime; //activity.State = model.Properties.State; return activity; } /// <summary> /// Converts a ElascitPoolAcitivy model to the powershell model. /// </summary> /// <param name="model">The model from the service</param> /// <returns>The converted model</returns> private AzureSqlElasticPoolActivityModel CreateActivityModelFromResponse(ElasticPoolActivity model) { AzureSqlElasticPoolActivityModel activity = new AzureSqlElasticPoolActivityModel { ElasticPoolName = model.ElasticPoolName, EndTime = model.EndTime, ErrorCode = model.ErrorCode, ErrorMessage = model.ErrorMessage, ErrorSeverity = model.ErrorSeverity, Operation = model.Operation, OperationId = model.OperationId, PercentComplete = model.PercentComplete, RequestedDatabaseDtuMax = model.RequestedDatabaseDtuMax, RequestedDatabaseDtuMin = model.RequestedDatabaseDtuMin, RequestedDtu = model.RequestedDtu, RequestedElasticPoolName = model.RequestedElasticPoolName, RequestedStorageLimitInGB = model.RequestedStorageLimitInGB, ServerName = model.ServerName, StartTime = model.StartTime, State = model.State }; return activity; } /// <summary> /// Gets the Location of the server. /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the server</param> /// <returns></returns> public string GetServerLocation(string resourceGroupName, string serverName) { AzureSqlServerAdapter serverAdapter = new AzureSqlServerAdapter(Context); var server = serverAdapter.GetServer(resourceGroupName, serverName); return server.Location; } /// <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 Database Server</param> /// <param name="pool">The service response</param> /// <returns>The converted model</returns> private AzureSqlElasticPoolModel CreateElasticPoolModelFromResponse(string resourceGroup, string serverName, Management.Sql.Models.ElasticPool pool) { DatabaseEdition edition = DatabaseEdition.None; Enum.TryParse<DatabaseEdition>(pool.Edition, out edition); AzureSqlElasticPoolModel model = new AzureSqlElasticPoolModel { ResourceId = pool.Id, ResourceGroupName = resourceGroup, ServerName = serverName, ElasticPoolName = pool.Name, CreationDate = pool.CreationDate ?? DateTime.MinValue, DatabaseDtuMax = pool.DatabaseDtuMax.Value, DatabaseDtuMin = pool.DatabaseDtuMin.Value, Dtu = pool.Dtu, State = pool.State, StorageMB = pool.StorageMB, Tags = TagsConversionHelper.CreateTagDictionary(TagsConversionHelper.CreateTagHashtable(pool.Tags), false), Location = pool.Location, Edition = edition }; return model; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Security; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Web; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Capabilities.Caps; using OSDArray=OpenMetaverse.StructuredData.OSDArray; using OSDMap=OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.CoreModules.InterGrid { public struct OGPState { public string first_name; public string last_name; public UUID agent_id; public UUID local_agent_id; public UUID region_id; public uint circuit_code; public UUID secure_session_id; public UUID session_id; public bool agent_access; public string sim_access; public uint god_level; public bool god_overide; public bool identified; public bool transacted; public bool age_verified; public bool allow_redirect; public int limited_to_estate; public string inventory_host; public bool src_can_see_mainland; public int src_estate_id; public int src_version; public int src_parent_estate_id; public bool visible_to_parent; public string teleported_into_region; } public class OpenGridProtocolModule : IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_scene = new List<Scene>(); private Dictionary<string, AgentCircuitData> CapsLoginID = new Dictionary<string, AgentCircuitData>(); private Dictionary<UUID, OGPState> m_OGPState = new Dictionary<UUID, OGPState>(); private Dictionary<string, string> m_loginToRegionState = new Dictionary<string, string>(); private string LastNameSuffix = "_EXTERNAL"; private string FirstNamePrefix = ""; private string httpsCN = ""; private bool httpSSL = false; private uint httpsslport = 0; private bool GridMode = false; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { bool enabled = false; IConfig cfg = null; IConfig httpcfg = null; IConfig startupcfg = null; try { cfg = config.Configs["OpenGridProtocol"]; } catch (NullReferenceException) { enabled = false; } try { httpcfg = config.Configs["Network"]; } catch (NullReferenceException) { } try { startupcfg = config.Configs["Startup"]; } catch (NullReferenceException) { } if (startupcfg != null) { GridMode = enabled = startupcfg.GetBoolean("gridmode", false); } if (cfg != null) { enabled = cfg.GetBoolean("ogp_enabled", false); LastNameSuffix = cfg.GetString("ogp_lastname_suffix", "_EXTERNAL"); FirstNamePrefix = cfg.GetString("ogp_firstname_prefix", ""); if (enabled) { m_log.Warn("[OGP]: Open Grid Protocol is on, Listening for Clients on /agent/"); lock (m_scene) { if (m_scene.Count == 0) { MainServer.Instance.AddLLSDHandler("/agent/", ProcessAgentDomainMessage); MainServer.Instance.AddLLSDHandler("/", ProcessRegionDomainSeed); try { ServicePointManager.ServerCertificateValidationCallback += customXertificateValidation; } catch (NotImplementedException) { try { #pragma warning disable 0612, 0618 // Mono does not implement the ServicePointManager.ServerCertificateValidationCallback yet! Don't remove this! ServicePointManager.CertificatePolicy = new MonoCert(); #pragma warning restore 0612, 0618 } catch (Exception) { m_log.Error("[OGP]: Certificate validation handler change not supported. You may get ssl certificate validation errors teleporting from your region to some SSL regions."); } } } // can't pick the region 'agent' because it would conflict with our agent domain handler // a zero length region name would conflict with are base region seed cap if (!SceneListDuplicateCheck(scene.RegionInfo.RegionName) && scene.RegionInfo.RegionName.ToLower() != "agent" && scene.RegionInfo.RegionName.Length > 0) { MainServer.Instance.AddLLSDHandler( "/" + HttpUtility.UrlPathEncode(scene.RegionInfo.RegionName.ToLower()), ProcessRegionDomainSeed); } if (!m_scene.Contains(scene)) m_scene.Add(scene); } } } lock (m_scene) { if (m_scene.Count == 1) { if (httpcfg != null) { httpSSL = httpcfg.GetBoolean("http_listener_ssl", false); httpsCN = httpcfg.GetString("http_listener_cn", scene.RegionInfo.ExternalHostName); if (httpsCN.Length == 0) httpsCN = scene.RegionInfo.ExternalHostName; httpsslport = (uint)httpcfg.GetInt("http_listener_sslport",((int)scene.RegionInfo.HttpPort + 1)); } } } } public void PostInitialise() { } public void Close() { //scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; } public string Name { get { return "OpenGridProtocolModule"; } } public bool IsSharedModule { get { return true; } } #endregion public OSD ProcessRegionDomainSeed(string path, OSD request, string endpoint) { string[] pathSegments = path.Split('/'); if (pathSegments.Length <= 1) { return GenerateNoHandlerMessage(); } return GenerateRezAvatarRequestMessage(pathSegments[1]); //m_log.InfoFormat("[OGP]: path {0}, segments {1} segment[1] {2} Last segment {3}", // path, pathSegments.Length, pathSegments[1], pathSegments[pathSegments.Length - 1]); //return new OSDMap(); } public OSD ProcessAgentDomainMessage(string path, OSD request, string endpoint) { // /agent/* string[] pathSegments = path.Split('/'); if (pathSegments.Length <= 1) { return GenerateNoHandlerMessage(); } if (pathSegments[0].Length == 0 && pathSegments[1].Length == 0) { return GenerateRezAvatarRequestMessage(""); } m_log.InfoFormat("[OGP]: path {0}, segments {1} segment[1] {2} Last segment {3}", path, pathSegments.Length, pathSegments[1], pathSegments[pathSegments.Length - 1]); switch (pathSegments[pathSegments.Length - 1]) { case "rez_avatar": return RezAvatarMethod(path, request); //break; case "derez_avatar": return DerezAvatarMethod(path, request); //break; } if (path.Length < 2) { return GenerateNoHandlerMessage(); } switch (pathSegments[pathSegments.Length - 2] + "/" + pathSegments[pathSegments.Length - 1]) { case "rez_avatar/rez": return RezAvatarMethod(path, request); //break; case "rez_avatar/request": return RequestRezAvatarMethod(path, request); case "rez_avatar/place": return RequestRezAvatarMethod(path, request); case "rez_avatar/derez": return DerezAvatarMethod(path, request); //break; default: return GenerateNoHandlerMessage(); } //return null; } private OSD GenerateRezAvatarRequestMessage(string regionname) { Scene region = null; bool usedroot = false; if (regionname.Length == 0) { region = GetRootScene(); usedroot = true; } else { region = GetScene(HttpUtility.UrlDecode(regionname).ToLower()); } // this shouldn't happen since we don't listen for a region that is down.. but // it might if the region was taken down or is in the middle of restarting if (region == null) { region = GetRootScene(); usedroot = true; } UUID statekeeper = UUID.Random(); RegionInfo reg = region.RegionInfo; OSDMap responseMap = new OSDMap(); string rezHttpProtocol = "http://"; //string regionCapsHttpProtocol = "http://"; string httpaddr = reg.ExternalHostName; string urlport = reg.HttpPort.ToString(); string requestpath = "/agent/" + statekeeper + "/rez_avatar/request"; if (!usedroot) { lock (m_loginToRegionState) { if (!m_loginToRegionState.ContainsKey(requestpath)) { m_loginToRegionState.Add(requestpath, region.RegionInfo.RegionName.ToLower()); } } } if (httpSSL) { rezHttpProtocol = "https://"; //regionCapsHttpProtocol = "https://"; urlport = httpsslport.ToString(); if (httpsCN.Length > 0) httpaddr = httpsCN; } responseMap["connect"] = OSD.FromBoolean(true); OSDMap capabilitiesMap = new OSDMap(); capabilitiesMap["rez_avatar/request"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + requestpath); responseMap["capabilities"] = capabilitiesMap; return responseMap; } // Using OpenSim.Framework.Capabilities.Caps here one time.. // so the long name is probably better then a using statement public void OnRegisterCaps(UUID agentID, Caps caps) { /* If we ever want to register our own caps here.... * string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("CAPNAME", new RestStreamHandler("POST", capsBase + CAPSPOSTFIX!, delegate(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return METHODHANDLER(request, path, param, agentID, caps); })); * */ } public OSD RequestRezAvatarMethod(string path, OSD request) { //m_log.Debug("[REQUESTREZAVATAR]: " + request.ToString()); OSDMap requestMap = (OSDMap)request; Scene homeScene = null; lock (m_loginToRegionState) { if (m_loginToRegionState.ContainsKey(path)) { homeScene = GetScene(m_loginToRegionState[path]); m_loginToRegionState.Remove(path); if (homeScene == null) homeScene = GetRootScene(); } else { homeScene = GetRootScene(); } } // Homescene is still null, we must have no regions that are up if (homeScene == null) return GenerateNoHandlerMessage(); RegionInfo reg = homeScene.RegionInfo; ulong regionhandle = GetOSCompatibleRegionHandle(reg); //string RegionURI = reg.ServerURI; //int RegionPort = (int)reg.HttpPort; UUID RemoteAgentID = requestMap["agent_id"].AsUUID(); // will be used in the future. The client always connects with the aditi agentid currently UUID LocalAgentID = RemoteAgentID; string FirstName = requestMap["first_name"].AsString(); string LastName = requestMap["last_name"].AsString(); FirstName = FirstNamePrefix + FirstName; LastName = LastName + LastNameSuffix; OGPState userState = GetOGPState(LocalAgentID); userState.first_name = requestMap["first_name"].AsString(); userState.last_name = requestMap["last_name"].AsString(); userState.age_verified = requestMap["age_verified"].AsBoolean(); userState.transacted = requestMap["transacted"].AsBoolean(); userState.agent_access = requestMap["agent_access"].AsBoolean(); userState.allow_redirect = requestMap["allow_redirect"].AsBoolean(); userState.identified = requestMap["identified"].AsBoolean(); userState.god_level = (uint)requestMap["god_level"].AsInteger(); userState.sim_access = requestMap["sim_access"].AsString(); userState.agent_id = RemoteAgentID; userState.limited_to_estate = requestMap["limited_to_estate"].AsInteger(); userState.src_can_see_mainland = requestMap["src_can_see_mainland"].AsBoolean(); userState.src_estate_id = requestMap["src_estate_id"].AsInteger(); userState.local_agent_id = LocalAgentID; userState.teleported_into_region = reg.RegionName.ToLower(); UpdateOGPState(LocalAgentID, userState); OSDMap responseMap = new OSDMap(); if (RemoteAgentID == UUID.Zero) { responseMap["connect"] = OSD.FromBoolean(false); responseMap["message"] = OSD.FromString("No agent ID was specified in rez_avatar/request"); m_log.Error("[OGP]: rez_avatar/request failed because no avatar UUID was provided in the request body"); return responseMap; } responseMap["sim_host"] = OSD.FromString(reg.ExternalHostName); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(reg.ExternalHostName).ToString()); responseMap["connect"] = OSD.FromBoolean(true); responseMap["sim_port"] = OSD.FromInteger(reg.InternalEndPoint.Port); responseMap["region_x"] = OSD.FromInteger(reg.RegionLocX * (uint)Constants.RegionSize); // LLX responseMap["region_y"] = OSD.FromInteger(reg.RegionLocY * (uint)Constants.RegionSize); // LLY responseMap["region_id"] = OSD.FromUUID(reg.originRegionID); if (reg.RegionSettings.Maturity == 1) { responseMap["sim_access"] = OSD.FromString("Mature"); } else if (reg.RegionSettings.Maturity == 2) { responseMap["sim_access"] = OSD.FromString("Adult"); } else { responseMap["sim_access"] = OSD.FromString("PG"); } // Generate a dummy agent for the user so we can get back a CAPS path AgentCircuitData agentData = new AgentCircuitData(); agentData.AgentID = LocalAgentID; agentData.BaseFolder = UUID.Zero; agentData.CapsPath = CapsUtil.GetRandomCapsObjectPath(); agentData.child = false; agentData.circuitcode = (uint)(Util.RandomClass.Next()); agentData.firstname = FirstName; agentData.lastname = LastName; agentData.SecureSessionID = UUID.Random(); agentData.SessionID = UUID.Random(); agentData.startpos = new Vector3(128f, 128f, 100f); // Pre-Fill our region cache with information on the agent. UserAgentData useragent = new UserAgentData(); useragent.AgentIP = "unknown"; useragent.AgentOnline = true; useragent.AgentPort = (uint)0; useragent.Handle = regionhandle; useragent.InitialRegion = reg.originRegionID; useragent.LoginTime = Util.UnixTimeSinceEpoch(); useragent.LogoutTime = 0; useragent.Position = agentData.startpos; useragent.Region = reg.originRegionID; useragent.SecureSessionID = agentData.SecureSessionID; useragent.SessionID = agentData.SessionID; UserProfileData userProfile = new UserProfileData(); userProfile.AboutText = "OGP User"; userProfile.CanDoMask = (uint)0; userProfile.Created = Util.UnixTimeSinceEpoch(); userProfile.CurrentAgent = useragent; userProfile.CustomType = "OGP"; userProfile.FirstLifeAboutText = "I'm testing OpenGrid Protocol"; userProfile.FirstLifeImage = UUID.Zero; userProfile.FirstName = agentData.firstname; userProfile.GodLevel = 0; userProfile.HomeLocation = agentData.startpos; userProfile.HomeLocationX = agentData.startpos.X; userProfile.HomeLocationY = agentData.startpos.Y; userProfile.HomeLocationZ = agentData.startpos.Z; userProfile.HomeLookAt = Vector3.Zero; userProfile.HomeLookAtX = userProfile.HomeLookAt.X; userProfile.HomeLookAtY = userProfile.HomeLookAt.Y; userProfile.HomeLookAtZ = userProfile.HomeLookAt.Z; userProfile.HomeRegion = reg.RegionHandle; userProfile.HomeRegionID = reg.originRegionID; userProfile.HomeRegionX = reg.RegionLocX; userProfile.HomeRegionY = reg.RegionLocY; userProfile.ID = agentData.AgentID; userProfile.Image = UUID.Zero; userProfile.LastLogin = Util.UnixTimeSinceEpoch(); userProfile.Partner = UUID.Zero; userProfile.PasswordHash = "$1$"; userProfile.PasswordSalt = ""; userProfile.RootInventoryFolderID = UUID.Zero; userProfile.SurName = agentData.lastname; userProfile.UserAssetURI = homeScene.CommsManager.NetworkServersInfo.AssetURL; userProfile.UserFlags = 0; userProfile.UserInventoryURI = homeScene.CommsManager.NetworkServersInfo.InventoryURL; userProfile.WantDoMask = 0; userProfile.WebLoginKey = UUID.Random(); // Do caps registration // get seed capagentData.firstname = FirstName;agentData.lastname = LastName; if (homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID) == null && !GridMode) { homeScene.CommsManager.UserAdminService.AddUser( agentData.firstname, agentData.lastname, CreateRandomStr(7), "", homeScene.RegionInfo.RegionLocX, homeScene.RegionInfo.RegionLocY, agentData.AgentID); UserProfileData userProfile2 = homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID); if (userProfile2 != null) { userProfile = userProfile2; userProfile.AboutText = "OGP USER"; userProfile.FirstLifeAboutText = "OGP USER"; homeScene.CommsManager.UserService.UpdateUserProfile(userProfile); } } // Stick our data in the cache so the region will know something about us homeScene.CommsManager.UserProfileCacheService.PreloadUserCache(userProfile); // Call 'new user' event handler string reason; if (!homeScene.NewUserConnection(agentData, out reason)) { responseMap["connect"] = OSD.FromBoolean(false); responseMap["message"] = OSD.FromString(String.Format("Connection refused: {0}", reason)); m_log.ErrorFormat("[OGP]: rez_avatar/request failed: {0}", reason); return responseMap; } //string raCap = string.Empty; UUID AvatarRezCapUUID = LocalAgentID; string rezAvatarPath = "/agent/" + AvatarRezCapUUID + "/rez_avatar/rez"; string derezAvatarPath = "/agent/" + AvatarRezCapUUID + "/rez_avatar/derez"; // Get a reference to the user's cap so we can pull out the Caps Object Path Caps userCap = homeScene.CapsModule.GetCapsHandlerForUser(agentData.AgentID); string rezHttpProtocol = "http://"; string regionCapsHttpProtocol = "http://"; string httpaddr = reg.ExternalHostName; string urlport = reg.HttpPort.ToString(); if (httpSSL) { rezHttpProtocol = "https://"; regionCapsHttpProtocol = "https://"; urlport = httpsslport.ToString(); if (httpsCN.Length > 0) httpaddr = httpsCN; } // DEPRECATED responseMap["seed_capability"] = OSD.FromString( regionCapsHttpProtocol + httpaddr + ":" + reg.HttpPort + CapsUtil.GetCapsSeedPath(userCap.CapsObjectPath)); // REPLACEMENT responseMap["region_seed_capability"] = OSD.FromString( regionCapsHttpProtocol + httpaddr + ":" + reg.HttpPort + CapsUtil.GetCapsSeedPath(userCap.CapsObjectPath)); responseMap["rez_avatar"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + rezAvatarPath); responseMap["rez_avatar/rez"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + rezAvatarPath); responseMap["rez_avatar/derez"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + derezAvatarPath); // Add the user to the list of CAPS that are outstanding. // well allow the caps hosts in this dictionary lock (CapsLoginID) { if (CapsLoginID.ContainsKey(rezAvatarPath)) { CapsLoginID[rezAvatarPath] = agentData; // This is a joke, if you didn't notice... It's so unlikely to happen, that I'll print this message if it does occur! m_log.Error("[OGP]: Holy anomoly batman! Caps path already existed! All the UUID Duplication worries were founded!"); } else { CapsLoginID.Add(rezAvatarPath, agentData); } } //m_log.Debug("Response:" + responseMap.ToString()); return responseMap; } public OSD RezAvatarMethod(string path, OSD request) { m_log.WarnFormat("[REZAVATAR]: {0}", request.ToString()); OSDMap responseMap = new OSDMap(); AgentCircuitData userData = null; // Only people we've issued a cap can go further if (TryGetAgentCircuitData(path,out userData)) { OSDMap requestMap = (OSDMap)request; // take these values to start. There's a few more UUID SecureSessionID=requestMap["secure_session_id"].AsUUID(); UUID SessionID = requestMap["session_id"].AsUUID(); int circuitcode = requestMap["circuit_code"].AsInteger(); OSDArray Parameter = new OSDArray(); if (requestMap.ContainsKey("parameter")) { Parameter = (OSDArray)requestMap["parameter"]; } //int version = 1; int estateID = 1; int parentEstateID = 1; UUID regionID = UUID.Zero; bool visibleToParent = true; for (int i = 0; i < Parameter.Count; i++) { OSDMap item = (OSDMap)Parameter[i]; // if (item.ContainsKey("version")) // { // version = item["version"].AsInteger(); // } if (item.ContainsKey("estate_id")) { estateID = item["estate_id"].AsInteger(); } if (item.ContainsKey("parent_estate_id")) { parentEstateID = item["parent_estate_id"].AsInteger(); } if (item.ContainsKey("region_id")) { regionID = item["region_id"].AsUUID(); } if (item.ContainsKey("visible_to_parent")) { visibleToParent = item["visible_to_parent"].AsBoolean(); } } //Update our Circuit data with the real values userData.SecureSessionID = SecureSessionID; userData.SessionID = SessionID; OGPState userState = GetOGPState(userData.AgentID); // Locate a home scene suitable for the user. Scene homeScene = null; homeScene = GetScene(userState.teleported_into_region); if (homeScene == null) homeScene = GetRootScene(); if (homeScene != null) { // Get a referenceokay - to their Cap object so we can pull out the capobjectroot Caps userCap = homeScene.CapsModule.GetCapsHandlerForUser(userData.AgentID); //Update the circuit data in the region so this user is authorized homeScene.UpdateCircuitData(userData); homeScene.ChangeCircuitCode(userData.circuitcode,(uint)circuitcode); // Load state // Keep state changes userState.first_name = requestMap["first_name"].AsString(); userState.secure_session_id = requestMap["secure_session_id"].AsUUID(); userState.age_verified = requestMap["age_verified"].AsBoolean(); userState.region_id = homeScene.RegionInfo.originRegionID; // replace 0000000 with our regionid userState.transacted = requestMap["transacted"].AsBoolean(); userState.agent_access = requestMap["agent_access"].AsBoolean(); userState.inventory_host = requestMap["inventory_host"].AsString(); userState.identified = requestMap["identified"].AsBoolean(); userState.session_id = requestMap["session_id"].AsUUID(); userState.god_level = (uint)requestMap["god_level"].AsInteger(); userState.last_name = requestMap["last_name"].AsString(); userState.god_overide = requestMap["god_override"].AsBoolean(); userState.circuit_code = (uint)requestMap["circuit_code"].AsInteger(); userState.limited_to_estate = requestMap["limited_to_estate"].AsInteger(); userState.src_estate_id = estateID; userState.region_id = regionID; userState.src_parent_estate_id = parentEstateID; userState.visible_to_parent = visibleToParent; // Save state changes UpdateOGPState(userData.AgentID, userState); // Get the region information for the home region. RegionInfo reg = homeScene.RegionInfo; // Dummy positional and look at info.. we don't have it. OSDArray PositionArray = new OSDArray(); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(40)); OSDArray LookAtArray = new OSDArray(); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); // Our region's X and Y position in OpenSimulator space. uint fooX = reg.RegionLocX; uint fooY = reg.RegionLocY; m_log.InfoFormat("[OGP]: region x({0}) region y({1})", fooX, fooY); m_log.InfoFormat("[OGP]: region http {0} {1}", reg.ServerURI, reg.HttpPort); m_log.InfoFormat("[OGO]: region UUID {0} ", reg.RegionID); // Convert the X and Y position to LL space responseMap["region_x"] = OSD.FromInteger(fooX * (uint)Constants.RegionSize); // convert it to LL X responseMap["region_y"] = OSD.FromInteger(fooY * (uint)Constants.RegionSize); // convert it to LL Y // Give em a new seed capability responseMap["seed_capability"] = OSD.FromString("http://" + reg.ExternalHostName + ":" + reg.HttpPort + "/CAPS/" + userCap.CapsObjectPath + "0000/"); responseMap["region"] = OSD.FromUUID(reg.originRegionID); responseMap["look_at"] = LookAtArray; responseMap["sim_port"] = OSD.FromInteger(reg.InternalEndPoint.Port); responseMap["sim_host"] = OSD.FromString(reg.ExternalHostName);// + ":" + reg.InternalEndPoint.Port.ToString()); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(reg.ExternalHostName).ToString()); responseMap["session_id"] = OSD.FromUUID(SessionID); responseMap["secure_session_id"] = OSD.FromUUID(SecureSessionID); responseMap["circuit_code"] = OSD.FromInteger(circuitcode); responseMap["position"] = PositionArray; responseMap["region_id"] = OSD.FromUUID(reg.originRegionID); responseMap["sim_access"] = OSD.FromString("Mature"); responseMap["connect"] = OSD.FromBoolean(true); m_log.InfoFormat("[OGP]: host: {0}, IP {1}", responseMap["sim_host"].ToString(), responseMap["sim_ip"].ToString()); } } return responseMap; } public OSD DerezAvatarMethod(string path, OSD request) { m_log.ErrorFormat("DerezPath: {0}, Request: {1}", path, request.ToString()); //LLSD llsdResponse = null; OSDMap responseMap = new OSDMap(); string[] PathArray = path.Split('/'); m_log.InfoFormat("[OGP]: prefix {0}, uuid {1}, suffix {2}", PathArray[1], PathArray[2], PathArray[3]); string uuidString = PathArray[2]; m_log.InfoFormat("[OGP]: Request to Derez avatar with UUID {0}", uuidString); UUID userUUID = UUID.Zero; if (UUID.TryParse(uuidString, out userUUID)) { UUID RemoteID = (UUID)uuidString; UUID LocalID = RemoteID; // FIXME: TODO: Routine to map RemoteUUIDs to LocalUUIds // would be done already.. but the client connects with the Aditi UUID // regardless over the UDP stack OGPState userState = GetOGPState(LocalID); if (userState.agent_id != UUID.Zero) { //OSDMap outboundRequestMap = new OSDMap(); OSDMap inboundRequestMap = (OSDMap)request; string rezAvatarString = inboundRequestMap["rez_avatar"].AsString(); if (rezAvatarString.Length == 0) { rezAvatarString = inboundRequestMap["rez_avatar/rez"].AsString(); } OSDArray LookAtArray = new OSDArray(); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); OSDArray PositionArray = new OSDArray(); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(40)); OSDArray lookArray = new OSDArray(); lookArray.Add(OSD.FromInteger(128)); lookArray.Add(OSD.FromInteger(128)); lookArray.Add(OSD.FromInteger(40)); responseMap["connect"] = OSD.FromBoolean(true);// it's okay to give this user up responseMap["look_at"] = LookAtArray; m_log.WarnFormat("[OGP]: Invoking rez_avatar on host:{0} for avatar: {1} {2}", rezAvatarString, userState.first_name, userState.last_name); OSDMap rezResponseMap = invokeRezAvatarCap(responseMap, rezAvatarString,userState); // If invoking it returned an error, parse and end if (rezResponseMap.ContainsKey("connect")) { if (rezResponseMap["connect"].AsBoolean() == false) { return responseMap; } } string rezRespSeedCap = ""; // DEPRECATED if (rezResponseMap.ContainsKey("seed_capability")) rezRespSeedCap = rezResponseMap["seed_capability"].AsString(); // REPLACEMENT if (rezResponseMap.ContainsKey("region_seed_capability")) rezRespSeedCap = rezResponseMap["region_seed_capability"].AsString(); // REPLACEMENT if (rezResponseMap.ContainsKey("rez_avatar/rez")) rezRespSeedCap = rezResponseMap["rez_avatar/rez"].AsString(); // DEPRECATED string rezRespSim_ip = rezResponseMap["sim_ip"].AsString(); string rezRespSim_host = rezResponseMap["sim_host"].AsString(); int rrPort = rezResponseMap["sim_port"].AsInteger(); int rrX = rezResponseMap["region_x"].AsInteger(); int rrY = rezResponseMap["region_y"].AsInteger(); m_log.ErrorFormat("X:{0}, Y:{1}", rrX, rrY); UUID rrRID = rezResponseMap["region_id"].AsUUID(); OSDArray RezResponsePositionArray = null; string rrAccess = rezResponseMap["sim_access"].AsString(); if (rezResponseMap.ContainsKey("position")) { RezResponsePositionArray = (OSDArray)rezResponseMap["position"]; } // DEPRECATED responseMap["seed_capability"] = OSD.FromString(rezRespSeedCap); // REPLACEMENT r3 responseMap["region_seed_capability"] = OSD.FromString(rezRespSeedCap); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(rezRespSim_ip).ToString()); responseMap["sim_host"] = OSD.FromString(rezRespSim_host); responseMap["sim_port"] = OSD.FromInteger(rrPort); responseMap["region_x"] = OSD.FromInteger(rrX); responseMap["region_y"] = OSD.FromInteger(rrY); responseMap["region_id"] = OSD.FromUUID(rrRID); responseMap["sim_access"] = OSD.FromString(rrAccess); if (RezResponsePositionArray != null) { responseMap["position"] = RezResponsePositionArray; } responseMap["look_at"] = lookArray; responseMap["connect"] = OSD.FromBoolean(true); ShutdownConnection(LocalID,this); // PLEASE STOP CHANGING THIS TO an M_LOG, M_LOG DOESN'T WORK ON MULTILINE .TOSTRINGS Console.WriteLine("RESPONSEDEREZ: " + responseMap.ToString()); return responseMap; } else { return GenerateNoStateMessage(LocalID); } } else { return GenerateNoHandlerMessage(); } //return responseMap; } private OSDMap invokeRezAvatarCap(OSDMap responseMap, string CapAddress, OGPState userState) { Scene reg = GetRootScene(); WebRequest DeRezRequest = WebRequest.Create(CapAddress); DeRezRequest.Method = "POST"; DeRezRequest.ContentType = "application/xml+llsd"; OSDMap RAMap = new OSDMap(); OSDMap AgentParms = new OSDMap(); OSDMap RegionParms = new OSDMap(); OSDArray Parameter = new OSDArray(2); OSDMap version = new OSDMap(); version["version"] = OSD.FromInteger(userState.src_version); Parameter.Add(version); OSDMap SrcData = new OSDMap(); SrcData["estate_id"] = OSD.FromInteger(reg.RegionInfo.EstateSettings.EstateID); SrcData["parent_estate_id"] = OSD.FromInteger((reg.RegionInfo.EstateSettings.ParentEstateID == 100 ? 1 : reg.RegionInfo.EstateSettings.ParentEstateID)); SrcData["region_id"] = OSD.FromUUID(reg.RegionInfo.originRegionID); SrcData["visible_to_parent"] = OSD.FromBoolean(userState.visible_to_parent); Parameter.Add(SrcData); AgentParms["first_name"] = OSD.FromString(userState.first_name); AgentParms["last_name"] = OSD.FromString(userState.last_name); AgentParms["agent_id"] = OSD.FromUUID(userState.agent_id); RegionParms["region_id"] = OSD.FromUUID(userState.region_id); AgentParms["circuit_code"] = OSD.FromInteger(userState.circuit_code); AgentParms["secure_session_id"] = OSD.FromUUID(userState.secure_session_id); AgentParms["session_id"] = OSD.FromUUID(userState.session_id); AgentParms["agent_access"] = OSD.FromBoolean(userState.agent_access); AgentParms["god_level"] = OSD.FromInteger(userState.god_level); AgentParms["god_overide"] = OSD.FromBoolean(userState.god_overide); AgentParms["identified"] = OSD.FromBoolean(userState.identified); AgentParms["transacted"] = OSD.FromBoolean(userState.transacted); AgentParms["age_verified"] = OSD.FromBoolean(userState.age_verified); AgentParms["limited_to_estate"] = OSD.FromInteger(userState.limited_to_estate); AgentParms["inventory_host"] = OSD.FromString(userState.inventory_host); // version 1 RAMap = AgentParms; // Planned for version 2 // RAMap["agent_params"] = AgentParms; RAMap["region_params"] = RegionParms; RAMap["parameter"] = Parameter; string RAMapString = RAMap.ToString(); m_log.InfoFormat("[OGP] RAMap string {0}", RAMapString); OSD LLSDofRAMap = RAMap; // RENAME if this works m_log.InfoFormat("[OGP]: LLSD of map as string was {0}", LLSDofRAMap.ToString()); //m_log.InfoFormat("[OGP]: LLSD+XML: {0}", LLSDParser.SerializeXmlString(LLSDofRAMap)); byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap); //string bufferDump = System.Text.Encoding.ASCII.GetString(buffer); //m_log.InfoFormat("[OGP]: buffer form is {0}",bufferDump); //m_log.InfoFormat("[OGP]: LLSD of map was {0}",buffer.Length); Stream os = null; try { // send the Post DeRezRequest.ContentLength = buffer.Length; //Count bytes to send os = DeRezRequest.GetRequestStream(); os.Write(buffer, 0, buffer.Length); //Send it os.Close(); m_log.InfoFormat("[OGP]: Derez Avatar Posted Rez Avatar request to remote sim {0}", CapAddress); } catch (WebException ex) { m_log.InfoFormat("[OGP] Bad send on de_rez_avatar {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } m_log.Info("[OGP] waiting for a reply after rez avatar send"); string rez_avatar_reply = null; { // get the response try { WebResponse webResponse = DeRezRequest.GetResponse(); if (webResponse == null) { m_log.Info("[OGP:] Null reply on rez_avatar post"); } StreamReader sr = new StreamReader(webResponse.GetResponseStream()); rez_avatar_reply = sr.ReadToEnd().Trim(); m_log.InfoFormat("[OGP]: rez_avatar reply was {0} ", rez_avatar_reply); } catch (WebException ex) { m_log.InfoFormat("[OGP]: exception on read after send of rez avatar {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } OSD rezResponse = null; try { rezResponse = OSDParser.DeserializeLLSDXml(rez_avatar_reply); responseMap = (OSDMap)rezResponse; } catch (Exception ex) { m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } } return responseMap; } public OSD GenerateNoHandlerMessage() { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("LLSDRequest"); map["message"] = OSD.FromString("No handler registered for LLSD Requests"); map["login"] = OSD.FromString("false"); map["connect"] = OSD.FromString("false"); return map; } public OSD GenerateNoStateMessage(UUID passedAvatar) { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("derez failed"); map["message"] = OSD.FromString("Unable to locate OGP state for avatar " + passedAvatar.ToString()); map["login"] = OSD.FromString("false"); map["connect"] = OSD.FromString("false"); return map; } private bool TryGetAgentCircuitData(string path, out AgentCircuitData userdata) { userdata = null; lock (CapsLoginID) { if (CapsLoginID.ContainsKey(path)) { userdata = CapsLoginID[path]; DiscardUsedCap(path); return true; } } return false; } private void DiscardUsedCap(string path) { CapsLoginID.Remove(path); } private Scene GetRootScene() { Scene ReturnScene = null; lock (m_scene) { if (m_scene.Count > 0) { ReturnScene = m_scene[0]; } } return ReturnScene; } private Scene GetScene(string scenename) { Scene ReturnScene = null; lock (m_scene) { foreach (Scene s in m_scene) { if (s.RegionInfo.RegionName.ToLower() == scenename) { ReturnScene = s; break; } } } return ReturnScene; } private ulong GetOSCompatibleRegionHandle(RegionInfo reg) { return Util.UIntsToLong(reg.RegionLocX, reg.RegionLocY); } private OGPState InitializeNewState() { OGPState returnState = new OGPState(); returnState.first_name = ""; returnState.last_name = ""; returnState.agent_id = UUID.Zero; returnState.local_agent_id = UUID.Zero; returnState.region_id = UUID.Zero; returnState.circuit_code = 0; returnState.secure_session_id = UUID.Zero; returnState.session_id = UUID.Zero; returnState.agent_access = true; returnState.god_level = 0; returnState.god_overide = false; returnState.identified = false; returnState.transacted = false; returnState.age_verified = false; returnState.limited_to_estate = 1; returnState.inventory_host = "http://inv4.mysql.aditi.lindenlab.com"; returnState.allow_redirect = true; returnState.sim_access = ""; returnState.src_can_see_mainland = true; returnState.src_estate_id = 1; returnState.src_version = 1; returnState.src_parent_estate_id = 1; returnState.visible_to_parent = true; returnState.teleported_into_region = ""; return returnState; } private OGPState GetOGPState(UUID agentId) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) { return m_OGPState[agentId]; } else { return InitializeNewState(); } } } public void DeleteOGPState(UUID agentId) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) m_OGPState.Remove(agentId); } } private void UpdateOGPState(UUID agentId, OGPState state) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) { m_OGPState[agentId] = state; } else { m_OGPState.Add(agentId,state); } } } private bool SceneListDuplicateCheck(string str) { // no lock, called from locked space! bool found = false; foreach (Scene s in m_scene) { if (s.RegionInfo.RegionName == str) { found = true; break; } } return found; } public void ShutdownConnection(UUID avatarId, OpenGridProtocolModule mod) { Scene homeScene = GetRootScene(); ScenePresence avatar = null; if (homeScene.TryGetAvatar(avatarId,out avatar)) { KillAUser ku = new KillAUser(avatar,mod); Watchdog.StartThread(ku.ShutdownNoLogout, "OGPShutdown", ThreadPriority.Normal, true); } } private string CreateRandomStr(int len) { Random rnd = new Random(Environment.TickCount); string returnstring = ""; string chars = "abcdefghijklmnopqrstuvwxyz0123456789"; for (int i = 0; i < len; i++) { returnstring += chars.Substring(rnd.Next(chars.Length), 1); } return returnstring; } // Temporary hack to allow teleporting to and from Vaak private static bool customXertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { //if (cert.Subject == "[email protected], CN=*.vaak.lindenlab.com, O=\"Linden Lab, Inc.\", L=San Francisco, S=California, C=US") //{ return true; //} //return false; } } public class KillAUser { private ScenePresence avToBeKilled = null; private OpenGridProtocolModule m_mod = null; public KillAUser(ScenePresence avatar, OpenGridProtocolModule mod) { avToBeKilled = avatar; m_mod = mod; } public void ShutdownNoLogout() { UUID avUUID = UUID.Zero; if (avToBeKilled != null) { avUUID = avToBeKilled.UUID; avToBeKilled.MakeChildAgent(); avToBeKilled.ControllingClient.SendLogoutPacketWhenClosing = false; int sleepMS = 30000; while (sleepMS > 0) { Watchdog.UpdateThread(); Thread.Sleep(1000); sleepMS -= 1000; } // test for child agent because they might have come back if (avToBeKilled.IsChildAgent) { m_mod.DeleteOGPState(avUUID); avToBeKilled.ControllingClient.Close(); } } Watchdog.RemoveThread(); } } public class MonoCert : ICertificatePolicy { #region ICertificatePolicy Members public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } #endregion } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; public enum AFSDKErrorCode { // General /** Unknown */ AFSDKErrorCodeUnknown, /** Library isn't initialized yet */ AFSDKErrorCodeLibraryNotInitialized, /** Internet isn't reachable (and is required) */ AFSDKErrorCodeInternetNotReachable, /** You need to set the application delegate to proceed */ AFSDKErrorCodeNeedsApplicationDelegate, // Initialization /** Missing the API Key */ AFSDKErrorCodeInitializationMissingAPIKey, /** Missing the Features bitmask */ AFSDKErrorCodeInitializationMissingFeatures, // Advertising sdk /** No ad available */ AFSDKErrorCodeAdvertisingNoAd, /** The request call isn't appropriate */ AFSDKErrorCodeAdvertisingBadCall, /** An ad is currently displayed for this format */ AFSDKErrorCodeAdvertisingAlreadyDisplayed, /** The request was canceled by the developer */ AFSDKErrorCodeAdvertisingCanceledByDevelopper, // Engage sdk /** The panel is already displayed */ AFSDKErrorCodePanelAlreadyDisplayed, /** The notification wasn't found */ AFSDKErrorCodeOpenNotificationNotFound, // In-app purchase /** The property object is not valid */ AFSDKErrorCodeIAPPropertyNotValid, /** The property object is missing a title attribute */ AFSDKErrorCodeIAPTitleMissing, /** The property object is missing a message attribute */ AFSDKErrorCodeIAPMessageMissing, /** The property object is missing a cancel button title attribute */ AFSDKErrorCodeIAPCancelButtonTitleMissing, /** The property object is missing a buy button title attribute */ AFSDKErrorCodeIAPBuyButtonTitleMissing, /** The property object is missing a buy block handler */ AFSDKErrorCodeIAPBuyBlockMissing, // Mediation sdk /** The placement id is not valid. */ AFSDKErrorCodeMediationPlacementIdNotValid, /** The payload received for the placement id is not valid */ AFSDKErrorCodeMediationPayloadNotValid, /** The received custom class does not exist */ AFSDKErrorCodeMediationCustomClassNotFound, /** The received custom class does not conform to protocol */ AFSDKErrorCodeMediationCustomClassNotConformToProtocol, /** The received placement id does not have any ads to show */ AFSDKErrorCodeMediationNoAds, /** The ad request timed out */ AFSDKErrorCodeMediationAdRequestTimeout, /** The interstitial has expired, you need to create a new one */ AFSDKErrorCodeMediationInterstitialExpired, /** The interstitial has already been used, you need to create a new one */ AFSDKErrorCodeMediationInterstitialAlreadyUsed, } public class AppsfireSDKEvents : MonoBehaviour { /* Interface to native implementation */ [DllImport("__Internal")] private static extern void afsdk_iniAndSetCallbackHandler(string handlerName); /* Base SDK Events */ // is initializing public delegate void AFSDKIsInitializingHandler(); public static event AFSDKIsInitializingHandler afsdkIsInitializing; // is initialized public delegate void AFSDKIsInitializedHandler(); public static event AFSDKIsInitializedHandler afsdkIsInitialized; /* Engage SDK Events */ // notifications count was updated public delegate void AFSDKNotificationsNumberChangedHandler(); public static event AFSDKNotificationsNumberChangedHandler afsdkNotificationsNumberChanged; // panel was presented public delegate void AFSDKPanelWasPresentedHandler(); public static event AFSDKPanelWasPresentedHandler afsdkPanelWasPresented; // panel was dismissed public delegate void AFSDKPanelWasDismissedHandler(); public static event AFSDKPanelWasDismissedHandler afsdkPanelWasDismissed; /* Advertising SDK Delegate */ // modal ads refreshed and available public delegate void AFSDKAdModalAdsRefreshedAndAvailableHandler(); public static event AFSDKAdModalAdsRefreshedAndAvailableHandler afsdkadModalAdsRefreshedAndAvailable; // modal ads refreshed and none is available public delegate void AFSDKAdModalAdsRefreshedAndNotAvailableHandler(); public static event AFSDKAdModalAdsRefreshedAndNotAvailableHandler afsdkadModalAdsRefreshedAndNotAvailable; /* Modal Ad Delegate */ // modal ad request did fail with error code public delegate void AFSDKAdModalAdRequestDidFailWithErrorCodeHandler(AFSDKErrorCode errorCode); public static event AFSDKAdModalAdRequestDidFailWithErrorCodeHandler afsdkadModalAdRequestDidFailWithErrorCode; // modal ad will appear public delegate void AFSDKAdModalAdWillAppearHandler(); public static event AFSDKAdModalAdWillAppearHandler afsdkadModalAdWillAppear; // modal ad did appear public delegate void AFSDKAdModalAdDidAppearHandler(); public static event AFSDKAdModalAdDidAppearHandler afsdkadModalAdDidAppear; // modal ad will disappear public delegate void AFSDKAdModalAdWillDisappearHandler(); public static event AFSDKAdModalAdWillDisappearHandler afsdkadModalAdWillWisappear; // modal ad did disappear public delegate void AFSDKAdModalAdDidDisappearHandler(); public static event AFSDKAdModalAdDidDisappearHandler afsdkadModalAdDidDisappear; /*! * Awake */ void Awake() { if (Application.platform == RuntimePlatform.IPhonePlayer) { gameObject.name = this.GetType().ToString(); afsdk_iniAndSetCallbackHandler(gameObject.name); } // DontDestroyOnLoad(this); } /* * Events Base SDK */ // sdk is initializing public void AFSDKIsInitializing(string empty) { if (afsdkIsInitializing != null) afsdkIsInitializing(); } // sdk is initialized public void AFSDKIsInitialized(string empty) { if (afsdkIsInitialized != null) afsdkIsInitialized(); } /* * Events Engage SDK */ // notifications count was updated public void AFSDKNotificationsNumberChanged(string empty) { if (afsdkNotificationsNumberChanged != null) afsdkNotificationsNumberChanged(); } // panel was presented public void AFSDKPanelWasPresented(string empty) { if (afsdkPanelWasPresented != null) afsdkPanelWasPresented(); } // panel was dismissed public void AFSDKPanelWasDismissed(string empty) { if (afsdkPanelWasDismissed != null) afsdkPanelWasDismissed(); } /* * Events Monetization SDK */ // modal ads refreshed and available public void AFSDKAdModalAdsRefreshedAndAvailable(string empty) { if (afsdkadModalAdsRefreshedAndAvailable != null) afsdkadModalAdsRefreshedAndAvailable(); } // modal ads refreshed and none is available public void AFSDKAdModalAdsRefreshedAndNotAvailable(string empty) { if (afsdkadModalAdsRefreshedAndNotAvailable != null) afsdkadModalAdsRefreshedAndNotAvailable(); } /* * Events Modal Ad */ // modal ad request did fail witht error code public void AFSDKAdModalAdRequestDidFailWithErrorCode(string errorCode) { if (afsdkadModalAdRequestDidFailWithErrorCode != null) afsdkadModalAdRequestDidFailWithErrorCode((AFSDKErrorCode)Int32.Parse(errorCode)); } // modal ad will appear public void AFSDKAdModalAdWillAppear(string empty) { if (afsdkadModalAdWillAppear != null) afsdkadModalAdWillAppear(); } // modal ad did appear public void AFSDKAdModalAdDidAppear(string empty) { if (afsdkadModalAdDidAppear != null) afsdkadModalAdDidAppear(); } // modal ad will disappear public void AFSDKAdModalAdWillDisappear(string empty) { if (afsdkadModalAdWillWisappear != null) afsdkadModalAdWillWisappear(); } // modal ad did disappear public void AFSDKAdModalAdDidDisappear(string empty) { if (afsdkadModalAdDidDisappear != null) afsdkadModalAdDidDisappear(); } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Provider; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Microsoft.WSMan.Management { /// <summary> /// Executes action on a target object specified by RESOURCE_URI, where /// parameters are specified by key value pairs. /// eg., Call StartService method on the spooler service /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// </summary> [Cmdlet(VerbsLifecycle.Invoke, "WSManAction", DefaultParameterSetName = "URI", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141446")] public class InvokeWSManActionCommand : AuthenticatingWSManCommand, IDisposable { /// <summary> /// The following is the definition of the input parameter "Action". /// Indicates the method which needs to be executed on the management object /// specified by the ResourceURI and selectors /// </summary> [Parameter(Mandatory = true, Position = 1)] [ValidateNotNullOrEmpty] public String Action { get { return action; } set { action = value; } } private String action; /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public String ApplicationName { get { return applicationname; } set { applicationname = value; } } private String applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Alias("cn")] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] [Alias("CURI", "CU")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "FilePath". /// Updates the management resource specified by the ResourceURI and SelectorSet /// via this input file /// </summary> [Parameter] [ValidateNotNullOrEmpty] public String FilePath { get { return filepath; } set { filepath = value; } } private String filepath; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hashtable and is used to pass a set of switches to the /// service to modify or refine the nature of the request. /// </summary> [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] [ValidateRange(1, Int32.MaxValue)] public Int32 Port { get { return port; } set { port = value; } } private Int32 port = 0; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are are more than 1 instance of the resource /// class /// </summary> [Parameter(Position = 2, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable SelectorSet { get { return selectorset; } set { selectorset = value; } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This hashtable can /// be created using New-WSManSessionOption /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("so")] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; /// <summary> /// The following is the definition of the input parameter "ValueSet". /// ValueSet is a hahs table which helps to modify resource represented by the /// ResourceURI and SelectorSet. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable ValueSet { get { return valueset; } set { valueset = value; } } private Hashtable valueset; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [Alias("ruri")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ResourceURI { get { return resourceuri; } set { resourceuri = value; } } private Uri resourceuri; private WSManHelper helper; IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); IWSManSession m_session = null; string connectionStr = string.Empty; /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { helper = new WSManHelper(this); helper.WSManOp = "invoke"; //create the connection string connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { //create the resourcelocator object IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); //create the session object m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); string resultXml = m_session.Invoke(action, m_resource, input, 0); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(resultXml); WriteObject(xmldoc.DocumentElement); } finally { if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } }//End ProcessRecord() #region IDisposable Members /// <summary> /// public dispose method /// </summary> public void Dispose() { //CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// public dispose method /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// BeginProcessing method. /// </summary> protected override void EndProcessing() { // WSManHelper helper = new WSManHelper(); helper.CleanUp(); } }//End Class }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework; using FarseerPhysics; using FarseerPhysics.Dynamics; using FarseerPhysics.Collision; using FarseerPhysics.Factories; using PhysicsSimulator = FarseerPhysics.Dynamics.World; using FarseerPhysics.Common; using FarseerPhysics.Common.Decomposition; namespace Pinball { public class Background : GameObject { private static Texture2D backgroundTexture; public Background(PhysicsSimulator physicsSimulator, Vector2 position) { base.Body = BodyFactory.CreateBody(physicsSimulator, position);//, 240, 320, 1000f); base.Body.IsStatic = true; //base.Body.Position = position; List<Vertices> verticesList = new List<Vertices>(); verticesList.AddRange(CreateYellowOneVertices()); verticesList.AddRange(CreateGreenOneVertices()); verticesList.AddRange(CreateBlueOneVertices()); verticesList.AddRange(CreateMagentaOneVertices()); verticesList.AddRange(CreateRedOneVertices()); verticesList.AddRange(CreateOrangeOneVertices()); verticesList.AddRange(CreateLightBlueOneVertices()); verticesList.AddRange(CreateYellowTwoVertices()); verticesList.AddRange(CreateGreenTwoVertices()); verticesList.AddRange(CreateBlueTwoVertices()); verticesList.AddRange(CreateGreenThreeVertices()); verticesList.AddRange(CreateRedTwoVertices()); verticesList.AddRange(CreateRedTwoVertices()); verticesList.AddRange(CreateMagentaThreeVertices()); verticesList.AddRange(CreateOrangeTwoVertices()); foreach (Vertices vertices in verticesList) { base.Fixtures.AddLast(FixtureFactory.CreatePolygon(vertices, 1, base.Body, Vector2.Zero)); base.Fixtures.Last.Value.CollisionCategories = CollisionCategory.Cat9; base.Fixtures.Last.Value.CollidesWith = CollisionCategory.Cat2; } // Magenta Two Fixture Section base.Fixtures.AddLast(FixtureFactory.CreateRectangle(3, 58, 1, base.Body, new Vector2(89, 89))); base.Fixtures.Last.Value.CollisionCategories = CollisionCategory.Cat9; base.Fixtures.Last.Value.CollidesWith = CollisionCategory.Cat2; // Red Three Fixture Section base.Fixtures.AddLast(FixtureFactory.CreateRectangle(3, 22, 1, base.Body, new Vector2(89, -81))); base.Fixtures.Last.Value.CollisionCategories = CollisionCategory.Cat9; base.Fixtures.Last.Value.CollidesWith = CollisionCategory.Cat2; } public static void LoadContent(ContentManager contentManager) { backgroundTexture = contentManager.Load<Texture2D>(@"GameTextures\GameBackground"); } public void Draw(float elapsedTime, SpriteBatch spriteBatch) { base.Draw(elapsedTime, spriteBatch, backgroundTexture, Color.White); } private List<Vertices> CreateYellowOneVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(1, 1)); vertices.Add(new Vector2(1, 100)); vertices.Add(new Vector2(1, 200)); vertices.Add(new Vector2(1, 319)); vertices.Add(new Vector2(44, 319)); vertices.Add(new Vector2(44, 304)); vertices.Add(new Vector2(37, 301)); vertices.Add(new Vector2(31, 298)); vertices.Add(new Vector2(27, 298)); vertices.Add(new Vector2(20, 293)); vertices.Add(new Vector2(16, 293)); vertices.Add(new Vector2(16, 239)); vertices.Add(new Vector2(16, 218)); vertices.Add(new Vector2(20, 210)); vertices.Add(new Vector2(24, 207)); vertices.Add(new Vector2(27, 206)); vertices.Add(new Vector2(33, 202)); vertices.Add(new Vector2(33, 183)); vertices.Add(new Vector2(33, 167)); vertices.Add(new Vector2(29, 156)); vertices.Add(new Vector2(26, 148)); vertices.Add(new Vector2(24, 141)); vertices.Add(new Vector2(19, 127)); vertices.Add(new Vector2(13, 110)); vertices.Add(new Vector2(8, 97)); vertices.Add(new Vector2(4, 89)); vertices.Add(new Vector2(4, 86)); vertices.Add(new Vector2(3, 83)); vertices.Add(new Vector2(3, 60)); vertices.Add(new Vector2(3, 40)); vertices.Add(new Vector2(3, 18)); vertices.Add(new Vector2(4, 15)); vertices.Add(new Vector2(6, 12)); vertices.Add(new Vector2(9, 11)); vertices.Add(new Vector2(9, 1)); vertices.Add(new Vector2(1, 1)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateGreenOneVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(10, 11)); vertices.Add(new Vector2(15, 15)); vertices.Add(new Vector2(16, 17)); vertices.Add(new Vector2(16, 40)); vertices.Add(new Vector2(16, 60)); vertices.Add(new Vector2(16, 79)); //vertices.Add(new Vector2(21, 88)); //vertices.Add(new Vector2(27, 100)); //vertices.Add(new Vector2(33, 112)); //vertices.Add(new Vector2(42, 126)); //vertices.Add(new Vector2(44, 125)); //vertices.Add(new Vector2(42, 118)); //vertices.Add(new Vector2(37, 104)); //vertices.Add(new Vector2(33, 92)); //vertices.Add(new Vector2(32, 88)); vertices.Add(new Vector2(32, 79)); vertices.Add(new Vector2(32, 74)); vertices.Add(new Vector2(32, 58)); vertices.Add(new Vector2(36, 47)); vertices.Add(new Vector2(39, 41)); vertices.Add(new Vector2(39, 36)); vertices.Add(new Vector2(23, 36)); vertices.Add(new Vector2(23, 27)); vertices.Add(new Vector2(23, 19)); vertices.Add(new Vector2(29, 13)); vertices.Add(new Vector2(34, 9)); vertices.Add(new Vector2(10, 11)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateBlueOneVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(40, 40)); vertices.Add(new Vector2(43, 35)); vertices.Add(new Vector2(47, 32)); vertices.Add(new Vector2(50, 38)); vertices.Add(new Vector2(52, 46)); vertices.Add(new Vector2(52, 48)); vertices.Add(new Vector2(49, 53)); vertices.Add(new Vector2(47, 56)); vertices.Add(new Vector2(46, 63)); vertices.Add(new Vector2(46, 72)); vertices.Add(new Vector2(46, 79)); vertices.Add(new Vector2(50, 87)); vertices.Add(new Vector2(54, 97)); vertices.Add(new Vector2(58, 100)); vertices.Add(new Vector2(63, 99)); vertices.Add(new Vector2(65, 97)); vertices.Add(new Vector2(65, 84)); vertices.Add(new Vector2(63, 74)); vertices.Add(new Vector2(59, 61)); vertices.Add(new Vector2(56, 53)); vertices.Add(new Vector2(56, 45)); vertices.Add(new Vector2(52, 35)); vertices.Add(new Vector2(47, 24)); vertices.Add(new Vector2(45, 22)); vertices.Add(new Vector2(42, 33)); vertices.Add(new Vector2(39, 26)); vertices.Add(new Vector2(39, 35)); vertices.Add(new Vector2(40, 40)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateMagentaOneVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(35, 10)); vertices.Add(new Vector2(38, 8)); vertices.Add(new Vector2(49, 8)); vertices.Add(new Vector2(54, 9)); vertices.Add(new Vector2(60, 16)); vertices.Add(new Vector2(64, 24)); vertices.Add(new Vector2(66, 30)); vertices.Add(new Vector2(67, 28)); vertices.Add(new Vector2(65, 22)); vertices.Add(new Vector2(80, 15)); vertices.Add(new Vector2(96, 9)); vertices.Add(new Vector2(114, 4)); vertices.Add(new Vector2(135, 2)); vertices.Add(new Vector2(156, 2)); vertices.Add(new Vector2(193, 2)); vertices.Add(new Vector2(193, 1)); vertices.Add(new Vector2(156, 1)); vertices.Add(new Vector2(100, 1)); vertices.Add(new Vector2(50, 1)); vertices.Add(new Vector2(35, 1)); vertices.Add(new Vector2(35, 10)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateRedOneVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(67, 32)); vertices.Add(new Vector2(70, 44)); vertices.Add(new Vector2(74, 57)); vertices.Add(new Vector2(78, 70)); vertices.Add(new Vector2(86, 84)); vertices.Add(new Vector2(95, 101)); vertices.Add(new Vector2(103, 113)); vertices.Add(new Vector2(106, 113)); vertices.Add(new Vector2(109, 97)); vertices.Add(new Vector2(113, 85)); vertices.Add(new Vector2(113, 82)); vertices.Add(new Vector2(105, 76)); vertices.Add(new Vector2(99, 67)); vertices.Add(new Vector2(98, 60)); vertices.Add(new Vector2(99, 51)); vertices.Add(new Vector2(106, 42)); vertices.Add(new Vector2(116, 35)); vertices.Add(new Vector2(117, 30)); vertices.Add(new Vector2(116, 25)); vertices.Add(new Vector2(114, 24)); vertices.Add(new Vector2(103, 24)); vertices.Add(new Vector2(92, 24)); vertices.Add(new Vector2(81, 29)); vertices.Add(new Vector2(70, 34)); vertices.Add(new Vector2(68, 28)); vertices.Add(new Vector2(67, 32)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateOrangeOneVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(194, 2)); vertices.Add(new Vector2(206, 6)); vertices.Add(new Vector2(213, 11)); vertices.Add(new Vector2(219, 20)); vertices.Add(new Vector2(223, 34)); vertices.Add(new Vector2(223, 60)); vertices.Add(new Vector2(223, 90)); vertices.Add(new Vector2(223, 120)); vertices.Add(new Vector2(223, 150)); vertices.Add(new Vector2(223, 170)); vertices.Add(new Vector2(223, 200)); vertices.Add(new Vector2(223, 230)); vertices.Add(new Vector2(223, 260)); vertices.Add(new Vector2(223, 278)); vertices.Add(new Vector2(225, 278)); vertices.Add(new Vector2(225, 200)); vertices.Add(new Vector2(225, 100)); vertices.Add(new Vector2(225, 1)); vertices.Add(new Vector2(194, 1)); vertices.Add(new Vector2(194, 2)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateLightBlueOneVertices() { Vertices vertices = new Vertices(); //vertices.Add(new Vector2(222, 278)); vertices.Add(new Vector2(210, 219)); vertices.Add(new Vector2(210, 200)); vertices.Add(new Vector2(210, 170)); vertices.Add(new Vector2(210, 150)); vertices.Add(new Vector2(210, 120)); vertices.Add(new Vector2(210, 91)); vertices.Add(new Vector2(208, 91)); vertices.Add(new Vector2(203, 99)); vertices.Add(new Vector2(195, 104)); vertices.Add(new Vector2(189, 107)); vertices.Add(new Vector2(194, 106)); vertices.Add(new Vector2(208, 114)); vertices.Add(new Vector2(198, 133)); vertices.Add(new Vector2(186, 158)); vertices.Add(new Vector2(181, 168)); vertices.Add(new Vector2(175, 178)); vertices.Add(new Vector2(175, 185)); vertices.Add(new Vector2(179, 185)); vertices.Add(new Vector2(184, 181)); vertices.Add(new Vector2(189, 180)); vertices.Add(new Vector2(194, 186)); vertices.Add(new Vector2(194, 191)); vertices.Add(new Vector2(191, 197)); vertices.Add(new Vector2(190, 200)); vertices.Add(new Vector2(198, 208)); vertices.Add(new Vector2(208, 219)); vertices.Add(new Vector2(210, 219)); //vertices.Add(new Vector2(222, 279)); //vertices.Add(new Vector2(222, 278)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateYellowTwoVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(188, 107)); vertices.Add(new Vector2(180, 109)); vertices.Add(new Vector2(174, 115)); vertices.Add(new Vector2(170, 125)); vertices.Add(new Vector2(169, 130)); vertices.Add(new Vector2(169, 133)); vertices.Add(new Vector2(172, 135)); vertices.Add(new Vector2(179, 126)); vertices.Add(new Vector2(186, 116)); vertices.Add(new Vector2(193, 107)); vertices.Add(new Vector2(188, 107)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateGreenTwoVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(209, 280)); vertices.Add(new Vector2(209, 282)); vertices.Add(new Vector2(204, 289)); vertices.Add(new Vector2(196, 294)); vertices.Add(new Vector2(189, 302)); vertices.Add(new Vector2(186, 307)); vertices.Add(new Vector2(185, 311)); vertices.Add(new Vector2(183, 319)); vertices.Add(new Vector2(225, 319)); vertices.Add(new Vector2(225, 300)); vertices.Add(new Vector2(225, 280)); vertices.Add(new Vector2(209, 280)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateBlueTwoVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(149, 124)); vertices.Add(new Vector2(153, 120)); vertices.Add(new Vector2(156, 115)); vertices.Add(new Vector2(157, 108)); vertices.Add(new Vector2(157, 101)); vertices.Add(new Vector2(151, 92)); vertices.Add(new Vector2(145, 89)); vertices.Add(new Vector2(137, 87)); vertices.Add(new Vector2(132, 88)); vertices.Add(new Vector2(132, 103)); vertices.Add(new Vector2(132, 116)); vertices.Add(new Vector2(140, 116)); vertices.Add(new Vector2(145, 120)); vertices.Add(new Vector2(149, 124)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateGreenThreeVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(31, 267)); vertices.Add(new Vector2(31, 278)); vertices.Add(new Vector2(43, 286)); vertices.Add(new Vector2(59, 294)); vertices.Add(new Vector2(63, 293)); vertices.Add(new Vector2(63, 290)); vertices.Add(new Vector2(52, 281)); vertices.Add(new Vector2(45, 276)); vertices.Add(new Vector2(38, 270)); vertices.Add(new Vector2(31, 267)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateRedTwoVertices() { Vertices vertices = new Vertices(); vertices.Add(new Vector2(197, 268)); vertices.Add(new Vector2(196, 268)); vertices.Add(new Vector2(189, 273)); vertices.Add(new Vector2(179, 280)); vertices.Add(new Vector2(170, 287)); vertices.Add(new Vector2(167, 290)); vertices.Add(new Vector2(167, 293)); vertices.Add(new Vector2(171, 294)); vertices.Add(new Vector2(175, 293)); vertices.Add(new Vector2(182, 288)); vertices.Add(new Vector2(190, 283)); vertices.Add(new Vector2(197, 277)); vertices.Add(new Vector2(197, 268)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } //private List<Vertices> CreateMagentaTwoVertices() //{ // Vertices vertices = new Vertices(); // vertices.Add(new Vector2(210, 278)); // vertices.Add(new Vector2(210, 270)); // vertices.Add(new Vector2(210, 260)); // vertices.Add(new Vector2(210, 250)); // vertices.Add(new Vector2(210, 240)); // vertices.Add(new Vector2(210, 230)); // vertices.Add(new Vector2(210, 220)); // vertices.Add(new Vector2(208, 220)); // vertices.Add(new Vector2(208, 230)); // vertices.Add(new Vector2(208, 240)); // vertices.Add(new Vector2(208, 250)); // vertices.Add(new Vector2(208, 260)); // vertices.Add(new Vector2(208, 270)); // vertices.Add(new Vector2(208, 278)); // vertices.Add(new Vector2(210, 278)); // for (int counter = 0; counter < vertices.Count; counter++) // { // vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); // } // return EarclipDecomposer.ConvexPartition(vertices); //} private List<Vertices> CreateMagentaThreeVertices() { Vertices vertices = new Vertices(); //vertices.Add(new Vector2(210, 90)); //vertices.Add(new Vector2(210, 80)); //vertices.Add(new Vector2(210, 70)); //vertices.Add(new Vector2(210, 60)); vertices.Add(new Vector2(210, 67)); vertices.Add(new Vector2(210, 47)); vertices.Add(new Vector2(206, 40)); vertices.Add(new Vector2(199, 34)); vertices.Add(new Vector2(199, 48)); vertices.Add(new Vector2(204, 57)); vertices.Add(new Vector2(208, 67)); vertices.Add(new Vector2(210, 67)); //vertices.Add(new Vector2(208, 75)); //vertices.Add(new Vector2(208, 80)); //vertices.Add(new Vector2(208, 85)); //vertices.Add(new Vector2(208, 90)); //vertices.Add(new Vector2(210, 90)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } private List<Vertices> CreateOrangeTwoVertices() { Vertices vertices = new Vertices(); //vertices.Add(new Vector2(10, 11)); //vertices.Add(new Vector2(15, 15)); //vertices.Add(new Vector2(16, 17)); //vertices.Add(new Vector2(16, 40)); //vertices.Add(new Vector2(16, 60)); //vertices.Add(new Vector2(16, 79)); vertices.Add(new Vector2(17, 80)); vertices.Add(new Vector2(21, 88)); vertices.Add(new Vector2(27, 100)); vertices.Add(new Vector2(33, 112)); vertices.Add(new Vector2(41, 126)); vertices.Add(new Vector2(43, 126)); vertices.Add(new Vector2(44, 125)); vertices.Add(new Vector2(44, 123)); vertices.Add(new Vector2(42, 118)); vertices.Add(new Vector2(37, 104)); vertices.Add(new Vector2(33, 92)); vertices.Add(new Vector2(32, 80)); //vertices.Add(new Vector2(32, 88)); //vertices.Add(new Vector2(32, 74)); //vertices.Add(new Vector2(32, 58)); //vertices.Add(new Vector2(36, 47)); //vertices.Add(new Vector2(39, 41)); //vertices.Add(new Vector2(39, 36)); //vertices.Add(new Vector2(23, 36)); //vertices.Add(new Vector2(23, 27)); //vertices.Add(new Vector2(23, 19)); //vertices.Add(new Vector2(29, 13)); //vertices.Add(new Vector2(34, 9)); //vertices.Add(new Vector2(10, 11)); vertices.Add(new Vector2(17, 80)); for (int counter = 0; counter < vertices.Count; counter++) { vertices[counter] = new Vector2(vertices[counter].X - 120, vertices[counter].Y - 160); } return EarclipDecomposer.ConvexPartition(vertices); } } }
// Copyright 2017, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Language.V1 { /// <summary> /// Settings for a <see cref="LanguageServiceClient"/>. /// </summary> public sealed partial class LanguageServiceSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="LanguageServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="LanguageServiceSettings"/>. /// </returns> public static LanguageServiceSettings GetDefault() => new LanguageServiceSettings(); /// <summary> /// Constructs a new <see cref="LanguageServiceSettings"/> object with default settings. /// </summary> public LanguageServiceSettings() { } private LanguageServiceSettings(LanguageServiceSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); AnalyzeSentimentSettings = existing.AnalyzeSentimentSettings; AnalyzeEntitiesSettings = existing.AnalyzeEntitiesSettings; AnalyzeSyntaxSettings = existing.AnalyzeSyntaxSettings; AnnotateTextSettings = existing.AnnotateTextSettings; OnCopy(existing); } partial void OnCopy(LanguageServiceSettings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="LanguageServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="LanguageServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "NonIdempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.Unavailable); /// <summary> /// "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 60000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(60000), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>LanguageServiceClient.AnalyzeSentiment</c> and <c>LanguageServiceClient.AnalyzeSentimentAsync</c>. /// </summary> /// <remarks> /// The default <c>LanguageServiceClient.AnalyzeSentiment</c> and /// <c>LanguageServiceClient.AnalyzeSentimentAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings AnalyzeSentimentSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>LanguageServiceClient.AnalyzeEntities</c> and <c>LanguageServiceClient.AnalyzeEntitiesAsync</c>. /// </summary> /// <remarks> /// The default <c>LanguageServiceClient.AnalyzeEntities</c> and /// <c>LanguageServiceClient.AnalyzeEntitiesAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings AnalyzeEntitiesSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>LanguageServiceClient.AnalyzeSyntax</c> and <c>LanguageServiceClient.AnalyzeSyntaxAsync</c>. /// </summary> /// <remarks> /// The default <c>LanguageServiceClient.AnalyzeSyntax</c> and /// <c>LanguageServiceClient.AnalyzeSyntaxAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings AnalyzeSyntaxSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>LanguageServiceClient.AnnotateText</c> and <c>LanguageServiceClient.AnnotateTextAsync</c>. /// </summary> /// <remarks> /// The default <c>LanguageServiceClient.AnnotateText</c> and /// <c>LanguageServiceClient.AnnotateTextAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings AnnotateTextSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="LanguageServiceSettings"/> object.</returns> public LanguageServiceSettings Clone() => new LanguageServiceSettings(this); } /// <summary> /// LanguageService client wrapper, for convenient use. /// </summary> public abstract partial class LanguageServiceClient { /// <summary> /// The default endpoint for the LanguageService service, which is a host of "language.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("language.googleapis.com", 443); /// <summary> /// The default LanguageService scopes. /// </summary> /// <remarks> /// The default LanguageService scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="LanguageServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="LanguageServiceClient"/>.</returns> public static async Task<LanguageServiceClient> CreateAsync(ServiceEndpoint endpoint = null, LanguageServiceSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="LanguageServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param> /// <returns>The created <see cref="LanguageServiceClient"/>.</returns> public static LanguageServiceClient Create(ServiceEndpoint endpoint = null, LanguageServiceSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="LanguageServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param> /// <returns>The created <see cref="LanguageServiceClient"/>.</returns> public static LanguageServiceClient Create(Channel channel, LanguageServiceSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); LanguageService.LanguageServiceClient grpcClient = new LanguageService.LanguageServiceClient(channel); return new LanguageServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, LanguageServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, LanguageServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, LanguageServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, LanguageServiceSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC LanguageService client. /// </summary> public virtual LanguageService.LanguageServiceClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync( Document document, CallSettings callSettings = null) => AnalyzeSentimentAsync( new AnalyzeSentimentRequest { Document = GaxPreconditions.CheckNotNull(document, nameof(document)), }, callSettings); /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync( Document document, CancellationToken cancellationToken) => AnalyzeSentimentAsync( document, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual AnalyzeSentimentResponse AnalyzeSentiment( Document document, CallSettings callSettings = null) => AnalyzeSentiment( new AnalyzeSentimentRequest { Document = GaxPreconditions.CheckNotNull(document, nameof(document)), }, callSettings); /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync( AnalyzeSentimentRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual AnalyzeSentimentResponse AnalyzeSentiment( AnalyzeSentimentRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync( Document document, EncodingType encodingType, CallSettings callSettings = null) => AnalyzeEntitiesAsync( new AnalyzeEntitiesRequest { Document = GaxPreconditions.CheckNotNull(document, nameof(document)), EncodingType = encodingType, }, callSettings); /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync( Document document, EncodingType encodingType, CancellationToken cancellationToken) => AnalyzeEntitiesAsync( document, encodingType, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual AnalyzeEntitiesResponse AnalyzeEntities( Document document, EncodingType encodingType, CallSettings callSettings = null) => AnalyzeEntities( new AnalyzeEntitiesRequest { Document = GaxPreconditions.CheckNotNull(document, nameof(document)), EncodingType = encodingType, }, callSettings); /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync( AnalyzeEntitiesRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual AnalyzeEntitiesResponse AnalyzeEntities( AnalyzeEntitiesRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync( Document document, EncodingType encodingType, CallSettings callSettings = null) => AnalyzeSyntaxAsync( new AnalyzeSyntaxRequest { Document = GaxPreconditions.CheckNotNull(document, nameof(document)), EncodingType = encodingType, }, callSettings); /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync( Document document, EncodingType encodingType, CancellationToken cancellationToken) => AnalyzeSyntaxAsync( document, encodingType, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual AnalyzeSyntaxResponse AnalyzeSyntax( Document document, EncodingType encodingType, CallSettings callSettings = null) => AnalyzeSyntax( new AnalyzeSyntaxRequest { Document = GaxPreconditions.CheckNotNull(document, nameof(document)), EncodingType = encodingType, }, callSettings); /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync( AnalyzeSyntaxRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual AnalyzeSyntaxResponse AnalyzeSyntax( AnalyzeSyntaxRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// A convenience method that provides all the features that analyzeSentiment, /// analyzeEntities, and analyzeSyntax provide in one call. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="features"> /// The enabled features. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnnotateTextResponse> AnnotateTextAsync( Document document, AnnotateTextRequest.Types.Features features, EncodingType encodingType, CallSettings callSettings = null) => AnnotateTextAsync( new AnnotateTextRequest { Document = GaxPreconditions.CheckNotNull(document, nameof(document)), Features = GaxPreconditions.CheckNotNull(features, nameof(features)), EncodingType = encodingType, }, callSettings); /// <summary> /// A convenience method that provides all the features that analyzeSentiment, /// analyzeEntities, and analyzeSyntax provide in one call. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="features"> /// The enabled features. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnnotateTextResponse> AnnotateTextAsync( Document document, AnnotateTextRequest.Types.Features features, EncodingType encodingType, CancellationToken cancellationToken) => AnnotateTextAsync( document, features, encodingType, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// A convenience method that provides all the features that analyzeSentiment, /// analyzeEntities, and analyzeSyntax provide in one call. /// </summary> /// <param name="document"> /// Input document. /// </param> /// <param name="features"> /// The enabled features. /// </param> /// <param name="encodingType"> /// The encoding type used by the API to calculate offsets. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual AnnotateTextResponse AnnotateText( Document document, AnnotateTextRequest.Types.Features features, EncodingType encodingType, CallSettings callSettings = null) => AnnotateText( new AnnotateTextRequest { Document = GaxPreconditions.CheckNotNull(document, nameof(document)), Features = GaxPreconditions.CheckNotNull(features, nameof(features)), EncodingType = encodingType, }, callSettings); /// <summary> /// A convenience method that provides all the features that analyzeSentiment, /// analyzeEntities, and analyzeSyntax provide in one call. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<AnnotateTextResponse> AnnotateTextAsync( AnnotateTextRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// A convenience method that provides all the features that analyzeSentiment, /// analyzeEntities, and analyzeSyntax provide in one call. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual AnnotateTextResponse AnnotateText( AnnotateTextRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// LanguageService client wrapper implementation, for convenient use. /// </summary> public sealed partial class LanguageServiceClientImpl : LanguageServiceClient { private readonly ApiCall<AnalyzeSentimentRequest, AnalyzeSentimentResponse> _callAnalyzeSentiment; private readonly ApiCall<AnalyzeEntitiesRequest, AnalyzeEntitiesResponse> _callAnalyzeEntities; private readonly ApiCall<AnalyzeSyntaxRequest, AnalyzeSyntaxResponse> _callAnalyzeSyntax; private readonly ApiCall<AnnotateTextRequest, AnnotateTextResponse> _callAnnotateText; /// <summary> /// Constructs a client wrapper for the LanguageService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="LanguageServiceSettings"/> used within this client </param> public LanguageServiceClientImpl(LanguageService.LanguageServiceClient grpcClient, LanguageServiceSettings settings) { this.GrpcClient = grpcClient; LanguageServiceSettings effectiveSettings = settings ?? LanguageServiceSettings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); _callAnalyzeSentiment = clientHelper.BuildApiCall<AnalyzeSentimentRequest, AnalyzeSentimentResponse>( GrpcClient.AnalyzeSentimentAsync, GrpcClient.AnalyzeSentiment, effectiveSettings.AnalyzeSentimentSettings); _callAnalyzeEntities = clientHelper.BuildApiCall<AnalyzeEntitiesRequest, AnalyzeEntitiesResponse>( GrpcClient.AnalyzeEntitiesAsync, GrpcClient.AnalyzeEntities, effectiveSettings.AnalyzeEntitiesSettings); _callAnalyzeSyntax = clientHelper.BuildApiCall<AnalyzeSyntaxRequest, AnalyzeSyntaxResponse>( GrpcClient.AnalyzeSyntaxAsync, GrpcClient.AnalyzeSyntax, effectiveSettings.AnalyzeSyntaxSettings); _callAnnotateText = clientHelper.BuildApiCall<AnnotateTextRequest, AnnotateTextResponse>( GrpcClient.AnnotateTextAsync, GrpcClient.AnnotateText, effectiveSettings.AnnotateTextSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(LanguageService.LanguageServiceClient grpcClient, LanguageServiceSettings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC LanguageService client. /// </summary> public override LanguageService.LanguageServiceClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_AnalyzeSentimentRequest(ref AnalyzeSentimentRequest request, ref CallSettings settings); partial void Modify_AnalyzeEntitiesRequest(ref AnalyzeEntitiesRequest request, ref CallSettings settings); partial void Modify_AnalyzeSyntaxRequest(ref AnalyzeSyntaxRequest request, ref CallSettings settings); partial void Modify_AnnotateTextRequest(ref AnnotateTextRequest request, ref CallSettings settings); /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync( AnalyzeSentimentRequest request, CallSettings callSettings = null) { Modify_AnalyzeSentimentRequest(ref request, ref callSettings); return _callAnalyzeSentiment.Async(request, callSettings); } /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override AnalyzeSentimentResponse AnalyzeSentiment( AnalyzeSentimentRequest request, CallSettings callSettings = null) { Modify_AnalyzeSentimentRequest(ref request, ref callSettings); return _callAnalyzeSentiment.Sync(request, callSettings); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync( AnalyzeEntitiesRequest request, CallSettings callSettings = null) { Modify_AnalyzeEntitiesRequest(ref request, ref callSettings); return _callAnalyzeEntities.Async(request, callSettings); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override AnalyzeEntitiesResponse AnalyzeEntities( AnalyzeEntitiesRequest request, CallSettings callSettings = null) { Modify_AnalyzeEntitiesRequest(ref request, ref callSettings); return _callAnalyzeEntities.Sync(request, callSettings); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync( AnalyzeSyntaxRequest request, CallSettings callSettings = null) { Modify_AnalyzeSyntaxRequest(ref request, ref callSettings); return _callAnalyzeSyntax.Async(request, callSettings); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override AnalyzeSyntaxResponse AnalyzeSyntax( AnalyzeSyntaxRequest request, CallSettings callSettings = null) { Modify_AnalyzeSyntaxRequest(ref request, ref callSettings); return _callAnalyzeSyntax.Sync(request, callSettings); } /// <summary> /// A convenience method that provides all the features that analyzeSentiment, /// analyzeEntities, and analyzeSyntax provide in one call. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<AnnotateTextResponse> AnnotateTextAsync( AnnotateTextRequest request, CallSettings callSettings = null) { Modify_AnnotateTextRequest(ref request, ref callSettings); return _callAnnotateText.Async(request, callSettings); } /// <summary> /// A convenience method that provides all the features that analyzeSentiment, /// analyzeEntities, and analyzeSyntax provide in one call. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override AnnotateTextResponse AnnotateText( AnnotateTextRequest request, CallSettings callSettings = null) { Modify_AnnotateTextRequest(ref request, ref callSettings); return _callAnnotateText.Sync(request, callSettings); } } // Partial classes to enable page-streaming }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc.Routing; namespace Microsoft.AspNetCore.Routing { /// <summary> /// Extension methods for using <see cref="LinkGenerator"/> to generate links to Razor Pages. /// </summary> public static class PageLinkGeneratorExtensions { /// <summary> /// Generates a URI with an absolute path based on the provided values. /// </summary> /// <param name="generator">The <see cref="LinkGenerator"/>.</param> /// <param name="httpContext">The <see cref="HttpContext"/> associated with the current request.</param> /// <param name="page"> /// The page name. Used to resolve endpoints. Optional. If <c>null</c> is provided, the current page route value /// will be used. /// </param> /// <param name="handler"> /// The page handler name. Used to resolve endpoints. Optional. /// </param> /// <param name="values">The route values. Optional. Used to resolve endpoints and expand parameters in the route template.</param> /// <param name="pathBase"> /// An optional URI path base. Prepended to the path in the resulting URI. If not provided, the value of <see cref="HttpRequest.PathBase"/> will be used. /// </param> /// <param name="fragment">A URI fragment. Optional. Appended to the resulting URI.</param> /// <param name="options"> /// An optional <see cref="LinkOptions"/>. Settings on provided object override the settings with matching /// names from <c>RouteOptions</c>. /// </param> /// <returns>A URI with an absolute path, or <c>null</c> if a URI cannot be created.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static string? GetPathByPage( this LinkGenerator generator, HttpContext httpContext, string? page = default, string? handler = default, object? values = default, PathString? pathBase = default, FragmentString fragment = default, LinkOptions? options = default) { if (generator == null) { throw new ArgumentNullException(nameof(generator)); } if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } var address = CreateAddress(httpContext, page, handler, values); return generator.GetPathByAddress<RouteValuesAddress>( httpContext, address, address.ExplicitValues, address.AmbientValues, pathBase, fragment, options); } /// <summary> /// Generates a URI with an absolute path based on the provided values. /// </summary> /// <param name="generator">The <see cref="LinkGenerator"/>.</param> /// <param name="page"> /// The page name. Used to resolve endpoints. /// </param> /// <param name="handler"> /// The page handler name. Used to resolve endpoints. Optional. /// </param> /// <param name="values">The route values. Optional. Used to resolve endpoints and expand parameters in the route template.</param> /// <param name="pathBase">An optional URI path base. Prepended to the path in the resulting URI.</param> /// <param name="fragment">A URI fragment. Optional. Appended to the resulting URI.</param> /// <param name="options"> /// An optional <see cref="LinkOptions"/>. Settings on provided object override the settings with matching /// names from <c>RouteOptions</c>. /// </param> /// <returns>A URI with an absolute path, or <c>null</c> if a URI cannot be created.</returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static string? GetPathByPage( this LinkGenerator generator, string page, string? handler = default, object? values = default, PathString pathBase = default, FragmentString fragment = default, LinkOptions? options = default) { if (generator == null) { throw new ArgumentNullException(nameof(generator)); } if (page == null) { throw new ArgumentNullException(nameof(page)); } var address = CreateAddress(httpContext: null, page, handler, values); return generator.GetPathByAddress(address, address.ExplicitValues, pathBase, fragment, options); } /// <summary> /// Generates an absolute URI based on the provided values. /// </summary> /// <param name="generator">The <see cref="LinkGenerator"/>.</param> /// <param name="httpContext">The <see cref="HttpContext"/> associated with the current request.</param> /// <param name="page"> /// The page name. Used to resolve endpoints. Optional. If <c>null</c> is provided, the current page route value /// will be used. /// </param> /// <param name="handler"> /// The page handler name. Used to resolve endpoints. Optional. /// </param> /// <param name="values">The route values. Optional. Used to resolve endpoints and expand parameters in the route template.</param> /// <param name="scheme"> /// The URI scheme, applied to the resulting URI. Optional. If not provided, the value of <see cref="HttpRequest.Scheme"/> will be used. /// </param> /// <param name="host"> /// The URI host/authority, applied to the resulting URI. Optional. If not provided, the value <see cref="HttpRequest.Host"/> will be used. /// </param> /// <param name="pathBase"> /// An optional URI path base. Prepended to the path in the resulting URI. If not provided, the value of <see cref="HttpRequest.PathBase"/> will be used. /// </param> /// <param name="fragment">A URI fragment. Optional. Appended to the resulting URI.</param> /// <param name="options"> /// An optional <see cref="LinkOptions"/>. Settings on provided object override the settings with matching /// names from <c>RouteOptions</c>. /// </param> /// <returns>A absolute URI, or <c>null</c> if a URI cannot be created.</returns> /// <remarks> /// <para> /// The value of <paramref name="host" /> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static string? GetUriByPage( this LinkGenerator generator, HttpContext httpContext, string? page = default, string? handler = default, object? values = default, string? scheme = default, HostString? host = default, PathString? pathBase = default, FragmentString fragment = default, LinkOptions? options = default) { if (generator == null) { throw new ArgumentNullException(nameof(generator)); } if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } var address = CreateAddress(httpContext, page, handler, values); return generator.GetUriByAddress<RouteValuesAddress>( httpContext, address, address.ExplicitValues, address.AmbientValues, scheme, host, pathBase, fragment, options); } /// <summary> /// Generates an absolute URI based on the provided values. /// </summary> /// <param name="generator">The <see cref="LinkGenerator"/>.</param> /// <param name="page">The page name. Used to resolve endpoints.</param> /// <param name="handler">The page handler name. May be null.</param> /// <param name="values">The route values. May be null. Used to resolve endpoints and expand parameters in the route template.</param> /// <param name="scheme">The URI scheme, applied to the resulting URI.</param> /// <param name="host">The URI host/authority, applied to the resulting URI.</param> /// <param name="pathBase">An optional URI path base. Prepended to the path in the resulting URI.</param> /// <param name="fragment">A URI fragment. Optional. Appended to the resulting URI.</param> /// <param name="options"> /// An optional <see cref="LinkOptions"/>. Settings on provided object override the settings with matching /// names from <c>RouteOptions</c>. /// </param> /// <returns>A absolute URI, or <c>null</c> if a URI cannot be created.</returns> /// <remarks> /// <para> /// The value of <paramref name="host" /> should be a trusted value. Relying on the value of the current request /// can allow untrusted input to influence the resulting URI unless the <c>Host</c> header has been validated. /// See the deployment documentation for instructions on how to properly validate the <c>Host</c> header in /// your deployment environment. /// </para> /// </remarks> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static string? GetUriByPage( this LinkGenerator generator, string page, string? handler, object? values, string scheme, HostString host, PathString pathBase = default, FragmentString fragment = default, LinkOptions? options = default) { if (generator == null) { throw new ArgumentNullException(nameof(generator)); } if (page == null) { throw new ArgumentNullException(nameof(page)); } var address = CreateAddress(httpContext: null, page, handler, values); return generator.GetUriByAddress<RouteValuesAddress>(address, address.ExplicitValues, scheme, host, pathBase, fragment, options); } private static RouteValuesAddress CreateAddress(HttpContext? httpContext, string? page, string? handler, object? values) { var explicitValues = new RouteValueDictionary(values); var ambientValues = GetAmbientValues(httpContext); UrlHelperBase.NormalizeRouteValuesForPage(context: null, page, handler, explicitValues, ambientValues); return new RouteValuesAddress() { AmbientValues = ambientValues, ExplicitValues = explicitValues }; } private static RouteValueDictionary? GetAmbientValues(HttpContext? httpContext) { return httpContext?.Features.Get<IRouteValuesFeature>()?.RouteValues; } } }
using BellRichM.Logging; using BellRichM.Weather.Api.Configuration; using BellRichM.Weather.Api.Data; using BellRichM.Weather.Api.Models; using System; using System.Collections.Generic; using System.Data.Common; using System.Globalization; using System.Linq; using System.Threading.Tasks; namespace BellRichM.Weather.Api.Repositories { /// <inheritdoc/> public class ConditionRepository : IConditionRepository { private const string DataFields = @" , CAST(MAX(outTemp) as TEXT) as maxTemp , CAST(MIN(outTemp) as TEXT) as minTemp , CAST(MAX(outHumidity) as TEXT) as maxHumidity , CAST(MIN(outHumidity) as TEXT) as minHumidity , CAST(MAX(dewpoint) as TEXT) as maxDewpoint , CAST(MIN(dewpoint) as TEXT) as minDewpoint , CAST(MAX(heatIndex) as TEXT) as maxHeatIndex , CAST(MIN(windchill) as TEXT) as minWindchill , CAST(MAX(barometer) as TEXT) as maxBarometer , CAST(MIN(barometer) as TEXT) as minBarometer , CAST(MAX(ET) as TEXT) as maxET , CAST(MIN(ET) as TEXT) as minET , CAST(MAX(UV) as TEXT) as maxUV , CAST(MIN(UV) as TEXT) as minUV , CAST(MAX(radiation) as TEXT) as maxRadiation , CAST(MIN(radiation) as TEXT) as minRadiation , CAST(MAX(rainRate) as TEXT) as maxRainRate , CAST(SUM(rain) as TEXT) as rainTotal , CAST(MAX(windGust) as TEXT) as maxWindGust , CAST(AVG(windSpeed) as TEXT) as avgWindSpeed FROM condition "; private const string GroupSelect = @" SELECT c1.year, c1.month, c1.day, c1.windGustDir, c1.windGust, AVG(c1.windDir) as windDir, AVG(c1.windSpeed) as windSpeed, AVG(c1.outTemp) as outTemp, AVG(c1.heatindex) as heatindex, AVG(windchill) as windchill, AVG(dewpoint) as dewpoint, AVG(barometer) as barometer, SUM(c1.rain) as rain, AVG(c1.rainRate) as rainRate, AVG(c1.outHumidity) as outHumidity FROM condition c1 INNER JOIN ( SELECT MAX(windGust) as windGustMax, year, month, day FROM condition "; private readonly ILoggerAdapter<ConditionRepository> _logger; private readonly string _connectionString; private readonly DbProviderFactory _conditionDbProviderFactory; /// <summary> /// Initializes a new instance of the <see cref="ConditionRepository"/> class. /// </summary> /// <param name="logger">The <see cref="ILoggerAdapter{T}"/>.</param> /// <param name="conditionDbProviderFactory">The <see cref="ConditionRepositoryDbProviderFactory"/>.</param> /// <param name="conditionRepositoryConfiguration">The config.</param> public ConditionRepository(ILoggerAdapter<ConditionRepository> logger, ConditionRepositoryDbProviderFactory conditionDbProviderFactory, IConditionRepositoryConfiguration conditionRepositoryConfiguration) { if (conditionRepositoryConfiguration == null) { throw new ArgumentNullException(nameof(conditionRepositoryConfiguration)); } if (conditionDbProviderFactory == null) { throw new ArgumentNullException(nameof(conditionDbProviderFactory)); } _logger = logger; _conditionDbProviderFactory = conditionDbProviderFactory.ConditionDbProviderFactory; _connectionString = conditionRepositoryConfiguration.ConnectionString; } /// <inheritdoc/> public async Task<IEnumerable<MinMaxCondition>> GetYear(int offset, int limit) { _logger.LogDiagnosticDebug("GetYear: {@offset} {@limit}", offset, limit); var statement = "SELECT year" + DataFields + @" GROUP BY year ORDER BY year LIMIT @limit OFFSET @offset ; "; var records = new List<MinMaxCondition>(); var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = statement; using (dbCommand) { dbCommand.AddParamWithValue("@offset", offset); dbCommand.AddParamWithValue("@limit", limit); dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { while (await rdr.ReadAsync().ConfigureAwait(true)) { var minMaxCondition = ReadDataFields(rdr); minMaxCondition.Year = System.Convert.ToInt32(rdr["year"], CultureInfo.InvariantCulture); records.Add(minMaxCondition); } } } } return records; } /// <inheritdoc/> public async Task<MinMaxCondition> GetHourDetail(int year, int month, int day, int hour) { _logger.LogDiagnosticDebug("GetHourDetail: {@year} {@month} {@day} {@hour}", year, month, day, hour); var statement = @" SELECT year, month, day, hour" + DataFields + @" WHERE year = @year AND month = @month AND DAY = @day AND HOUR = @hour GROUP BY year, month, day, hour ; "; MinMaxCondition minMaxCondition = null; var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = statement; using (dbCommand) { dbCommand.AddParamWithValue("@year", year); dbCommand.AddParamWithValue("@month", month); dbCommand.AddParamWithValue("@day", day); dbCommand.AddParamWithValue("@hour", hour); dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { while (await rdr.ReadAsync().ConfigureAwait(true)) { minMaxCondition = ReadDataFields(rdr); minMaxCondition.Year = System.Convert.ToInt32(rdr["year"], CultureInfo.InvariantCulture); minMaxCondition.Month = System.Convert.ToInt32(rdr["month"], CultureInfo.InvariantCulture); minMaxCondition.Day = System.Convert.ToInt32(rdr["day"], CultureInfo.InvariantCulture); minMaxCondition.Hour = System.Convert.ToInt32(rdr["hour"], CultureInfo.InvariantCulture); } } } } return minMaxCondition; } /// <inheritdoc/> public async Task<IEnumerable<MinMaxGroup>> GetMinMaxConditionsByMinute(int dayOfYear, int startHour, int endHour, int offset, int limit) { _logger.LogDiagnosticDebug("GetYear: {@offset} {@limit}", offset, limit); var statement = "SELECT year, month, day, dayOfYear, hour, minute" + DataFields + @" WHERE dayOfYear = @dayOfYear AND hour <= @endHour AND hour >= @startHour GROUP BY year, dayOfYear, hour, minute ORDER BY dayOfYear, hour, minute LIMIT @limit OFFSET @offset ; "; _logger.LogDiagnosticDebug("statement:\n {statement}\n", statement); var minMaxGroups = new List<MinMaxGroup>(); var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = statement; using (dbCommand) { dbCommand.AddParamWithValue("@dayOfYear", dayOfYear); dbCommand.AddParamWithValue("@startHour", startHour); dbCommand.AddParamWithValue("@endHour", endHour); dbCommand.AddParamWithValue("@offset", offset); dbCommand.AddParamWithValue("@limit", 10000); // TODO temp to dump out some test data dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { while (await rdr.ReadAsync().ConfigureAwait(true)) { var minMaxCondition = ReadDataFields(rdr); minMaxCondition.Year = System.Convert.ToInt32(rdr["year"], CultureInfo.InvariantCulture); minMaxCondition.Month = System.Convert.ToInt32(rdr["month"], CultureInfo.InvariantCulture); minMaxCondition.Day = System.Convert.ToInt32(rdr["day"], CultureInfo.InvariantCulture); minMaxCondition.DayOfYear = System.Convert.ToInt32(rdr["dayOfYear"], CultureInfo.InvariantCulture); minMaxCondition.Hour = System.Convert.ToInt32(rdr["hour"], CultureInfo.InvariantCulture); minMaxCondition.Minute = System.Convert.ToInt32(rdr["minute"], CultureInfo.InvariantCulture); var minMaxGroup = minMaxGroups.FirstOrDefault(g => g.DayOfYear == minMaxCondition.DayOfYear && g.Hour == minMaxCondition.Hour && g.Minute == minMaxCondition.Minute); if (minMaxGroup is null) { minMaxGroup = new MinMaxGroup { Month = minMaxCondition.Month, Day = minMaxCondition.Day, DayOfYear = minMaxCondition.DayOfYear, Hour = minMaxCondition.Hour, Minute = minMaxCondition.Minute }; minMaxGroups.Add(minMaxGroup); } minMaxGroup.MinMaxConditions.Add(minMaxCondition); } } } } return minMaxGroups; } /// <inheritdoc/> public async Task<IEnumerable<MinMaxGroup>> GetMinMaxConditionsByHour(int startDayOfYear, int endDayOfYear, int offset, int limit) { _logger.LogDiagnosticDebug("GetYear: {@offset} {@limit}", offset, limit); var statement = "SELECT year, month, day, dayOfYear, hour" + DataFields + @" WHERE dayOfYear <= @endDayOfYear AND dayOfYear >= @startDayOfYear GROUP BY year, dayOfYear, hour ORDER BY dayOfYear, hour LIMIT @limit OFFSET @offset ; "; _logger.LogDiagnosticDebug("statement:\n {statement}\n", statement); var minMaxGroups = new List<MinMaxGroup>(); var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = statement; using (dbCommand) { dbCommand.AddParamWithValue("@startDayOfYear", startDayOfYear); dbCommand.AddParamWithValue("@endDayOfYear", endDayOfYear); dbCommand.AddParamWithValue("@offset", offset); dbCommand.AddParamWithValue("@limit", 100000); // TODO temp to dump out some test data dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { while (await rdr.ReadAsync().ConfigureAwait(true)) { var minMaxCondition = ReadDataFields(rdr); minMaxCondition.Year = System.Convert.ToInt32(rdr["year"], CultureInfo.InvariantCulture); minMaxCondition.Month = System.Convert.ToInt32(rdr["month"], CultureInfo.InvariantCulture); minMaxCondition.Day = System.Convert.ToInt32(rdr["day"], CultureInfo.InvariantCulture); minMaxCondition.DayOfYear = System.Convert.ToInt32(rdr["dayOfYear"], CultureInfo.InvariantCulture); minMaxCondition.Hour = System.Convert.ToInt32(rdr["hour"], CultureInfo.InvariantCulture); var minMaxGroup = minMaxGroups.FirstOrDefault(g => g.DayOfYear == minMaxCondition.DayOfYear && g.Hour == minMaxCondition.Hour); if (minMaxGroup is null) { minMaxGroup = new MinMaxGroup { Month = minMaxCondition.Month, Day = minMaxCondition.Day, DayOfYear = minMaxCondition.DayOfYear, Hour = minMaxCondition.Hour }; minMaxGroups.Add(minMaxGroup); } minMaxGroup.MinMaxConditions.Add(minMaxCondition); } } } } return minMaxGroups; } /// <inheritdoc/> public async Task<IEnumerable<MinMaxGroup>> GetMinMaxConditionsByDay(int startDayOfYear, int endDayOfYear, int offset, int limit) { _logger.LogDiagnosticDebug("GetYear: {@offset} {@limit}", offset, limit); var statement = "SELECT year, month, day" + " , CAST(strftime('%j', '2016-' || substr('00' || month, -2, 2) || '-' || substr('00' || day, -2, 2)) as INT) as dayOfYear" + DataFields + @" WHERE CAST(strftime('%j', '2016-' || substr('00' || month, -2, 2) || '-' || substr('00' || day, -2, 2)) as INT) <= @endDayOfYear AND CAST(strftime('%j', '2016-' || substr('00' || month, -2, 2) || '-' || substr('00' || day, -2, 2)) as INT) >= @startDayOfYear GROUP BY year, month, day ORDER BY month, day, year LIMIT @limit OFFSET @offset ; "; _logger.LogDiagnosticDebug("statement:\n {statement}\n", statement); var minMaxGroups = new List<MinMaxGroup>(); var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = statement; using (dbCommand) { dbCommand.AddParamWithValue("@startDayOfYear", startDayOfYear); dbCommand.AddParamWithValue("@endDayOfYear", endDayOfYear); dbCommand.AddParamWithValue("@offset", offset); dbCommand.AddParamWithValue("@limit", 10000); // TODO temp to dump out some test data dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { while (await rdr.ReadAsync().ConfigureAwait(true)) { var minMaxCondition = ReadDataFields(rdr); minMaxCondition.Year = System.Convert.ToInt32(rdr["year"], CultureInfo.InvariantCulture); minMaxCondition.Month = System.Convert.ToInt32(rdr["month"], CultureInfo.InvariantCulture); minMaxCondition.Day = System.Convert.ToInt32(rdr["day"], CultureInfo.InvariantCulture); minMaxCondition.DayOfYear = System.Convert.ToInt32(rdr["dayOfYear"], CultureInfo.InvariantCulture); var minMaxGroup = minMaxGroups.FirstOrDefault(g => g.Month == minMaxCondition.Month && g.Day == minMaxCondition.Day); if (minMaxGroup is null) { minMaxGroup = new MinMaxGroup { Month = minMaxCondition.Month, Day = minMaxCondition.Day, DayOfYear = minMaxCondition.DayOfYear }; minMaxGroups.Add(minMaxGroup); } minMaxGroup.MinMaxConditions.Add(minMaxCondition); } } } } return minMaxGroups; } /// <inheritdoc/> public async Task<IEnumerable<MinMaxGroup>> GetMinMaxConditionsByWeek(int startWeekOfYear, int endWeekOfYear, int offset, int limit) { _logger.LogDiagnosticDebug("GetYear: {@offset} {@limit}", offset, limit); var statement = "SELECT year, week" + DataFields + @" WHERE week <= @endWeekOfYear AND week >= @startWeekOfYear GROUP BY year, week ORDER BY week, year LIMIT @limit OFFSET @offset ; "; _logger.LogDiagnosticDebug("statement:\n {statement}\n", statement); var minMaxGroups = new List<MinMaxGroup>(); var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = statement; using (dbCommand) { dbCommand.AddParamWithValue("@startWeekOfYear", startWeekOfYear); dbCommand.AddParamWithValue("@endWeekOfYear", endWeekOfYear); dbCommand.AddParamWithValue("@offset", offset); dbCommand.AddParamWithValue("@limit", 10000); // TODO temp to dump out some test data dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { while (await rdr.ReadAsync().ConfigureAwait(true)) { var minMaxCondition = ReadDataFields(rdr); minMaxCondition.Year = System.Convert.ToInt32(rdr["year"], CultureInfo.InvariantCulture); minMaxCondition.Week = System.Convert.ToInt32(rdr["week"], CultureInfo.InvariantCulture); var minMaxGroup = minMaxGroups.FirstOrDefault(g => g.Week == minMaxCondition.Week); if (minMaxGroup is null) { minMaxGroup = new MinMaxGroup { Week = minMaxCondition.Week }; minMaxGroups.Add(minMaxGroup); } minMaxGroup.MinMaxConditions.Add(minMaxCondition); } } } } return minMaxGroups; } /// <inheritdoc/> public async Task<IEnumerable<Condition>> GetConditionsByDay(int offset, int limit, TimePeriodModel timePeriodModel) { _logger.LogDiagnosticDebug("GetConditionsByDay: {@offset} {@limit} {@timePeriod}", offset, limit, timePeriodModel); if (timePeriodModel == null) { throw new ArgumentNullException(nameof(timePeriodModel)); } var statement = GroupSelect + @" GROUP BY year, month, day ) as c2 ON c1.windGust = c2.windGustMax AND c1.year = c2.year AND c1.month = c2.month AND c1.day = c2.day WHERE dateTime>=@startDateTime AND dateTime<=@endDateTime GROUP BY c1.year, c1.month, c1.day LIMIT @limit OFFSET @offset ;"; _logger.LogDiagnosticDebug("statement:\n {statement}\n", statement); var conditions = new List<Condition>(); var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = statement; using (dbCommand) { dbCommand.AddParamWithValue("@startDateTime", timePeriodModel.StartDateTime); dbCommand.AddParamWithValue("@endDateTime", timePeriodModel.EndDateTime); dbCommand.AddParamWithValue("@offset", offset); dbCommand.AddParamWithValue("@limit", 10000); // TODO temp to dump out some test data dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { while (await rdr.ReadAsync().ConfigureAwait(true)) { conditions.Add(this.ReadGroupedCondition(rdr)); } } } } return conditions; } /// <inheritdoc/> public async Task<int> GetYearCount() { _logger.LogDiagnosticDebug("GetYearCount"); var statement = @" SELECT COUNT(DISTINCT year) as yearCount FROM v_condition ; "; int yearCount = 0; var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = statement; using (dbCommand) { dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { if (await rdr.ReadAsync().ConfigureAwait(true)) { yearCount = System.Convert.ToInt32(rdr["yearCount"], CultureInfo.InvariantCulture); } } } return yearCount; } } /// <inheritdoc/> public async Task<int> GetDayCount() { _logger.LogDiagnosticDebug("GetDayCount"); // TODO - Find a faster way var statement = @" SELECT COUNT(DISTINCT CAST(year as TEXT) || CAST(month as TEXT) || CAST(day as TEXT)) as dataCount FROM condition ; "; return await GetDataCount(statement).ConfigureAwait(true); } private async Task<int> GetDataCount(string statement) { int dataCount = 0; var dbConnection = _conditionDbProviderFactory.CreateConnection(); dbConnection.ConnectionString = _connectionString; using (dbConnection) { var dbCommand = dbConnection.CreateCommand(); #pragma warning disable CA2100 // Trusting that calling procedures are correct... dbCommand.CommandText = statement; #pragma warning restore CA2100 using (dbCommand) { dbConnection.Open(); using (var rdr = dbCommand.ExecuteReader()) { if (await rdr.ReadAsync().ConfigureAwait(true)) { dataCount = System.Convert.ToInt32(rdr["dataCount"], CultureInfo.InvariantCulture); } } } return dataCount; } } private Condition ReadGroupedCondition(DbDataReader rdr) { return new Condition { Year = System.Convert.ToInt32(rdr["year"], CultureInfo.InvariantCulture), Month = System.Convert.ToInt32(rdr["month"], CultureInfo.InvariantCulture), Day = System.Convert.ToInt32(rdr["day"], CultureInfo.InvariantCulture), WindGustDirection = rdr.GetValue<double>("windGustDir"), WindGust = rdr.GetValue<double>("windGust"), WindDirection = rdr.GetValue<double>("windDir"), WindSpeed = rdr.GetValue<double>("windSpeed"), OutsideTemperature = rdr.GetValue<double>("outTemp"), HeatIndex = rdr.GetValue<double>("heatindex"), Windchill = rdr.GetValue<double>("windchill"), Barometer = rdr.GetValue<double>("barometer"), DewPoint = rdr.GetValue<double>("dewpoint"), Rain = rdr.GetValue<double>("rain"), RainRate = rdr.GetValue<double>("rainRate"), OutsideHumidity = rdr.GetValue<double>("outHumidity"), }; } private MinMaxCondition ReadDataFields(DbDataReader rdr) { var minMaxcondition = new MinMaxCondition { MaxTemp = rdr.GetStringValue("maxTemp"), MinTemp = rdr.GetStringValue("minTemp"), MaxHumidity = rdr.GetStringValue("maxHumidity"), MinHumidity = rdr.GetStringValue("minHumidity"), MaxDewpoint = rdr.GetStringValue("maxDewpoint"), MinDewpoint = rdr.GetStringValue("minDewpoint"), MaxHeatIndex = rdr.GetStringValue("maxHeatIndex"), MinWindchill = rdr.GetStringValue("minWindchill"), MaxBarometer = rdr.GetStringValue("maxBarometer"), MinBarometer = rdr.GetStringValue("minBarometer"), MaxET = rdr.GetStringValue("maxET"), MinET = rdr.GetStringValue("minET"), MaxUV = rdr.GetStringValue("maxUV"), MinUV = rdr.GetStringValue("minUV"), MaxRadiation = rdr.GetStringValue("maxRadiation"), MinRadiation = rdr.GetStringValue("minRadiation"), MaxRainRate = rdr.GetStringValue("maxRainRate"), RainTotal = rdr.GetStringValue("rainTotal"), MaxWindGust = rdr.GetStringValue("maxWindGust"), AvgWindSpeed = rdr.GetStringValue("avgWindSpeed"), }; return minMaxcondition; } } }
using System; using System.Collections; namespace WiremockUI { public enum DiffEngineLevel { FastImperfect, Medium, SlowPerfect } public class DiffEngine { private IDiffList _source; private IDiffList _dest; private ArrayList _matchList; private DiffEngineLevel _level; private DiffStateList _stateList; public DiffEngine() { _source = null; _dest = null; _matchList = null; _stateList = null; _level = DiffEngineLevel.FastImperfect; } private int GetSourceMatchLength(int destIndex, int sourceIndex, int maxLength) { int matchCount; for (matchCount = 0; matchCount < maxLength; matchCount++) { if ( _dest.GetByIndex(destIndex + matchCount).CompareTo(_source.GetByIndex(sourceIndex + matchCount)) != 0 ) { break; } } return matchCount; } private void GetLongestSourceMatch(DiffState curItem, int destIndex,int destEnd, int sourceStart,int sourceEnd) { int maxDestLength = (destEnd - destIndex) + 1; int curLength = 0; int curBestLength = 0; int curBestIndex = -1; int maxLength = 0; for (int sourceIndex = sourceStart; sourceIndex <= sourceEnd; sourceIndex++) { maxLength = Math.Min(maxDestLength,(sourceEnd - sourceIndex) + 1); if (maxLength <= curBestLength) { //No chance to find a longer one any more break; } curLength = GetSourceMatchLength(destIndex,sourceIndex,maxLength); if (curLength > curBestLength) { //This is the best match so far curBestIndex = sourceIndex; curBestLength = curLength; } //jump over the match sourceIndex += curBestLength; } //DiffState cur = _stateList.GetByIndex(destIndex); if (curBestIndex == -1) { curItem.SetNoMatch(); } else { curItem.SetMatch(curBestIndex, curBestLength); } } private void ProcessRange(int destStart, int destEnd, int sourceStart, int sourceEnd) { int curBestIndex = -1; int curBestLength = -1; int maxPossibleDestLength = 0; DiffState curItem = null; DiffState bestItem = null; for (int destIndex = destStart; destIndex <= destEnd; destIndex++) { maxPossibleDestLength = (destEnd - destIndex) + 1; if (maxPossibleDestLength <= curBestLength) { //we won't find a longer one even if we looked break; } curItem = _stateList.GetByIndex(destIndex); if (!curItem.HasValidLength(sourceStart, sourceEnd, maxPossibleDestLength)) { //recalc new best length since it isn't valid or has never been done. GetLongestSourceMatch(curItem, destIndex, destEnd, sourceStart, sourceEnd); } if (curItem.Status == DiffStatus.Matched) { switch (_level) { case DiffEngineLevel.FastImperfect: if (curItem.Length > curBestLength) { //this is longest match so far curBestIndex = destIndex; curBestLength = curItem.Length; bestItem = curItem; } //Jump over the match destIndex += curItem.Length - 1; break; case DiffEngineLevel.Medium: if (curItem.Length > curBestLength) { //this is longest match so far curBestIndex = destIndex; curBestLength = curItem.Length; bestItem = curItem; //Jump over the match destIndex += curItem.Length - 1; } break; default: if (curItem.Length > curBestLength) { //this is longest match so far curBestIndex = destIndex; curBestLength = curItem.Length; bestItem = curItem; } break; } } } if (curBestIndex < 0) { //we are done - there are no matches in this span } else { int sourceIndex = bestItem.StartIndex; _matchList.Add(DiffResultSpan.CreateNoChange(curBestIndex,sourceIndex,curBestLength)); if (destStart < curBestIndex) { //Still have more lower destination data if (sourceStart < sourceIndex) { //Still have more lower source data // Recursive call to process lower indexes ProcessRange(destStart, curBestIndex -1,sourceStart, sourceIndex -1); } } int upperDestStart = curBestIndex + curBestLength; int upperSourceStart = sourceIndex + curBestLength; if (destEnd > upperDestStart) { //we still have more upper dest data if (sourceEnd > upperSourceStart) { //set still have more upper source data // Recursive call to process upper indexes ProcessRange(upperDestStart,destEnd,upperSourceStart,sourceEnd); } } } } public double ProcessDiff(IDiffList source, IDiffList destination,DiffEngineLevel level) { _level = level; return ProcessDiff(source,destination); } public double ProcessDiff(IDiffList source, IDiffList destination) { DateTime dt = DateTime.Now; _source = source; _dest = destination; _matchList = new ArrayList(); int dcount = _dest.Count(); int scount = _source.Count(); if ((dcount > 0)&&(scount > 0)) { _stateList = new DiffStateList(dcount); ProcessRange(0,dcount - 1,0, scount - 1); } TimeSpan ts = DateTime.Now - dt; return ts.TotalSeconds; } private bool AddChanges( ArrayList report, int curDest, int nextDest, int curSource, int nextSource) { bool retval = false; int diffDest = nextDest - curDest; int diffSource = nextSource - curSource; int minDiff = 0; if (diffDest > 0) { if (diffSource > 0) { minDiff = Math.Min(diffDest,diffSource); report.Add(DiffResultSpan.CreateReplace(curDest,curSource,minDiff)); if (diffDest > diffSource) { curDest+=minDiff; report.Add(DiffResultSpan.CreateAddDestination(curDest,diffDest - diffSource)); } else { if (diffSource > diffDest) { curSource+= minDiff; report.Add(DiffResultSpan.CreateDeleteSource(curSource,diffSource - diffDest)); } } } else { report.Add(DiffResultSpan.CreateAddDestination(curDest,diffDest)); } retval = true; } else { if (diffSource > 0) { report.Add(DiffResultSpan.CreateDeleteSource(curSource,diffSource)); retval = true; } } return retval; } public ArrayList DiffReport() { ArrayList retval = new ArrayList(); int dcount = _dest.Count(); int scount = _source.Count(); //Deal with the special case of empty files if (dcount == 0) { if (scount > 0) { retval.Add(DiffResultSpan.CreateDeleteSource(0,scount)); } return retval; } else { if (scount == 0) { retval.Add(DiffResultSpan.CreateAddDestination(0,dcount)); return retval; } } _matchList.Sort(); int curDest = 0; int curSource = 0; DiffResultSpan last = null; //Process each match record foreach (DiffResultSpan drs in _matchList) { if ((!AddChanges(retval,curDest,drs.DestIndex,curSource,drs.SourceIndex))&& (last != null)) { last.AddLength(drs.Length); } else { retval.Add(drs); } curDest = drs.DestIndex + drs.Length; curSource = drs.SourceIndex + drs.Length; last = drs; } //Process any tail end data AddChanges(retval,curDest,dcount,curSource,scount); return retval; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId { public abstract class SymbolKeyTestBase : CSharpTestBase { [Flags] internal enum SymbolKeyComparison { None = 0x0, IgnoreCase = 0x1, IgnoreAssemblyIds = 0x2 } [Flags] internal enum SymbolCategory { All = 0, DeclaredNamespace = 2, DeclaredType = 4, NonTypeMember = 8, Parameter = 16, } #region "Verification" internal static void ResolveAndVerifySymbolList(IEnumerable<ISymbol> newSymbols, IEnumerable<ISymbol> originalSymbols, CSharpCompilation originalComp) { var newlist = newSymbols.OrderBy(s => s.Name).ToList(); var origlist = originalSymbols.OrderBy(s => s.Name).ToList(); Assert.Equal(origlist.Count, newlist.Count); for (int i = 0; i < newlist.Count; i++) { ResolveAndVerifySymbol(newlist[i], origlist[i], originalComp); } } internal static void ResolveAndVerifyTypeSymbol(ExpressionSyntax node, ITypeSymbol sourceSymbol, SemanticModel model, CSharpCompilation sourceComp) { var typeinfo = model.GetTypeInfo(node); ResolveAndVerifySymbol(typeinfo.Type ?? typeinfo.ConvertedType, sourceSymbol, sourceComp); } internal static void ResolveAndVerifySymbol(ExpressionSyntax node, ISymbol sourceSymbol, SemanticModel model, CSharpCompilation sourceComp, SymbolKeyComparison comparison = SymbolKeyComparison.None) { var syminfo = model.GetSymbolInfo(node); ResolveAndVerifySymbol(syminfo.Symbol, sourceSymbol, sourceComp, comparison); } internal static void ResolveAndVerifySymbol(ISymbol symbol1, ISymbol symbol2, Compilation compilation2, SymbolKeyComparison comparison = SymbolKeyComparison.None) { // same ID AssertSymbolKeysEqual(symbol1, symbol2, comparison); var resolvedSymbol = ResolveSymbol(symbol1, compilation2, comparison); Assert.NotNull(resolvedSymbol); // same Symbol Assert.Equal(symbol2, resolvedSymbol); Assert.Equal(symbol2.GetHashCode(), resolvedSymbol.GetHashCode()); } internal static ISymbol ResolveSymbol(ISymbol originalSymbol, Compilation targetCompilation, SymbolKeyComparison comparison) { var sid = SymbolKey.Create(originalSymbol, CancellationToken.None); // Verify that serialization works. var serialized = sid.ToString(); var deserialized = new SymbolKey(serialized); var comparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false); Assert.True(comparer.Equals(sid, deserialized)); var symInfo = sid.Resolve(targetCompilation, (comparison & SymbolKeyComparison.IgnoreAssemblyIds) == SymbolKeyComparison.IgnoreAssemblyIds); return symInfo.Symbol; } internal static void AssertSymbolKeysEqual(ISymbol symbol1, ISymbol symbol2, SymbolKeyComparison comparison, bool expectEqual = true) { var sid1 = SymbolKey.Create(symbol1, CancellationToken.None); var sid2 = SymbolKey.Create(symbol2, CancellationToken.None); // default is Insensitive var ignoreCase = (comparison & SymbolKeyComparison.IgnoreCase) == SymbolKeyComparison.IgnoreCase; // default is NOT ignore var ignoreAssemblyIds = (comparison & SymbolKeyComparison.IgnoreAssemblyIds) == SymbolKeyComparison.IgnoreAssemblyIds; var message = string.Concat( ignoreCase ? "SymbolID IgnoreCase" : "SymbolID", ignoreAssemblyIds ? " IgnoreAssemblyIds " : " ", "Compare"); var ret = CodeAnalysis.SymbolKey.GetComparer(ignoreCase, ignoreAssemblyIds).Equals(sid2, sid1); if (expectEqual) { Assert.True(ret, message); } else { Assert.False(ret, message); } } #endregion #region "Utilities" internal static List<BlockSyntax> GetBlockSyntaxList(MethodSymbol symbol) { var list = new List<BlockSyntax>(); foreach (var node in symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax())) { BlockSyntax body = null; if (node is BaseMethodDeclarationSyntax baseMethod) { body = baseMethod.Body; } else if (node is AccessorDeclarationSyntax accessor) { body = accessor.Body; } if (body != null || body.Statements.Any()) { list.Add(body); } } return list; } internal static IEnumerable<ISymbol> GetSourceSymbols(Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation, SymbolCategory category) { // NYI for local symbols var list = GetSourceSymbols(compilation, includeLocal: false); List<SymbolKind> kinds = new List<SymbolKind>(); if ((category & SymbolCategory.DeclaredNamespace) != 0) { kinds.Add(SymbolKind.Namespace); } if ((category & SymbolCategory.DeclaredType) != 0) { kinds.Add(SymbolKind.NamedType); kinds.Add(SymbolKind.TypeParameter); } if ((category & SymbolCategory.NonTypeMember) != 0) { kinds.Add(SymbolKind.Field); kinds.Add(SymbolKind.Event); kinds.Add(SymbolKind.Property); kinds.Add(SymbolKind.Method); } if ((category & SymbolCategory.Parameter) != 0) { kinds.Add(SymbolKind.Parameter); } return list.Where(s => { if (s.IsImplicitlyDeclared) { return false; } foreach (var k in kinds) { if (s.Kind == k) { return true; } } return false; }); } internal static IList<ISymbol> GetSourceSymbols(CSharpCompilation compilation, bool includeLocal) { var list = new List<ISymbol>(); LocalSymbolDumper localDumper = includeLocal ? new LocalSymbolDumper(compilation) : null; GetSourceMemberSymbols(compilation.SourceModule.GlobalNamespace, list, localDumper); // ?? // if (includeLocal) GetSourceAliasSymbols(compilation, list); list.Add(compilation.Assembly); list.AddRange(compilation.Assembly.Modules); return list; } #endregion #region "Private Helpers" private static void GetSourceMemberSymbols(NamespaceOrTypeSymbol symbol, List<ISymbol> list, LocalSymbolDumper localDumper) { foreach (var memberSymbol in symbol.GetMembers()) { list.Add(memberSymbol); switch (memberSymbol.Kind) { case SymbolKind.NamedType: case SymbolKind.Namespace: GetSourceMemberSymbols((NamespaceOrTypeSymbol)memberSymbol, list, localDumper); break; case SymbolKind.Method: var method = (MethodSymbol)memberSymbol; foreach (var parameter in method.Parameters) { list.Add(parameter); } if (localDumper != null) { localDumper.GetLocalSymbols(method, list); } break; case SymbolKind.Field: if (localDumper != null) { localDumper.GetLocalSymbols((FieldSymbol)memberSymbol, list); } break; } } } private static void GetSourceAliasSymbols(CSharpCompilation comp, List<ISymbol> list) { foreach (var tree in comp.SyntaxTrees) { var usingNodes = tree.GetRoot().DescendantNodes().OfType<UsingDirectiveSyntax>(); var model = comp.GetSemanticModel(tree); foreach (var u in usingNodes) { if (u.Alias != null) { // var sym = model.GetSymbolInfo(u.Alias.Identifier).Symbol; var sym = model.GetDeclaredSymbol(u); if (sym != null && !list.Contains(sym)) { list.Add(sym); } } } } } #endregion private class LocalSymbolDumper { private CSharpCompilation _compilation; public LocalSymbolDumper(CSharpCompilation compilation) { _compilation = compilation; } public void GetLocalSymbols(FieldSymbol symbol, List<ISymbol> list) { foreach (var node in symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax())) { var declarator = node as VariableDeclaratorSyntax; if (declarator != null && declarator.Initializer != null) { var model = _compilation.GetSemanticModel(declarator.SyntaxTree); // Expression var df = model.AnalyzeDataFlow(declarator.Initializer.Value); GetLocalAndType(df, list); GetAnonymousExprSymbols(declarator.Initializer.Value, model, list); } } } public void GetLocalSymbols(MethodSymbol symbol, List<ISymbol> list) { foreach (var node in symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax())) { BlockSyntax body = null; if (node is BaseMethodDeclarationSyntax baseMethod) { body = baseMethod.Body; } else if (node is AccessorDeclarationSyntax accessor) { body = accessor.Body; } var model = _compilation.GetSemanticModel(node.SyntaxTree); if (body != null && body.Statements.Any()) { var df = model.AnalyzeDataFlow(body); GetLocalAndType(df, list); GetAnonymousTypeOrFuncSymbols(body, model, list); GetLabelSymbols(body, model, list); } // C# specific (this|base access) var ctor = node as ConstructorDeclarationSyntax; if (ctor != null && ctor.Initializer != null) { foreach (var a in ctor.Initializer.ArgumentList.Arguments) { var df = model.AnalyzeDataFlow(a.Expression); // VisitLocals(arg, df); list.AddRange(df.VariablesDeclared.OfType<Symbol>()); GetAnonymousExprSymbols(a.Expression, model, list); } } } } private void GetLocalAndType(DataFlowAnalysis df, List<ISymbol> list) { foreach (var v in df.VariablesDeclared) { list.Add((Symbol)v); var local = v as LocalSymbol; if (local != null && (local.Type.Kind == SymbolKind.ArrayType || local.Type.Kind == SymbolKind.PointerType)) { list.Add(local.Type); } } } private void GetLabelSymbols(BlockSyntax body, SemanticModel model, List<ISymbol> list) { var labels = body.DescendantNodes().OfType<LabeledStatementSyntax>(); foreach (var n in labels) { // Label: -> 'Label' is token var sym = model.GetDeclaredSymbol(n); list.Add(sym); } var swlabels = body.DescendantNodes().OfType<SwitchLabelSyntax>(); foreach (var n in swlabels) { // label value has NO symbol, Type is expr's type // e.g. case "A": -> string type // var info1 = model.GetTypeInfo(n.Value); // var info2 = model.GetSymbolInfo(n.Value); var sym = model.GetDeclaredSymbol(n); list.Add(sym); } } private void GetAnonymousTypeOrFuncSymbols(BlockSyntax body, SemanticModel model, List<ISymbol> list) { IEnumerable<ExpressionSyntax> exprs = body.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>(); IEnumerable<ExpressionSyntax> tmp = body.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>(); exprs = exprs.Concat(tmp); tmp = body.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>(); exprs = exprs.Concat(tmp); tmp = body.DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>(); exprs = exprs.Concat(tmp); foreach (var expr in exprs) { GetAnonymousExprSymbols(expr, model, list); } } private void GetAnonymousExprSymbols(ExpressionSyntax expr, SemanticModel model, List<ISymbol> list) { var kind = expr.Kind(); if (kind != SyntaxKind.AnonymousObjectCreationExpression && kind != SyntaxKind.AnonymousMethodExpression && kind != SyntaxKind.ParenthesizedLambdaExpression && kind != SyntaxKind.SimpleLambdaExpression) { return; } var tinfo = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); if (conv.IsAnonymousFunction) { // Lambda has no Type unless in part of case expr (C# specific) // var f = (Func<int>)(() => { return 1; }); Type is delegate // method symbol var sinfo = model.GetSymbolInfo(expr); list.Add((Symbol)sinfo.Symbol); } else if (tinfo.Type != null && tinfo.Type.TypeKind != TypeKind.Delegate) { // bug#12625 // GetSymbolInfo -> .ctor (part of members) list.Add((Symbol)tinfo.Type); // NamedType with empty name foreach (var m in tinfo.Type.GetMembers()) { list.Add((Symbol)m); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return IsProcessRunning(processId, GetProcessIds()); } /// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId, string machineName) { return IsProcessRunning(processId, GetProcessIds(machineName)); } /// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns> public static ProcessInfo GetProcessInfo(int processId, string machineName) { ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); foreach (ProcessInfo processInfo in processInfos) { if (processInfo.ProcessId == processId) { return processInfo; } } return null; } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessInfos(machineName, true) : NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine } /// <summary>Gets the IDs of all processes on the specified machine.</summary> /// <param name="machineName">The machine to examine.</param> /// <returns>An array of process IDs from the specified machine.</returns> public static int[] GetProcessIds(string machineName) { // Due to the lack of support for EnumModules() on coresysserver, we rely // on PerformanceCounters to get the ProcessIds for both remote desktop // and the local machine, unlike Desktop on which we rely on PCs only for // remote machines. return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessIds(machineName, true) : GetProcessIds(); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return NtProcessManager.GetProcessIds(); } /// <summary>Gets the ID of a process from a handle to the process.</summary> /// <param name="processHandle">The handle.</param> /// <returns>The process ID.</returns> public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return NtProcessManager.GetProcessIdFromHandle(processHandle); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> public static ModuleInfo[] GetModuleInfos(int processId) { return NtProcessManager.GetModuleInfos(processId); } /// <summary>Gets whether the named machine is remote or local.</summary> /// <param name="machineName">The machine name.</param> /// <returns>true if the machine is remote; false if it's local.</returns> public static bool IsRemoteMachine(string machineName) { if (machineName == null) throw new ArgumentNullException("machineName"); if (machineName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName)); string baseName; if (machineName.StartsWith("\\", StringComparison.Ordinal)) baseName = machineName.Substring(2); else baseName = machineName; if (baseName.Equals(".")) return false; if (String.Compare(Interop.mincore.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase) == 0) return false; return true; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- static ProcessManager() { // In order to query information (OpenProcess) on some protected processes // like csrss, we need SeDebugPrivilege privilege. // After removing the dependency on Performance Counter, we don't have a chance // to run the code in CLR performance counter to ask for this privilege. // So we will try to get the privilege here. // We could fail if the user account doesn't have right to do this, but that's fair. Interop.mincore.LUID luid = new Interop.mincore.LUID(); if (!Interop.mincore.LookupPrivilegeValue(null, Interop.mincore.SeDebugPrivilege, out luid)) { return; } SafeTokenHandle tokenHandle = null; try { if (!Interop.mincore.OpenProcessToken( Interop.mincore.GetCurrentProcess(), Interop.mincore.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { return; } Interop.mincore.TokenPrivileges tp = new Interop.mincore.TokenPrivileges(); tp.Luid = luid; tp.Attributes = Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED; // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned). Interop.mincore.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } private static bool IsProcessRunning(int processId, int[] processIds) { return Array.IndexOf(processIds, processId) >= 0; } public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) { SafeProcessHandle processHandle = Interop.mincore.OpenProcess(access, false, processId); int result = Marshal.GetLastWin32Error(); if (!processHandle.IsInvalid) { return processHandle; } if (processId == 0) { throw new Win32Exception(5); } // If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true. if (!IsProcessRunning(processId)) { if (throwIfExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture))); } else { return SafeProcessHandle.InvalidHandle; } } throw new Win32Exception(result); } public static SafeThreadHandle OpenThread(int threadId, int access) { SafeThreadHandle threadHandle = Interop.mincore.OpenThread(access, false, threadId); int result = Marshal.GetLastWin32Error(); if (threadHandle.IsInvalid) { if (result == Interop.mincore.Errors.ERROR_INVALID_PARAMETER) throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture))); throw new Win32Exception(result); } return threadHandle; } } /// <devdoc> /// This static class provides the process api for the WinNt platform. /// We use the performance counter api to query process and thread /// information. Module information is obtained using PSAPI. /// </devdoc> /// <internalonly/> internal static class NtProcessManager { private const int ProcessPerfCounterId = 230; private const int ThreadPerfCounterId = 232; private const string PerfCounterQueryString = "230 232"; internal const int IdleProcessID = 0; private static Dictionary<String, ValueId> s_valueIds; static NtProcessManager() { s_valueIds = new Dictionary<String, ValueId>(); s_valueIds.Add("Pool Paged Bytes", ValueId.PoolPagedBytes); s_valueIds.Add("Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes); s_valueIds.Add("Elapsed Time", ValueId.ElapsedTime); s_valueIds.Add("Virtual Bytes Peak", ValueId.VirtualBytesPeak); s_valueIds.Add("Virtual Bytes", ValueId.VirtualBytes); s_valueIds.Add("Private Bytes", ValueId.PrivateBytes); s_valueIds.Add("Page File Bytes", ValueId.PageFileBytes); s_valueIds.Add("Page File Bytes Peak", ValueId.PageFileBytesPeak); s_valueIds.Add("Working Set Peak", ValueId.WorkingSetPeak); s_valueIds.Add("Working Set", ValueId.WorkingSet); s_valueIds.Add("ID Thread", ValueId.ThreadId); s_valueIds.Add("ID Process", ValueId.ProcessId); s_valueIds.Add("Priority Base", ValueId.BasePriority); s_valueIds.Add("Priority Current", ValueId.CurrentPriority); s_valueIds.Add("% User Time", ValueId.UserTime); s_valueIds.Add("% Privileged Time", ValueId.PrivilegedTime); s_valueIds.Add("Start Address", ValueId.StartAddress); s_valueIds.Add("Thread State", ValueId.ThreadState); s_valueIds.Add("Thread Wait Reason", ValueId.ThreadWaitReason); } internal static int SystemProcessID { get { const int systemProcessIDOnXP = 4; return systemProcessIDOnXP; } } public static int[] GetProcessIds(string machineName, bool isRemoteMachine) { ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine); int[] ids = new int[infos.Length]; for (int i = 0; i < infos.Length; i++) ids[i] = infos[i].ProcessId; return ids; } public static int[] GetProcessIds() { int[] processIds = new int[256]; int size; for (; ; ) { if (!Interop.mincore.EnumProcesses(processIds, processIds.Length * 4, out size)) throw new Win32Exception(); if (size == processIds.Length * 4) { processIds = new int[processIds.Length * 2]; continue; } break; } int[] ids = new int[size / 4]; Array.Copy(processIds, 0, ids, 0, ids.Length); return ids; } public static ModuleInfo[] GetModuleInfos(int processId) { return GetModuleInfos(processId, false); } public static ModuleInfo GetFirstModuleInfo(int processId) { ModuleInfo[] moduleInfos = GetModuleInfos(processId, true); if (moduleInfos.Length == 0) { return null; } else { return moduleInfos[0]; } } private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.mincore.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.mincore.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (; ; ) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.mincore.GetCurrentProcessId()), Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.mincore.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.mincore.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.mincore.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } List<ModuleInfo> moduleInfos = new List<ModuleInfo>(firstModuleOnly ? 1 : moduleCount); StringBuilder baseName = new StringBuilder(1024); StringBuilder fileName = new StringBuilder(1024); for (int i = 0; i < moduleCount; i++) { if (i > 0) { // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. if (firstModuleOnly) { break; } baseName.Clear(); fileName.Clear(); } IntPtr moduleHandle = moduleHandles[i]; Interop.mincore.NtModuleInfo ntModuleInfo = new Interop.mincore.NtModuleInfo(); if (!Interop.mincore.GetModuleInformation(processHandle, moduleHandle, ntModuleInfo, Marshal.SizeOf(ntModuleInfo))) { HandleError(); continue; } ModuleInfo moduleInfo = new ModuleInfo { _sizeOfImage = ntModuleInfo.SizeOfImage, _entryPoint = ntModuleInfo.EntryPoint, _baseOfDll = ntModuleInfo.BaseOfDll }; int ret = Interop.mincore.GetModuleBaseName(processHandle, moduleHandle, baseName, baseName.Capacity); if (ret == 0) { HandleError(); continue; } moduleInfo._baseName = baseName.ToString(); ret = Interop.mincore.GetModuleFileNameEx(processHandle, moduleHandle, fileName, fileName.Capacity); if (ret == 0) { HandleError(); continue; } moduleInfo._fileName = fileName.ToString(); if (moduleInfo._fileName != null && moduleInfo._fileName.Length >= 4 && moduleInfo._fileName.StartsWith(@"\\?\", StringComparison.Ordinal)) { moduleInfo._fileName = fileName.ToString(4, fileName.Length - 4); } moduleInfos.Add(moduleInfo); } return moduleInfos.ToArray(); } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } } private static void HandleError() { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case Interop.mincore.Errors.ERROR_INVALID_HANDLE: case Interop.mincore.Errors.ERROR_PARTIAL_COPY: // It's possible that another thread casued this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. break; default: throw new Win32Exception(lastError); } } public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { Interop.NtDll.NtProcessBasicInfo info = new Interop.NtDll.NtProcessBasicInfo(); int status = Interop.NtDll.NtQueryInformationProcess(processHandle, Interop.NtDll.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null); if (status != 0) { throw new InvalidOperationException(SR.CantGetProcessId, new Win32Exception(status)); } // We should change the signature of this function and ID property in process class. return info.UniqueProcessId.ToInt32(); } public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine) { PerformanceCounterLib library = null; try { library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en")); return GetProcessInfos(library); } catch (Exception e) { if (isRemoteMachine) { throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e); } else { throw e; } } // We don't want to call library.Close() here because that would cause us to unload all of the perflibs. // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW! } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) { ProcessInfo[] processInfos; int retryCount = 5; do { try { byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString); processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr); } catch (Exception e) { throw new InvalidOperationException(SR.CouldntGetProcessInfos, e); } --retryCount; } while (processInfos.Length == 0 && retryCount != 0); if (processInfos.Length == 0) throw new InvalidOperationException(SR.ProcessDisabled); return processInfos; } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()"); #endif Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(); List<ThreadInfo> threadInfos = new List<ThreadInfo>(); GCHandle dataHandle = new GCHandle(); try { dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject(); Interop.mincore.PERF_DATA_BLOCK dataBlock = new Interop.mincore.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataBlockPtr, dataBlock); IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength); Interop.mincore.PERF_INSTANCE_DEFINITION instance = new Interop.mincore.PERF_INSTANCE_DEFINITION(); Interop.mincore.PERF_COUNTER_BLOCK counterBlock = new Interop.mincore.PERF_COUNTER_BLOCK(); for (int i = 0; i < dataBlock.NumObjectTypes; i++) { Interop.mincore.PERF_OBJECT_TYPE type = new Interop.mincore.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(typePtr, type); IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength); IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength); List<Interop.mincore.PERF_COUNTER_DEFINITION> counterList = new List<Interop.mincore.PERF_COUNTER_DEFINITION>(); for (int j = 0; j < type.NumCounters; j++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = new Interop.mincore.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(counterPtr, counter); string counterName = library.GetCounterName(counter.CounterNameTitleIndex); if (type.ObjectNameTitleIndex == processIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); else if (type.ObjectNameTitleIndex == threadIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); counterList.Add(counter); counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength); } Interop.mincore.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray(); for (int j = 0; j < type.NumInstances; j++) { Marshal.PtrToStructure(instancePtr, instance); IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset); string instanceName = Marshal.PtrToStringUni(namePtr); if (instanceName.Equals("_Total")) continue; IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength); Marshal.PtrToStructure(counterBlockPtr, counterBlock); if (type.ObjectNameTitleIndex == processIndex) { ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) { // Sometimes we'll get a process structure that is not completely filled in. // We can catch some of these by looking for non-"idle" processes that have id 0 // and ignoring those. #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring."); #endif } else { if (processInfos.ContainsKey(processInfo.ProcessId)) { // We've found two entries in the perfcounters that claim to be the // same process. We throw an exception. Is this really going to be // helpfull to the user? Should we just ignore? #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id"); #endif } else { // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe", // if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe" // at the end. If instanceName ends in ".", ".e", or ".ex" we remove it. string processName = instanceName; if (processName.Length == 15) { if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14); else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13); else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12); } processInfo.ProcessName = processName; processInfos.Add(processInfo.ProcessId, processInfo); } } } else if (type.ObjectNameTitleIndex == threadIndex) { ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (threadInfo._threadId != 0) threadInfos.Add(threadInfo); } instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength); } typePtr = (IntPtr)((long)typePtr + type.TotalByteLength); } } finally { if (dataHandle.IsAllocated) dataHandle.Free(); } for (int i = 0; i < threadInfos.Count; i++) { ThreadInfo threadInfo = (ThreadInfo)threadInfos[i]; ProcessInfo processInfo; if (processInfos.TryGetValue(threadInfo._processId, out processInfo)) { processInfo._threadInfoList.Add(threadInfo); } } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } static ThreadInfo GetThreadInfo(Interop.mincore.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.mincore.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (ulong)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; } internal static ThreadWaitReason GetThreadWaitReason(int value) { switch (value) { case 0: case 7: return ThreadWaitReason.Executive; case 1: case 8: return ThreadWaitReason.FreePage; case 2: case 9: return ThreadWaitReason.PageIn; case 3: case 10: return ThreadWaitReason.SystemAllocation; case 4: case 11: return ThreadWaitReason.ExecutionDelay; case 5: case 12: return ThreadWaitReason.Suspended; case 6: case 13: return ThreadWaitReason.UserRequest; case 14: return ThreadWaitReason.EventPairHigh; ; case 15: return ThreadWaitReason.EventPairLow; case 16: return ThreadWaitReason.LpcReceive; case 17: return ThreadWaitReason.LpcReply; case 18: return ThreadWaitReason.VirtualMemory; case 19: return ThreadWaitReason.PageOut; default: return ThreadWaitReason.Unknown; } } static ProcessInfo GetProcessInfo(Interop.mincore.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.mincore.PERF_COUNTER_DEFINITION[] counters) { ProcessInfo processInfo = new ProcessInfo(); for (int i = 0; i < counters.Length; i++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: processInfo.ProcessId = (int)value; break; case ValueId.PoolPagedBytes: processInfo.PoolPagedBytes = value; break; case ValueId.PoolNonpagedBytes: processInfo.PoolNonPagedBytes = value; break; case ValueId.VirtualBytes: processInfo.VirtualBytes = value; break; case ValueId.VirtualBytesPeak: processInfo.VirtualBytesPeak = value; break; case ValueId.WorkingSetPeak: processInfo.WorkingSetPeak = value; break; case ValueId.WorkingSet: processInfo.WorkingSet = value; break; case ValueId.PageFileBytesPeak: processInfo.PageFileBytesPeak = value; break; case ValueId.PageFileBytes: processInfo.PageFileBytes = value; break; case ValueId.PrivateBytes: processInfo.PrivateBytes = value; break; case ValueId.BasePriority: processInfo.BasePriority = (int)value; break; } } return processInfo; } static ValueId GetValueId(string counterName) { if (counterName != null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) return id; } return ValueId.Unknown; } static long ReadCounterValue(int counterType, IntPtr dataPtr) { if ((counterType & Interop.mincore.PerfCounterOptions.NtPerfCounterSizeLarge) != 0) return Marshal.ReadInt64(dataPtr); else return (long)Marshal.ReadInt32(dataPtr); } enum ValueId { Unknown = -1, PoolPagedBytes, PoolNonpagedBytes, ElapsedTime, VirtualBytesPeak, VirtualBytes, PrivateBytes, PageFileBytes, PageFileBytesPeak, WorkingSetPeak, WorkingSet, ThreadId, ProcessId, BasePriority, CurrentPriority, UserTime, PrivilegedTime, StartAddress, ThreadState, ThreadWaitReason } } internal static class NtProcessInfoHelper { private static int GetNewBufferSize(int existingBufferSize, int requiredSize) { if (requiredSize == 0) { // // On some old OS like win2000, requiredSize will not be set if the buffer // passed to NtQuerySystemInformation is not enough. // int newSize = existingBufferSize * 2; if (newSize < existingBufferSize) { // In reality, we should never overflow. // Adding the code here just in case it happens. throw new OutOfMemoryException(); } return newSize; } else { // allocating a few more kilo bytes just in case there are some new process // kicked in since new call to NtQuerySystemInformation int newSize = requiredSize + 1024 * 10; if (newSize < requiredSize) { throw new OutOfMemoryException(); } return newSize; } } public static ProcessInfo[] GetProcessInfos() { int requiredSize = 0; int status; ProcessInfo[] processInfos; GCHandle bufferHandle = new GCHandle(); // Start with the default buffer size. int bufferSize = DefaultCachedBufferSize; // Get the cached buffer. long[] buffer = Interlocked.Exchange(ref CachedBuffer, null); try { do { if (buffer == null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; } else { // If we have cached buffer, set the size properly. bufferSize = buffer.Length * sizeof(long); } bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); status = Interop.NtDll.NtQuerySystemInformation( Interop.NtDll.NtQuerySystemProcessInformation, bufferHandle.AddrOfPinnedObject(), bufferSize, out requiredSize); if ((uint)status == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH) { if (bufferHandle.IsAllocated) bufferHandle.Free(); buffer = null; bufferSize = GetNewBufferSize(bufferSize, requiredSize); } } while ((uint)status == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH); if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status)); } // Parse the data block to get process information processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject()); } finally { // Cache the final buffer for use on the next call. Interlocked.Exchange(ref CachedBuffer, buffer); if (bufferHandle.IsAllocated) bufferHandle.Free(); } return processInfos; } // Use a smaller buffer size on debug to ensure we hit the retry path. #if DEBUG private const int DefaultCachedBufferSize = 1024; #else private const int DefaultCachedBufferSize = 128 * 1024; #endif // Cache a single buffer for use in GetProcessInfos(). private static long[] CachedBuffer; static ProcessInfo[] GetProcessInfos(IntPtr dataPtr) { // 60 is a reasonable number for processes on a normal machine. Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60); long totalOffset = 0; while (true) { IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset); SystemProcessInformation pi = new SystemProcessInformation(); Marshal.PtrToStructure(currentPtr, pi); // get information for a process ProcessInfo processInfo = new ProcessInfo(); // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. processInfo.ProcessId = pi.UniqueProcessId.ToInt32(); processInfo.SessionId = (int)pi.SessionId; processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; ; processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage; processInfo.VirtualBytes = (long)pi.VirtualSize; processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize; processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize; processInfo.WorkingSet = (long)pi.WorkingSetSize; processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage; processInfo.PageFileBytes = (long)pi.PagefileUsage; processInfo.PrivateBytes = (long)pi.PrivatePageCount; processInfo.BasePriority = pi.BasePriority; if (pi.NamePtr == IntPtr.Zero) { if (processInfo.ProcessId == NtProcessManager.SystemProcessID) { processInfo.ProcessName = "System"; } else if (processInfo.ProcessId == NtProcessManager.IdleProcessID) { processInfo.ProcessName = "Idle"; } else { // for normal process without name, using the process ID. processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture); } } else { string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength / sizeof(char))); processInfo.ProcessName = processName; } // get the threads for current process processInfos[processInfo.ProcessId] = processInfo; currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi)); int i = 0; while (i < pi.NumberOfThreads) { SystemThreadInformation ti = new SystemThreadInformation(); Marshal.PtrToStructure(currentPtr, ti); ThreadInfo threadInfo = new ThreadInfo(); threadInfo._processId = (int)ti.UniqueProcess; threadInfo._threadId = (ulong)ti.UniqueThread; threadInfo._basePriority = ti.BasePriority; threadInfo._currentPriority = ti.Priority; threadInfo._startAddress = ti.StartAddress; threadInfo._threadState = (ThreadState)ti.ThreadState; threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason); processInfo._threadInfoList.Add(threadInfo); currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti)); i++; } if (pi.NextEntryOffset == 0) { break; } totalOffset += pi.NextEntryOffset; } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } // This function generates the short form of process name. // // This is from GetProcessShortName in NT code base. // Check base\screg\winreg\perfdlls\process\perfsprc.c for details. internal static string GetProcessShortName(String name) { if (String.IsNullOrEmpty(name)) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName"); #endif return String.Empty; } int slash = -1; int period = -1; for (int i = 0; i < name.Length; i++) { if (name[i] == '\\') slash = i; else if (name[i] == '.') period = i; } if (period == -1) period = name.Length - 1; // set to end of string else { // if a period was found, then see if the extension is // .EXE, if so drop it, if not, then use end of string // (i.e. include extension in name) String extension = name.Substring(period); if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase)) period--; // point to character before period else period = name.Length - 1; // set to end of string } if (slash == -1) slash = 0; // set to start of string else slash++; // point to character next to slash // copy characters between period (or end of string) and // slash (or start of string) to make image name return name.Substring(slash, period - slash + 1); } // native struct defined in ntexapi.h [StructLayout(LayoutKind.Sequential)] internal class SystemProcessInformation { internal uint NextEntryOffset; internal uint NumberOfThreads; private long _SpareLi1; private long _SpareLi2; private long _SpareLi3; private long _CreateTime; private long _UserTime; private long _KernelTime; internal ushort NameLength; // UNICODE_STRING internal ushort MaximumNameLength; internal IntPtr NamePtr; // This will point into the data block returned by NtQuerySystemInformation internal int BasePriority; internal IntPtr UniqueProcessId; internal IntPtr InheritedFromUniqueProcessId; internal uint HandleCount; internal uint SessionId; internal UIntPtr PageDirectoryBase; internal UIntPtr PeakVirtualSize; // SIZE_T internal UIntPtr VirtualSize; internal uint PageFaultCount; internal UIntPtr PeakWorkingSetSize; internal UIntPtr WorkingSetSize; internal UIntPtr QuotaPeakPagedPoolUsage; internal UIntPtr QuotaPagedPoolUsage; internal UIntPtr QuotaPeakNonPagedPoolUsage; internal UIntPtr QuotaNonPagedPoolUsage; internal UIntPtr PagefileUsage; internal UIntPtr PeakPagefileUsage; internal UIntPtr PrivatePageCount; private long _ReadOperationCount; private long _WriteOperationCount; private long _OtherOperationCount; private long _ReadTransferCount; private long _WriteTransferCount; private long _OtherTransferCount; } [StructLayout(LayoutKind.Sequential)] internal class SystemThreadInformation { private long _KernelTime; private long _UserTime; private long _CreateTime; private uint _WaitTime; internal IntPtr StartAddress; internal IntPtr UniqueProcess; internal IntPtr UniqueThread; internal int Priority; internal int BasePriority; internal uint ContextSwitches; internal uint ThreadState; internal uint WaitReason; } } }
// 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(IPreviewFactoryService)), Shared] internal class PreviewFactoryService : ForegroundThreadAffinitizedObject, IPreviewFactoryService { private const double DefaultZoomLevel = 0.75; private readonly ITextViewRoleSet _previewRoleSet; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly IDifferenceBufferFactoryService _differenceBufferService; private readonly IWpfDifferenceViewerFactoryService _differenceViewerService; [ImportingConstructor] public PreviewFactoryService( ITextBufferFactoryService textBufferFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, ITextEditorFactoryService textEditorFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextDifferencingSelectorService differenceSelectorService, IDifferenceBufferFactoryService differenceBufferService, IWpfDifferenceViewerFactoryService differenceViewerService) { _textBufferFactoryService = textBufferFactoryService; _contentTypeRegistryService = contentTypeRegistryService; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _differenceSelectorService = differenceSelectorService; _differenceBufferService = differenceBufferService; _differenceViewerService = differenceViewerService; _previewRoleSet = textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken) { return GetSolutionPreviews(oldSolution, newSolution, DefaultZoomLevel, cancellationToken); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: The order in which previews are added to the below list is significant. // Preview for a changed document is preferred over preview for changed references and so on. var previewItems = new List<SolutionPreviewItem>(); SolutionChangeSummary changeSummary = null; if (newSolution != null) { var solutionChanges = newSolution.GetChanges(oldSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { cancellationToken.ThrowIfCancellationRequested(); var projectId = projectChanges.ProjectId; var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; foreach (var documentId in projectChanges.GetChangedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, (c) => CreateChangedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, (c) => CreateAddedDocumentPreviewViewAsync(newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, (c) => CreateRemovedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetChangedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, (c) => CreateChangedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, (c) => CreateAddedAdditionalDocumentPreviewViewAsync(newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, (c) => CreateRemovedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var metadataReference in projectChanges.GetAddedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.AddingReferenceTo, metadataReference.Display, oldProject.Name)))); } foreach (var metadataReference in projectChanges.GetRemovedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.RemovingReferenceFrom, metadataReference.Display, oldProject.Name)))); } foreach (var projectReference in projectChanges.GetAddedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.AddingReferenceTo, newSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name)))); } foreach (var projectReference in projectChanges.GetRemovedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.RemovingReferenceFrom, oldSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name)))); } foreach (var analyzer in projectChanges.GetAddedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.AddingAnalyzerReferenceTo, analyzer.Display, oldProject.Name)))); } foreach (var analyzer in projectChanges.GetRemovedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.RemovingAnalyzerReferenceFrom, analyzer.Display, oldProject.Name)))); } } foreach (var project in solutionChanges.GetAddedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.AddingProject, project.Name)))); } foreach (var project in solutionChanges.GetRemovedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.RemovingProject, project.Name)))); } foreach (var projectChanges in solutionChanges.GetProjectChanges().Where(pc => pc.OldProject.AllProjectReferences != pc.NewProject.AllProjectReferences)) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(projectChanges.OldProject.Id, null, (c) => Task.FromResult<object>(string.Format(EditorFeaturesResources.ChangingProjectReferencesFor, projectChanges.OldProject.Name)))); } changeSummary = new SolutionChangeSummary(oldSolution, newSolution, solutionChanges); } return new SolutionPreviewResult(previewItems, changeSummary); } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateAddedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateAddedDocumentPreviewViewCoreAsync(ITextBuffer newBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.AddingToWithContent, document.Name, document.Project.Name); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); var span = new SnapshotSpan(newBuffer.CurrentSnapshot, Span.FromBounds(0, newBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(null, workspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = CreateNewBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateAddedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = CreateNewPlainTextBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.Project.Solution.WithAdditionalDocumentText(document.Id, newBuffer.AsTextContainer().CurrentText)); rightWorkspace.OpenAdditionalDocument(document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateRemovedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateRemovedDocumentPreviewViewCoreAsync(ITextBuffer oldBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.RemovingFromWithContent, document.Name, document.Project.Name); var span = new SnapshotSpan(oldBuffer.CurrentSnapshot, Span.FromBounds(0, oldBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(workspace, null, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocument = document.Project .RemoveDocument(document.Id) .AddDocument(document.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateRemovedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocumentId = DocumentId.CreateNewId(document.Project.Id); var leftSolution = document.Project.Solution .RemoveAdditionalDocument(document.Id) .AddAdditionalDocument(leftDocumentId, document.Name, oldBuffer.AsTextContainer().CurrentText); var leftDocument = leftSolution.GetAdditionalDocument(leftDocumentId); var leftWorkspace = new PreviewWorkspace(leftSolution); leftWorkspace.OpenAdditionalDocument(leftDocumentId); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { return CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, DefaultZoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. // We also need to show the spans that are in conflict. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); var newRoot = newDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken); var conflictNodes = newRoot.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind); var conflictSpans = conflictNodes.Select(n => n.Span.ToSpan()).ToList(); var conflictDescriptions = conflictNodes.SelectMany(n => n.GetAnnotations(ConflictAnnotation.Kind)) .Select(a => ConflictAnnotation.GetDescription(a)) .Distinct(); var warningNodes = newRoot.GetAnnotatedNodesAndTokens(WarningAnnotation.Kind); var warningSpans = warningNodes.Select(n => n.Span.ToSpan()).ToList(); var warningDescriptions = warningNodes.SelectMany(n => n.GetAnnotations(WarningAnnotation.Kind)) .Select(a => WarningAnnotation.GetDescription(a)) .Distinct(); AttachConflictAndWarningAnnotationToBuffer(newBuffer, conflictSpans, warningSpans); var description = conflictSpans.Count == 0 && warningSpans.Count == 0 ? null : string.Join(Environment.NewLine, conflictDescriptions.Concat(warningDescriptions)); var allSpans = new NormalizedSpanCollection(conflictSpans.Concat(warningSpans).Concat(changedSpans)); var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, allSpans, cancellationToken); if (!originalLineSpans.Any()) { // This means that we have no differences (likely because of conflicts). // In such cases, use the same spans for the left (old) buffer as the right (new) buffer. originalLineSpans = changedLineSpans; } // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocument = oldDocument.Project .RemoveDocument(oldDocument.Id) .AddDocument(oldDocument.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); var rightWorkspace = new PreviewWorkspace( oldDocument.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkspace, zoomLevel, cancellationToken); } public Task<object> CreateChangedAdditionalDocumentPreviewViewAsync(TextDocument oldDocument, TextDocument newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewPlainTextBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); string description = null; var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, changedSpans, cancellationToken); // TODO: Why aren't we attaching conflict / warning annotations here like we do for regular documents above? // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocumentId = DocumentId.CreateNewId(oldDocument.Project.Id); var leftSolution = oldDocument.Project.Solution .RemoveAdditionalDocument(oldDocument.Id) .AddAdditionalDocument(leftDocumentId, oldDocument.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftSolution); leftWorkspace.OpenAdditionalDocument(leftDocumentId); var rightWorkSpace = new PreviewWorkspace( oldDocument.Project.Solution.WithAdditionalDocumentText(oldDocument.Id, newBuffer.AsTextContainer().CurrentText)); rightWorkSpace.OpenAdditionalDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkSpace, zoomLevel, cancellationToken); } private Task<object> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string description, List<LineSpan> originalSpans, List<LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!(originalSpans.Any() && changedSpans.Any())) { // Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw. // So if either is empty (signalling that there are no changes to preview in the document), then we bail out. // This can happen in cases where the user has already applied the fix and light bulb has already been dismissed, // but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at // this point, the preview that we return will never be displayed to the user. So returning null here is harmless. return SpecializedTasks.Default<object>(); } var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, oldBuffer.CurrentSnapshot, "...", description, originalSpans.ToArray()); var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, newBuffer.CurrentSnapshot, "...", description, changedSpans.ToArray()); return CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } private static void AttachConflictAndWarningAnnotationToBuffer(ITextBuffer newBuffer, IEnumerable<Span> conflictSpans, IEnumerable<Span> warningSpans) { // Attach the spans to the buffer. newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.ConflictSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, conflictSpans)); newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.WarningSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, warningSpans)); } private ITextBuffer CreateNewBuffer(Document document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // is it okay to create buffer from threads other than UI thread? var contentTypeService = document.Project.LanguageServices.GetService<IContentTypeLanguageService>(); var contentType = contentTypeService.GetDefaultContentType(); return _textBufferFactoryService.CreateTextBuffer(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private ITextBuffer CreateNewPlainTextBuffer(TextDocument document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var contentType = _textBufferFactoryService.TextContentType; return _textBufferFactoryService.CreateTextBuffer(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private async Task<object> CreateNewDifferenceViewerAsync(PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, IProjectionBuffer originalBuffer, IProjectionBuffer changedBuffer, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // leftWorkspace can be null if the change is adding a document. // rightWorkspace can be null if the change is removing a document. // However both leftWorkspace and rightWorkspace can't be null at the same time. Contract.ThrowIfTrue((leftWorkspace == null) && (rightWorkspace == null)); var diffBuffer = _differenceBufferService.CreateDifferenceBuffer( originalBuffer, changedBuffer, new StringDifferenceOptions(), disableEditing: true); var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, _previewRoleSet); diffViewer.Closed += (s, e) => { if (leftWorkspace != null) { leftWorkspace.Dispose(); leftWorkspace = null; } if (rightWorkspace != null) { rightWorkspace.Dispose(); rightWorkspace = null; } }; const string DiffOverviewMarginName = "deltadifferenceViewerOverview"; if (leftWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.RightViewOnly; diffViewer.RightView.ZoomLevel *= zoomLevel; diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else if (rightWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.LeftViewOnly; diffViewer.LeftView.ZoomLevel *= zoomLevel; diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else { diffViewer.ViewMode = DifferenceViewMode.Inline; diffViewer.InlineView.ZoomLevel *= zoomLevel; diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } // Disable focus / tab stop for the diff viewer. diffViewer.RightView.VisualElement.Focusable = false; diffViewer.LeftView.VisualElement.Focusable = false; diffViewer.InlineView.VisualElement.Focusable = false; // This code path must be invoked on UI thread. AssertIsForeground(); // We use ConfigureAwait(true) to stay on the UI thread. await diffViewer.SizeToFitAsync().ConfigureAwait(true); if (leftWorkspace != null) { leftWorkspace.EnableDiagnostic(); } if (rightWorkspace != null) { rightWorkspace.EnableDiagnostic(); } return diffViewer; } private List<LineSpan> CreateLineSpans(ITextSnapshot textSnapshot, NormalizedSpanCollection allSpans, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var result = new List<LineSpan>(); foreach (var span in allSpans) { cancellationToken.ThrowIfCancellationRequested(); var lineSpan = GetLineSpan(textSnapshot, span); MergeLineSpans(result, lineSpan); } return result; } // Find the lines that surround the span of the difference. Try to expand the span to // include both the previous and next lines so that we can show more context to the // user. private LineSpan GetLineSpan( ITextSnapshot snapshot, Span span) { var startLine = snapshot.GetLineNumberFromPosition(span.Start); var endLine = snapshot.GetLineNumberFromPosition(span.End); if (startLine > 0) { startLine--; } if (endLine < snapshot.LineCount) { endLine++; } return LineSpan.FromBounds(startLine, endLine); } // Adds a line span to the spans we've been collecting. If the line span overlaps or // abuts a previous span then the two are merged. private static void MergeLineSpans(List<LineSpan> lineSpans, LineSpan nextLineSpan) { if (lineSpans.Count > 0) { var lastLineSpan = lineSpans.Last(); // We merge them if there's no more than one line between the two. Otherwise // we'd show "..." between two spans where we could just show the actual code. if (nextLineSpan.Start >= lastLineSpan.Start && nextLineSpan.Start <= (lastLineSpan.End + 1)) { nextLineSpan = LineSpan.FromBounds(lastLineSpan.Start, nextLineSpan.End); lineSpans.RemoveAt(lineSpans.Count - 1); } } lineSpans.Add(nextLineSpan); } private IHierarchicalDifferenceCollection ComputeEditDifferences(TextDocument oldDocument, TextDocument newDocument, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Get the text that's actually in the editor. var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var newText = newDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); // Defer to the editor to figure out what changes the client made. var diffService = _differenceSelectorService.GetTextDifferencingService( oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(oldText.ToString(), newText.ToString(), new StringDifferenceOptions() { DifferenceType = StringDifferenceTypes.Word | StringDifferenceTypes.Line, }); } private NormalizedSpanCollection GetOriginalSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } private NormalizedSpanCollection GetChangedSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.RightDecomposition.GetSpanInOriginal(difference.Right); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } } }
// 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.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Text { // ASCIIEncoding // // Note that ASCIIEncoding is optimized with no best fit and ? for fallback. // It doesn't come in other flavors. // // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit). // // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd // use fallbacks, and we cannot guarantee that fallbacks are normalized. public class ASCIIEncoding : Encoding { // Allow for devirtualization (see https://github.com/dotnet/coreclr/pull/9230) internal sealed class ASCIIEncodingSealed : ASCIIEncoding { } // Used by Encoding.ASCII for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly ASCIIEncodingSealed s_default = new ASCIIEncodingSealed(); public ASCIIEncoding() : base(Encoding.CodePageASCII) { } internal override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; this.decoderFallback = DecoderFallback.ReplacementFallback; } // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...) // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: or it'll break VB's way of calling these. // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(String chars) { // Validate input if (chars==null) throw new ArgumentNullException("chars"); Contract.EndContractBlock(); fixed (char* pChars = chars) return GetByteCount(pChars, chars.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(String chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty byte arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0]) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty byte arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0]) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty char arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString(byte[] bytes, int byteIndex, int byteCount) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (byteCount == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + byteIndex, byteCount, this); } // // End of standard methods copied from EncodingNLS.cs // // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // Start by assuming default count, then +/- for fallback characters char* charEnd = chars + charCount; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer"); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // If we have an encoder AND we aren't using default fallback, // then we may have a complicated count. if (fallback != null && fallback.MaxCharCount == 1) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if (charLeftOver > 0) charCount++; return (charCount); } // Count is more complicated if you have a funky fallback // For fallback we may need a fallback buffer, we know we're not default fallback int byteCount = 0; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback); chars = charsForFallback; } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // no chars >= 0x80 are allowed. if (ch > 0x7f) { if (fallbackBuffer == null) { // Initialize the buffer if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false); } // Get Fallback charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; continue; } // We'll use this one byteCount++; } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; } internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; if (encoder != null) { charLeftOver = encoder.charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer"); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // See if we do the fast default or slightly slower fallback if (fallback != null && fallback.MaxCharCount == 1) { // Fast version char cReplacement = fallback.DefaultString[0]; // Check for replacements in range, otherwise fall back to slow version. if (cReplacement <= (char)0x7f) { // We should have exactly as many output bytes as input bytes, unless there's a left // over character, in which case we may need one more. // If we had a left over character will have to add a ? (This happens if they had a funky // fallback last time, but not this time.) (We can't spit any out though // because with fallback encoder each surrogate is treated as a seperate code point) if (charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if (byteCount == 0) ThrowBytesOverflow(encoder, true); // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = (byte)cReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if (byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow(encoder, byteCount < 1); // Just use what we can charEnd = chars + byteCount; } // We just do a quick copy while (chars < charEnd) { char ch2 = *(chars++); if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement; else *(bytes++) = unchecked((byte)(ch2)); } // Clear encoder if (encoder != null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // prepare our end byte* byteEnd = bytes + byteCount; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Initialize the buffer Debug.Assert(encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback // This will fallback a pair if *chars is a low surrogate charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback); chars = charsForFallback; } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // All characters >= 0x80 must fall back. if (ch > 0x7f) { // Initialize the buffer if (fallbackBuffer == null) { if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Get Fallback charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; // Go ahead & continue (& do the fallback) continue; } // We'll use this one // Bounds check if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { Debug.Assert(chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already."); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // Are we throwing or using buffer? ThrowBytesOverflow(encoder, bytes == byteStart); // throw? break; // don't throw, stop } // Go ahead and add it *bytes = unchecked((byte)ch); bytes++; } // Need to do encoder stuff if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder.m_throwOnOverflow), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII DecoderFallbackBuffer fallbackBuffer = null; // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *bytes; bytes++; // If unknown we have to do fallback count if (b >= 0x80) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - count, null); } // Use fallback buffer byteBuffer[0] = b; charCount--; // Have to unreserve the one we already allocated for b charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes); } } // Fallback buffer must be empty Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer"); // Converted sequence is same length as input return charCount; } internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f // Only need decoder fallback buffer if not using ? fallback. // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; char* charsForFallback; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Try it the fast way char replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow(decoder, charCount < 1); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while (bytes < byteEnd) { byte b = *(bytes++); if (b >= 0x80) // This is an invalid byte in the ASCII encoding. *(chars++) = replacementChar; else *(chars++) = unchecked((char)b); } // bytes & chars used are the same if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; // Not quite so fast loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *(bytes); bytes++; if (b >= 0x80) { // This is an invalid byte in the ASCII encoding. if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd); } // Use fallback buffer byteBuffer[0] = b; // Note that chars won't get updated unless this succeeds charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered bool fallbackResult = fallbackBuffer.InternalFallback(byteBuffer, bytes, ref charsForFallback); chars = charsForFallback; if (!fallbackResult) { // May or may not throw, but we didn't get this byte Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)"); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if (chars >= charEnd) { Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)"); bytes--; // unused byte ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } *(chars) = unchecked((char)b); chars++; } } // Might have had decoder fallback stuff. if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer"); return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) public override bool IsSingleByte { get { return true; } } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } }
using System; using NLog; using NServiceKit.Logging; namespace NServiceKit.Logging.NLogger { /// <summary> /// Wrapper over the NLog 2.0 beta and above logger /// </summary> public class NLogLogger : NServiceKit.Logging.ILog { private readonly NLog.Logger log; public NLogLogger(string typeName) { log = NLog.LogManager.GetLogger(typeName); } /// <summary> /// Initializes a new instance of the <see cref="NLogLogger"/> class. /// </summary> /// <param name="type">The type.</param> public NLogLogger(Type type) { log = NLog.LogManager.GetLogger(UseFullTypeNames ? type.FullName : type.Name); } public static bool UseFullTypeNames { get; set; } public bool IsDebugEnabled { get { return log.IsDebugEnabled; } } public bool IsInfoEnabled { get { return log.IsInfoEnabled; } } public bool IsWarnEnabled { get { return log.IsWarnEnabled; } } public bool IsErrorEnabled { get { return log.IsErrorEnabled; } } public bool IsFatalEnabled { get { return log.IsFatalEnabled; } } /// <summary> /// Logs a Debug message. /// </summary> /// <param name="message">The message.</param> public void Debug(object message) { if (IsDebugEnabled) Write(LogLevel.Debug, message.ToString()); } /// <summary> /// Logs a Debug message and exception. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Debug(object message, Exception exception) { if(IsDebugEnabled) Write(LogLevel.Debug,exception,message.ToString()); } /// <summary> /// Logs a Debug format message. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The args.</param> public void DebugFormat(string format, params object[] args) { if (IsDebugEnabled) Write(LogLevel.Debug, format, args); } /// <summary> /// Logs a Error message. /// </summary> /// <param name="message">The message.</param> public void Error(object message) { if (IsErrorEnabled) Write(LogLevel.Error,message.ToString()); } /// <summary> /// Logs a Error message and exception. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Error(object message, Exception exception) { if (IsErrorEnabled) Write(LogLevel.Error, exception, message.ToString()); } /// <summary> /// Logs a Error format message. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The args.</param> public void ErrorFormat(string format, params object[] args) { if (IsErrorEnabled) Write(LogLevel.Error,format,args); } /// <summary> /// Logs a Fatal message. /// </summary> /// <param name="message">The message.</param> public void Fatal(object message) { if (IsFatalEnabled) Write(LogLevel.Fatal,message.ToString()); } /// <summary> /// Logs a Fatal message and exception. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Fatal(object message, Exception exception) { if (IsFatalEnabled) Write(LogLevel.Fatal, exception, message.ToString()); } /// <summary> /// Logs a Error format message. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The args.</param> public void FatalFormat(string format, params object[] args) { if (IsFatalEnabled) Write(LogLevel.Fatal, format, args); } /// <summary> /// Logs an Info message and exception. /// </summary> /// <param name="message">The message.</param> public void Info(object message) { if (IsInfoEnabled) Write(LogLevel.Info,message.ToString()); } /// <summary> /// Logs an Info message and exception. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Info(object message, Exception exception) { if (IsInfoEnabled) Write(LogLevel.Info,exception,message.ToString()); } /// <summary> /// Logs an Info format message. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The args.</param> public void InfoFormat(string format, params object[] args) { if (IsInfoEnabled) Write(LogLevel.Info, format, args); } /// <summary> /// Logs a Warning message. /// </summary> /// <param name="message">The message.</param> public void Warn(object message) { if (IsWarnEnabled) Write(LogLevel.Warn,message.ToString()); } /// <summary> /// Logs a Warning message and exception. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public void Warn(object message, Exception exception) { if (IsWarnEnabled) Write(LogLevel.Warn,exception,message.ToString()); } /// <summary> /// Logs a Warning format message. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The args.</param> public void WarnFormat(string format, params object[] args) { if (IsWarnEnabled) Write(LogLevel.Warn, format, args); } private void Write(LogLevel level, string format, params object[] args) { //preserve call site info - see here: http://stackoverflow.com/questions/3947136/problem-matching-specific-nlog-logger-name var logEventInfo = new LogEventInfo(level, log.Name, null, format, args); log.Log(typeof(NLogLogger), logEventInfo); } private void Write(LogLevel level, Exception exception, string format, params object[] args) { var exceptionEventInfo = new LogEventInfo(level, log.Name, null, format, args, exception); log.Log(typeof(NLogLogger), exceptionEventInfo); } } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System; using System.Xml.Serialization; using System.Collections.Specialized; using System.Collections.Generic; using Amazon.S3.Util; namespace Amazon.S3.Model { /// <summary> /// The parameters to upload a part by copying data from an existing object as data source. /// </summary> public class CopyPartRequest : S3Request { #region Private Members private string srcBucket; private string srcKey; private string srcVersionId; private string dstBucket; private string dstKey; private string uploadID; private List<string> etagsToMatch; private List<string> etagsToNotMatch; private DateTime? modifiedSinceDate; private DateTime? unmodifiedSinceDate; private int? partNumber; private long? firstByte; private long? lastByte; private ServerSideEncryptionMethod serverSideEncryption; #endregion #region SourceBucket /// <summary> /// The name of the bucket containing the object to copy. /// </summary> [XmlElementAttribute(ElementName = "SourceBucket")] public string SourceBucket { get { return this.srcBucket; } set { this.srcBucket = value; } } /// <summary> /// Sets the name of the bucket containing the object to copy. /// </summary> /// <param name="srcBucket">Name of the bucket containing the object to copy</param> /// <returns>the request with the SourceBucket set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithSourceBucket(string srcBucket) { this.srcBucket = srcBucket; return this; } /// <summary> /// Checks if SourceBucket property is set. /// </summary> /// <returns>true if SourceBucket property is set.</returns> internal bool IsSetSourceBucket() { return !System.String.IsNullOrEmpty(this.srcBucket); } #endregion #region SourceKey /// <summary> /// The key of the object to copy. /// </summary> [XmlElementAttribute(ElementName = "SourceKey")] public string SourceKey { get { return this.srcKey; } set { this.srcKey = value; } } /// <summary> /// Sets the key of the object to copy. /// </summary> /// <param name="srcKey">Key of the S3 object to copy</param> /// <returns>the request with the SourceKey set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithSourceKey(string srcKey) { this.srcKey = srcKey; return this; } /// <summary> /// Checks if SourceKey property is set. /// </summary> /// <returns>true if SourceKey property is set.</returns> internal bool IsSetSourceKey() { return !System.String.IsNullOrEmpty(this.srcKey); } #endregion #region SourceVersionId /// <summary> /// Specifies a particular version of the source object to copy. By default the latest version is copied. /// </summary> [XmlElementAttribute(ElementName = "SourceVersionId")] public string SourceVersionId { get { return this.srcVersionId; } set { this.srcVersionId = value; } } /// <summary> /// Specifies a particular version of the source object to copy. By default the latest version is copied. /// </summary> /// <param name="srcVersionId">Id of the version of the source object to be copied</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithSourceVersionId(string srcVersionId) { this.srcVersionId = srcVersionId; return this; } /// <summary> /// Checks if SourceVersionId property is set. /// </summary> /// <returns>true if SourceVersionId property is set.</returns> internal bool IsSetSourceVersionId() { return !System.String.IsNullOrEmpty(this.srcVersionId); } #endregion #region DestinationBucket /// <summary> /// The name of the bucket to contain the copy of the source object. /// </summary> [XmlElementAttribute(ElementName = "DestinationBucket")] public string DestinationBucket { get { return this.dstBucket; } set { this.dstBucket = value; } } /// <summary> /// Sets the name of the bucket to contain the copy of the source object. /// </summary> /// <param name="dstBucket">Name of the bucket to contain the copy</param> /// <returns>the request with the DestinationBucket set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithDestinationBucket(string dstBucket) { this.dstBucket = dstBucket; return this; } /// <summary> /// Checks if DestinationBucket property is set. /// </summary> /// <returns>true if DestinationBucket property is set.</returns> internal bool IsSetDestinationBucket() { return !System.String.IsNullOrEmpty(this.dstBucket); } #endregion #region DestinationKey /// <summary> /// The key to be given to the copy of the source object. /// </summary> [XmlElementAttribute(ElementName = "DestinationKey")] public string DestinationKey { get { return this.dstKey; } set { this.dstKey = value; } } /// <summary> /// Sets the key to be given to the copy of the source object. /// </summary> /// <param name="dstKey">Key of the copy of the source object</param> /// <returns>the response with the Destinationkey set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithDestinationKey(string dstKey) { this.dstKey = dstKey; return this; } /// <summary> /// Checks if DestinationKey property is set. /// </summary> /// <returns>true if DestinationKey property is set.</returns> internal bool IsSetDestinationKey() { return !System.String.IsNullOrEmpty(this.dstKey); } #endregion #region UploadID /// <summary> /// The ID identifying multipart upload for which we are copying a part. /// </summary> [XmlElementAttribute(ElementName = "UploadID")] public string UploadID { get { return this.uploadID; } set { this.uploadID = value; } } /// <summary> /// Sets the ID identifying multipart upload for which we are copying a part. /// </summary> /// <param name="uploadID">Id of the multipart upload</param> /// <returns>the request with the UploadID set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithUploadID(string uploadID) { this.uploadID = uploadID; return this; } /// <summary> /// Checks if UploadID property is set. /// </summary> /// <returns>true if UploadID property is set.</returns> internal bool IsSetUploadID() { return !System.String.IsNullOrEmpty(this.uploadID); } #endregion #region ETagsToMatch /// <summary> /// Collection of ETags to be matched as a pre-condition for copying the source object /// otherwise returns a PreconditionFailed. /// </summary> /// <remarks> /// Copies the object if its entity tag (ETag) matches one of /// the specified tags; otherwise return a 412 (precondition failed). /// Constraints: This property can be used with IfUnmodifiedSince, /// but cannot be used with other conditional copy properties. /// </remarks> [XmlElementAttribute(ElementName = "ETagsToMatch")] public List<string> ETagToMatch { get { if (this.etagsToMatch == null) { this.etagsToMatch = new List<String>(); } return this.etagsToMatch; } set { this.etagsToMatch = value; } } /// <summary> /// Adds the specified Etags to the ETagsToMatch property for this request. /// </summary> /// <remarks> /// Copies the object if its entity tag (ETag) matches one of /// the specified tags; otherwise return a 412 (precondition failed). /// Constraints: This property can be used with IfUnmodifiedSince, /// but cannot be used with other conditional copy properties. /// </remarks> /// <param name="etagsToMatch">The items to be added to the ETagsToMatch collection.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithETagsToMatch(params string[] etagsToMatch) { if (etagsToMatch != null) { this.ETagToMatch.AddRange(etagsToMatch); } return this; } /// <summary> /// Adds the specified Etags to the ETagsToMatch property for this request. /// </summary> /// <remarks> /// Copies the object if its entity tag (ETag) matches one of /// the specified tags; otherwise return a 412 (precondition failed). /// Constraints: This property can be used with IfUnmodifiedSince, /// but cannot be used with other conditional copy properties. /// </remarks> /// <param name="etagsToMatch">The items to be added to the ETagsToMatch collection.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithETagsToMatch(IEnumerable<String> etagsToMatch) { if (etagsToMatch != null) { this.ETagToMatch.AddRange(etagsToMatch); } return this; } /// <summary> /// Checks if ETagsToMatch property is set. /// </summary> /// <returns>true if ETagToMatch property is set.</returns> internal bool IsSetETagToMatch() { return ((etagsToMatch != null) && (etagsToMatch.Count > 0)); } #endregion #region ETagsToNotMatch /// <summary> /// Collection of ETags that must not be matched as a pre-condition for copying the source object /// otherwise returns a PreconditionFailed. /// </summary> /// <remarks> /// Copies the object if its entity tag (ETag) does not match any of the specified /// tags; otherwise returns a 412 (failed condition). /// Constraints: This header can be used with IfModifiedSince, but cannot /// be used with other conditional copy properties. /// </remarks> [XmlElementAttribute(ElementName = "ETagsToNotMatch")] public List<string> ETagsToNotMatch { get { if (this.etagsToNotMatch == null) { this.etagsToNotMatch = new List<String>(); } return this.etagsToNotMatch; } set { this.etagsToNotMatch = value; } } /// <summary> /// Adds the specified Etags to the ETagsToNotMatch property for this request. /// </summary> /// <remarks> /// Copies the object if its entity tag (ETag) does not match any of the specified /// tags; otherwise returns a 412 (failed condition). /// Constraints: This header can be used with IfModifiedSince, but cannot /// be used with other conditional copy properties. /// </remarks> /// <param name="etagsToNotMatch">The ETags to add to the ETagsToNotMatch property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithETagsToNotMatch(params string[] etagsToNotMatch) { if (etagsToNotMatch != null) { ETagsToNotMatch.AddRange(etagsToNotMatch); } return this; } /// <summary> /// Adds the Etags to the ETagsToNotMatch property for this request. /// </summary> /// <remarks> /// Copies the object if its entity tag (ETag) does not match any of the specified /// tags; otherwise returns a 412 (failed condition). /// Constraints: This header can be used with IfModifiedSince, but cannot /// be used with other conditional copy properties. /// </remarks> /// <param name="etagsToNotMatch">The ETags to add to the ETagsToNotMatch property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithETagsToNotMatch(IEnumerable<String> etagsToNotMatch) { if (etagsToNotMatch != null) { ETagsToNotMatch.AddRange(etagsToNotMatch); } return this; } /// <summary> /// Checks if ETagToNotMatch property is set. /// </summary> /// <returns>true if ETagToNotMatch property is set.</returns> internal bool IsSetETagToNotMatch() { return ((etagsToNotMatch != null) && (etagsToNotMatch.Count > 0)); } #endregion #region ModifiedSinceDate /// <summary> /// Copies the object if it has been modified since the specified time, otherwise returns a PreconditionFailed. /// </summary> /// <remarks> /// Copies the object if it has been modified since the /// specified time; otherwise returns a 412 (failed condition). /// Constraints: This property can be used with ETagToNotMatch, /// but cannot be used with other conditional copy properties. /// </remarks> [XmlElementAttribute(ElementName = "ModifiedSinceDate")] public DateTime ModifiedSinceDate { get { return this.modifiedSinceDate.GetValueOrDefault(); } set { this.modifiedSinceDate = value; } } /// <summary> /// Copies the object if it has been modified since the specified time, otherwise returns a PreconditionFailed. /// </summary> /// <remarks> /// Copies the object if it has been modified since the /// specified time; otherwise returns a 412 (failed condition). /// Constraints: This property can be used with ETagToNotMatch, /// but cannot be used with other conditional copy properties. /// </remarks> /// <param name="modifiedSinceDate">The date/time to check the modification timestamp against</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithModifiedSinceDate(DateTime modifiedSinceDate) { this.modifiedSinceDate = modifiedSinceDate; return this; } /// <summary> /// Checks if ModifiedSinceDate property is set. /// </summary> /// <returns>true if ModifiedSinceDate property is set.</returns> internal bool IsSetModifiedSinceDate() { return this.modifiedSinceDate.HasValue; } #endregion #region UnmodifiedSinceDate /// <summary> /// Copies the object if it has not been modified since the specified time, otherwise returns a PreconditionFailed. /// </summary> /// <remarks> /// Copies the object if it hasn't been modified since the /// specified time; otherwise returns a 412 (precondition failed). /// Constraints: This property can be used with ETagToMatch, /// but cannot be used with other conditional copy properties. /// </remarks> [XmlElementAttribute(ElementName = "UnmodifiedSinceDate")] public DateTime UnmodifiedSinceDate { get { return this.unmodifiedSinceDate.GetValueOrDefault(); } set { this.unmodifiedSinceDate = value; } } /// <summary> /// Copies the object if it has not been modified since the specified time, otherwise returns a PreconditionFailed. /// </summary> /// <remarks> /// Copies the object if it hasn't been modified since the /// specified time; otherwise returns a 412 (precondition failed). /// Constraints: This property can be used with ETagToMatch, /// but cannot be used with other conditional copy properties. /// </remarks> /// <param name="unmodifiedSinceDate">The date/time to check the modification timestamp against</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithUnmodifiedSinceDate(DateTime unmodifiedSinceDate) { this.unmodifiedSinceDate = unmodifiedSinceDate; return this; } /// <summary> /// Checks if UnmodifiedSinceDate property is set. /// </summary> /// <returns>true if UnmodifiedSinceDate property is set.</returns> internal bool IsSetUnmodifiedSinceDate() { return this.unmodifiedSinceDate.HasValue; } #endregion #region Timeout /// <summary> /// Custom timeout value (in milliseconds) to set in the HttpWebRequest object used for the request. /// </summary> /// <param name="timeout">Timeout property</param> /// <remarks> /// <para> /// A value less than or equal to 0 will be silently ignored /// </para> /// <para> /// You should only set a custom timeout if you are certain that /// the file will not be transferred within the default intervals /// for an HttpWebRequest. /// </para> /// </remarks> /// <returns>this instance</returns> /// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/> /// <seealso cref="P:System.Net.HttpWebRequest.Timeout"/> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] new public CopyPartRequest WithTimeout(int timeout) { Timeout = timeout; return this; } #endregion #region ReadWriteTimeout /// <summary> /// Custom read-write timeout value (in milliseconds) to set in the HttpWebRequest object used for the request. /// </summary> /// <param name="readWriteTimeout">ReadWriteTimeout property</param> /// <remarks>A value less than or equal to 0 will be silently ignored</remarks> /// <returns>this instance</returns> /// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] new public CopyPartRequest WithReadWriteTimeout(int readWriteTimeout) { ReadWriteTimeout = readWriteTimeout; return this; } #endregion #region PartNumber /// <summary> /// The number of the part to be copied. /// </summary> /// <remarks> /// Valid part numbers are from 1 to 10,000 inclusive and will uniquely identify the part /// and determine the relative ordering within the destination object. If a part already /// exists with the PartNumber it will be overwritten. /// </remarks> public int PartNumber { get { return this.partNumber.GetValueOrDefault(); } set { this.partNumber = value; } } /// <summary> /// Sets the number of the part to be copied. /// </summary> /// <remarks> /// Valid part numbers are from 1 to 10,000 inclusive and will uniquely identify the part /// and determine the relative ordering within the destination object. If a part already /// exists with the PartNumber it will be overwritten. /// </remarks> /// <param name="partNumber">value to set the PartNumber property to</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithPartNumber(int partNumber) { this.partNumber = partNumber; return this; } /// <summary> /// Checks if PartNumber property is set. /// </summary> /// <returns>true if PartNumber property is set.</returns> internal bool IsSetPartNumber() { return this.partNumber.HasValue; } #endregion #region FirstByte /// <summary> /// The location of the first byte in the range if only a portion of the /// source object is to be copied as the part. /// </summary> /// <remarks> /// The LastByte property must also be set or this value will be ignored. /// </remarks> public long FirstByte { get { return this.firstByte.GetValueOrDefault(); } set { this.firstByte = value; } } /// <summary> /// Sets the location of the first byte in the range if only a portion of the /// source object is to be copied as the part. /// </summary> /// <remarks> /// The LastByte property must also be set or this value will be ignored. /// </remarks> /// <param name="firstByte">The value to set the FirstByte property too</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithFirstByte(long firstByte) { this.firstByte = firstByte; return this; } /// <summary> /// Checks if FirstByte property is set. /// </summary> /// <returns>true if FirstByte property is set.</returns> internal bool IsSetFirstByte() { return this.firstByte.HasValue; } #endregion #region LastByte /// <summary> /// The location of the last byte in the range if only a portion of the /// source object is to be copied as the part. /// </summary> /// <remarks> /// The FirstByte property must also be set or this value will be ignored. /// </remarks> public long LastByte { get { return this.lastByte.GetValueOrDefault(); } set { this.lastByte = value; } } /// <summary> /// The location of the last byte in the range if only a portion of the /// source object is to be copied as the part. /// </summary> /// <remarks> /// The FirstByte property must also be set or this value will be ignored. /// </remarks> /// <param name="lastByte">The value to set the LastByte property to</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithLastByte(long lastByte) { this.lastByte = lastByte; return this; } /// <summary> /// Checks if LastByte property is set. /// </summary> /// <returns>true if LastByte property is set.</returns> internal bool IsSetLastByte() { return this.lastByte.HasValue; } #endregion #region ServerSideEncryption /// <summary> /// <para> /// Specifies the encryption to be used on the server for the new object. /// </para> /// <para> /// Default: None /// </para> /// </summary> public ServerSideEncryptionMethod ServerSideEncryptionMethod { get { return this.serverSideEncryption; } set { this.serverSideEncryption = value; } } /// <summary> /// <para> /// Specifies the encryption to be used on the server for the new object. /// </para> /// <para> /// Default: None /// </para> /// </summary> /// <param name="serverSideEncryption">ServerSideEncryptionMethod for the new object</param> /// <returns>The response with the ServerSideEncryptionMethod set.</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CopyPartRequest WithServerSideEncryptionMethod(ServerSideEncryptionMethod serverSideEncryption) { this.serverSideEncryption = serverSideEncryption; return this; } #endregion #region Constructor public CopyPartRequest() { Timeout = System.Threading.Timeout.Infinite; } #endregion } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; namespace qx.ui.basic { /// <summary> /// <para>A multi-purpose widget, which combines a label with an icon.</para> /// <para>The intended purpose of qx.ui.basic.Atom is to easily align the common icon-text /// combination in different ways.</para> /// <para>This is useful for all types of buttons, tooltips, ...</para> /// <para>Example</para> /// <para>Here is a little example of how to use the widget.</para> /// <code> /// var atom = new qx.ui.basic.Atom("Icon Right", "icon/32/actions/go-next.png"); /// this.getRoot().add(atom); /// </code> /// <para>This example creates an atom with the label &#8220;Icon Right&#8221; and an icon.</para> /// <para>External Documentation</para> /// /// Documentation of this widget in the qooxdoo manual. /// </summary> [JsType(JsMode.Prototype, Name = "qx.ui.basic.Atom", OmitOptionalParameters = true, Export = false)] public partial class Atom : qx.ui.core.Widget { #region Events /// <summary> /// Fired on change of the property <see cref="Gap"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeGap; /// <summary> /// Fired on change of the property <see cref="Icon"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeIcon; /// <summary> /// Fired on change of the property <see cref="Label"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeLabel; /// <summary> /// Fired on change of the property <see cref="Show"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeShow; #endregion Events #region Properties /// <summary> /// <para>The appearance ID. This ID is used to identify the appearance theme /// entry to use for this widget. This controls the styling of the element.</para> /// </summary> [JsProperty(Name = "appearance", NativeField = true)] public string Appearance { get; set; } /// <summary> /// <para>Whether the content should be rendered centrally when to much space /// is available. Affects both axis.</para> /// </summary> [JsProperty(Name = "center", NativeField = true)] public bool Center { get; set; } /// <summary> /// <para>The space between the icon and the label</para> /// </summary> /// <remarks> /// Allow nulls: false /// </remarks> [JsProperty(Name = "gap", NativeField = true)] public double Gap { get; set; } /// <summary> /// <para>Any URI String supported by qx.ui.basic.Image to display an icon</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "icon", NativeField = true)] public string Icon { get; set; } /// <summary> /// <para>The position of the icon in relation to the text. /// Only useful/needed if text and icon is configured and &#8216;show&#8217; is configured as &#8216;both&#8217; (default)</para> /// </summary> /// <remarks> /// Possible values: "top","right","bottom","left","top-left","bottom-left" /// </remarks> [JsProperty(Name = "iconPosition", NativeField = true)] public object IconPosition { get; set; } /// <summary> /// <para>The label/caption/text of the qx.ui.basic.Atom instance</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "label", NativeField = true)] public string Label { get; set; } /// <summary> /// <para>Switches between rich HTML and text content. The text mode (false) supports /// advanced features like ellipsis when the available space is not /// enough. HTML mode (true) supports multi-line content and all the /// markup features of HTML content.</para> /// </summary> [JsProperty(Name = "rich", NativeField = true)] public bool Rich { get; set; } /// <summary> /// <para>Configure the visibility of the sub elements/widgets. /// Possible values: both, label, icon</para> /// </summary> /// <remarks> /// Possible values: "both","label","icon" /// </remarks> [JsProperty(Name = "show", NativeField = true)] public object Show { get; set; } #endregion Properties #region Methods public Atom() { throw new NotImplementedException(); } /// <param name="label">Label to use</param> /// <param name="icon">Icon to use</param> public Atom(string label, string icon = null) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property center.</para> /// </summary> [JsMethod(Name = "getCenter")] public bool GetCenter() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property gap.</para> /// </summary> [JsMethod(Name = "getGap")] public double GetGap() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property icon.</para> /// </summary> [JsMethod(Name = "getIcon")] public string GetIcon() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property iconPosition.</para> /// </summary> [JsMethod(Name = "getIconPosition")] public object GetIconPosition() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property label.</para> /// </summary> [JsMethod(Name = "getLabel")] public string GetLabel() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property rich.</para> /// </summary> [JsMethod(Name = "getRich")] public bool GetRich() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property show.</para> /// </summary> [JsMethod(Name = "getShow")] public object GetShow() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property center /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property center.</param> [JsMethod(Name = "initCenter")] public void InitCenter(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property gap /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property gap.</param> [JsMethod(Name = "initGap")] public void InitGap(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property icon /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property icon.</param> [JsMethod(Name = "initIcon")] public void InitIcon(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property iconPosition /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property iconPosition.</param> [JsMethod(Name = "initIconPosition")] public void InitIconPosition(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property label /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property label.</param> [JsMethod(Name = "initLabel")] public void InitLabel(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property rich /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property rich.</param> [JsMethod(Name = "initRich")] public void InitRich(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property show /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property show.</param> [JsMethod(Name = "initShow")] public void InitShow(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property center equals true.</para> /// </summary> [JsMethod(Name = "isCenter")] public void IsCenter() { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property rich equals true.</para> /// </summary> [JsMethod(Name = "isRich")] public void IsRich() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property center.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetCenter")] public void ResetCenter() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property gap.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetGap")] public void ResetGap() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property icon.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetIcon")] public void ResetIcon() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property iconPosition.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetIconPosition")] public void ResetIconPosition() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property label.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetLabel")] public void ResetLabel() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property rich.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetRich")] public void ResetRich() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property show.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetShow")] public void ResetShow() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property center.</para> /// </summary> /// <param name="value">New value for property center.</param> [JsMethod(Name = "setCenter")] public void SetCenter(bool value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property gap.</para> /// </summary> /// <param name="value">New value for property gap.</param> [JsMethod(Name = "setGap")] public void SetGap(double value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property icon.</para> /// </summary> /// <param name="value">New value for property icon.</param> [JsMethod(Name = "setIcon")] public void SetIcon(string value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property iconPosition.</para> /// </summary> /// <param name="value">New value for property iconPosition.</param> [JsMethod(Name = "setIconPosition")] public void SetIconPosition(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property label.</para> /// </summary> /// <param name="value">New value for property label.</param> [JsMethod(Name = "setLabel")] public void SetLabel(string value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property rich.</para> /// </summary> /// <param name="value">New value for property rich.</param> [JsMethod(Name = "setRich")] public void SetRich(bool value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property show.</para> /// </summary> /// <param name="value">New value for property show.</param> [JsMethod(Name = "setShow")] public void SetShow(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property center.</para> /// </summary> [JsMethod(Name = "toggleCenter")] public void ToggleCenter() { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property rich.</para> /// </summary> [JsMethod(Name = "toggleRich")] public void ToggleRich() { throw new NotImplementedException(); } #endregion Methods } }
using System; using System.Collections; using NDatabase.Api; using NDatabase.Api.Query; using NDatabase.Exceptions; using NDatabase.Meta; namespace NDatabase.Core.Query.Criteria.Evaluations { internal sealed class ContainsEvaluation : AEvaluation { /// <summary> /// For criteria query on objects, we use the oid of the object instead of the object itself. /// </summary> /// <remarks> /// For criteria query on objects, we use the oid of the object instead of the object itself. /// So comparison will be done with OID It is faster and avoid the need of the object /// (class) having to implement Serializable in client server mode /// </remarks> private readonly OID _oid; private readonly IInternalQuery _query; public ContainsEvaluation(object theObject, string attributeName, IQuery query) : base(theObject, attributeName) { _query = (IInternalQuery) query; if (IsNative()) return; // For non native object, we just need the oid of it _oid = _query.GetQueryEngine().GetObjectId(TheObject, false); } public override bool Evaluate(object candidate) { candidate = AsAttributeValuesMapValue(candidate); if (candidate == null && TheObject == null && _oid == null) return true; if (candidate == null) return false; if (candidate is OID) { var oid = (OID) candidate; candidate = _query.GetQueryEngine().GetObjectFromOid(oid); } if (candidate is IDictionary) { // The value in the map, just take the object with the attributeName var map = (IDictionary)candidate; candidate = map[AttributeName]; // The value valueToMatch was redefined, so we need to re-make some // tests if (candidate == null && TheObject == null && _oid == null) return true; if (candidate == null) return false; } var clazz = candidate.GetType(); if (clazz.IsArray) return CheckIfArrayContainsValue(candidate); var collection = candidate as ICollection; if (collection != null) return CheckIfCollectionContainsValue(collection); var candidateAsString = candidate as string; if (candidateAsString != null) return CheckIfStringContainsValue(candidateAsString); throw new OdbRuntimeException( NDatabaseError.QueryContainsCriterionTypeNotSupported.AddParameter(candidate.GetType().FullName)); } private bool CheckIfStringContainsValue(string candidate) { var value = TheObject as string; return value != null && candidate.Contains(value); } private bool CheckIfCollectionContainsValue(ICollection collection) { var typeDefinition = GetTypeDefinition(collection); // If the object to compared is native if (IsNative()) return CheckIfCollectionContainsNativeValue(collection, typeDefinition); return typeDefinition == typeof (AbstractObjectInfo) ? CheckIfCollectionContainsAbstractObjectInfo(collection) : CheckIfCollectionContainsItem(collection); } private bool CheckIfCollectionContainsItem(IEnumerable collection) { foreach (var item in collection) { if (item == null && TheObject == null && _oid == null) return true; if (Equals(item, TheObject)) return true; if (_oid == null || item == null) continue; if (!OdbType.IsNative(item.GetType())) continue; if (Equals(item, _oid)) return true; } return false; } private bool CheckIfCollectionContainsAbstractObjectInfo(IEnumerable collection) { foreach (AbstractObjectInfo abstractObjectInfo in collection) { if (abstractObjectInfo.IsNull() && TheObject == null && _oid == null) return true; if (_oid == null) continue; if (!abstractObjectInfo.IsNonNativeObject()) continue; var nnoi1 = (NonNativeObjectInfo) abstractObjectInfo; var isEqual = nnoi1.GetOid() != null && _oid != null && nnoi1.GetOid().Equals(_oid); if (isEqual) return true; } return false; } private bool CheckIfCollectionContainsNativeValue(IEnumerable collection, Type typeDefinition) { if (typeDefinition == typeof (AbstractObjectInfo)) { foreach (AbstractObjectInfo abstractObjectInfo in collection) { if (abstractObjectInfo == null && TheObject == null) return true; if (abstractObjectInfo != null && TheObject == null) return false; if (abstractObjectInfo != null && TheObject.Equals(abstractObjectInfo.GetObject())) return true; } } else { foreach (var item in collection) { if (item == null && TheObject == null) return true; if (item != null && TheObject == null) return false; if (TheObject.Equals(item)) return true; } } return false; } private static Type GetTypeDefinition(ICollection collection) { var typeDefinition = typeof (object); if (collection.GetType().IsGenericType) typeDefinition = collection.GetType().GetGenericArguments()[0]; else { if (collection.Count > 0) { var enumerator = collection.GetEnumerator(); enumerator.MoveNext(); var abstractObjectInfo = enumerator.Current as AbstractObjectInfo; if (abstractObjectInfo != null) typeDefinition = typeof (AbstractObjectInfo); } } return typeDefinition; } private bool CheckIfArrayContainsValue(object valueToMatch) { var arrayLength = ((Array)valueToMatch).GetLength(0); for (var i = 0; i < arrayLength; i++) { var element = ((Array)valueToMatch).GetValue(i); if (element == null && TheObject == null) return true; var abstractObjectInfo = (AbstractObjectInfo)element; if (abstractObjectInfo != null && abstractObjectInfo.GetObject() != null && abstractObjectInfo.GetObject().Equals(TheObject)) return true; } return false; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SystemCompositionContainerBuilder.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Builder for the MEF composition container. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Composition.Mef.Hosting { using System; using System.Collections.Generic; using System.Composition.Convention; using System.Composition.Hosting; using System.Composition.Hosting.Core; using System.Linq; using Kephas.Composition.Conventions; using Kephas.Composition.Hosting; using Kephas.Composition.Mef.Conventions; using Kephas.Composition.Mef.ExportProviders; using Kephas.Composition.Mef.Resources; using Kephas.Composition.Mef.ScopeFactory; using Kephas.Composition.Metadata; using Kephas.Diagnostics.Contracts; /// <summary> /// Builder for the MEF composition container. /// </summary> /// <remarks> /// This class is not thread safe. /// </remarks> public class SystemCompositionContainerBuilder : CompositionContainerBuilderBase<SystemCompositionContainerBuilder> { /// <summary> /// The scope factories. /// </summary> private readonly ICollection<Type> scopeFactories = new HashSet<Type>(); /// <summary> /// The container configuration. /// </summary> private ContainerConfiguration configuration; /// <summary> /// Initializes a new instance of the <see cref="SystemCompositionContainerBuilder"/> class. /// </summary> /// <param name="context">The context.</param> public SystemCompositionContainerBuilder(ICompositionRegistrationContext context) : base(context) { Requires.NotNull(context, nameof(context)); } /// <summary> /// Gets the export providers. /// </summary> /// <value> /// The export providers. /// </value> protected IList<IExportProvider> ExportProviders { get; } = new List<IExportProvider>(); /// <summary> /// Sets the composition conventions. /// </summary> /// <param name="conventions">The conventions.</param> /// <returns>This builder.</returns> public override SystemCompositionContainerBuilder WithConventions(IConventionsBuilder conventions) { // ReSharper disable once SuspiciousTypeConversion.Global var mefConventions = conventions as IMefConventionBuilderProvider; if (mefConventions == null) { throw new InvalidOperationException(string.Format(Strings.InvalidConventions, typeof(IMefConventionBuilderProvider).FullName)); } return base.WithConventions(conventions); } /// <summary> /// Sets the container configuration. /// </summary> /// <param name="containerConfiguration">The container configuration.</param> /// <returns>This builder.</returns> public SystemCompositionContainerBuilder WithConfiguration(ContainerConfiguration containerConfiguration) { Requires.NotNull(containerConfiguration, nameof(containerConfiguration)); this.configuration = containerConfiguration; return this; } /// <summary> /// Registers the scope factory <typeparamref name="TFactory"/>. /// </summary> /// <typeparam name="TFactory">Type of the factory.</typeparam> /// <returns> /// This builder. /// </returns> public SystemCompositionContainerBuilder WithScopeFactory<TFactory>() where TFactory : IMefScopeFactory { this.scopeFactories.Add(typeof(TFactory)); return this; } /// <summary> /// Adds the export provider. /// </summary> /// <remarks> /// Can be used multiple times, the factories are added to the existing ones. /// </remarks> /// <param name="exportProvider">The export provider.</param> /// <returns> /// This builder. /// </returns> public virtual SystemCompositionContainerBuilder WithExportProvider(IExportProvider exportProvider) { Requires.NotNull(exportProvider, nameof(exportProvider)); this.ExportProviders.Add(exportProvider); return this; } /// <summary> /// Registers the scope factory. /// </summary> /// <typeparam name="TFactory">Type of the factory.</typeparam> /// <param name="conventions">The conventions.</param> /// <returns> /// This builder. /// </returns> protected SystemCompositionContainerBuilder RegisterScopeFactory<TFactory>(IConventionsBuilder conventions) where TFactory : IMefScopeFactory { return this.RegisterScopeFactory(conventions, typeof(TFactory)); } /// <summary> /// Registers the scope factory. /// </summary> /// <param name="conventions">The conventions.</param> /// <param name="factoryType">Type of the factory.</param> /// <returns> /// This builder. /// </returns> protected SystemCompositionContainerBuilder RegisterScopeFactory(IConventionsBuilder conventions, Type factoryType) { var mefConventions = ((IMefConventionBuilderProvider)conventions).GetConventionBuilder(); var scopeName = factoryType.ExtractMetadataValue<CompositionScopeAttribute, string>(a => a.Value); mefConventions .ForType(factoryType) .Export(b => b.AsContractType<IMefScopeFactory>() .AsContractName(scopeName)) .Shared(); return this; } /// <summary> /// Factory method for creating the MEF conventions builder. /// </summary> /// <returns>A newly created MEF conventions builder.</returns> protected override IConventionsBuilder CreateConventionsBuilder() { return new MefConventionsBuilder(); } /// <summary> /// Creates a new composition container based on the provided conventions and assembly parts. /// </summary> /// <param name="conventions">The conventions.</param> /// <param name="parts">The parts candidating for composition.</param> /// <returns> /// A new composition container. /// </returns> protected override ICompositionContext CreateContainerCore(IConventionsBuilder conventions, IEnumerable<Type> parts) { this.RegisterScopeFactoryConventions(conventions); var containerConfiguration = this.configuration ?? new ContainerConfiguration(); var conventionBuilder = this.GetConventionBuilder(conventions); containerConfiguration .WithDefaultConventions(conventionBuilder) .WithParts(parts); this.RegisterScopeFactoryParts(containerConfiguration, parts); foreach (var provider in this.ExportProviders) { containerConfiguration.WithProvider((ExportDescriptorProvider)provider); } // add the default export descriptor providers. containerConfiguration .WithProvider(new ExportFactoryExportDescriptorProvider()) .WithProvider(new ExportFactoryWithMetadataExportDescriptorProvider()); foreach (var partBuilder in this.GetPartBuilders(conventions)) { if (partBuilder.Instance != null) { containerConfiguration.WithProvider(new FactoryExportDescriptorProvider(partBuilder.ContractType, () => partBuilder.Instance)); } else { containerConfiguration.WithProvider(new FactoryExportDescriptorProvider(partBuilder.ContractType, ctx => partBuilder.InstanceFactory(ctx), partBuilder.IsSingleton || partBuilder.IsScoped)); } } return this.CreateCompositionContext(containerConfiguration); } /// <summary> /// Creates the composition context based on the provided container configuration. /// </summary> /// <param name="containerConfiguration">The container configuration.</param> /// <returns> /// The new composition context. /// </returns> protected virtual ICompositionContext CreateCompositionContext(ContainerConfiguration containerConfiguration) { return new SystemCompositionContainer(containerConfiguration); } /// <summary> /// Gets the convention builder out of the provided abstract conventions. /// </summary> /// <param name="conventions">The conventions.</param> /// <returns> /// The convention builder. /// </returns> protected virtual ConventionBuilder GetConventionBuilder(IConventionsBuilder conventions) { var mefConventions = ((IMefConventionBuilderProvider)conventions).GetConventionBuilder(); return mefConventions; } /// <summary> /// Gets the part builders. /// </summary> /// <param name="conventions">The conventions.</param> /// <returns> /// An enumerator that allows foreach to be used to process the part builders in this collection. /// </returns> protected virtual IEnumerable<MefPartBuilder> GetPartBuilders(IConventionsBuilder conventions) { return (conventions as MefConventionsBuilder)?.GetPartBuilders(); } /// <summary> /// Registers the scope factories into the conventions. /// </summary> /// <param name="conventions">The conventions.</param> private void RegisterScopeFactoryConventions(IConventionsBuilder conventions) { this.scopeFactories.Add(typeof(DefaultMefScopeFactory)); foreach (var scopeFactory in this.scopeFactories) { this.RegisterScopeFactory(conventions, scopeFactory); } } /// <summary> /// Registers the scope factory parts into the container configuration. /// </summary> /// <param name="containerConfiguration">The container configuration.</param> /// <param name="registeredParts">The registered parts.</param> private void RegisterScopeFactoryParts(ContainerConfiguration containerConfiguration, IEnumerable<Type> registeredParts) { if (this.scopeFactories.Count == 0) { return; } containerConfiguration.WithParts(this.scopeFactories.Where(f => !registeredParts.Contains(f))); } } }
using System; using System.IO; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Runtime.InteropServices; using Checkers; using Checkers.Agents; using System.Net; using System.Net.Sockets; namespace Checkers { /// <summary> /// Represents the main game form. /// </summary> public sealed partial class MainForm : Form { #region Helper Enums private enum ClientMessage : byte { Closed = 0, ChatMessage = 1, AbortGame = 2, MakeMove = 3, } #endregion /// <summary> /// Initializes a new instance of the <see cref="MainForm"/> class. /// </summary> public MainForm() { InitializeComponent(); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); } #region Event Handler Methods /// <summary> /// Handles the Load event of the frmMain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void frmMain_Load(object sender, System.EventArgs e) { // Hack: Get actual minimal size ClientSize = new Size(CheckersUI.Width + 8, CheckersUI.Height + 8); MinimumSize = Size; // Set initial size Size = new Size(MinimumSize.Width + 130, MinimumSize.Height); // Load settings settings = CheckersSettings.Load(); UpdateBoard(); } /// <summary> /// Handles the Activated event of the frmMain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void frmMain_Activated(object sender, System.EventArgs e) { tmrFlashWindow.Stop(); if(gameType == CheckersGameType.NetGame) txtSend.Select(); } /// <summary> /// Handles the Deactivate event of the frmMain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void frmMain_Deactivate(object sender, System.EventArgs e) { if((gameType == CheckersGameType.NetGame) && (CheckersUI.IsPlaying) && (CheckersUI.Game.Turn == 1)) if(settings.FlashWindowOnTurn) DoFlashWindow(); } /// <summary> /// Handles the Closing event of the frmMain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param> private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if(!DoCloseGame()) e.Cancel = true; } /// <summary> /// Handles the Click event of the menuGameNew control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuGameNew_Click(object sender, System.EventArgs e) { DoNewGame(); } /// <summary> /// Handles the Click event of the menuGameEnd control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuGameEnd_Click(object sender, System.EventArgs e) { DoCloseGame(); } /// <summary> /// Handles the Click event of the menuGameExit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuGameExit_Click(object sender, System.EventArgs e) { Close(); } /// <summary> /// Handles the Popup event of the menuView control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuView_Popup(object sender, System.EventArgs e) { menuViewGamePanel.Checked = (Width != MinimumSize.Width); menuViewNetPanel.Checked = (Height != MinimumSize.Height); } /// <summary> /// Handles the Click event of the menuViewGamePanel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuViewGamePanel_Click(object sender, System.EventArgs e) { menuViewGamePanel.Checked = !menuViewGamePanel.Checked; Width = ((menuViewGamePanel.Checked) ? (MinimumSize.Width + 140) : (MinimumSize.Width)); } /// <summary> /// Handles the Click event of the menuViewNetPanel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuViewNetPanel_Click(object sender, System.EventArgs e) { menuViewNetPanel.Checked = !menuViewNetPanel.Checked; Height = ((menuViewNetPanel.Checked) ? (MinimumSize.Height + 80) : (MinimumSize.Height)); } /// <summary> /// Handles the Click event of the menuViewHint control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuViewHint_Click(object sender, System.EventArgs e) { CheckersUI.ShowHint(); } /// <summary> /// Handles the Click event of the menuViewLastMoved control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuViewLastMoved_Click(object sender, System.EventArgs e) { CheckersUI.ShowLastMove(); } /// <summary> /// Handles the Click event of the menuViewPreferences control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuViewPreferences_Click(object sender, System.EventArgs e) { PreferencesDialog form = new PreferencesDialog(); form.Settings = settings; if(form.ShowDialog(this) == DialogResult.Cancel) return; settings = form.Settings; UpdateBoard(); } /// <summary> /// Handles the Click event of the menuHelpAbout control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuHelpAbout_Click(object sender, System.EventArgs e) { (new frmAbout()).ShowDialog(this); } /// <summary> /// Handles the Popup event of the menuChat control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuChat_Popup(object sender, System.EventArgs e) { menuChatClear.Enabled = txtChat.TextLength > 0; menuChatCopy.Enabled = txtChat.SelectionLength > 0; } /// <summary> /// Handles the Click event of the menuChatCopy control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuChatCopy_Click(object sender, System.EventArgs e) { Clipboard.SetDataObject(txtChat.Text, true); } /// <summary> /// Handles the Click event of the menuChatSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuChatSave_Click(object sender, System.EventArgs e) { if(dlgSaveChat.ShowDialog(this) != DialogResult.OK) return; txtChat.SaveFile(dlgSaveChat.FileName, ((Path.GetExtension(dlgSaveChat.FileName) == ".rtf") ? (RichTextBoxStreamType.RichText) : (RichTextBoxStreamType.PlainText))); } /// <summary> /// Handles the Click event of the menuChatClear control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuChatClear_Click(object sender, System.EventArgs e) { if(MessageBox.Show(this, "Clear the chat window?", "Checkers", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; txtChat.Clear(); } /// <summary> /// Handles the Click event of the menuChatSelectAll control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void menuChatSelectAll_Click(object sender, System.EventArgs e) { txtChat.SelectAll(); } /// <summary> /// Handles the GameStarted event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void CheckersUI_GameStarted(object sender, System.EventArgs e) { DoStarted(); PlaySound(CheckersSounds.Begin); } /// <summary> /// Handles the GameStopped event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void CheckersUI_GameStopped(object sender, System.EventArgs e) { DoStopped(); } /// <summary> /// Handles the TurnChanged event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void CheckersUI_TurnChanged(object sender, System.EventArgs e) { DoNextTurn(); } /// <summary> /// Handles the WinnerDeclared event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void CheckersUI_WinnerDeclared(object sender, System.EventArgs e) { DoWinnerDeclared(); if(((gameType == CheckersGameType.SinglePlayer) || (gameType == CheckersGameType.NetGame)) && (CheckersUI.Winner != 1)) PlaySound(CheckersSounds.Lost); else PlaySound(CheckersSounds.Winner); } /// <summary> /// Handles the PiecePickedUp event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void CheckersUI_PiecePickedUp(object sender, System.EventArgs e) { PlaySound(CheckersSounds.Select); } /// <summary> /// Handles the PieceMoved event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Checkers.UI.MoveEventArgs"/> instance containing the event data.</param> private void CheckersUI_PieceMoved(object sender, Checkers.UI.MoveEventArgs e) { if(!e.IsWinningMove) { if(e.Move.Kinged) PlaySound(CheckersSounds.King); else if(e.Move.Jumped.Length == 1) PlaySound(CheckersSounds.Jump); else if(e.Move.Jumped.Length > 1) PlaySound(CheckersSounds.JumpMultiple); else PlaySound(CheckersSounds.Drop); if((settings.ShowTextFeedback) && (e.MovedByPlayer) && (e.Move.Jumped.Length > 1)) { if((e.Move.Piece.Player == 2) && (gameType != CheckersGameType.Multiplayer)) return; CheckersUI.Text = ""; if(e.Move.Jumped.Length > 3) { tmrTextDisplay.Interval = 2500; CheckersUI.TextBorderColor = Color.White; CheckersUI.ForeColor = Color.LightSalmon; CheckersUI.Text = "INCREDIBLE !!"; } else if(e.Move.Jumped.Length > 2) { tmrTextDisplay.Interval = 2000; CheckersUI.TextBorderColor = Color.White; CheckersUI.ForeColor = Color.RoyalBlue; CheckersUI.Text = "AWESOME !!"; } else { tmrTextDisplay.Interval = 1000; CheckersUI.TextBorderColor = Color.Black; CheckersUI.ForeColor = Color.PaleTurquoise; CheckersUI.Text = "NICE !!"; } tmrTextDisplay.Start(); } } if((gameType == CheckersGameType.NetGame) && (e.MovedByPlayer) && (remotePlayer != null)) DoMovePieceNet(e.Move); } /// <summary> /// Handles the PieceMovedPartial event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Checkers.UI.MoveEventArgs"/> instance containing the event data.</param> private void CheckersUI_PieceMovedPartial(object sender, Checkers.UI.MoveEventArgs e) { if(e.Move.Kinged) PlaySound(CheckersSounds.King); else if(e.Move.Jumped.Length == 1) PlaySound(CheckersSounds.Jump); else if(e.Move.Jumped.Length > 1) PlaySound(CheckersSounds.JumpMultiple); else PlaySound(CheckersSounds.Drop); } /// <summary> /// Handles the PieceBadMove event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Checkers.UI.MoveEventArgs"/> instance containing the event data.</param> private void CheckersUI_PieceBadMove(object sender, Checkers.UI.MoveEventArgs e) { PlaySound(CheckersSounds.BadMove); } /// <summary> /// Handles the PieceDeselected event of the CheckersUI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void CheckersUI_PieceDeselected(object sender, System.EventArgs e) { PlaySound(CheckersSounds.Deselect); } /// <summary> /// Handles the Tick event of the CheckersAgent control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Checkers.AgentTickEventArgs"/> instance containing the event data.</param> private void CheckersAgent_Tick(object sender, AgentTickEventArgs e) { Application.DoEvents(); } /// <summary> /// Handles the Tick event of the tmrTimePassed control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void tmrTimePassed_Tick(object sender, System.EventArgs e) { DoUpdateTimePassed(); } /// <summary> /// Handles the Tick event of the tmrTextDisplay control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void tmrTextDisplay_Tick(object sender, System.EventArgs e) { tmrTextDisplay.Stop(); CheckersUI.Text = ""; } /// <summary> /// Handles the Tick event of the tmrFlashWindow control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void tmrFlashWindow_Tick(object sender, System.EventArgs e) { if(Form.ActiveForm == this) { tmrFlashWindow.Stop(); return; } FlashWindow(Handle, 1); } /// <summary> /// Handles the Tick event of the tmrConnection control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void tmrConnection_Tick(object sender, System.EventArgs e) { if(gameType != CheckersGameType.NetGame) return; CheckForClientMessage(); } /// <summary> /// Handles the LinkClicked event of the lnkLocalIP control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.LinkLabelLinkClickedEventArgs"/> instance containing the event data.</param> private void lnkLocalIP_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { Clipboard.SetDataObject(lnkLocalIP.Text, true); } /// <summary> /// Handles the LinkClicked event of the lnkRemoteIP control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.LinkLabelLinkClickedEventArgs"/> instance containing the event data.</param> private void lnkRemoteIP_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { Clipboard.SetDataObject(lnkRemoteIP.Text, true); } /// <summary> /// Handles the Enter event of the txtSend control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void txtSend_Enter(object sender, System.EventArgs e) { AcceptButton = btnSend; } /// <summary> /// Handles the Leave event of the txtSend control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void txtSend_Leave(object sender, System.EventArgs e) { AcceptButton = null; } /// <summary> /// Handles the Click event of the btnSend control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void btnSend_Click(object sender, System.EventArgs e) { DoSendMessage(); } #endregion #region Game Methods /// <summary> /// Starts a new game. /// </summary> private void DoNewGame() { if((CheckersUI.IsPlaying) || (CheckersUI.Winner != 0)) { if(!DoCloseGame()) return; // Stop current game (with no winner) CheckersUI.Stop(); } // Get new game type NewGameDialog newGame = new NewGameDialog(settings, agentNames); // Set defaults newGame.GameType = gameType; newGame.Player1Name = lblNameP1.Text; newGame.Player2Name = lblNameP2.Text; // Show dialog if(newGame.ShowDialog(this) == DialogResult.Cancel) return; // Set new game parameters gameType = newGame.GameType; agent = null; // Set Game Panel properties lblNameP1.Text = newGame.Player1Name; lblNameP2.Text = newGame.Player2Name; picPawnP1.Image = newGame.ImageSet[0]; picPawnP2.Image = newGame.ImageSet[2]; // Set UI properties switch(gameType) { case CheckersGameType.SinglePlayer: CheckersUI.Player1Active = true; CheckersUI.Player2Active = false; agent = agents[newGame.AgentIndex]; break; case CheckersGameType.Multiplayer: CheckersUI.Player1Active = true; CheckersUI.Player2Active = true; break; case CheckersGameType.NetGame: remotePlayer = newGame.RemotePlayer; if(remotePlayer == null) { MessageBox.Show(this, "Remote user disconnected before the game began", "Checkers", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } CheckersUI.Player1Active = true; CheckersUI.Player2Active = (remotePlayer == null); if(!menuViewNetPanel.Checked) menuViewNetPanel_Click(menuViewNetPanel, EventArgs.Empty); tmrConnection.Start(); panNet.Visible = true; lnkLocalIP.Text = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString(); lnkRemoteIP.Text = ((IPEndPoint)remotePlayer.Socket.RemoteEndPoint).Address.ToString(); AppendMessage("", "Connected to player"); break; default: return; } CheckersUI.CustomPawn1 = newGame.ImageSet[0]; CheckersUI.CustomKing1 = newGame.ImageSet[1]; CheckersUI.CustomPawn2 = newGame.ImageSet[2]; CheckersUI.CustomKing2 = newGame.ImageSet[3]; // Create the new game CheckersGame game = new CheckersGame(); game.FirstMove = newGame.FirstMove; // Start a new checkers game CheckersUI.Play(game); } /// <summary> /// Called after a game is started. /// </summary> private void DoStarted() { if(agent != null) agent.Tick += new AgentTickEventHandler(CheckersAgent_Tick); playTime = DateTime.Now; tmrTimePassed.Start(); DoUpdateTimePassed(); panGameInfo.Visible = true; menuGameEnd.Enabled = true; DoNextTurn(); } /// <summary> /// Called after a game is stopped. /// </summary> private void DoStopped() { if(agent != null) agent.Tick -= new AgentTickEventHandler(CheckersAgent_Tick); panGameInfo.Visible = false; menuGameEnd.Enabled = false; tmrTimePassed.Stop(); txtTimePassed.Text = "0:00"; CheckersUI.Text = ""; } /// <summary> /// Called after a player's turn is up. /// </summary> private void DoNextTurn() { DoShowTurn(CheckersUI.Game.Turn); UpdatePlayerInfo(); if((gameType == CheckersGameType.SinglePlayer) && (CheckersUI.Game.Turn == 2)) { // Move agent after we leave this event BeginInvoke(new DoMoveAgentDelegate(DoMoveAgent)); } } /// <summary> /// Called after a winner is declared. /// </summary> private void DoWinnerDeclared() { UpdatePlayerInfo(); tmrTimePassed.Stop(); DoUpdateTimePassed(); DoShowWinner(CheckersUI.Winner); } /// <summary> /// Called after the game is closed. /// </summary> private bool DoCloseGame() { return DoCloseGame(false); } /// <summary> /// Called after the game is closed. /// </summary> private bool DoCloseGame(bool forced) { if((!CheckersUI.IsPlaying) && (CheckersUI.Winner == 0)) return true; if(CheckersUI.IsPlaying) { if(!forced) { // Confirm the quit if(MessageBox.Show(this, "Quit current game?", "Checkers", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return false; } // Forceful end sound PlaySound(CheckersSounds.ForceEnd); } else { PlaySound(CheckersSounds.EndGame); } picTurn.Visible = false; if(gameType == CheckersGameType.NetGame) { tmrConnection.Stop(); panNet.Visible = false; lnkLocalIP.Text = ""; lnkRemoteIP.Text = ""; if(remotePlayer != null) { try { BinaryWriter bw = new BinaryWriter(new NetworkStream(remotePlayer.Socket, false)); bw.Write((byte)ClientMessage.Closed); remotePlayer.Close(); bw.Close(); } catch(IOException) { } catch(SocketException) { } catch(InvalidOperationException) { } AppendMessage("", "Connection closed"); remotePlayer = null; } } CheckersUI.Stop(); return true; } /// <summary> /// Updates the time passed. /// </summary> private void DoUpdateTimePassed() { TimeSpan time = DateTime.Now.Subtract(playTime); txtTimePassed.Text = ((int)time.TotalMinutes).ToString().PadLeft(2, '0') + ":" + time.Seconds.ToString().PadLeft(2, '0'); } /// <summary> /// Moves the agent. /// </summary> private void DoMoveAgent() { // Do events before moving //Refresh(); Application.DoEvents(); if((gameType == CheckersGameType.SinglePlayer) && (CheckersUI.Game.Turn == 2)) CheckersUI.MovePiece(agent); } /// <summary> /// Shows the current player's turn. /// </summary> private void DoShowTurn(int player) { SuspendLayout(); picTurn.Visible = false; lblNameP1.BackColor = Color.FromKnownColor(KnownColor.Control); lblNameP1.ForeColor = Color.FromKnownColor(KnownColor.ControlText); lblNameP2.BackColor = Color.FromKnownColor(KnownColor.Control); lblNameP2.ForeColor = Color.FromKnownColor(KnownColor.ControlText); if(player == 1) { picTurn.Image = imlTurn.Images[0]; picTurn.Top = picPawnP1.Top + 1; picTurn.Visible = true; lblNameP1.BackColor = Color.FromKnownColor(KnownColor.Highlight); lblNameP1.ForeColor = Color.FromKnownColor(KnownColor.HighlightText); } else if(player == 2) { picTurn.Image = imlTurn.Images[((gameType == CheckersGameType.Multiplayer) ? (0) : (1))]; picTurn.Top = picPawnP2.Top + 1; picTurn.Visible = true; lblNameP2.BackColor = Color.FromKnownColor(KnownColor.Highlight); lblNameP2.ForeColor = Color.FromKnownColor(KnownColor.HighlightText); } ResumeLayout(); } /// <summary> /// Shows the declared winner. /// </summary> private void DoShowWinner(int player) { SuspendLayout(); tmrTextDisplay.Stop(); CheckersUI.Text = ""; CheckersUI.TextBorderColor = Color.White; CheckersUI.ForeColor = Color.Gold; picTurn.Visible = false; lblNameP1.BackColor = Color.FromKnownColor(KnownColor.Control); lblNameP1.ForeColor = Color.FromKnownColor(KnownColor.ControlText); lblNameP2.BackColor = Color.FromKnownColor(KnownColor.Control); lblNameP2.ForeColor = Color.FromKnownColor(KnownColor.ControlText); if(player == 1) { picTurn.Image = imlTurn.Images[2]; picTurn.Top = picPawnP1.Top + 1; picTurn.Visible = true; // Display appropriate message if((gameType == CheckersGameType.SinglePlayer) || (gameType == CheckersGameType.NetGame)) { CheckersUI.Text = "You Win!"; } else { CheckersUI.Text = lblNameP1.Text + "\nWins"; } } else if(player == 2) { picTurn.Image = imlTurn.Images[2]; picTurn.Top = picPawnP2.Top + 1; picTurn.Visible = true; if((gameType == CheckersGameType.SinglePlayer) || (gameType == CheckersGameType.NetGame)) { CheckersUI.ForeColor = Color.Coral; CheckersUI.Text = "You Lose!"; } else { CheckersUI.Text = lblNameP2.Text + "\nWins"; } } ResumeLayout(); } /// <summary> /// Flashes the window. /// </summary> private void DoFlashWindow() { if(Form.ActiveForm == this) return; FlashWindow(Handle, 1); tmrFlashWindow.Start(); } /// <summary> /// Updates the player info. /// </summary> private void UpdatePlayerInfo() { SuspendLayout(); // Update player information txtRemainingP1.Text = CheckersUI.Game.GetRemainingCount(1).ToString(); txtJumpsP1.Text = CheckersUI.Game.GetJumpedCount(2).ToString(); txtRemainingP2.Text = CheckersUI.Game.GetRemainingCount(2).ToString(); txtJumpsP2.Text = CheckersUI.Game.GetJumpedCount(1).ToString(); ResumeLayout(); } /// <summary> /// Sends a message to the opponent. /// </summary> private void DoSendMessage() { if((gameType != CheckersGameType.NetGame) || (remotePlayer == null)) { MessageBox.Show(this, "Not connected to any other players", "Checkers", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if(txtSend.Text.Trim() == "") return; try { BinaryWriter bw = new BinaryWriter(new NetworkStream(remotePlayer.Socket, false)); bw.Write((byte)ClientMessage.ChatMessage); bw.Write(txtSend.Text.Trim()); bw.Close(); } catch(IOException) { } catch(SocketException) { } catch(InvalidOperationException) { } AppendMessage(lblNameP1.Text, txtSend.Text); txtSend.Text = ""; txtSend.Select(); } /// <summary> /// Sends the player's move to the opponent's game. /// </summary> private void DoMovePieceNet(CheckersMove move) { try { BinaryWriter bw = new BinaryWriter(new NetworkStream(remotePlayer.Socket, false)); bw.Write((byte)ClientMessage.MakeMove); bw.Write(move.InitialPiece.Location.X); bw.Write(move.InitialPiece.Location.Y); bw.Write(move.Path.Length); foreach(Point point in move.Path) { bw.Write(point.X); bw.Write(point.Y); } bw.Close(); } catch(IOException) { AppendMessage("", "Connection closed"); CloseNetGame(); remotePlayer = null; } catch(SocketException ex) { AppendMessage("", "Disconnected from opponent: " + ex.Message); CloseNetGame(); remotePlayer = null; } catch(InvalidOperationException ex) { AppendMessage("", "Disconnected from opponent: " + ex.Message); CloseNetGame(); remotePlayer = null; } } /// <summary> /// Updates the board. /// </summary> private void UpdateBoard() { CheckersUI.BackColor = settings.BackColor; CheckersUI.BoardBackColor = settings.BoardBackColor; CheckersUI.BoardForeColor = settings.BoardForeColor; CheckersUI.BoardGridColor = settings.BoardGridColor; CheckersUI.HighlightSelection = settings.HighlightSelection; CheckersUI.HighlightPossibleMoves = settings.HighlightPossibleMoves; CheckersUI.ShowJumpMessage = settings.ShowJumpMessage; } /// <summary> /// Plays a sound. /// </summary> private void PlaySound(CheckersSounds sound) { // Play sound if(settings.MuteSounds) return; string soundFileName = settings.sounds[(int)sound]; string fileName = ((Path.IsPathRooted(soundFileName)) ? (soundFileName) : (Path.GetDirectoryName(Application.ExecutablePath) + "\\Sounds\\" + soundFileName)); // Play sound sndPlaySound(fileName, IntPtr.Zero, (SoundFlags.SND_FileName | SoundFlags.SND_ASYNC | SoundFlags.SND_NOWAIT)); } /// <summary> /// Checks for a message from the opponent. /// </summary> private void CheckForClientMessage() { if(inCheckForClientMessage) return; inCheckForClientMessage = true; if(remotePlayer == null) return; try { NetworkStream ns = new NetworkStream(remotePlayer.Socket, false); BinaryReader br = new BinaryReader(ns); BinaryWriter bw = new BinaryWriter(ns); while(ns.DataAvailable) { switch((ClientMessage)br.ReadByte()) { case ClientMessage.Closed: throw new IOException(); case ClientMessage.ChatMessage: AppendMessage(lblNameP2.Text, br.ReadString()); if(settings.FlashWindowOnGameEvents) DoFlashWindow(); break; case ClientMessage.AbortGame: AppendMessage("", "Game has been aborted by opponent"); CloseNetGame(); break; case ClientMessage.MakeMove: if(CheckersUI.Game.Turn != 2) { AppendMessage("", "Opponent took turn out of place; game aborted"); CloseNetGame(); bw.Write((byte)ClientMessage.AbortGame); break; } // Get move Point location = RotateOpponentPiece(br); CheckersPiece piece = CheckersUI.Game.PieceAt(location); int count = br.ReadInt32(); Point[] path = new Point[count]; for(int i = 0; i < count; i++) path[i] = RotateOpponentPiece(br); // Move the piece an break if successful if(piece != null) { if(CheckersUI.MovePiece(piece, path, true, true)) { if(settings.FlashWindowOnTurn) DoFlashWindow(); break; } } AppendMessage("", "Opponent made a bad move; game aborted"); CloseNetGame(); bw.Write((byte)ClientMessage.AbortGame); break; } } br.Close(); bw.Close(); } catch(IOException) { AppendMessage("", "Connection closed"); CloseNetGame(); remotePlayer = null; } catch(SocketException ex) { AppendMessage("", "Disconnected from opponent: " + ex.Message); CloseNetGame(); remotePlayer = null; } catch(InvalidOperationException ex) { AppendMessage("", "Disconnected from opponent: " + ex.Message); CloseNetGame(); remotePlayer = null; } inCheckForClientMessage = false; } /// <summary> /// Closes the network game. /// </summary> private void CloseNetGame() { if(settings.FlashWindowOnGameEvents) DoFlashWindow(); if(CheckersUI.IsPlaying) CheckersUI.Game.DeclareStalemate(); } /// <summary> /// Appends a new message. /// </summary> private void AppendMessage(string name, string message) { txtChat.SelectionStart = txtChat.TextLength; txtChat.SelectionLength = 0; if(name == "") { txtChat.SelectionColor = Color.Red; txtChat.AppendText("[" + DateTime.Now.ToShortTimeString() + "] "); } else if(name == lblNameP1.Text) { txtChat.SelectionColor = Color.Red; txtChat.AppendText("[" + DateTime.Now.ToShortTimeString() + "] "); txtChat.AppendText(" " + name + ": "); txtChat.SelectionColor = Color.Black; PlaySound(CheckersSounds.SendMessage); } else { txtChat.SelectionColor = Color.Blue; txtChat.AppendText("[" + DateTime.Now.ToShortTimeString() + "] "); txtChat.AppendText(" " + name + ": "); txtChat.SelectionColor = Color.Black; PlaySound(CheckersSounds.ReceiveMessage); } txtChat.AppendText(message); txtChat.AppendText("\n"); txtChat.Select(txtChat.TextLength, 0); txtChat.ScrollToCaret(); int min = 0, max = 0; GetScrollRange(txtChat.Handle, 1, ref min, ref max); SendMessage(txtChat.Handle, EM_SETSCROLLPOS, 0, new Win32Point(0, max - txtChat.Height)); } /// <summary> /// Rotates the opponent's incoming piece. /// </summary> private Point RotateOpponentPiece(BinaryReader br) { int x = br.ReadInt32(); int y = br.ReadInt32(); return RotateOpponentPiece(new Point(x, y)); } /// <summary> /// Rotates the opponent's incoming piece. /// </summary> private Point RotateOpponentPiece(Point location) { return new Point(CheckersGame.BoardSize.Width - location.X - 1, CheckersGame.BoardSize.Height - location.Y - 1); } #endregion #region Win32 Members [DllImport("user32", EntryPoint = "GetScrollRange", SetLastError = true, CallingConvention = CallingConvention.Winapi)] private static extern int GetScrollRange(IntPtr hWnd, int nBar, ref int lpMinPos, ref int lpMaxPos); [DllImport("user32", EntryPoint = "SendMessageA", ExactSpelling = true, SetLastError = true, CallingConvention = CallingConvention.Winapi)] private static extern int SendMessage(IntPtr hWnd, int ByVal, int wParam, Win32Point lParam); [StructLayout(LayoutKind.Sequential)] private class Win32Point { public int x; public int y; public Win32Point() { x = 0; y = 0; } public Win32Point(int x, int y) { this.x = x; this.y = y; } } private static readonly int EM_SETSCROLLPOS = 0x400 + 222; [DllImport("user32", EntryPoint = "FlashWindow", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] private static extern int FlashWindow(IntPtr hWnd, int bInvert); [DllImport("winmm.dll", EntryPoint = "PlaySound", SetLastError = true, CallingConvention = CallingConvention.Winapi)] private static extern bool sndPlaySound(string pszSound, IntPtr hMod, SoundFlags sf); [Flags] public enum SoundFlags : int { SND_SYNC = 0x0000, /* play synchronously (default) */ SND_ASYNC = 0x0001, /* play asynchronously */ SND_NODEFAULT = 0x0002, /* silence (!default) if sound not found */ SND_MEMORY = 0x0004, /* pszSound points to a memory file */ SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */ SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */ SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */ SND_ALIAS = 0x00010000, /* name is a registry alias */ SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */ SND_FileName = 0x00020000, /* name is file name */ SND_RESOURCE = 0x00040004 /* name is resource name or atom */ } #endregion private delegate void DoMoveAgentDelegate(); private readonly CheckersAgent[] agents = { new MinMaxSimpleAgent(0), new MinMaxSimpleAgent(1), new MinMaxSimpleAgent(2), new MinMaxSimpleAgent(3), new MinMaxComplexAgent(3) }; private readonly string[] agentNames = { "Beginner", "Intermediate", "Advanced", "Expert", "Uber (Experimental)" }; private CheckersGameType gameType = CheckersGameType.None; private CheckersAgent agent = null; private CheckersSettings settings; private DateTime playTime; private MenuItem menuViewHint; private TcpClient remotePlayer = null; private bool inCheckForClientMessage = false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Text; using Xunit; namespace System.Tests { public class CharTests { [Theory] [InlineData('h', 'h', 0)] [InlineData('h', 'a', 1)] [InlineData('h', 'z', -1)] [InlineData('h', null, 1)] public void CompareTo_Other_ReturnsExpected(char c, object value, int expected) { if (value is char charValue) { Assert.Equal(expected, Math.Sign(c.CompareTo(charValue))); } Assert.Equal(expected, Math.Sign(c.CompareTo(value))); } [Theory] [InlineData("a")] [InlineData(234)] public void CompareTo_ObjectNotDouble_ThrowsArgumentException(object value) { AssertExtensions.Throws<ArgumentException>(null, () => ((char)123).CompareTo(value)); } public static IEnumerable<object[]> ConvertFromUtf32_TestData() { yield return new object[] { 0x10000, "\uD800\uDC00" }; yield return new object[] { 0x103FF, "\uD800\uDFFF" }; yield return new object[] { 0xFFFFF, "\uDBBF\uDFFF" }; yield return new object[] { 0x10FC00, "\uDBFF\uDC00" }; yield return new object[] { 0x10FFFF, "\uDBFF\uDFFF" }; yield return new object[] { 0, "\0" }; yield return new object[] { 0x3FF, "\u03FF" }; yield return new object[] { 0xE000, "\uE000" }; yield return new object[] { 0xFFFF, "\uFFFF" }; } [Theory] [MemberData(nameof(ConvertFromUtf32_TestData))] public static void ConvertFromUtf32(int utf32, string expected) { Assert.Equal(expected, char.ConvertFromUtf32(utf32)); } [Theory] [InlineData(0xD800)] [InlineData(0xDC00)] [InlineData(0xDFFF)] [InlineData(0x110000)] [InlineData(-1)] [InlineData(int.MaxValue)] [InlineData(int.MinValue)] public static void ConvertFromUtf32_InvalidUtf32_ThrowsArgumentOutOfRangeException(int utf32) { AssertExtensions.Throws<ArgumentOutOfRangeException>("utf32", () => char.ConvertFromUtf32(utf32)); } public static IEnumerable<object[]> ConvertToUtf32_String_Int_TestData() { yield return new object[] { "\uD800\uDC00", 0, 0x10000 }; yield return new object[] { "\uDBBF\uDFFF", 0, 0xFFFFF }; yield return new object[] { "\uDBFF\uDC00", 0, 0x10FC00 }; yield return new object[] { "\uDBFF\uDFFF", 0, 0x10FFFF }; yield return new object[] { "\u0000\u0001", 0, 0 }; yield return new object[] { "\u0000\u0001", 1, 1 }; yield return new object[] { "\u0000", 0, 0 }; yield return new object[] { "\u0020\uD7FF", 0, 32 }; yield return new object[] { "\u0020\uD7FF", 1, 0xD7FF }; yield return new object[] { "abcde", 4, 'e' }; // Invalid unicode yield return new object[] { "\uD800\uD800\uDFFF", 1, 0x103FF }; yield return new object[] { "\uD800\uD7FF", 1, 0xD7FF }; // High, non-surrogate yield return new object[] { "\uD800\u0000", 1, 0 }; // High, non-surrogate yield return new object[] { "\uDF01\u0000", 1, 0 }; // Low, non-surrogate } [Theory] [MemberData(nameof(ConvertToUtf32_String_Int_TestData))] public static void ConvertToUtf32_String_Int(string s, int index, int expected) { Assert.Equal(expected, char.ConvertToUtf32(s, index)); } [Fact] public static void ConvertToUtf32_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.ConvertToUtf32(null, 0)); // String is null AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 0)); // High, high AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 1)); // High, high AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD7FF", 0)); // High, non-surrogate AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\u0000", 0)); // High, non-surrogate AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 0)); // Low, high AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 1)); // Low, high AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 0)); // Low, low AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 1)); // Low, hig AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDF01\u0000", 0)); // Low, non-surrogateh AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", 5)); // Index >= string.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("", 0)); // Index >= string.Length } public static IEnumerable<object[]> ConvertToUtf32_Char_Char_TestData() { yield return new object[] { '\uD800', '\uDC00', 0x10000 }; yield return new object[] { '\uD800', '\uDFFF', 0x103FF }; yield return new object[] { '\uDBBF', '\uDFFF', 0xFFFFF }; yield return new object[] { '\uDBFF', '\uDC00', 0x10FC00 }; yield return new object[] { '\uDBFF', '\uDFFF', 0x10FFFF }; } [Theory] [MemberData(nameof(ConvertToUtf32_Char_Char_TestData))] public static void ConvertToUtf32_Char_Char(char highSurrogate, char lowSurrogate, int expected) { Assert.Equal(expected, char.ConvertToUtf32(highSurrogate, lowSurrogate)); } [Fact] public static void ConvertToUtf32_Char_Char_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD800')); // High, high AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD7FF')); // High, non-surrogate AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\u0000')); // High, non-surrogate AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDD00', '\uDE00')); // Low, low AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDC01', '\uD940')); // Low, high AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDF01', '\u0000')); // Low, non-surrogate AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0032', '\uD7FF')); // Non-surrogate, non-surrogate AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0000', '\u0000')); // Non-surrogate, non-surrogate } [Theory] [InlineData('a', 'a', true)] [InlineData('a', 'A', false)] [InlineData('a', 'b', false)] [InlineData('a', (int)'a', false)] [InlineData('a', "a", false)] [InlineData('a', null, false)] public static void Equals(char c, object obj, bool expected) { if (obj is char) { Assert.Equal(expected, c.Equals((char)obj)); Assert.Equal(expected, c.GetHashCode().Equals(obj.GetHashCode())); } Assert.Equal(expected, c.Equals(obj)); } [Theory] [InlineData('0', 0)] [InlineData('9', 9)] [InlineData('T', -1)] public static void GetNumericValue_Char(char c, int expected) { Assert.Equal(expected, char.GetNumericValue(c)); } [Theory] [InlineData("\uD800\uDD07", 0, 1)] [InlineData("9", 0, 9)] [InlineData("99", 1, 9)] [InlineData(" 7 ", 1, 7)] [InlineData("Test 7", 5, 7)] [InlineData("T", 0, -1)] public static void GetNumericValue_String_Int(string s, int index, int expected) { Assert.Equal(expected, char.GetNumericValue(s, index)); } [Fact] public static void GetNumericValue_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.GetNumericValue(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", 3)); // Index >= string.Length } [Fact] public void GetTypeCode_Invoke_ReturnsBoolean() { Assert.Equal(TypeCode.Char, 'a'.GetTypeCode()); } [Fact] public static void IsControl_Char() { foreach (char c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c)); } [Fact] public static void IsControl_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c.ToString(), 0)); } [Fact] public static void IsControl_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsControl(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", 3)); // Index >= string.Length } [Fact] public static void IsDigit_Char() { foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c)); } [Fact] public static void IsDigit_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c.ToString(), 0)); } [Fact] public static void IsDigit_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsDigit(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", 3)); // Index >= string.Length } [Fact] public static void IsLetter_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetter(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetter(c)); } [Fact] public static void IsLetter_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetter(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetter(c.ToString(), 0)); } [Fact] public static void IsLetter_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLetter(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", 3)); // Index >= string.Length } [Fact] public static void IsLetterOrDigit_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetterOrDigit(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetterOrDigit(c)); } [Fact] public static void IsLetterOrDigit_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetterOrDigit(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetterOrDigit(c.ToString(), 0)); } [Fact] public static void IsLetterOrDigit_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLetterOrDigit(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", 3)); // Index >= string.Length } [Fact] public static void IsLower_Char() { foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c)); } [Fact] public static void IsLower_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c.ToString(), 0)); } [Fact] public static void IsLower_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLower(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", 3)); // Index >= string.Length } [Fact] public static void IsNumber_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsNumber(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsNumber(c)); } [Fact] public static void IsNumber_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsNumber(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsNumber(c.ToString(), 0)); } [Fact] public static void IsNumber_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsNumber(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", 3)); // Index >= string.Length } [Fact] public static void IsPunctuation_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsPunctuation(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsPunctuation(c)); } [Fact] public static void IsPunctuation_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsPunctuation(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsPunctuation(c.ToString(), 0)); } [Fact] public static void IsPunctuation_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsPunctuation(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", 3)); // Index >= string.Length } [Fact] public static void IsSeparator_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSeparator(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSeparator(c)); } [Fact] public static void IsSeparator_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSeparator(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSeparator(c.ToString(), 0)); } [Fact] public static void IsSeparator_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSeparator(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", 3)); // Index >= string.Length } [Fact] public static void IsLowSurrogate_Char() { foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c)); } [Fact] public static void IsLowSurrogate_String_Int() { foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); } [Fact] public static void IsLowSurrogate_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLowSurrogate(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void IsHighSurrogate_Char() { foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c)); } [Fact] public static void IsHighSurrogate_String_Int() { foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); } [Fact] public static void IsHighSurrogate_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsHighSurrogate(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void IsSurrogate_Char() { foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c)); } [Fact] public static void IsSurrogate_String_Int() { foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c.ToString(), 0)); } [Fact] public static void IsSurrogate_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSurrogate(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void IsSurrogatePair_Char() { foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(char.IsSurrogatePair(hs, ls)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(char.IsSurrogatePair(hs, ls)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(char.IsSurrogatePair(hs, ls)); } [Fact] public static void IsSurrogatePair_String_Int() { foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0)); Assert.False(char.IsSurrogatePair("\ud800\udc00", 1)); // Index + 1 >= s.Length } [Fact] public static void IsSurrogatePair_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSurrogatePair(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", 3)); // Index >= string.Length } [Fact] public static void IsSymbol_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSymbol(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSymbol(c)); } [Fact] public static void IsSymbol_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSymbol(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSymbol(c.ToString(), 0)); } [Fact] public static void IsSymbol_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSymbol(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", 3)); // Index >= string.Length } [Fact] public static void IsUpper_Char() { foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c)); } [Fact] public static void IsUpper_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c.ToString(), 0)); } [Fact] public static void IsUpper_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsUpper(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", 3)); // Index >= string.Length } [Fact] public static void IsWhitespace_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsWhiteSpace(c)); foreach (char c in GetTestCharsNotInCategory(categories)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c)); } } [Fact] public static void IsWhiteSpace_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsWhiteSpace(c.ToString(), 0)); // Some control chars are also considered whitespace for legacy reasons. // if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') Assert.True(char.IsWhiteSpace("\u000b", 0)); Assert.True(char.IsWhiteSpace("\u0085", 0)); foreach (char c in GetTestCharsNotInCategory(categories)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c.ToString(), 0)); } } [Fact] public static void IsWhiteSpace_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsWhiteSpace(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", 3)); // Index >= string.Length } [Fact] public static void MaxValue() { Assert.Equal(0xffff, char.MaxValue); } [Fact] public static void MinValue() { Assert.Equal(0, char.MinValue); } [Fact] public static void ToLower() { Assert.Equal('a', char.ToLower('A')); Assert.Equal('a', char.ToLower('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLower(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToLower(c)); } } [Fact] public static void ToLowerInvariant() { Assert.Equal('a', char.ToLowerInvariant('A')); Assert.Equal('a', char.ToLowerInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLowerInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToLowerInvariant(c)); } } [Theory] [InlineData('a', "a")] [InlineData('\uabcd', "\uabcd")] public static void ToString(char c, string expected) { Assert.Equal(expected, c.ToString()); Assert.Equal(expected, char.ToString(c)); } [Fact] public static void ToUpper() { Assert.Equal('A', char.ToUpper('A')); Assert.Equal('A', char.ToUpper('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpper(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToUpper(c)); } } [Fact] public static void ToUpperInvariant() { Assert.Equal('A', char.ToUpperInvariant('A')); Assert.Equal('A', char.ToUpperInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpperInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToUpperInvariant(c)); } } public static IEnumerable<object[]> Parse_TestData() { yield return new object[] { "a", 'a' }; yield return new object[] { "4", '4' }; yield return new object[] { " ", ' ' }; yield return new object[] { "\n", '\n' }; yield return new object[] { "\0", '\0' }; yield return new object[] { "\u0135", '\u0135' }; yield return new object[] { "\u05d9", '\u05d9' }; yield return new object[] { "\ue001", '\ue001' }; // Private use codepoint // Lone surrogate yield return new object[] { "\ud801", '\ud801' }; // High surrogate yield return new object[] { "\udc01", '\udc01' }; // Low surrogate } [Theory] [MemberData(nameof(Parse_TestData))] public static void Parse(string s, char expected) { char c; Assert.True(char.TryParse(s, out c)); Assert.Equal(expected, c); Assert.Equal(expected, char.Parse(s)); } [Theory] [InlineData(null, typeof(ArgumentNullException))] [InlineData("", typeof(FormatException))] [InlineData("\n\r", typeof(FormatException))] [InlineData("kj", typeof(FormatException))] [InlineData(" a", typeof(FormatException))] [InlineData("a ", typeof(FormatException))] [InlineData("\\u0135", typeof(FormatException))] [InlineData("\u01356", typeof(FormatException))] [InlineData("\ud801\udc01", typeof(FormatException))] // Surrogate pair public static void Parse_Invalid(string s, Type exceptionType) { char c; Assert.False(char.TryParse(s, out c)); Assert.Equal(default(char), c); Assert.Throws(exceptionType, () => char.Parse(s)); } private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories) { Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length); for (int i = 0; i < s_latinTestSet.Length; i++) { if (Array.Exists(categories, uc => uc == (UnicodeCategory)i)) continue; char[] latinSet = s_latinTestSet[i]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[i]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories) { for (int i = 0; i < categories.Length; i++) { char[] latinSet = s_latinTestSet[(int)categories[i]]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[(int)categories[i]]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static char[][] s_latinTestSet = new char[][] { new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter new char[] {}, // UnicodeCategory.TitlecaseLetter new char[] {}, // UnicodeCategory.ModifierLetter new char[] {}, // UnicodeCategory.OtherLetter new char[] {}, // UnicodeCategory.NonSpacingMark new char[] {}, // UnicodeCategory.SpacingCombiningMark new char[] {}, // UnicodeCategory.EnclosingMark new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber new char[] {}, // UnicodeCategory.LetterNumber new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator new char[] {}, // UnicodeCategory.LineSeparator new char[] {}, // UnicodeCategory.ParagraphSeparator new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control new char[] {}, // UnicodeCategory.Format new char[] {}, // UnicodeCategory.Surrogate new char[] {}, // UnicodeCategory.PrivateUse new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol new char[] {}, // UnicodeCategory.OtherNotAssigned }; private static char[][] s_unicodeTestSet = new char[][] { new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u1b44','\ua8b5' }, // UnicodeCategory.SpacingCombiningMark new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator new char[] {'\u2028'}, // UnicodeCategory.LineSeparator new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator new char[] {}, // UnicodeCategory.Control new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol new char[] {'\u09c6','\u0dfa','\u2e5c'}, // UnicodeCategory.OtherNotAssigned }; private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // Range from '\ud800' to '\udbff' private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // Range from '\udc00' to '\udfff' private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' }; private static readonly UnicodeCategory[] s_categoryForLatin1 = { UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0000 - 0007 UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0008 - 000F UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0010 - 0017 UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0018 - 001F UnicodeCategory.SpaceSeparator, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, // 0020 - 0027 UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.OtherPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, // 0028 - 002F UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, // 0030 - 0037 UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.OtherPunctuation, // 0038 - 003F UnicodeCategory.OtherPunctuation, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0040 - 0047 UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0048 - 004F UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0050 - 0057 UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.OpenPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.ModifierSymbol, UnicodeCategory.ConnectorPunctuation, // 0058 - 005F UnicodeCategory.ModifierSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0060 - 0067 UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0068 - 006F UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0070 - 0077 UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.OpenPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.ClosePunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.Control, // 0078 - 007F UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0080 - 0087 UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0088 - 008F UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0090 - 0097 UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0098 - 009F UnicodeCategory.SpaceSeparator, UnicodeCategory.OtherPunctuation, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol, UnicodeCategory.OtherSymbol, // 00A0 - 00A7 UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.DashPunctuation, UnicodeCategory.OtherSymbol, UnicodeCategory.ModifierSymbol, // 00A8 - 00AF UnicodeCategory.OtherSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.ModifierSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.OtherSymbol, UnicodeCategory.OtherPunctuation, // 00B0 - 00B7 UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherNumber, UnicodeCategory.LowercaseLetter, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.OtherPunctuation, // 00B8 - 00BF UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 00C0 - 00C7 UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 00C8 - 00CF UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.MathSymbol, // 00D0 - 00D7 UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, // 00D8 - 00DF UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00E0 - 00E7 UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00E8 - 00EF UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.MathSymbol, // 00F0 - 00F7 UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00F8 - 00FF }; public static IEnumerable<object[]> UpperLowerCasing_TestData() { // lower upper Culture yield return new object[] { 'a', 'A', "en-US" }; yield return new object[] { 'i', 'I', "en-US" }; yield return new object[] { '\u0131', 'I', "tr-TR" }; yield return new object[] { 'i', '\u0130', "tr-TR" }; yield return new object[] { '\u0660', '\u0660', "en-US" }; } [Fact] public static void LatinRangeTest() { StringBuilder sb = new StringBuilder(256); string latineString = sb.ToString(); for (int i=0; i < latineString.Length; i++) { Assert.Equal(s_categoryForLatin1[i], char.GetUnicodeCategory(latineString[i])); Assert.Equal(s_categoryForLatin1[i], char.GetUnicodeCategory(latineString, i)); } } [Fact] public static void NonLatinRangeTest() { for (int i=256; i <= 0xFFFF; i++) { Assert.Equal(CharUnicodeInfo.GetUnicodeCategory((char)i), char.GetUnicodeCategory((char)i)); } string nonLatinString = "\u0100\u0200\u0300\u0400\u0500\u0600\u0700\u0800\u0900\u0A00\u0B00\u0C00\u0D00\u0E00\u0F00" + "\u1000\u2000\u3000\u4000\u5000\u6000\u7000\u8000\u9000\uA000\uB000\uC000\uD000\uE000\uF000"; for (int i=0; i < nonLatinString.Length; i++) { Assert.Equal(CharUnicodeInfo.GetUnicodeCategory(nonLatinString[i]), char.GetUnicodeCategory(nonLatinString, i)); } } [Theory] [MemberData(nameof(UpperLowerCasing_TestData))] public static void CasingTest(char lowerForm, char upperForm, string cultureName) { CultureInfo ci = CultureInfo.GetCultureInfo(cultureName); Assert.Equal(lowerForm, char.ToLower(upperForm, ci)); Assert.Equal(upperForm, char.ToUpper(lowerForm, ci)); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; namespace IronPythonTest { public enum DeTestEnum { Value_0, Value_1, Value_2, Value_3, Value_4 } public enum DeTestEnumLong : long { Value_1 = 12345678901234L, Value_2 = 43210987654321L } public struct DeTestStruct { public int intVal; //public string stringVal; //public float floatVal; //public double doubleVal; //public DeTestEnum eshort; //public DeTestEnumLong elong; #pragma warning disable 169 void Init() { intVal = 0; //stringVal = "Hello"; //floatVal = 0; //doubleVal = 0; //eshort = DeTestEnum.Value_3; //elong = DeTestEnumLong.Value_2; } #pragma warning restore 169 } public class DeTest { public delegate DeTestStruct TestStruct(DeTestStruct dts); public delegate string TestTrivial(string s1); public delegate string TestStringDelegate(string s1, string s2, string s3, string s4, string s5, string s6); public delegate int TestEnumDelegate(DeTestEnum e); public delegate long TestEnumDelegateLong(DeTestEnumLong e); public delegate string TestComplexDelegate(string s, int i, float f, double d, DeTestEnum e, string s2, DeTestEnum e2, DeTestEnumLong e3); public event TestStruct e_struct; public event TestTrivial e_tt; public event TestTrivial e_tt2; public event TestStringDelegate e_tsd; public event TestEnumDelegate e_ted; public event TestComplexDelegate e_tcd; public event TestEnumDelegateLong e_tedl; public TestStruct d_struct; public TestTrivial d_tt; public TestTrivial d_tt2; public TestStringDelegate d_tsd; public TestEnumDelegate d_ted; public TestComplexDelegate d_tcd; public TestEnumDelegateLong d_tedl; public string stringVal; public string stringVal2; public int intVal; public float floatVal; public double doubleVal; public DeTestEnum enumVal; public DeTestEnumLong longEnumVal; public DeTest() { } public void Init() { e_struct = ActualTestStruct; e_tt = VoidTestTrivial; e_tsd = VoidTestString; e_ted = VoidTestEnum; e_tedl = VoidTestEnumLong; e_tcd = VoidTestComplex; e_struct = ActualTestStruct; d_tt = VoidTestTrivial; d_tsd = VoidTestString; d_ted = VoidTestEnum; d_tedl = VoidTestEnumLong; d_tcd = VoidTestComplex; } public void RunTest() { if (e_struct != null) { DeTestStruct dts; dts.intVal = intVal; //dts.stringVal = stringVal; //dts.floatVal = floatVal; //dts.doubleVal = doubleVal; //dts.elong = longEnumVal; //dts.eshort = enumVal; e_struct(dts); } if (e_tt != null) { e_tt(stringVal); } if (e_tt2 != null) { e_tt2(stringVal2); } if (d_tt != null) { d_tt(stringVal); } if (e_tsd != null) { e_tsd(stringVal, stringVal2, stringVal, stringVal2, stringVal, stringVal2); } if (d_tsd != null) { d_tsd(stringVal, stringVal2, stringVal, stringVal2, stringVal, stringVal2); } if (e_ted != null) { e_ted(enumVal); } if (d_ted != null) { d_ted(enumVal); } if (e_tedl != null) { e_tedl(longEnumVal); } if (d_tedl != null) { d_tedl(longEnumVal); } if (e_tcd != null) { e_tcd(stringVal, intVal, floatVal, doubleVal, enumVal, stringVal2, enumVal, longEnumVal); } if (d_tcd != null) { d_tcd(stringVal, intVal, floatVal, doubleVal, enumVal, stringVal2, enumVal, longEnumVal); } } public DeTestStruct ActualTestStruct(DeTestStruct dts) { object x = dts; return (DeTestStruct)x; } public string ActualTestTrivial(string s1) { return s1; } public string VoidTestTrivial(string s1) { return String.Empty; } public string ActualTestString(string s1, string s2, string s3, string s4, string s5, string s6) { return s1 + " " + s2 + " " + s3 + " " + s4 + " " + s5 + " " + s6; } public string VoidTestString(string s1, string s2, string s3, string s4, string s5, string s6) { return String.Empty; } public int ActualTestEnum(DeTestEnum e) { return (int)e + 1000; } public int VoidTestEnum(DeTestEnum e) { return 0; } public long ActualTestEnumLong(DeTestEnumLong e) { return (long)e + 1000000000; } public long VoidTestEnumLong(DeTestEnumLong e) { return 0; } public string ActualTestComplex(string s, int i, float f, double d, DeTestEnum e, string s2, DeTestEnum e2, DeTestEnumLong e3) { return s + " " + i.ToString() + " " + f.ToString() + " " + d.ToString() + " " + s2 + " " + e2.ToString() + " " + e3.ToString(); } public string VoidTestComplex(string s, int i, float f, double d, DeTestEnum e, string s2, DeTestEnum e2, DeTestEnumLong e3) { return String.Empty; } public void SetupE() { e_tt = ActualTestTrivial; e_tt2 = ActualTestTrivial; e_tsd = ActualTestString; e_ted = ActualTestEnum; e_tedl = ActualTestEnumLong; e_tcd = ActualTestComplex; } public void SetupS() { e_struct += ActualTestStruct; e_struct += ActualTestStruct; } public void SetupD() { d_tt = ActualTestTrivial; d_tt2 = ActualTestTrivial; d_tsd = ActualTestString; d_ted = ActualTestEnum; d_tedl = ActualTestEnumLong; d_tcd = ActualTestComplex; } public void Setup() { SetupE(); SetupD(); } public static DeTestStruct staticDeTestStruct(object o, DeTestStruct dts) { object oo = dts; return (DeTestStruct)oo; } public static void Test() { DeTest dt = new DeTest(); dt.SetupS(); dt.RunTest(); } } public delegate float FloatDelegate(float f); public class ReturnTypes { public event FloatDelegate floatEvent; public float RunFloat(float f) { return floatEvent(f); } } public delegate void VoidDelegate(); public class SimpleType { public event VoidDelegate SimpleEvent; public void RaiseEvent() { if (SimpleEvent != null) SimpleEvent(); } } }
/* * Copyright (c) 2010, www.wojilu.com. All rights reserved. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using wojilu.Web.Mvc; using wojilu.Web.Context; using wojilu.Apps.Forum.Domain; using wojilu.Apps.Forum.Service; using wojilu.Members.Groups.Domain; namespace wojilu.Web.Controller.Forum.Utils { public class ForumLocationUtil { public static readonly String separator = "&rsaquo;&rsaquo;"; private static String alang( MvcContext ctx, String key ) { return ctx.controller.alang( key ); } public static String GetBoard( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); int length = separator.Length + 1; sb.Remove( sb.Length - length, separator.Length ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetRecent( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.Append( alang( ctx, "recentPostList" ) ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetTopicRecent( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.Append( alang( ctx, "recentTopicList" ) ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetPostRecent( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.Append( alang( ctx, "allRecentPost" ) ); sb.Append( "</div></div>" ); return sb.ToString(); } //------------------------------------------ public static String GetPollAdd( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.Append( "<span style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pAddPoll" ) + "</span>" ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetQuestionAdd( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.Append( "<span style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pAddQuestion" ) + "</span>" ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetReply( List<ForumBoard> boards, ForumTopic topic, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.AppendFormat( "<a href=\"{0}\" style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pReply" ) + ": {1}</a>", alink.ToAppData( topic ), topic.Title ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetSetReward( List<ForumBoard> boards, ForumTopic topic, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.AppendFormat( "<span style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pReward" ) + ": <a href=\"{0}\">{1}</a></span>", alink.ToAppData( topic ), topic.Title ); sb.Append( "</div></div>" ); return sb.ToString(); } //-------------------- public static String GetPost( List<ForumBoard> boards, ForumPost post, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.AppendFormat( "<a href=\"{0}\" style=\"margin-left:5px;\">" + alang( ctx, "pPost" ) + ": {1}</a>", alink.ToAppData( post ), post.Title ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetPostEdit( List<ForumBoard> boards, ForumPost post, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.AppendFormat( "<span style=\"margin-left:5px;\">" + alang( ctx, "pPostEdit" ) + ": <a href=\"{0}\">{1}</a></span>", alink.ToAppData( post ), post.Title ); sb.Append( "</div></div>" ); return sb.ToString(); } //------------------------- public static String GetTopic( List<ForumBoard> boards, ForumTopic topic, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); String url = LinkUtil.appendListPageToTopic( alink.ToAppData( topic ), ctx ); sb.AppendFormat( "<a href=\"{0}\" style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pTopic" ) + ": {1}</a>", url, topic.Title ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetTopicAdd( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.Append( "<span style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pAddTopic" ) + "</span>" ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetTopicSort( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.Append( "<span style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pSortStickyTopic" ) + "</span>" ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetGlobalTopicSort( MvcContext ctx ) { StringBuilder sb = getBuilder( null, ctx ); sb.Append( "<span style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pSortStickyTopic" ) + "</span>" ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetTopicEdit( List<ForumBoard> boards, ForumTopic topic, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.AppendFormat( "<span style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pTopicEdit" ) + ": <a href=\"{0}\">{1}</a></span>", alink.ToAppData( topic ), topic.Title ); //sb.AppendFormat( "<span style=\"font-weight:normal;margin-left:5px;\">" + alang( ctx, "pTopicEdit" ) + ": {0}</span>", topic.Title ); sb.Append( "</div></div>" ); return sb.ToString(); } public static String GetTopicAttachment( List<ForumBoard> boards, ForumTopic topic, MvcContext ctx ) { StringBuilder sb = getBuilder( boards, ctx ); sb.AppendFormat( "<a href=\"{0}\" style=\"font-weight:normal;margin-left:5px;\">{1}</a>", alink.ToAppData( topic ), topic.Title ); sb.Append( "</div></div>" ); return sb.ToString(); } //---------------------------------------------------------------------------------------------------------------------------- private static StringBuilder getBuilder( List<ForumBoard> boards, MvcContext ctx ) { StringBuilder sb = new StringBuilder( "<div id=\"forumLocationContainer\"><div id=\"forumLocation\">" ); appendAppBoard( sb, boards, ctx ); return sb; } private static void appendAppBoard( StringBuilder sb, List<ForumBoard> boards, MvcContext ctx ) { appendApp( sb, ctx ); appendBoard( sb, boards, ctx ); } private static void appendApp( StringBuilder sb, MvcContext ctx ) { if (ctx.owner.obj.GetType() == typeof( Group )) { } else { sb.Append( "<span style=\"\" class=\"menuMore\" list=\"locationBoards\">" ); sb.AppendFormat( "<a href=\"{0}\" id=\"locationHome\">{1} <img src=\"{2}down.gif\" /></a>", ctx.GetLink().To( new ForumController().Index ), ((AppContext)ctx.app).UserApp.Name, sys.Path.Img ); addLocationMenu( sb, ctx ); sb.Append( "</span>" ); sb.Append( " " ); sb.Append( separator ); sb.Append( " " ); } } private static void addLocationMenu( StringBuilder sb, MvcContext ctx ) { sb.Append( "<div class=\"menuItems\" id=\"locationBoards\">" ); ForumBoardService service = new ForumBoardService(); Tree<ForumBoard> tree = new Tree<ForumBoard>( service.GetBoardAll( ctx.app.Id, ctx.viewer.IsLogin ) ); List<ForumBoard> categories = tree.GetRoots(); foreach (ForumBoard category in categories) { sb.AppendFormat( "<div class=\"forum_location_category\">{0}</div>", category.Name ); sb.Append( "<div class=\"forum_location_forums\">" ); List<ForumBoard> children = tree.GetChildren( category.Id ); foreach (ForumBoard board in children) { sb.AppendFormat( "<a href=\"{0}\">{1}</a> ", alink.ToAppData( board ), board.Name ); } sb.Append( "</div>" ); } sb.Append( "</div>" ); } private static void appendBoard( StringBuilder sb, List<ForumBoard> boards, MvcContext ctx ) { if (boards == null) return; for (int i = 0; i < boards.Count; i++) { String url = alink.ToAppData( boards[i] ); if (i == boards.Count - 1) url = LinkUtil.appendListPageToBoard( url, ctx ); sb.AppendFormat( "<a href=\"{0}\" class=\"left5 right5\">{1}</a> {2} ", url, boards[i].Name, separator ); } } } }
// 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 MinScalarSingle() { var test = new SimpleBinaryOpTest__MinScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinScalarSingle { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[ElementCount]; private static Single[] _data2 = new Single[ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single> _dataTable; static SimpleBinaryOpTest__MinScalarSingle() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__MinScalarSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.MinScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.MinScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.MinScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.MinScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.MinScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.MinScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.MinScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__MinScalarSingle(); var result = Sse.MinScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.MinScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(Math.Min(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.MinScalar)}<Single>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* Copyright 2012-2022 Marco De Salvo 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 Microsoft.VisualStudio.TestTools.UnitTesting; using RDFSharp.Model; using System; using System.Collections.Generic; using System.Linq; namespace RDFSharp.Test.Model { [TestClass] public class RDFMaxCountConstraintTest { #region Tests [TestMethod] public void ShouldCreateMaxCountConstraint() { RDFMaxCountConstraint maxCountConstraint = new RDFMaxCountConstraint(2); Assert.IsNotNull(maxCountConstraint); Assert.IsTrue(maxCountConstraint.MaxCount == 2); } [TestMethod] public void ShouldCreateMaxCountConstraintLowerThanZero() { RDFMaxCountConstraint maxCountConstraint = new RDFMaxCountConstraint(-2); Assert.IsNotNull(maxCountConstraint); Assert.IsTrue(maxCountConstraint.MaxCount == 0); } [TestMethod] public void ShouldExportMaxCountConstraint() { RDFMaxCountConstraint maxCountConstraint = new RDFMaxCountConstraint(2); RDFGraph graph = maxCountConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape"))); Assert.IsNotNull(graph); Assert.IsTrue(graph.TriplesCount == 1); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape")) && t.Value.Predicate.Equals(RDFVocabulary.SHACL.MAX_COUNT) && t.Value.Object.Equals(new RDFTypedLiteral("2", RDFModelEnums.RDFDatatypes.XSD_INTEGER)))); } //NS-CONFORMS:TRUE [TestMethod] public void ShouldConformNodeShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); nodeShape.AddConstraint(new RDFMaxCountConstraint(3)); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMaxCountConstraint(2)); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMaxCountConstraint(2)); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //PS-CONFORMS:TRUE [TestMethod] public void ShouldConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); propertyShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //NS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformNodeShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); nodeShape.AddConstraint(new RDFMaxCountConstraint(0)); nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage")); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 2); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); Assert.IsTrue(validationReport.Results[1].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[1].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[1].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[1].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[1].ResultValue); Assert.IsNull(validationReport.Results[1].ResultPath); Assert.IsTrue(validationReport.Results[1].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[1].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddConstraint(new RDFMaxCountConstraint(0)); nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage")); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMaxCountConstraint(0)); nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage")); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMaxCountConstraint(0)); nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage")); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } //PS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum of 1 occurrences"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); propertyShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum of 1 occurrences"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum of 1 occurrences"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMaxCountConstraint(1)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum of 1 occurrences"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } //MIXED-CONFORMS:TRUE [TestMethod] public void ShouldConformNodeShapeWithPropertyShape() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:birthDate"), new RDFTypedLiteral("1990-12-12", RDFModelEnums.RDFDatatypes.XSD_DATE))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:MaxCountExampleShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:birthDate")); propShape.AddConstraint(new RDFMaxCountConstraint(1)); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //MIXED-CONFORMS:FALSE [TestMethod] public void ShouldNotConformNodeShapeWithPropertyShape() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:birthDate"), new RDFTypedLiteral("1990-12-12", RDFModelEnums.RDFDatatypes.XSD_DATE))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:birthDate"), new RDFTypedLiteral("1990-12-18", RDFModelEnums.RDFDatatypes.XSD_DATE))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:MaxCountExampleShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:birthDate")); propShape.AddConstraint(new RDFMaxCountConstraint(1)); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a maximum of 1 occurrences"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:birthDate"))); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MAX_COUNT_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape"))); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using System.Web.Mvc; using MvcContrib.FluentHtml.Elements; using MvcContrib.FluentHtml.Expressions; namespace MvcContrib.FluentHtml { /// <summary> /// Extensions of IViewModelContainer&lt;T&gt; /// </summary> public static class ViewModelContainerExtensions { /// <summary> /// Generate an HTML input element of type 'text' and set its value from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static TextBox TextBox<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new TextBox(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'password' and set its value from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static Password Password<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new Password(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'hidden' and set its value from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static Hidden Hidden<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new Hidden(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'checkbox' and set its value from the ViewModel based on the expression provided. /// The checkbox element has an accompanying input element of type 'hidden' to support binding upon form post. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static CheckBox CheckBox<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { var checkbox = new CheckBox(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors); var val = expression.GetValueFrom(view.ViewModel) as bool?; if (val.HasValue) { checkbox.Checked(val.Value); } return checkbox; } /// <summary> /// Generate a list of HTML input elements of type 'checkbox' and set its value from the ViewModel based on the expression provided. /// Each checkbox element has an accompanying input element of type 'hidden' to support binding upon form post. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static CheckBoxList CheckBoxList<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new CheckBoxList(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Selected(expression.GetValueFrom(view.ViewModel) as IEnumerable); } /// <summary> /// Generate an HTML textarea element and set its value from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static TextArea TextArea<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new TextArea(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML select element and set the selected option value from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static Select<T> Select<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new Select<T>(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Selected(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML select element and set the selected options from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static MultiSelect<T> MultiSelect<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new MultiSelect<T>(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Selected(expression.GetValueFrom(view.ViewModel) as IEnumerable); } /// <summary> /// Generate an HTML label element, point its "for" attribute to the input element from the provided expression, and set its inner text from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member that has an input element associated with it.</param> public static Label Label<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new Label(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetNameFor()); } /// <summary> /// Generate an HTML span element and set its inner text from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static Literal Literal<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new Literal(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML span element and hidden input element. Set the inner text of the span element and the value /// of the hidden input element from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static FormLiteral FormLiteral<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new FormLiteral(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'radio'. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static RadioButton RadioButton<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new RadioButton(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors); } /// <summary> /// Generate a set of HTML input elements of type 'radio' -- each wrapped inside a label. The whole thing is wrapped in an HTML /// div element. The values of the input elements and he label text are taken from the options specified. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static RadioSet RadioSet<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new RadioSet(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Selected(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'number' and set its value from the ViewModel based on the expression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static NumberBox NumberBox<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new NumberBox(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'search' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static SearchBox SearchBox<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new SearchBox(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'range' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static RangeBox RangeBox<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new RangeBox(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'tel' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static TelephoneBox TelephoneBox<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new TelephoneBox(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'date' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static DatePicker DatePicker<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new DatePicker(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'month' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static MonthPicker MonthPicker<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new MonthPicker(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'week' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static WeekPicker WeekPicker<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new WeekPicker(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'datetime' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static DateTimePicker DateTimePicker<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new DateTimePicker(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'datetime-local' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static DateTimeLocalPicker DateTimeLocalPicker<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new DateTimeLocalPicker(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'time' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static TimePicker TimePicker<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new TimePicker(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'color' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static ColorPicker ColorPicker<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new ColorPicker(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'url' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static UrlBox UrlBox<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new UrlBox(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// Generate an HTML input element of type 'email' and set its value from the ViewModel based on the expression provided. /// </summary> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static EmailBox EmailBox<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new EmailBox(expression.GetNameFor(view), expression.GetMemberExpression(), view.GetBehaviors()) .Value(expression.GetValueFrom(view.ViewModel)); } /// <summary> /// If ModelState contains an error for the specified view model member, generate an HTML span element with the /// ModelState error message is the specified message is null. If no class is specified the class attribute /// of the span element will be 'field-validation-error'. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> public static ValidationMessage ValidationMessage<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return ValidationMessage(view, expression, null); } /// <summary> /// If ModelState contains an error for the specified view model member, generate an HTML span element with the /// specified message as inner text, or with the ModelState error message if the specified message is null. If no /// class is specified the class attribute of the span element will be 'field-validation-error'. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member associated with the element.</param> /// <param name="message">The error message.</param> public static ValidationMessage ValidationMessage<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression, string message) where T : class { string errorMessage = null; var name = expression.GetNameFor(view); if (view.ViewData.ModelState.ContainsKey(name)) { var modelState = view.ViewData.ModelState[name]; if(modelState != null && modelState.Errors != null && modelState.Errors.Count > 0) { errorMessage = modelState.Errors[0] == null ? null : message ?? modelState.Errors[0].ErrorMessage; } } return new ValidationMessage(expression.GetMemberExpression(), view.Behaviors).Value(errorMessage); } /// <summary> /// Generate an HTML input element of type 'hidden,' set it's name from the expression with '.Index' appended. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member to use to derive the 'name' attribute.</param> public static Index Index<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new Index(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors); } /// <summary> /// Generate an HTML input element of type 'hidden,' set it's name from the expression with '.Index' appended /// and set its value from the ViewModel from the valueExpression provided. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member to use to derive the 'name' attribute.</param> /// <param name="valueExpression">Expression indicating the ViewModel member to use to get the value of the element.</param> public static Hidden Index<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression, Expression<Func<T, object>> valueExpression) where T : class { var name = expression.GetNameFor(view) + ".Index"; var value = valueExpression.GetValueFrom(view.ViewModel); var id = name.FormatAsHtmlId() + (value == null ? null : "_" + value.ToString().FormatAsHtmlId()); var hidden = new Hidden(name, expression.GetMemberExpression(), view.Behaviors).Value(value).Id(id); return hidden; } /// <summary> /// Returns a name to match the value for the HTML name attribute form elements using the same expression. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member.</param> public static string NameFor<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return expression.GetNameFor(view); } /// <summary> /// Returns a name to match the value for the HTML id attribute form elements using the same expression. /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <param name="view">The view.</param> /// <param name="expression">Expression indicating the ViewModel member.</param> public static string IdFor<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return expression.GetNameFor(view).FormatAsHtmlId(); } /// <summary> /// Generate an HTML input element of type 'submit.' /// </summary> /// <param name="view">The view.</param> /// <param name="text">Value of the 'value' and 'name' attributes. Also used to derive the 'id' attribute.</param> public static SubmitButton SubmitButton<T>(this IViewModelContainer<T> view, string text) where T : class { return new SubmitButton(text, view.Behaviors); } /// <summary> /// Renders a partial /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <typeparam name="TPartialViewModel">The type of model of the partial.</typeparam> /// <param name="view">The view.</param> /// <param name="partialViewName">The name of the partial to render.</param> /// <param name="modelExpression">Expression of the model for the partial.</param> /// <param name="viewData">View data for the partial. (If the view data has a Model, it will be replaced by the model as specified in the expression parameter, if it is not null.)</param> [Obsolete("Use overload that takes Func<string, object>[] viewDataItems instead. This will will avoid inavertently passing in the model twice -- once via the modelExpression parameter and again in the viewData parameter. The viewData parameter was meant only to provide a way to pass in weakly typed view data which is more approriately done with an array of key value pairs.")] public static void RenderPartial<T, TPartialViewModel>(this IViewModelContainer<T> view, string partialViewName, Expression<Func<T, TPartialViewModel>> modelExpression, ViewDataDictionary viewData) where T : class where TPartialViewModel : class { new PartialRenderer<T, TPartialViewModel>(view, partialViewName, modelExpression).ViewData(viewData).Render(); } /// <summary> /// Renders a partial /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <typeparam name="TPartialViewModel">The type of model of the partial.</typeparam> /// <param name="view">The view.</param> /// <param name="partialViewName">The name of the partial to render.</param> /// <param name="modelExpression">Expression of the model for the partial.</param> public static void RenderPartial<T, TPartialViewModel>(this IViewModelContainer<T> view, string partialViewName, Expression<Func<T, TPartialViewModel>> modelExpression) where T : class where TPartialViewModel : class { new PartialRenderer<T, TPartialViewModel>(view, partialViewName, modelExpression).Render(); } /// <summary> /// Renders a partial /// </summary> /// <typeparam name="T">The type of the ViewModel.</typeparam> /// <typeparam name="TPartialViewModel">The type of model of the partial.</typeparam> /// <param name="view">The view.</param> /// <param name="partialViewName">The name of the partial to render.</param> /// <param name="modelExpression">Expression of the model for the partial.</param> /// <param name="viewDataItems">A list of funcs, each epxressing a weakly typed view data item for the partial. For example: index => i</param> public static void RenderPartial<T, TPartialViewModel>(this IViewModelContainer<T> view, string partialViewName, Expression<Func<T, TPartialViewModel>> modelExpression, params Func<string, object>[] viewDataItems) where T : class where TPartialViewModel : class { var viewDataDictionary = new ViewDataDictionary(); foreach (var item in viewDataItems) { viewDataDictionary.Add(new KeyValuePair<string, object>(item.Method.GetParameters()[0].Name, item(null))); } new PartialRenderer<T, TPartialViewModel>(view, partialViewName, modelExpression).ViewData(viewDataDictionary).Render(); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.IO.IsolatedStorage.IsolatedStorageFile.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.IO.IsolatedStorage { sealed public partial class IsolatedStorageFile : IsolatedStorage, IDisposable { #region Methods and constructors public void Close() { } public void CopyFile(string sourceFileName, string destinationFileName) { } public void CopyFile(string sourceFileName, string destinationFileName, bool overwrite) { } public void CreateDirectory(string dir) { } public IsolatedStorageFileStream CreateFile(string path) { Contract.Ensures(0 <= path.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFileStream>() != null); return default(IsolatedStorageFileStream); } public void DeleteDirectory(string dir) { } public void DeleteFile(string file) { } public bool DirectoryExists(string path) { return default(bool); } public void Dispose() { } public bool FileExists(string path) { return default(bool); } public DateTimeOffset GetCreationTime(string path) { Contract.Ensures(false); return default(DateTimeOffset); } public string[] GetDirectoryNames() { Contract.Ensures(Contract.Result<string[]>() != null); return default(string[]); } public string[] GetDirectoryNames(string searchPattern) { Contract.Ensures(Contract.Result<string[]>() != null); return default(string[]); } public static System.Collections.IEnumerator GetEnumerator(IsolatedStorageScope scope) { Contract.Ensures(Contract.Result<System.Collections.IEnumerator>() != null); return default(System.Collections.IEnumerator); } public string[] GetFileNames(string searchPattern) { Contract.Ensures(Contract.Result<string[]>() != null); return default(string[]); } public string[] GetFileNames() { Contract.Ensures(Contract.Result<string[]>() != null); return default(string[]); } public DateTimeOffset GetLastAccessTime(string path) { Contract.Ensures(false); return default(DateTimeOffset); } public DateTimeOffset GetLastWriteTime(string path) { Contract.Ensures(false); return default(DateTimeOffset); } public static IsolatedStorageFile GetMachineStoreForApplication() { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetMachineStoreForAssembly() { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetMachineStoreForDomain() { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } protected override System.Security.Permissions.IsolatedStoragePermission GetPermission(System.Security.PermissionSet ps) { return default(System.Security.Permissions.IsolatedStoragePermission); } public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Type applicationEvidenceType) { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Object applicationIdentity) { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, System.Security.Policy.Evidence domainEvidence, Type domainEvidenceType, System.Security.Policy.Evidence assemblyEvidence, Type assemblyEvidenceType) { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType) { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Object domainIdentity, Object assemblyIdentity) { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetUserStoreForApplication() { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetUserStoreForAssembly() { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetUserStoreForDomain() { Contract.Ensures(0 <= string.Empty.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFile>() != null); return default(IsolatedStorageFile); } public static IsolatedStorageFile GetUserStoreForSite() { Contract.Ensures(false); return default(IsolatedStorageFile); } public override bool IncreaseQuotaTo(long newQuotaSize) { return default(bool); } internal IsolatedStorageFile() { } public void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName) { } public void MoveFile(string sourceFileName, string destinationFileName) { } public IsolatedStorageFileStream OpenFile(string path, FileMode mode) { Contract.Ensures(0 <= path.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFileStream>() != null); return default(IsolatedStorageFileStream); } public IsolatedStorageFileStream OpenFile(string path, FileMode mode, FileAccess access) { Contract.Ensures(0 <= path.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFileStream>() != null); return default(IsolatedStorageFileStream); } public IsolatedStorageFileStream OpenFile(string path, FileMode mode, FileAccess access, FileShare share) { Contract.Ensures(0 <= path.Length); Contract.Ensures(Contract.Result<System.IO.IsolatedStorage.IsolatedStorageFileStream>() != null); return default(IsolatedStorageFileStream); } public override void Remove() { } public static void Remove(IsolatedStorageScope scope) { } #endregion #region Properties and indexers public override long AvailableFreeSpace { get { return default(long); } } public override ulong CurrentSize { get { return default(ulong); } } public static bool IsEnabled { get { Contract.Ensures(Contract.Result<bool>() == true); return default(bool); } } public override ulong MaximumSize { get { return default(ulong); } } public override long Quota { get { return default(long); } internal set { } } public override long UsedSize { get { return default(long); } } #endregion } }
// <copyright file="PointerInputDevice.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Interactions { /// <summary> /// Represents the origin of the coordinates for mouse movement. /// </summary> public enum CoordinateOrigin { /// <summary> /// The coordinate origin is the origin of the view port of the browser. /// </summary> Viewport, /// <summary> /// The origin of the movement is the most recent pointer location. /// </summary> Pointer, /// <summary> /// The origin of the movement is the center of the element specified. /// </summary> Element } /// <summary> /// Specifies the type of pointer a pointer device represents. /// </summary> public enum PointerKind { /// <summary> /// The pointer device is a mouse. /// </summary> Mouse, /// <summary> /// The pointer device is a pen or stylus. /// </summary> Pen, /// <summary> /// The pointer device is a touch screen device. /// </summary> Touch } /// <summary> /// Specifies the button used during a pointer down or up action. /// </summary> public enum MouseButton { /// <summary> /// This button is used for signifying touch actions. /// </summary> Touch = 0, /// <summary> /// The button used is the primary button. /// </summary> Left = 0, /// <summary> /// The button used is the middle button or mouse wheel. /// </summary> Middle = 1, /// <summary> /// The button used is the secondary button. /// </summary> Right = 2 } /// <summary> /// Represents a pointer input device, such as a stylus, mouse, or finger on a touch screen. /// </summary> public class PointerInputDevice : InputDevice { private PointerKind pointerKind; /// <summary> /// Initializes a new instance of the <see cref="PointerInputDevice"/> class. /// </summary> public PointerInputDevice() : this(PointerKind.Mouse) { } /// <summary> /// Initializes a new instance of the <see cref="PointerInputDevice"/> class. /// </summary> /// <param name="pointerKind">The kind of pointer represented by this input device.</param> public PointerInputDevice(PointerKind pointerKind) : this(pointerKind, Guid.NewGuid().ToString()) { } /// <summary> /// Initializes a new instance of the <see cref="PointerInputDevice"/> class. /// </summary> /// <param name="pointerKind">The kind of pointer represented by this input device.</param> /// <param name="deviceName">The unique name for this input device.</param> public PointerInputDevice(PointerKind pointerKind, string deviceName) : base(deviceName) { this.pointerKind = pointerKind; } /// <summary> /// Gets the type of device for this input device. /// </summary> public override InputDeviceKind DeviceKind { get { return InputDeviceKind.Pointer; } } /// <summary> /// Returns a value for this input device that can be transmitted across the wire to a remote end. /// </summary> /// <returns>A <see cref="Dictionary{TKey, TValue}"/> representing this action.</returns> public override Dictionary<string, object> ToDictionary() { Dictionary<string, object> toReturn = new Dictionary<string, object>(); toReturn["type"] = "pointer"; toReturn["id"] = this.DeviceName; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["pointerType"] = this.pointerKind.ToString().ToLowerInvariant(); toReturn["parameters"] = parameters; return toReturn; } /// <summary> /// Creates a pointer down action. /// </summary> /// <param name="button">The button of the pointer that should be pressed.</param> /// <returns>The action representing the pointer down gesture.</returns> public Interaction CreatePointerDown(MouseButton button) { return new PointerDownInteraction(this, button); } /// <summary> /// Creates a pointer up action. /// </summary> /// <param name="button">The button of the pointer that should be released.</param> /// <returns>The action representing the pointer up gesture.</returns> public Interaction CreatePointerUp(MouseButton button) { return new PointerUpInteraction(this, button); } /// <summary> /// Creates a pointer move action to a specific element. /// </summary> /// <param name="target">The <see cref="IWebElement"/> used as the target for the move.</param> /// <param name="xOffset">The horizontal offset from the origin of the move.</param> /// <param name="yOffset">The vertical offset from the origin of the move.</param> /// <param name="duration">The length of time the move gesture takes to complete.</param> /// <returns>The action representing the pointer move gesture.</returns> public Interaction CreatePointerMove(IWebElement target, int xOffset, int yOffset, TimeSpan duration) { return new PointerMoveInteraction(this, target, CoordinateOrigin.Element, xOffset, yOffset, duration); } /// <summary> /// Creates a pointer move action to an absolute coordinate. /// </summary> /// <param name="origin">The origin of coordinates for the move. Values can be relative to /// the view port origin, or the most recent pointer position.</param> /// <param name="xOffset">The horizontal offset from the origin of the move.</param> /// <param name="yOffset">The vertical offset from the origin of the move.</param> /// <param name="duration">The length of time the move gesture takes to complete.</param> /// <returns>The action representing the pointer move gesture.</returns> /// <exception cref="ArgumentException">Thrown when passing CoordinateOrigin.Element into origin. /// Users should us the other CreatePointerMove overload to move to a specific element.</exception> public Interaction CreatePointerMove(CoordinateOrigin origin, int xOffset, int yOffset, TimeSpan duration) { if (origin == CoordinateOrigin.Element) { throw new ArgumentException("Using a value of CoordinateOrigin.Element without an element is not supported.", nameof(origin)); } return new PointerMoveInteraction(this, null, origin, xOffset, yOffset, duration); } /// <summary> /// Creates a pointer cancel action. /// </summary> /// <returns>The action representing the pointer cancel gesture.</returns> public Interaction CreatePointerCancel() { return new PointerCancelInteraction(this); } private class PointerDownInteraction : Interaction { private MouseButton button; private double? width; private double? height; private double? pressure; private double? tangentialPressure; private int? tiltX; private int? tiltY; private int? twist; private double? altitudeAngle; private double? azimuthAngle; public PointerDownInteraction(InputDevice sourceDevice, MouseButton button) : base(sourceDevice) { this.button = button; } public override Dictionary<string, object> ToDictionary() { Dictionary<string, object> toReturn = new Dictionary<string, object>(); toReturn["type"] = "pointerDown"; toReturn["button"] = Convert.ToInt32(this.button, CultureInfo.InvariantCulture); if (this.width.HasValue) { toReturn["width"] = this.width.Value; } if (this.height.HasValue) { toReturn["height"] = this.width.Value; } if (this.pressure.HasValue) { toReturn["pressure"] = this.width.Value; } if (this.tangentialPressure.HasValue) { toReturn["tangentialPressure"] = this.width.Value; } if (this.tiltX.HasValue) { toReturn["tiltX"] = this.width.Value; } if (this.tiltY.HasValue) { toReturn["tiltY"] = this.width.Value; } if (this.twist.HasValue) { toReturn["twist"] = this.width.Value; } if (this.altitudeAngle.HasValue) { toReturn["altitudeAngle"] = this.width.Value; } if (this.azimuthAngle.HasValue) { toReturn["azimuthAngle"] = this.width.Value; } return toReturn; } public override string ToString() { return "Pointer down"; } } private class PointerUpInteraction : Interaction { private MouseButton button; private double? width; private double? height; private double? pressure; private double? tangentialPressure; private int? tiltX; private int? tiltY; private int? twist; private double? altitudeAngle; private double? azimuthAngle; public PointerUpInteraction(InputDevice sourceDevice, MouseButton button) : base(sourceDevice) { this.button = button; } public override Dictionary<string, object> ToDictionary() { Dictionary<string, object> toReturn = new Dictionary<string, object>(); toReturn["type"] = "pointerUp"; toReturn["button"] = Convert.ToInt32(this.button, CultureInfo.InvariantCulture); if (this.width.HasValue) { toReturn["width"] = this.width.Value; } if (this.height.HasValue) { toReturn["height"] = this.width.Value; } if (this.pressure.HasValue) { toReturn["pressure"] = this.width.Value; } if (this.tangentialPressure.HasValue) { toReturn["tangentialPressure"] = this.width.Value; } if (this.tiltX.HasValue) { toReturn["tiltX"] = this.width.Value; } if (this.tiltY.HasValue) { toReturn["tiltY"] = this.width.Value; } if (this.twist.HasValue) { toReturn["twist"] = this.width.Value; } if (this.altitudeAngle.HasValue) { toReturn["altitudeAngle"] = this.width.Value; } if (this.azimuthAngle.HasValue) { toReturn["azimuthAngle"] = this.width.Value; } return toReturn; } public override string ToString() { return "Pointer up"; } } private class PointerCancelInteraction : Interaction { public PointerCancelInteraction(InputDevice sourceDevice) : base(sourceDevice) { } public override Dictionary<string, object> ToDictionary() { Dictionary<string, object> toReturn = new Dictionary<string, object>(); toReturn["type"] = "pointerCancel"; return toReturn; } public override string ToString() { return "Pointer cancel"; } } private class PointerMoveInteraction : Interaction { private IWebElement target; private int x = 0; private int y = 0; private TimeSpan duration = TimeSpan.MinValue; private CoordinateOrigin origin = CoordinateOrigin.Pointer; private double? width; private double? height; private double? pressure; private double? tangentialPressure; private int? tiltX; private int? tiltY; private int? twist; private double? altitudeAngle; private double? azimuthAngle; public PointerMoveInteraction(InputDevice sourceDevice, IWebElement target, CoordinateOrigin origin, int x, int y, TimeSpan duration) : base(sourceDevice) { if (target != null) { this.target = target; this.origin = CoordinateOrigin.Element; } else { if (this.origin != CoordinateOrigin.Element) { this.origin = origin; } } if (duration != TimeSpan.MinValue) { this.duration = duration; } this.x = x; this.y = y; } public override Dictionary<string, object> ToDictionary() { Dictionary<string, object> toReturn = new Dictionary<string, object>(); toReturn["type"] = "pointerMove"; if (this.duration != TimeSpan.MinValue) { toReturn["duration"] = Convert.ToInt64(this.duration.TotalMilliseconds); } if (this.target != null) { toReturn["origin"] = this.ConvertElement(); } else { toReturn["origin"] = this.origin.ToString().ToLowerInvariant(); } toReturn["x"] = this.x; toReturn["y"] = this.y; if (this.width.HasValue) { toReturn["width"] = this.width.Value; } if (this.height.HasValue) { toReturn["height"] = this.width.Value; } if (this.pressure.HasValue) { toReturn["pressure"] = this.width.Value; } if (this.tangentialPressure.HasValue) { toReturn["tangentialPressure"] = this.width.Value; } if (this.tiltX.HasValue) { toReturn["tiltX"] = this.width.Value; } if (this.tiltY.HasValue) { toReturn["tiltY"] = this.width.Value; } if (this.twist.HasValue) { toReturn["twist"] = this.width.Value; } if (this.altitudeAngle.HasValue) { toReturn["altitudeAngle"] = this.width.Value; } if (this.azimuthAngle.HasValue) { toReturn["azimuthAngle"] = this.width.Value; } return toReturn; } public override string ToString() { string originDescription = this.origin.ToString(); if (this.origin == CoordinateOrigin.Element) { originDescription = this.target.ToString(); } return string.Format(CultureInfo.InvariantCulture, "Pointer move [origin: {0}, x offset: {1}, y offset: {2}, duration: {3}ms]", originDescription, this.x, this.y, this.duration.TotalMilliseconds); } private Dictionary<string, object> ConvertElement() { IWebDriverObjectReference elementReference = this.target as IWebDriverObjectReference; if (elementReference == null) { IWrapsElement elementWrapper = this.target as IWrapsElement; if (elementWrapper != null) { elementReference = elementWrapper.WrappedElement as IWebDriverObjectReference; } } if (elementReference == null) { throw new ArgumentException("Target element cannot be converted to IWebElementReference"); } Dictionary<string, object> elementDictionary = elementReference.ToDictionary(); return elementDictionary; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gctv = Google.Cloud.Talent.V4Beta1; using sys = System; namespace Google.Cloud.Talent.V4Beta1 { /// <summary>Resource name for the <c>Application</c> resource.</summary> public sealed partial class ApplicationName : gax::IResourceName, sys::IEquatable<ApplicationName> { /// <summary>The possible contents of <see cref="ApplicationName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>. /// </summary> ProjectTenantProfileApplication = 1, } private static gax::PathTemplate s_projectTenantProfileApplication = new gax::PathTemplate("projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}"); /// <summary>Creates a <see cref="ApplicationName"/> 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="ApplicationName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ApplicationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ApplicationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ApplicationName"/> with the pattern /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="profileId">The <c>Profile</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="applicationId">The <c>Application</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ApplicationName"/> constructed from the provided ids.</returns> public static ApplicationName FromProjectTenantProfileApplication(string projectId, string tenantId, string profileId, string applicationId) => new ApplicationName(ResourceNameType.ProjectTenantProfileApplication, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), tenantId: gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)), profileId: gax::GaxPreconditions.CheckNotNullOrEmpty(profileId, nameof(profileId)), applicationId: gax::GaxPreconditions.CheckNotNullOrEmpty(applicationId, nameof(applicationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ApplicationName"/> with pattern /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="profileId">The <c>Profile</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="applicationId">The <c>Application</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ApplicationName"/> with pattern /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>. /// </returns> public static string Format(string projectId, string tenantId, string profileId, string applicationId) => FormatProjectTenantProfileApplication(projectId, tenantId, profileId, applicationId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ApplicationName"/> with pattern /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="profileId">The <c>Profile</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="applicationId">The <c>Application</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ApplicationName"/> with pattern /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>. /// </returns> public static string FormatProjectTenantProfileApplication(string projectId, string tenantId, string profileId, string applicationId) => s_projectTenantProfileApplication.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)), gax::GaxPreconditions.CheckNotNullOrEmpty(profileId, nameof(profileId)), gax::GaxPreconditions.CheckNotNullOrEmpty(applicationId, nameof(applicationId))); /// <summary>Parses the given resource name string into a new <see cref="ApplicationName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="applicationName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ApplicationName"/> if successful.</returns> public static ApplicationName Parse(string applicationName) => Parse(applicationName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ApplicationName"/> 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>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="applicationName">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="ApplicationName"/> if successful.</returns> public static ApplicationName Parse(string applicationName, bool allowUnparsed) => TryParse(applicationName, allowUnparsed, out ApplicationName 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="ApplicationName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="applicationName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ApplicationName"/>, 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 applicationName, out ApplicationName result) => TryParse(applicationName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ApplicationName"/> 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>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="applicationName">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="ApplicationName"/>, 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 applicationName, bool allowUnparsed, out ApplicationName result) { gax::GaxPreconditions.CheckNotNull(applicationName, nameof(applicationName)); gax::TemplatedResourceName resourceName; if (s_projectTenantProfileApplication.TryParseName(applicationName, out resourceName)) { result = FromProjectTenantProfileApplication(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(applicationName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ApplicationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string applicationId = null, string profileId = null, string projectId = null, string tenantId = null) { Type = type; UnparsedResource = unparsedResourceName; ApplicationId = applicationId; ProfileId = profileId; ProjectId = projectId; TenantId = tenantId; } /// <summary> /// Constructs a new instance of a <see cref="ApplicationName"/> class from the component parts of pattern /// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="profileId">The <c>Profile</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="applicationId">The <c>Application</c> ID. Must not be <c>null</c> or empty.</param> public ApplicationName(string projectId, string tenantId, string profileId, string applicationId) : this(ResourceNameType.ProjectTenantProfileApplication, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), tenantId: gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)), profileId: gax::GaxPreconditions.CheckNotNullOrEmpty(profileId, nameof(profileId)), applicationId: gax::GaxPreconditions.CheckNotNullOrEmpty(applicationId, nameof(applicationId))) { } /// <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>Application</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ApplicationId { get; } /// <summary> /// The <c>Profile</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProfileId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Tenant</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TenantId { 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.ProjectTenantProfileApplication: return s_projectTenantProfileApplication.Expand(ProjectId, TenantId, ProfileId, ApplicationId); 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 ApplicationName); /// <inheritdoc/> public bool Equals(ApplicationName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ApplicationName a, ApplicationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ApplicationName a, ApplicationName b) => !(a == b); } public partial class Application { /// <summary> /// <see cref="gctv::ApplicationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::ApplicationName ApplicationName { get => string.IsNullOrEmpty(Name) ? null : gctv::ApplicationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary><see cref="JobName"/>-typed view over the <see cref="Job"/> resource name property.</summary> public JobName JobAsJobName { get => string.IsNullOrEmpty(Job) ? null : JobName.Parse(Job, allowUnparsed: true); set => Job = value?.ToString() ?? ""; } /// <summary> /// <see cref="CompanyName"/>-typed view over the <see cref="Company"/> resource name property. /// </summary> public CompanyName CompanyAsCompanyName { get => string.IsNullOrEmpty(Company) ? null : CompanyName.Parse(Company, allowUnparsed: true); set => Company = value?.ToString() ?? ""; } } }
// ---------------------------------------------------------------------------------- // // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Sync.Upload { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Microsoft.WindowsAzure.Storage.Blob; using Sync.Download; using Tools.Vhd; using Tools.Vhd.Model.Persistence; public class PatchingBlobCreator : BlobCreatorBase { protected Uri baseVhdBlob; protected BlobUri baseVhdBlobUri; public PatchingBlobCreator(FileInfo localVhd, BlobUri destination, BlobUri baseVhdBlob, ICloudPageBlobObjectFactory blobObjectFactory, bool overWrite) : base(localVhd, destination, blobObjectFactory, overWrite) { this.baseVhdBlob = baseVhdBlob.Uri; this.baseVhdBlobUri = baseVhdBlob; } protected override void CreateRemoteBlobAndPopulateContext(UploadContext context) { CreateRemoteBlob(); PopulateContextWithUploadableRanges(localVhd, context, true); PopulateContextWithDataToUpload(localVhd, context); } private void CreateRemoteBlob() { var baseBlob = this.blobObjectFactory.Create(baseVhdBlobUri); if(!baseBlob.Exists()) { throw new InvalidOperationException(String.Format("Base image to patch doesn't exist in blob storage: {0}", baseVhdBlobUri.Uri)); } var blobVhdFooter = baseBlob.GetVhdFooter(); long blobSize; VhdFilePath localBaseVhdPath; IEnumerable<Guid> childrenVhdIds; using (var vhdFile = new VhdFileFactory().Create(localVhd.FullName)) { localBaseVhdPath = vhdFile.GetFilePathBy(blobVhdFooter.UniqueId); childrenVhdIds = vhdFile.GetChildrenIds(blobVhdFooter.UniqueId).ToArray(); blobSize = vhdFile.Footer.VirtualSize; } FileMetaData fileMetaData = GetFileMetaData(baseBlob, localBaseVhdPath); var md5Hash = baseBlob.GetBlobMd5Hash(); if (!md5Hash.SequenceEqual(fileMetaData.MD5Hash)) { var message = String.Format("Patching cannot proceed, MD5 hash of base image in blob storage ({0}) and base VHD file ({1}) does not match ", baseBlob.Uri, localBaseVhdPath); throw new InvalidOperationException(message); } Program.SyncOutput.MessageCreatingNewPageBlob(blobSize); CopyBaseImageToDestination(); using (var vds = new VirtualDiskStream(localVhd.FullName)) { var streamExtents = vds.Extents.ToArray(); var enumerable = streamExtents.Where(e => childrenVhdIds.Contains(e.Owner)).ToArray(); foreach (var streamExtent in enumerable) { var indexRange = streamExtent.Range; destinationBlob.ClearPages(indexRange.StartIndex, indexRange.Length); } } using(var bmds = new BlobMetaDataScope(destinationBlob)) { bmds.Current.RemoveBlobMd5Hash(); bmds.Current.SetUploadMetaData(OperationMetaData); bmds.Complete(); } } private void CopyBaseImageToDestination() { var source = this.blobObjectFactory.Create(baseVhdBlobUri); source.FetchAttributes(); var copyStatus = new ProgressStatus(0, source.Properties.Length); using (new ProgressTracker(copyStatus, Program.SyncOutput.ProgressCopyStatus, Program.SyncOutput.ProgressCopyComplete,TimeSpan.FromSeconds(1))) { destinationBlob.StartCopyFromBlob(source); destinationBlob.FetchAttributes(); while (true) { if (destinationBlob.CopyState.BytesCopied != null) { copyStatus.AddToProcessedBytes(destinationBlob.CopyState.BytesCopied.Value - copyStatus.BytesProcessed); } if (destinationBlob.CopyState.Status == CopyStatus.Success) { break; } if (destinationBlob.CopyState.Status == CopyStatus.Pending) { Thread.Sleep(TimeSpan.FromSeconds(1)); } else { throw new ApplicationException( string.Format("Cannot copy source '{0}' to destination '{1}', copy state is '{2}'", source.Uri, destinationBlob.Uri, destinationBlob.CopyState)); } destinationBlob.FetchAttributes(); } } } private FileMetaData GetFileMetaData(CloudPageBlob baseBlob, VhdFilePath localBaseVhdPath) { FileMetaData fileMetaData; if(File.Exists(localBaseVhdPath.AbsolutePath)) { fileMetaData = FileMetaData.Create(localBaseVhdPath.AbsolutePath); } else { var filePath = Path.Combine(localVhd.Directory.FullName, localBaseVhdPath.RelativePath); if (File.Exists(filePath)) { fileMetaData = FileMetaData.Create(filePath); } else { var message = String.Format("Cannot find the local base image for '{0}' in neither of the locations '{1}', '{2}'.", baseBlob.Uri, localBaseVhdPath.AbsolutePath, localBaseVhdPath.RelativePath); throw new InvalidOperationException(message); } } return fileMetaData; } } class BlobMetaDataScope : IDisposable { private readonly CloudPageBlob blob; private bool disposed; private bool completed; public BlobMetaDataScope(CloudPageBlob blob) { this.blob = blob; this.blob.FetchAttributes(); this.Current = blob; } public CloudPageBlob Current { get; private set; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected void Dispose(bool disposing) { if(disposing) { if(!this.disposed) { if(completed) { this.blob.SetMetadata(); this.blob.SetProperties(); } this.disposed = true; } } } public void Complete() { this.completed = true; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// An historical landmark or building. /// </summary> public class LandmarksOrHistoricalBuildings_Core : TypeCore, IPlace { public LandmarksOrHistoricalBuildings_Core() { this._TypeId = 147; this._Id = "LandmarksOrHistoricalBuildings"; this._Schema_Org_Url = "http://schema.org/LandmarksOrHistoricalBuildings"; string label = ""; GetLabel(out label, "LandmarksOrHistoricalBuildings", typeof(LandmarksOrHistoricalBuildings_Core)); this._Label = label; this._Ancestors = new int[]{266,206}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{206}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
namespace XenAdmin.TabPages { partial class WlbPage { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WlbPage)); this.panelConfiguration = new System.Windows.Forms.Panel(); this.pdSectionConfiguration = new XenAdmin.Controls.PDSection(); this.panelOptimize = new System.Windows.Forms.Panel(); this.wlbOptimizePool = new XenAdmin.Controls.Wlb.WlbOptimizePool(); this.tableLayoutPanelMain = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanelStatus = new System.Windows.Forms.TableLayoutPanel(); this.pictureBoxWarningTriangle = new System.Windows.Forms.PictureBox(); this.labelStatus = new System.Windows.Forms.Label(); this.panelButtons = new System.Windows.Forms.Panel(); this.flowLayoutPanelLeftButtons = new System.Windows.Forms.FlowLayoutPanel(); this.buttonConnect = new System.Windows.Forms.Button(); this.buttonConfigure = new System.Windows.Forms.Button(); this.buttonEnableDisableWlb = new System.Windows.Forms.Button(); this.flowLayoutPanelRightButtons = new System.Windows.Forms.FlowLayoutPanel(); this.buttonReports = new System.Windows.Forms.Button(); this.pageContainerPanel.SuspendLayout(); this.panelConfiguration.SuspendLayout(); this.panelOptimize.SuspendLayout(); this.tableLayoutPanelMain.SuspendLayout(); this.tableLayoutPanelStatus.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxWarningTriangle)).BeginInit(); this.panelButtons.SuspendLayout(); this.flowLayoutPanelLeftButtons.SuspendLayout(); this.flowLayoutPanelRightButtons.SuspendLayout(); this.SuspendLayout(); // // pageContainerPanel // resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel"); this.pageContainerPanel.BackColor = System.Drawing.Color.Transparent; this.pageContainerPanel.Controls.Add(this.tableLayoutPanelMain); // // panelConfiguration // resources.ApplyResources(this.panelConfiguration, "panelConfiguration"); this.panelConfiguration.BackColor = System.Drawing.Color.Transparent; this.panelConfiguration.Controls.Add(this.pdSectionConfiguration); this.panelConfiguration.Name = "panelConfiguration"; // // pdSectionConfiguration // this.pdSectionConfiguration.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionConfiguration, "pdSectionConfiguration"); this.pdSectionConfiguration.MinimumSize = new System.Drawing.Size(0, 34); this.pdSectionConfiguration.Name = "pdSectionConfiguration"; this.pdSectionConfiguration.ShowCellToolTips = false; // // panelOptimize // resources.ApplyResources(this.panelOptimize, "panelOptimize"); this.panelOptimize.BackColor = System.Drawing.Color.Transparent; this.panelOptimize.Controls.Add(this.wlbOptimizePool); this.panelOptimize.Name = "panelOptimize"; // // wlbOptimizePool // this.wlbOptimizePool.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.wlbOptimizePool, "wlbOptimizePool"); this.wlbOptimizePool.Name = "wlbOptimizePool"; // // tableLayoutPanelMain // this.tableLayoutPanelMain.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.tableLayoutPanelMain, "tableLayoutPanelMain"); this.tableLayoutPanelMain.Controls.Add(this.tableLayoutPanelStatus, 0, 0); this.tableLayoutPanelMain.Controls.Add(this.panelButtons, 0, 1); this.tableLayoutPanelMain.Controls.Add(this.panelConfiguration, 0, 2); this.tableLayoutPanelMain.Controls.Add(this.panelOptimize, 0, 3); this.tableLayoutPanelMain.Name = "tableLayoutPanelMain"; // // tableLayoutPanelStatus // resources.ApplyResources(this.tableLayoutPanelStatus, "tableLayoutPanelStatus"); this.tableLayoutPanelStatus.Controls.Add(this.pictureBoxWarningTriangle, 0, 0); this.tableLayoutPanelStatus.Controls.Add(this.labelStatus, 1, 0); this.tableLayoutPanelStatus.Name = "tableLayoutPanelStatus"; // // pictureBoxWarningTriangle // resources.ApplyResources(this.pictureBoxWarningTriangle, "pictureBoxWarningTriangle"); this.pictureBoxWarningTriangle.Name = "pictureBoxWarningTriangle"; this.pictureBoxWarningTriangle.TabStop = false; // // labelStatus // resources.ApplyResources(this.labelStatus, "labelStatus"); this.labelStatus.Name = "labelStatus"; this.labelStatus.UseMnemonic = false; // // panelButtons // this.panelButtons.BackColor = System.Drawing.Color.Transparent; this.panelButtons.Controls.Add(this.flowLayoutPanelLeftButtons); this.panelButtons.Controls.Add(this.flowLayoutPanelRightButtons); resources.ApplyResources(this.panelButtons, "panelButtons"); this.panelButtons.Name = "panelButtons"; // // flowLayoutPanelLeftButtons // this.flowLayoutPanelLeftButtons.Controls.Add(this.buttonConnect); this.flowLayoutPanelLeftButtons.Controls.Add(this.buttonConfigure); this.flowLayoutPanelLeftButtons.Controls.Add(this.buttonEnableDisableWlb); resources.ApplyResources(this.flowLayoutPanelLeftButtons, "flowLayoutPanelLeftButtons"); this.flowLayoutPanelLeftButtons.Name = "flowLayoutPanelLeftButtons"; // // buttonConnect // resources.ApplyResources(this.buttonConnect, "buttonConnect"); this.buttonConnect.Name = "buttonConnect"; this.buttonConnect.UseVisualStyleBackColor = true; this.buttonConnect.Click += new System.EventHandler(this.buttonConnect_Click); // // buttonConfigure // resources.ApplyResources(this.buttonConfigure, "buttonConfigure"); this.buttonConfigure.Name = "buttonConfigure"; this.buttonConfigure.UseVisualStyleBackColor = true; this.buttonConfigure.Click += new System.EventHandler(this.buttonConfigure_Click); // // buttonEnableDisableWlb // resources.ApplyResources(this.buttonEnableDisableWlb, "buttonEnableDisableWlb"); this.buttonEnableDisableWlb.Name = "buttonEnableDisableWlb"; this.buttonEnableDisableWlb.UseVisualStyleBackColor = true; this.buttonEnableDisableWlb.Click += new System.EventHandler(this.buttonEnableDisableWlb_Click); // // flowLayoutPanelRightButtons // resources.ApplyResources(this.flowLayoutPanelRightButtons, "flowLayoutPanelRightButtons"); this.flowLayoutPanelRightButtons.Controls.Add(this.buttonReports); this.flowLayoutPanelRightButtons.Name = "flowLayoutPanelRightButtons"; // // buttonReports // resources.ApplyResources(this.buttonReports, "buttonReports"); this.buttonReports.Name = "buttonReports"; this.buttonReports.UseVisualStyleBackColor = true; this.buttonReports.Click += new System.EventHandler(this.buttonReports_Click); // // WlbPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.Transparent; this.DoubleBuffered = true; this.Name = "WlbPage"; this.pageContainerPanel.ResumeLayout(false); this.panelConfiguration.ResumeLayout(false); this.panelOptimize.ResumeLayout(false); this.tableLayoutPanelMain.ResumeLayout(false); this.tableLayoutPanelMain.PerformLayout(); this.tableLayoutPanelStatus.ResumeLayout(false); this.tableLayoutPanelStatus.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxWarningTriangle)).EndInit(); this.panelButtons.ResumeLayout(false); this.panelButtons.PerformLayout(); this.flowLayoutPanelLeftButtons.ResumeLayout(false); this.flowLayoutPanelLeftButtons.PerformLayout(); this.flowLayoutPanelRightButtons.ResumeLayout(false); this.flowLayoutPanelRightButtons.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private XenAdmin.Controls.PDSection pdSectionConfiguration; private System.Windows.Forms.TableLayoutPanel tableLayoutPanelMain; private System.Windows.Forms.TableLayoutPanel tableLayoutPanelStatus; private System.Windows.Forms.Label labelStatus; private System.Windows.Forms.Panel panelConfiguration; private System.Windows.Forms.Panel panelOptimize; private System.Windows.Forms.Button buttonEnableDisableWlb; private System.Windows.Forms.Button buttonConfigure; private XenAdmin.Controls.Wlb.WlbOptimizePool wlbOptimizePool; private System.Windows.Forms.PictureBox pictureBoxWarningTriangle; private System.Windows.Forms.Button buttonConnect; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanelLeftButtons; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanelRightButtons; private System.Windows.Forms.Button buttonReports; private System.Windows.Forms.Panel panelButtons; } }
// This file was generated by CSLA Object Generator - CslaGenFork v4.5 // // Filename: FolderList // ObjectType: FolderList // CSLAType: ReadOnlyCollection using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using DocStore.Business.Util; namespace DocStore.Business { /// <summary> /// Collection of folder's basic information (read only list).<br/> /// This is a generated <see cref="FolderList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="FolderInfo"/> objects. /// </remarks> [Serializable] #if WINFORMS public partial class FolderList : ReadOnlyBindingListBase<FolderList, FolderInfo> #else public partial class FolderList : ReadOnlyListBase<FolderList, FolderInfo> #endif { #region Collection Business Methods /// <summary> /// Determines whether a <see cref="FolderInfo"/> item is in the collection. /// </summary> /// <param name="folderID">The FolderID of the item to search for.</param> /// <returns><c>true</c> if the FolderInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int folderID) { foreach (var folderInfo in this) { if (folderInfo.FolderID == folderID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="FolderInfo"/> item of the <see cref="FolderList"/> collection, based on a given FolderID. /// </summary> /// <param name="folderID">The FolderID.</param> /// <returns>A <see cref="FolderInfo"/> object.</returns> public FolderInfo FindFolderInfoByFolderID(int folderID) { for (var i = 0; i < this.Count; i++) { if (this[i].FolderID.Equals(folderID)) { return this[i]; } } return null; } #endregion #region Private Fields private static FolderList _list; #endregion #region Cache Management Methods /// <summary> /// Clears the in-memory FolderList cache so it is reloaded on the next request. /// </summary> public static void InvalidateCache() { _list = null; } /// <summary> /// Used by async loaders to load the cache. /// </summary> /// <param name="list">The list to cache.</param> internal static void SetCache(FolderList list) { _list = list; } internal static bool IsCached { get { return _list != null; } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="FolderList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="FolderList"/> collection.</returns> public static FolderList GetFolderList() { if (_list == null) _list = DataPortal.Fetch<FolderList>(); return _list; } /// <summary> /// Factory method. Loads a <see cref="FolderList"/> collection, based on given parameters. /// </summary> /// <param name="folderTypeID">The FolderTypeID parameter of the FolderList to fetch.</param> /// <param name="folderRef">The FolderRef parameter of the FolderList to fetch.</param> /// <param name="year">The Year parameter of the FolderList to fetch.</param> /// <param name="subject">The Subject parameter of the FolderList to fetch.</param> /// <param name="folderStatusID">The FolderStatusID parameter of the FolderList to fetch.</param> /// <param name="createDate">The CreateDate parameter of the FolderList to fetch.</param> /// <param name="createUserID">The CreateUserID parameter of the FolderList to fetch.</param> /// <param name="changeDate">The ChangeDate parameter of the FolderList to fetch.</param> /// <param name="changeUserID">The ChangeUserID parameter of the FolderList to fetch.</param> /// <returns>A reference to the fetched <see cref="FolderList"/> collection.</returns> public static FolderList GetFolderList(int? folderTypeID, string folderRef, int? year, string subject, int? folderStatusID, SmartDate createDate, int? createUserID, SmartDate changeDate, int? changeUserID) { return DataPortal.Fetch<FolderList>(new FilteredCriteria(folderTypeID, folderRef, year, subject, folderStatusID, createDate, createUserID, changeDate, changeUserID)); } /// <summary> /// Factory method. Asynchronously loads a <see cref="FolderList"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetFolderList(EventHandler<DataPortalResult<FolderList>> callback) { if (_list == null) DataPortal.BeginFetch<FolderList>((o, e) => { _list = e.Object; callback(o, e); }); else callback(null, new DataPortalResult<FolderList>(_list, null, null)); } /// <summary> /// Factory method. Asynchronously loads a <see cref="FolderList"/> collection, based on given parameters. /// </summary> /// <param name="folderTypeID">The FolderTypeID parameter of the FolderList to fetch.</param> /// <param name="folderRef">The FolderRef parameter of the FolderList to fetch.</param> /// <param name="year">The Year parameter of the FolderList to fetch.</param> /// <param name="subject">The Subject parameter of the FolderList to fetch.</param> /// <param name="folderStatusID">The FolderStatusID parameter of the FolderList to fetch.</param> /// <param name="createDate">The CreateDate parameter of the FolderList to fetch.</param> /// <param name="createUserID">The CreateUserID parameter of the FolderList to fetch.</param> /// <param name="changeDate">The ChangeDate parameter of the FolderList to fetch.</param> /// <param name="changeUserID">The ChangeUserID parameter of the FolderList to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetFolderList(int? folderTypeID, string folderRef, int? year, string subject, int? folderStatusID, SmartDate createDate, int? createUserID, SmartDate changeDate, int? changeUserID, EventHandler<DataPortalResult<FolderList>> callback) { DataPortal.BeginFetch<FolderList>(new FilteredCriteria(folderTypeID, folderRef, year, subject, folderStatusID, createDate, createUserID, changeDate, changeUserID), callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="FolderList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public FolderList() { // Use factory methods and do not use direct creation. var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Nested Criteria /// <summary> /// FilteredCriteria criteria. /// </summary> [Serializable] protected class FilteredCriteria : CriteriaBase<FilteredCriteria> { /// <summary> /// Maintains metadata about <see cref="FolderTypeID"/> property. /// </summary> public static readonly PropertyInfo<int?> FolderTypeIDProperty = RegisterProperty<int?>(p => p.FolderTypeID); /// <summary> /// Gets or sets the Folder Type ID. /// </summary> /// <value>The Folder Type ID.</value> public int? FolderTypeID { get { return ReadProperty(FolderTypeIDProperty); } set { LoadProperty(FolderTypeIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="FolderRef"/> property. /// </summary> public static readonly PropertyInfo<string> FolderRefProperty = RegisterProperty<string>(p => p.FolderRef); /// <summary> /// Gets or sets the Folder Ref. /// </summary> /// <value>The Folder Ref.</value> public string FolderRef { get { return ReadProperty(FolderRefProperty); } set { LoadProperty(FolderRefProperty, value); } } /// <summary> /// Maintains metadata about <see cref="Year"/> property. /// </summary> public static readonly PropertyInfo<int?> YearProperty = RegisterProperty<int?>(p => p.Year); /// <summary> /// Gets or sets the Year. /// </summary> /// <value>The Year.</value> public int? Year { get { return ReadProperty(YearProperty); } set { LoadProperty(YearProperty, value); } } /// <summary> /// Maintains metadata about <see cref="Subject"/> property. /// </summary> public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject); /// <summary> /// Gets or sets the Subject. /// </summary> /// <value>The Subject.</value> public string Subject { get { return ReadProperty(SubjectProperty); } set { LoadProperty(SubjectProperty, value); } } /// <summary> /// Maintains metadata about <see cref="FolderStatusID"/> property. /// </summary> public static readonly PropertyInfo<int?> FolderStatusIDProperty = RegisterProperty<int?>(p => p.FolderStatusID); /// <summary> /// Gets or sets the Folder Status ID. /// </summary> /// <value>The Folder Status ID.</value> public int? FolderStatusID { get { return ReadProperty(FolderStatusIDProperty); } set { LoadProperty(FolderStatusIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CreateDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate); /// <summary> /// Gets or sets the Create Date. /// </summary> /// <value>The Create Date.</value> public SmartDate CreateDate { get { return ReadProperty(CreateDateProperty); } set { LoadProperty(CreateDateProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CreateUserID"/> property. /// </summary> public static readonly PropertyInfo<int?> CreateUserIDProperty = RegisterProperty<int?>(p => p.CreateUserID); /// <summary> /// Gets or sets the Create User ID. /// </summary> /// <value>The Create User ID.</value> public int? CreateUserID { get { return ReadProperty(CreateUserIDProperty); } set { LoadProperty(CreateUserIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="ChangeDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate); /// <summary> /// Gets or sets the Change Date. /// </summary> /// <value>The Change Date.</value> public SmartDate ChangeDate { get { return ReadProperty(ChangeDateProperty); } set { LoadProperty(ChangeDateProperty, value); } } /// <summary> /// Maintains metadata about <see cref="ChangeUserID"/> property. /// </summary> public static readonly PropertyInfo<int?> ChangeUserIDProperty = RegisterProperty<int?>(p => p.ChangeUserID); /// <summary> /// Gets or sets the Change User ID. /// </summary> /// <value>The Change User ID.</value> public int? ChangeUserID { get { return ReadProperty(ChangeUserIDProperty); } set { LoadProperty(ChangeUserIDProperty, value); } } /// <summary> /// Initializes a new instance of the <see cref="FilteredCriteria"/> class. /// </summary> /// <remarks> A parameterless constructor is required by the MobileFormatter.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public FilteredCriteria() { } /// <summary> /// Initializes a new instance of the <see cref="FilteredCriteria"/> class. /// </summary> /// <param name="folderTypeID">The FolderTypeID.</param> /// <param name="folderRef">The FolderRef.</param> /// <param name="year">The Year.</param> /// <param name="subject">The Subject.</param> /// <param name="folderStatusID">The FolderStatusID.</param> /// <param name="createDate">The CreateDate.</param> /// <param name="createUserID">The CreateUserID.</param> /// <param name="changeDate">The ChangeDate.</param> /// <param name="changeUserID">The ChangeUserID.</param> public FilteredCriteria(int? folderTypeID, string folderRef, int? year, string subject, int? folderStatusID, SmartDate createDate, int? createUserID, SmartDate changeDate, int? changeUserID) { FolderTypeID = folderTypeID; FolderRef = folderRef; Year = year; Subject = subject; FolderStatusID = folderStatusID; CreateDate = createDate; CreateUserID = createUserID; ChangeDate = changeDate; ChangeUserID = changeUserID; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (obj is FilteredCriteria) { var c = (FilteredCriteria) obj; if (!FolderTypeID.Equals(c.FolderTypeID)) return false; if (!FolderRef.Equals(c.FolderRef)) return false; if (!Year.Equals(c.Year)) return false; if (!Subject.Equals(c.Subject)) return false; if (!FolderStatusID.Equals(c.FolderStatusID)) return false; if (!CreateDate.Equals(c.CreateDate)) return false; if (!CreateUserID.Equals(c.CreateUserID)) return false; if (!ChangeDate.Equals(c.ChangeDate)) return false; if (!ChangeUserID.Equals(c.ChangeUserID)) return false; return true; } return false; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return string.Concat("FilteredCriteria", FolderTypeID.ToString(), FolderRef.ToString(), Year.ToString(), Subject.ToString(), FolderStatusID.ToString(), CreateDate.ToString(), CreateUserID.ToString(), ChangeDate.ToString(), ChangeUserID.ToString()).GetHashCode(); } } #endregion #region Data Access /// <summary> /// Loads a <see cref="FolderList"/> collection from the database or from the cache. /// </summary> protected void DataPortal_Fetch() { if (IsCached) { LoadCachedList(); return; } using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("GetFolderList", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; var args = new DataPortalHookArgs(cmd); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } _list = this; } private void LoadCachedList() { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AddRange(_list); RaiseListChangedEvents = rlce; IsReadOnly = true; } /// <summary> /// Loads a <see cref="FolderList"/> collection from the database, based on given criteria. /// </summary> /// <param name="crit">The fetch criteria.</param> protected void DataPortal_Fetch(FilteredCriteria crit) { using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("GetFolderList", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FolderTypeID", crit.FolderTypeID == null ? (object)DBNull.Value : crit.FolderTypeID.Value).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@FolderRef", crit.FolderRef == null ? (object)DBNull.Value : crit.FolderRef).DbType = DbType.String; cmd.Parameters.AddWithValue("@Year", crit.Year == null ? (object)DBNull.Value : crit.Year.Value).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Subject", crit.Subject == null ? (object)DBNull.Value : crit.Subject).DbType = DbType.String; cmd.Parameters.AddWithValue("@FolderStatusID", crit.FolderStatusID == null ? (object)DBNull.Value : crit.FolderStatusID.Value).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@CreateDate", crit.CreateDate == null ? (object)DBNull.Value : crit.CreateDate.DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@CreateUserID", crit.CreateUserID == null ? (object)DBNull.Value : crit.CreateUserID.Value).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@ChangeDate", crit.ChangeDate == null ? (object)DBNull.Value : crit.ChangeDate.DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUserID", crit.ChangeUserID == null ? (object)DBNull.Value : crit.ChangeUserID.Value).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, crit); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); } } /// <summary> /// Loads all <see cref="FolderList"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(FolderInfo.GetFolderInfo(dr)); } 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 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class PortName_Property : PortsTest { //Determines how long the randomly generated PortName is private const int rndPortNameSize = 255; private enum ThrowAt { Set, Open }; private readonly DosDevices _dosDevices; public PortName_Property() { _dosDevices = new DosDevices(); } #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_COM1_After_Open() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying setting PortName=COM1 after open has been called"); VerifyExceptionAfterOpen(com, TCSupport.LocalMachineSerialInfo.FirstAvailablePortName, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasTwoSerialPorts))] public void PortName_COM2_After_Open() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Debug.WriteLine("Verifying setting PortName=COM2 after open has been called"); VerifyExceptionAfterOpen(com, TCSupport.LocalMachineSerialInfo.SecondAvailablePortName, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_Empty() { Debug.WriteLine("Verifying setting PortName=\"\""); VerifyException("", ThrowAt.Set, typeof(ArgumentException), typeof(ArgumentException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_null() { Debug.WriteLine("Verifying setting PortName=null"); VerifyException(null, ThrowAt.Set, typeof(ArgumentNullException), typeof(ArgumentNullException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_RND() { Random rndGen = new Random(); StringBuilder rndStrBuf = new StringBuilder(); for (int i = 0; i < rndPortNameSize; i++) { rndStrBuf.Append((char)rndGen.Next(0, ushort.MaxValue)); } Debug.WriteLine("Verifying setting PortName to a random string"); VerifyException(rndStrBuf.ToString(), ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_FileName() { string fileName = "PortNameEqualToFileName.txt"; FileStream testFile = File.Open(fileName, FileMode.Create); ASCIIEncoding asciiEncd = new ASCIIEncoding(); string testStr = "Hello World"; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); Debug.WriteLine("Verifying setting PortName={0}", fileName); VerifyException(fileName, ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException)); Debug.WriteLine("Verifying setting PortName={0}", Environment.CurrentDirectory + fileName); VerifyException(Environment.CurrentDirectory + fileName, ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException)); File.Delete(fileName); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_COM257() { Debug.WriteLine("Verifying setting PortName=COM257"); VerifyException("COM257", ThrowAt.Open, typeof(IOException), typeof(InvalidOperationException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_LPT() { Type expectedException = _dosDevices.CommonNameExists("LPT") ? typeof(ArgumentException) : typeof(ArgumentException); Debug.WriteLine("Verifying setting PortName=LPT"); VerifyException("LPT", ThrowAt.Open, expectedException, typeof(InvalidOperationException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_LPT1() { Type expectedException = _dosDevices.CommonNameExists("LPT1") ? typeof(ArgumentException) : typeof(ArgumentException); Debug.WriteLine("Verifying setting PortName=LPT1"); VerifyException("LPT1", ThrowAt.Open, expectedException, typeof(InvalidOperationException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_PHYSICALDRIVE0() { Type expectedException = _dosDevices.CommonNameExists("PHYSICALDRIVE0") ? typeof(ArgumentException) : typeof(ArgumentException); Debug.WriteLine("Verifying setting PortName=PHYSICALDRIVE0"); VerifyException("PHYSICALDRIVE0", ThrowAt.Open, expectedException, typeof(InvalidOperationException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_A() { Type expectedException = _dosDevices.CommonNameExists("A:") ? typeof(ArgumentException) : typeof(ArgumentException); Debug.WriteLine("Verifying setting PortName=A:"); VerifyException("A:", ThrowAt.Open, expectedException, typeof(InvalidOperationException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_C() { Debug.WriteLine("Verifying setting PortName=C:"); VerifyException("C:", ThrowAt.Open, new[] { typeof(ArgumentException), typeof(ArgumentException) }, typeof(InvalidOperationException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void PortName_SystemDrive() { Debug.WriteLine("Verifying setting PortName=%SYSTEMDRIVE%"); string portName = Environment.GetEnvironmentVariable("SystemDrive"); if (!string.IsNullOrEmpty(portName)) { VerifyException(portName, ThrowAt.Open, new[] { typeof(ArgumentException) }, typeof(InvalidOperationException)); } } #endregion #region Verification for Test Cases private void VerifyException(string portName, ThrowAt throwAt, Type expectedExceptionAtOpen, Type expectedExceptionAfterOpen) { VerifyException(portName, throwAt, new[] { expectedExceptionAtOpen }, expectedExceptionAfterOpen); } private void VerifyException(string portName, ThrowAt throwAt, Type[] expectedExceptionAtOpen, Type expectedExceptionAfterOpen) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { VerifyExceptionAtOpen(com, portName, throwAt, expectedExceptionAtOpen); if (com.IsOpen) com.Close(); VerifyExceptionAfterOpen(com, portName, expectedExceptionAfterOpen); } } private void VerifyExceptionAtOpen(SerialPort com, string portName, ThrowAt throwAt, Type expectedException) { VerifyExceptionAtOpen(com, portName, throwAt, new[] { expectedException }); } private void VerifyExceptionAtOpen(SerialPort com, string portName, ThrowAt throwAt, Type[] expectedExceptions) { string origPortName = com.PortName; SerialPortProperties serPortProp = new SerialPortProperties(); if (null != expectedExceptions && 0 < expectedExceptions.Length) { serPortProp.SetAllPropertiesToDefaults(); } else { serPortProp.SetAllPropertiesToOpenDefaults(); } if (ThrowAt.Open == throwAt) serPortProp.SetProperty("PortName", portName); else serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); try { com.PortName = portName; if (ThrowAt.Open == throwAt) com.Open(); if (null != expectedExceptions && 0 < expectedExceptions.Length) { Fail("ERROR!!! Expected Open() to throw "); for (int i = 0; i < expectedExceptions.Length; ++i) Console.Write(expectedExceptions[i] + " "); Debug.WriteLine(" and nothing was thrown"); } } catch (Exception e) { if (null == expectedExceptions || 0 == expectedExceptions.Length) { Fail("ERROR!!! Expected Open() NOT to throw an exception and the following was thrown:\n{0}", e); } else { bool exceptionFound = false; Type actualExceptionType = e.GetType(); for (int i = 0; i < expectedExceptions.Length; ++i) { if (actualExceptionType == expectedExceptions[i]) { exceptionFound = true; break; } } if (exceptionFound) { Debug.WriteLine("Caught expected exception:\n{0}", e.GetType()); } else { Fail("ERROR!!! Expected Open() throw "); for (int i = 0; i < expectedExceptions.Length; ++i) Console.Write(expectedExceptions[i] + " "); Debug.WriteLine(" and the following was thrown:\n{0}", e); } } } serPortProp.VerifyPropertiesAndPrint(com); com.PortName = origPortName; } private void VerifyExceptionAfterOpen(SerialPort com, string portName, Type expectedException) { SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", com.PortName); try { com.PortName = portName; if (null != expectedException) { Fail("ERROR!!! Expected setting the PortName after Open() to throw {0} and nothing was thrown", expectedException); } } catch (Exception e) { if (null == expectedException) { Fail("ERROR!!! Expected setting the PortName after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { Fail("ERROR!!! Expected setting the PortName after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } serPortProp.VerifyPropertiesAndPrint(com); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Sample.CommandService.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using Subtext.Extensibility; using Subtext.Extensibility.Interfaces; using Subtext.Framework.Configuration; namespace Subtext.Framework.Components { /// <summary> /// Summary description for Entry. /// </summary> [Serializable] public class Entry : IEntryIdentity { DateTime _dateSyndicated = NullValue.NullDateTime; public Entry(PostType postType, Blog blog) { Categories = new List<string>(); PostConfig = PostConfig.None; DateModifiedUtc = NullValue.NullDateTime; DateCreatedUtc = NullValue.NullDateTime; PostType = postType; Blog = blog; Id = NullValue.NullInt32; } public Entry(PostType postType) : this(postType, Config.CurrentBlog) { } /// <summary> /// Gets or sets the blog ID. /// </summary> /// <value>The blog ID.</value> public int BlogId { get; set; } public Blog Blog { get; set; } /// <summary> /// Gets a value indicating whether this instance has description. /// </summary> /// <value> /// <c>true</c> if this instance has description; otherwise, <c>false</c>. /// </value> public bool HasDescription { get { return !String.IsNullOrEmpty(Description); } } /// <summary> /// Gets or sets the description or excerpt for this blog post. /// Some blogs like to sydicate description only. /// </summary> /// <value>The description.</value> public string Description { //todo: let's rename this property to excerpt. get; set; } /// <summary> /// Gets a value indicating whether this instance has entry name. /// </summary> /// <value> /// <c>true</c> if this instance has entry name; otherwise, <c>false</c>. /// </value> public bool HasEntryName { get { return EntryName != null && EntryName.Trim().Length > 0; } } /// <summary> /// Gets or sets the title of this post. /// </summary> /// <value>The title.</value> public string Title { get; set; } /// <summary> /// Gets or sets the body of the Entry. This is the /// main content of the entry. /// </summary> /// <value></value> public string Body { get; set; } /// <summary> /// Gets or sets the author name of the entry. /// For comments, this is the name given by the commenter. /// </summary> /// <value>The author.</value> public string Author { get; set; } /// <summary> /// Gets or sets the email of the author. /// </summary> /// <value>The email.</value> public string Email { get; set; } /// <summary> /// Gets or sets the date this entry was last updated. /// </summary> /// <value></value> public DateTime DateModifiedUtc { get; set; } /// <summary> /// Gets or sets the date the item was published. /// </summary> /// <value></value> public DateTime DateSyndicated { get { if (Blog == null) { return _datePublishedUtc; } if (DatePublishedUtc.IsNull()) { return NullValue.NullDateTime; } return Blog.TimeZone.FromUtc(DatePublishedUtc); } } DateTime _datePublishedUtc = NullValue.NullDateTime; public DateTime DatePublishedUtc { get { return _datePublishedUtc; } set { if (value.IsNull()) { IncludeInMainSyndication = false; } _datePublishedUtc = value; } } /// <summary> /// Gets or sets a value indicating whether this entry is active. /// </summary> /// <value><c>true</c> if this instance is active; otherwise, <c>false</c>.</value> public bool IsActive { get { return EntryPropertyCheck(PostConfig.IsActive); } set { PostConfigSetter(PostConfig.IsActive, value); } } /// <summary> /// Gets or sets a value indicating whether this entry allows comments. /// </summary> /// <value><c>true</c> if [allows comments]; otherwise, <c>false</c>.</value> public bool AllowComments { get { return EntryPropertyCheck(PostConfig.AllowComments); } set { PostConfigSetter(PostConfig.AllowComments, value); } } /// <summary> /// Gets or sets a value indicating whether this entry is displayed on the home page. /// </summary> /// <value><c>true</c> if [display on home page]; otherwise, <c>false</c>.</value> public bool DisplayOnHomePage { get { return EntryPropertyCheck(PostConfig.DisplayOnHomepage); } set { PostConfigSetter(PostConfig.DisplayOnHomepage, value); } } /// <summary> /// Gets or sets a value indicating whether the description only should be syndicated. /// </summary> /// <value> /// <c>true</c> if [syndicate description only]; otherwise, <c>false</c>. /// </value> public bool SyndicateDescriptionOnly { get { return EntryPropertyCheck(PostConfig.SyndicateDescriptionOnly); } set { PostConfigSetter(PostConfig.SyndicateDescriptionOnly, value); } } /// <summary> /// Gets or sets a value indicating whether [include in main syndication]. /// </summary> /// <value> /// <c>true</c> if [include in main syndication]; otherwise, <c>false</c>. /// </value> public bool IncludeInMainSyndication { get { return EntryPropertyCheck(PostConfig.IncludeInMainSyndication); } set { PostConfigSetter(PostConfig.IncludeInMainSyndication, value); } } /// <summary> /// Whether or not this entry is aggregated. /// </summary> public bool IsAggregated { get { return EntryPropertyCheck(PostConfig.IsAggregated); } set { PostConfigSetter(PostConfig.IsAggregated, value); } } /// <summary> /// True if comments have been closed. Otherwise false. Comments are closed /// either explicitly or after by global age setting which overrides explicit settings /// </summary> public bool CommentingClosed { get { return (CommentingClosedByAge || EntryPropertyCheck(PostConfig.CommentsClosed)); } set { // Closing By Age overrides explicit closing if (!CommentingClosedByAge) { PostConfigSetter(PostConfig.CommentsClosed, value); } } } /// <summary> /// Returns true if the comments for this entry are closed due /// to the age of the entry. This is related to the DaysTillCommentsClose setting. /// </summary> public bool CommentingClosedByAge { get { if (Blog.DaysTillCommentsClose == int.MaxValue) { return false; } return DateTimeOffset.UtcNow > DatePublishedUtc.AddDays(Blog.DaysTillCommentsClose); } } public int FeedBackCount { get; set; } public PostConfig PostConfig { get; set; } /// <summary> /// Returns the categories for this entry. /// </summary> public ICollection<string> Categories { get; private set; } /// <summary> /// Gets and sets the enclosure for the entry. /// </summary> public Enclosure Enclosure { get; set; } /// <summary> /// Gets or sets the entry ID. /// </summary> /// <value>The entry ID.</value> public int Id { get; set; } /// <summary> /// Gets or sets the type of the post. /// </summary> /// <value>The type of the post.</value> public PostType PostType { get; set; } /// <summary> /// Gets or sets the name of the entry. This is used /// to create a friendly URL for this entry. /// </summary> /// <value>The name of the entry.</value> public string EntryName { get; set; } /// <summary> /// Gets or sets the date this item was created. /// </summary> /// <value></value> public DateTime DateCreatedUtc { get; set; } public DateTime DateCreated { get { return Blog.TimeZone.FromUtc(DateCreatedUtc); } } protected bool EntryPropertyCheck(PostConfig ep) { return (PostConfig & ep) == ep; } protected void PostConfigSetter(PostConfig ep, bool select) { if (select) { PostConfig = PostConfig | ep; } else { PostConfig = PostConfig & ~ep; } } /// <summary> /// Calculates a simple checksum of the specified text. /// This is used for comment filtering purposes. /// Once deployed, this algorithm shouldn't change. /// </summary> /// <param name="text">Text.</param> /// <returns></returns> public static int CalculateChecksum(string text) { if (text == null) { throw new ArgumentNullException("text"); } int checksum = 0; foreach (char c in text) { checksum += c; } return checksum; } public ICollection<FeedbackItem> Comments { get { if (_comments == null) { _comments = new List<FeedbackItem>(); } return _comments; } } List<FeedbackItem> _comments; } }
using System; using System.IO; using System.Collections.Generic; using Microsoft.Dnx.Runtime; using Microsoft.Dnx.Runtime.Common.CommandLine; using Newtonsoft.Json; using System.Linq; namespace Srclib.Nuget { class ScanConsoleCommand { private static PackageVersions pv = new PackageVersions(); /// <summary> /// Convert .csproj files into DNX configuration files /// </summary> /// <param name="path">path to project folder</param> public static void ConvertCsproj(string path) { HashSet<string> names = new HashSet<string>(); string dir = path.Substring(0, path.LastIndexOf('/')); if (!File.Exists(dir + "/project.json")) { //gac works correctly only in docker image string gac = "/gac/v4.5/"; string global = ""; string input = File.ReadAllText(path); string output = "{\n \"frameworks\": {\n \"dnx451\": {\n \"dependencies\": {\n"; int idx = input.IndexOf("<Reference Include=\""); while (idx != -1) { int quote = input.IndexOf('\"', idx + 20); int comma = input.IndexOf(',', idx + 20); if ((comma != -1) && (comma < quote)) { quote = comma; } string name = input.Substring(idx + 20, quote - idx - 20); if ((name.IndexOf('$') == -1) && (name.IndexOf('\\') == -1) && !names.Contains(name)) { names.Add(name); string version = pv.GetVersion(name.ToLower()); if (version != null) { output = output + " \"" + name + "\": \"" + version + "\",\n"; } else { output = output + " \"" + name + "\": \"\",\n"; if (File.Exists(gac + name + ".dll") && !name.Equals("mscorlib")) { global = global + gac + name + ".dll\n"; } } } idx = input.IndexOf("<Reference Include=\"", quote); } output = output + " }\n }\n }\n}"; File.WriteAllText(dir + "/project.json", output); if (global.Length > 0) { File.WriteAllText(dir + "/global.log", global); } } } /// <summary> /// finds all c# Visual Studio project files in project folder and subfolders /// </summary> /// <param name="root">directory info for project folder</param> /// <returns>returns an array of csproj files</returns> public static FileInfo[] FindVSProjects(DirectoryInfo root) { FileInfo[] files = null; DirectoryInfo[] subDirs = null; try { files = root.GetFiles("*.csproj"); } catch (Exception e) { } subDirs = root.GetDirectories(); foreach (DirectoryInfo dirInfo in subDirs) { // Resursive call for each subdirectory. FileInfo[] res = FindVSProjects(dirInfo); files = files.Concat(res).ToArray(); } return files; } private static string getGitUrl() { try { string config = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "./.git/config")); int i = config.IndexOf("\turl = "); if (i != -1) { int j = config.IndexOf('\n', i); string url = config.Substring(i + 7, j - i - 7); return url; } else { return null; } } catch (Exception e) { return null; } } public static void Register(CommandLineApplication cmdApp, Microsoft.Extensions.PlatformAbstractions.IApplicationEnvironment appEnvironment) { cmdApp.Command("scan", c => { c.Description = "Scan a directory tree and produce a JSON array of source units"; c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { string url = getGitUrl(); if (url.EndsWith("github.com/dotnet/coreclr")) { Console.Error.WriteLine("special case coreclr"); DepresolveConsoleCommand.RunForResult("/bin/bash", "-c \"rm `find -name project.json`\""); DepresolveConsoleCommand.RunForResult("/bin/bash", "-c \"rm `find -name '*.csproj'`\""); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./src/mscorlib/project.json"), "{\n \"frameworks\": {\n \"dnx451\": {\n \"dependencies\": {\n }\n }\n }\n}"); } else if (url.EndsWith("github.com/Microsoft/referencesource")) { Console.Error.WriteLine("special case referencesource"); string json = "{\n \"frameworks\": {\n \"dnx451\": {\n \"dependencies\": {\n }\n }\n }\n}"; File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./mscorlib/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Activities/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Xml.Linq/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Numerics/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web.Services/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.IdentityModel/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl/System.IO.v2.5/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl/System.Runtime.v1.5/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl/System.IO.v1.5/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl/System.Threading.Tasks.v2.5/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl/System.Threading.Tasks.v1.5/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl/System.Runtime.v2.5/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Activities.Presentation/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel.Activities/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web.ApplicationServices/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./XamlBuildTask/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.IdentityModel.Selectors/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Workflow.Runtime/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web.Extensions/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web.Mobile/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel.Activation/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Net/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Xml/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel.Channels/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Data.SqlXml/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Data.DataSetExtensions/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel.Discovery/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Activities.DurableInstancing/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel.Routing/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Core/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Workflow.ComponentModel/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web.Entity.Design/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Data.Entity.Design/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ComponentModel.DataAnnotations/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Runtime.DurableInstancing/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web.DynamicData/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel.Internals/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Data/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./SMDiagnostics/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.WorkflowServices/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Workflow.Activities/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel.WasHosting/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web.Entity/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Data.Entity/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Configuration/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Web.Routing/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Runtime.Serialization/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Runtime.Caching/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Xaml.Hosting/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.ServiceModel.Web/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Activities.Core.Presentation/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./System.Data.Linq/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl.Async/Microsoft.Threading.Tasks.Extensions.Desktop/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl.Async/Microsoft.Threading.Tasks.Extensions.Phone/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl.Async/Microsoft.Threading.Tasks.Extensions/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl.Async/Microsoft.Threading.Tasks/project.json"), json); File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "./Microsoft.Bcl.Async/Microsoft.Threading.Tasks.Extensions.Silverlight/project.json"), json); } else if (url.EndsWith("github.com/AutoMapper/AutoMapper")) { DepresolveConsoleCommand.RunForResult("/bin/bash", @"-c ""sed 's/..\\\\/..\//g' -i `find -name project.json`"""); } var dir = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), ".")); DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory()); FileInfo[] fis = FindVSProjects(di); string[] projects = new string[fis.Length]; for (int i = 0; i < fis.Length; i++) { projects[i] = fis[i].FullName; ConvertCsproj(projects[i]); } var sourceUnits = new List<SourceUnit>(); foreach(var proj in Scan(dir)) { sourceUnits.Add(SourceUnit.FromProject(proj, dir)); } if (sourceUnits.Count == 0) { //not a DNX project and not a VS project sourceUnits.Add(SourceUnit.FromDirectory("name", dir)); } Console.WriteLine(JsonConvert.SerializeObject(sourceUnits, Formatting.Indented)); await DepresolveConsoleCommand.RunResolve(dir); return 0; }); }); } static IEnumerable<Project> Scan(string dir) { if (Project.HasProjectFile(dir)) { Project proj; if (Project.TryGetProject(dir, out proj) && proj.CompilerServices == null) yield return proj; yield break; } foreach (var subdir in Directory.EnumerateDirectories(dir)) { // Skip directories starting with . if (subdir.StartsWith(".")) continue; foreach (var proj in Scan(subdir)) yield return proj; } } } }
/////////////////////////////////////////////////////////////////////////////////// // Open 3D Model Viewer (open3mod) (v2.0) // [TextureSet.cs] // (c) 2012-2015, Open3Mod Contributors // // Licensed under the terms and conditions of the 3-clause BSD license. See // the LICENSE file in the root folder of the repository for the details. // // HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Assimp; namespace open3mod { /// <summary> /// Maintains all the textures for a scene. The scene just adds the names /// of the textures it needs and TextureSet loads them asynchronously, /// offering a callback whenever a texture finishes. /// /// Textures are uniquely identified by string identifiers, which are /// (usually) their loading paths. These paths need not be unique and this is /// also not enforced - if two paths are different but point to the /// same physical file, it may happen that this file gets loaded twice. /// /// The class also handles replacing textures by other files (i.e. by /// dragging them onto the texture inspector view). Replacements are /// recorded so exporters and renderer can properly apply them. Replaced /// textures receive new, unique IDs even if they did already exist /// to avoid all the issues that could arise from cyclic replacements. /// </summary> public sealed class TextureSet : IDisposable { private readonly string _baseDir; private readonly Dictionary<string, Texture> _dict; private readonly List<string> _loaded; /// <summary> /// Texture callback delegate, see AddCallback() /// </summary> /// <param name="name"></param> /// <param name="tex"></param> /// <returns>Return false to unregister the callback</returns> public delegate bool TextureCallback(string name, Texture tex); private readonly List<TextureCallback> _textureCallbacks; private readonly Dictionary<string, KeyValuePair<string,string>> _replacements; private bool _disposed; private readonly List<TextureCallback> _replaceCallbacks; public TextureSet(string baseDir) { _baseDir = baseDir; _dict = new Dictionary<string, Texture>(); _replacements = new Dictionary<string, KeyValuePair<string, string> >(); _loaded = new List<string>(); // TODO use events _textureCallbacks = new List<TextureCallback>(); _replaceCallbacks = new List<TextureCallback>(); } /// <summary> /// Register a callback method that will be invoked every time a texture /// is being replaced. The callback is not invoked for previously /// replaced textures. /// </summary> /// <param name="callback">A callback that is safe to be invoked /// from any thread. The callback receives the previous name of /// the texture as first parameter, but the texture instance /// that is passed for the second parameter is already the /// new texture.</param> public void AddReplaceCallback(TextureCallback callback) { Debug.Assert(callback != null); _replaceCallbacks.Add(callback); } /// <summary> /// Register a callback method that will be invoked once a texture /// has finished loading. Upon adding the callback, it will /// immediately be invoked with the names of all textures that /// have already been loaded in the past. /// </summary> /// <param name="callback">A callback that is safe to be invoked /// from any thread.</param> public void AddCallback(TextureCallback callback) { Debug.Assert(callback != null); lock (_loaded) { if (InvokeCallbacks(callback)) return; _textureCallbacks.Add(callback); } } private bool InvokeCallbacks(TextureCallback callback) { foreach (var s in _loaded) { if (!callback(s, _dict[s])) { return true; } } foreach (var kv in _replacements) { if (!_loaded.Contains(kv.Value.Value)) { continue; } if (!callback(kv.Value.Key, Get(kv.Value.Value))) { return true; } } return false; } /// <summary> /// Add a texture to the TextureSet. This is the only place where /// Texture instances are actually created. The actual image for textures /// added to the set is loaded using a background thread. /// </summary> /// <param name="path">Texture's given path or, in case an embedded data source /// is specified for the texture, an arbitrary but unique value to identify /// the texture (preferably not a file path) /// </param> /// <param name="embeddedDataSource">Optional parameter that specifies /// an in-memory, embedded data source for the texture. </param> public void Add(string path, Assimp.EmbeddedTexture embeddedDataSource = null) { if(_dict.ContainsKey(path)) { return; } Texture.CompletionCallback closure = self => { lock(_loaded) { if (_disposed) { return; } Debug.Assert(_dict.ContainsKey(path)); _loaded.Add(path); // If this texture is being used as replacement for another texture, // we need to invoke callbacks for its ID too // TODO obviously, all the replacement code needs a re-design. foreach (var kv in _replacements) { if (kv.Value.Value == path) { for (int i = 0, e = _textureCallbacks.Count; i < e; ) { var callback = _textureCallbacks[i]; if (!callback(kv.Value.Key, self)) { _textureCallbacks.RemoveAt(i); --e; continue; } ++i; } } } for (int i = 0, e = _textureCallbacks.Count; i < e; ) { var callback = _textureCallbacks[i]; if (!callback(path, self)) { _textureCallbacks.RemoveAt(i); --e; continue; } ++i; } } }; _dict.Add(path, embeddedDataSource == null ? new Texture(path, _baseDir, closure) : new Texture(embeddedDataSource, path, closure)); } /// <summary> /// Check if a given texture exists. /// </summary> /// <param name="path">Texture id to check</param> public bool Exists(string path) { return _dict.ContainsKey(path); } /// <summary> /// Get a list of all texture ids Add()ed to the texture set. /// </summary> /// <returns></returns> public string[] GetTextureIds() { return _dict.Keys.ToArray(); } /// <summary> /// Get a given texture instance. /// </summary> /// <param name="path">Texture id to retrieve. A texture with /// this id _must_ be contained in the set</param> public Texture Get(string path) { Debug.Assert(Exists(path)); return _dict[path]; } /// <summary> /// Get a given texture instance or the texture instance it /// has been replaced with. /// </summary> /// <param name="path">Texture id to retrieve. A texture with /// this id _must_ either be contained in this set or it /// must have been replaced by another texture using Replace()</param> public Texture GetOriginalOrReplacement(string path) { if(_replacements.ContainsKey(path)) { return GetOriginalOrReplacement(_replacements[path].Key); } return _dict[path]; } /// <summary> /// Delete a texture from the set. /// </summary> /// <param name="path">Texture id to be removed. A texture with /// this id _must_ be contained in the set</param> public void Delete(string path) { Debug.Assert(Exists(path)); var old = Get(path); old.Dispose(); _dict.Remove(path); // TODO what to do with _replacements? } /// <summary> /// Replace a texture with another texture. This does two things: /// i) it loads the new texture /// ii) it creates a note that the texture has been replaced /// /// If the new texture does already exist in the texture set, /// the existing instance will _not_ be re-used. Instead, /// a new instance with an unique name will be created (this /// prevents cyclic replacements). /// </summary> /// <param name="path">Old texture id, must exist</param> /// <param name="newPath">New texture id, may already exist</param> /// <returns>The id of the replacement texture. This is /// the same as the id passed for the newPath parameter unless /// this id did already exist. </returns> public string Replace(string path, string newPath) { Debug.Assert(Exists(path)); Debug.Assert(path != newPath); string newId; if(Exists(newPath)) { newId = newPath + '_' + Guid.NewGuid(); } else { newId = newPath; Add(newPath); } var tex = GetOriginalOrReplacement(path); _replacements[path] = new KeyValuePair<string, string>(newId, newPath); if (_replaceCallbacks.Count > 0) { foreach (var v in _replaceCallbacks) { v(path, tex); } } return newId; } public void Dispose() { if(_disposed) { return; } _disposed = true; foreach (var k in _dict) { k.Value.Dispose(); } lock (_loaded) // TODO don't know if this is safe here { _dict.Clear(); _loaded.Clear(); } } /// <summary> /// Obtain an enumeration of all loaded textures. The enumeration is safe /// to use from any thread as well as with concurring texture load jobs. /// </summary> /// <returns></returns> public IEnumerable<Texture> GetLoadedTexturesCollectionThreadsafe() { lock (_loaded) { foreach(var v in _loaded) { yield return _dict[v]; } } } } } /* vi: set shiftwidth=4 tabstop=4: */
// GtkSharp.Generation.ObjectGen.cs - The Object Generatable. // // Author: Mike Kestner <[email protected]> // // Copyright (c) 2001-2003 Mike Kestner // Copyright (c) 2003-2004 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GtkSharp.Generation { using System; using System.Collections; using System.IO; using System.Text; using System.Xml; public class ObjectGen : ObjectBase { private ArrayList custom_attrs = new ArrayList(); private ArrayList strings = new ArrayList(); private ArrayList vm_nodes = new ArrayList(); private Hashtable childprops = new Hashtable(); private static Hashtable dirs = new Hashtable (); public ObjectGen (XmlElement ns, XmlElement elem) : base (ns, elem) { foreach (XmlNode node in elem.ChildNodes) { string name; if (!(node is XmlElement)) continue; XmlElement member = (XmlElement) node; switch (node.Name) { case "callback": Statistics.IgnoreCount++; break; case "custom-attribute": custom_attrs.Add (member.InnerXml); break; case "virtual_method": Statistics.IgnoreCount++; break; case "static-string": strings.Add (node); break; case "childprop": name = member.GetAttribute ("name"); while (childprops.ContainsKey (name)) name += "mangled"; childprops.Add (name, new ChildProperty (member, this)); break; default: if (!IsNodeNameHandled (node.Name)) Console.WriteLine ("Unexpected node " + node.Name + " in " + CName); break; } } } public override bool Validate () { ArrayList invalids = new ArrayList (); foreach (ChildProperty prop in childprops.Values) { if (!prop.Validate ()) { Console.WriteLine ("in Object " + QualifiedName); invalids.Add (prop); } } foreach (ChildProperty prop in invalids) childprops.Remove (prop); return base.Validate (); } private bool DisableVoidCtor { get { return Elem.HasAttribute ("disable_void_ctor"); } } private bool DisableGTypeCtor { get { return Elem.HasAttribute ("disable_gtype_ctor"); } } private class DirectoryInfo { public string assembly_name; public Hashtable objects; public DirectoryInfo (string assembly_name) { this.assembly_name = assembly_name; objects = new Hashtable (); } } private static DirectoryInfo GetDirectoryInfo (string dir, string assembly_name) { DirectoryInfo result; if (dirs.ContainsKey (dir)) { result = dirs [dir] as DirectoryInfo; if (result.assembly_name != assembly_name) { Console.WriteLine ("Can't put multiple assemblies in one directory."); return null; } return result; } result = new DirectoryInfo (assembly_name); dirs.Add (dir, result); return result; } public override void Generate (GenerationInfo gen_info) { gen_info.CurrentType = Name; string asm_name = gen_info.AssemblyName.Length == 0 ? NS.ToLower () + "-sharp" : gen_info.AssemblyName; DirectoryInfo di = GetDirectoryInfo (gen_info.Dir, asm_name); StreamWriter sw = gen_info.Writer = gen_info.OpenStream (Name); sw.WriteLine ("namespace " + NS + " {"); sw.WriteLine (); sw.WriteLine ("\tusing System;"); sw.WriteLine ("\tusing System.Collections;"); sw.WriteLine ("\tusing System.Runtime.InteropServices;"); sw.WriteLine (); SymbolTable table = SymbolTable.Table; sw.WriteLine ("#region Autogenerated code"); if (IsDeprecated) sw.WriteLine ("\t[Obsolete]"); foreach (string attr in custom_attrs) sw.WriteLine ("\t" + attr); sw.Write ("\t{0} {1}class " + Name, IsInternal ? "internal" : "public", IsAbstract ? "abstract " : ""); string cs_parent = table.GetCSType(Elem.GetAttribute("parent")); if (cs_parent != "") { di.objects.Add (CName, QualifiedName); sw.Write (" : " + cs_parent); } foreach (string iface in interfaces) { if (Parent != null && Parent.Implements (iface)) continue; sw.Write (", " + table.GetCSType (iface)); } foreach (string iface in managed_interfaces) { if (Parent != null && Parent.Implements (iface)) continue; sw.Write (", " + iface); } sw.WriteLine (" {"); sw.WriteLine (); GenCtors (gen_info); GenProperties (gen_info, null); GenFields (gen_info); GenChildProperties (gen_info); bool has_sigs = (sigs != null && sigs.Count > 0); if (!has_sigs) { foreach (string iface in interfaces) { ClassBase igen = table.GetClassGen (iface); if (igen != null && igen.Signals != null) { has_sigs = true; break; } } } if (has_sigs && Elem.HasAttribute("parent")) { GenSignals (gen_info, null); } if (vm_nodes.Count > 0) { if (gen_info.GlueEnabled) { GenVirtualMethods (gen_info); } else { Statistics.VMIgnored = true; Statistics.ThrottledCount += vm_nodes.Count; } } GenMethods (gen_info, null, null); if (interfaces.Count != 0) { Hashtable all_methods = new Hashtable (); foreach (Method m in Methods.Values) all_methods[m.Name] = m; Hashtable collisions = new Hashtable (); foreach (string iface in interfaces) { ClassBase igen = table.GetClassGen (iface); foreach (Method m in igen.Methods.Values) { Method collision = all_methods[m.Name] as Method; if (collision != null && collision.Signature.Types == m.Signature.Types) collisions[m.Name] = true; else all_methods[m.Name] = m; } } foreach (string iface in interfaces) { if (Parent != null && Parent.Implements (iface)) continue; ClassBase igen = table.GetClassGen (iface); igen.GenMethods (gen_info, collisions, this); igen.GenProperties (gen_info, this); igen.GenSignals (gen_info, this); } } foreach (XmlElement str in strings) { sw.Write ("\t\tpublic static string " + str.GetAttribute ("name")); sw.WriteLine (" {\n\t\t\t get { return \"" + str.GetAttribute ("value") + "\"; }\n\t\t}"); } if (cs_parent != String.Empty && GetExpected (CName) != QualifiedName) { sw.WriteLine (); sw.WriteLine ("\t\tstatic " + Name + " ()"); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\tGtkSharp." + Studlify (asm_name) + ".ObjectManager.Initialize ();"); sw.WriteLine ("\t\t}"); } sw.WriteLine ("#endregion"); AppendCustom (sw, gen_info.CustomDir); sw.WriteLine ("\t}"); sw.WriteLine ("}"); sw.Close (); gen_info.Writer = null; Statistics.ObjectCount++; } protected override void GenCtors (GenerationInfo gen_info) { if (!Elem.HasAttribute("parent")) return; if (!DisableGTypeCtor) { gen_info.Writer.WriteLine("\t\t[Obsolete]"); gen_info.Writer.WriteLine("\t\tprotected " + Name + "(GLib.GType gtype) : base(gtype) {}"); } gen_info.Writer.WriteLine("\t\tpublic " + Name + "(IntPtr raw) : base(raw) {}"); if (ctors.Count == 0 && !DisableVoidCtor) { gen_info.Writer.WriteLine(); gen_info.Writer.WriteLine("\t\tprotected " + Name + "() : base(IntPtr.Zero)"); gen_info.Writer.WriteLine("\t\t{"); gen_info.Writer.WriteLine("\t\t\tCreateNativeObject (new string [0], new GLib.Value [0]);"); gen_info.Writer.WriteLine("\t\t}"); } gen_info.Writer.WriteLine(); base.GenCtors (gen_info); } protected void GenChildProperties (GenerationInfo gen_info) { if (childprops.Count == 0) return; StreamWriter sw = gen_info.Writer; ObjectGen child_ancestor = Parent as ObjectGen; while (child_ancestor.CName != "GtkContainer" && child_ancestor.childprops.Count == 0) child_ancestor = child_ancestor.Parent as ObjectGen; sw.WriteLine ("\t\tpublic class " + Name + "Child : " + child_ancestor.NS + "." + child_ancestor.Name + "." + child_ancestor.Name + "Child {"); sw.WriteLine ("\t\t\tprotected internal " + Name + "Child (Gtk.Container parent, Gtk.Widget child) : base (parent, child) {}"); sw.WriteLine (""); foreach (ChildProperty prop in childprops.Values) prop.Generate (gen_info, "\t\t\t", null); sw.WriteLine ("\t\t}"); sw.WriteLine (""); sw.WriteLine ("\t\tpublic override Gtk.Container.ContainerChild this [Gtk.Widget child] {"); sw.WriteLine ("\t\t\tget {"); sw.WriteLine ("\t\t\t\treturn new " + Name + "Child (this, child);"); sw.WriteLine ("\t\t\t}"); sw.WriteLine ("\t\t}"); sw.WriteLine (""); } private void GenVMGlue (GenerationInfo gen_info, XmlElement elem) { StreamWriter sw = gen_info.GlueWriter; string vm_name = elem.GetAttribute ("cname"); string method = gen_info.GluelibName + "_" + NS + Name + "_override_" + vm_name; sw.WriteLine (); sw.WriteLine ("void " + method + " (GType type, gpointer cb);"); sw.WriteLine (); sw.WriteLine ("void"); sw.WriteLine (method + " (GType type, gpointer cb)"); sw.WriteLine ("{"); sw.WriteLine ("\t{0} *klass = ({0} *) g_type_class_peek (type);", NS + Name + "Class"); sw.WriteLine ("\tklass->" + vm_name + " = cb;"); sw.WriteLine ("}"); } static bool vmhdrs_needed = true; private void GenVirtualMethods (GenerationInfo gen_info) { if (vmhdrs_needed) { gen_info.GlueWriter.WriteLine ("#include <glib-object.h>"); gen_info.GlueWriter.WriteLine ("#include \"vmglueheaders.h\""); gen_info.GlueWriter.WriteLine (); vmhdrs_needed = false; } foreach (XmlElement elem in vm_nodes) { GenVMGlue (gen_info, elem); } } /* Keep this in sync with the one in glib/GType.cs */ private static string GetExpected (string cname) { for (int i = 1; i < cname.Length; i++) { if (Char.IsUpper (cname[i])) { if (i == 1 && cname[0] == 'G') return "GLib." + cname.Substring (1); else return cname.Substring (0, i) + "." + cname.Substring (i); } } throw new ArgumentException ("cname doesn't follow the NamespaceType capitalization style: " + cname); } private static bool NeedsMap (Hashtable objs, string assembly_name) { foreach (string key in objs.Keys) if (GetExpected (key) != ((string) objs[key])) return true; return false; } private static string Studlify (string name) { string result = ""; string[] subs = name.Split ('-'); foreach (string sub in subs) result += Char.ToUpper (sub[0]) + sub.Substring (1); return result; } public static void GenerateMappers () { foreach (string dir in dirs.Keys) { DirectoryInfo di = dirs[dir] as DirectoryInfo; if (!NeedsMap (di.objects, di.assembly_name)) continue; GenerationInfo gen_info = new GenerationInfo (dir, di.assembly_name); GenerateMapper (di, gen_info); } } private static void GenerateMapper (DirectoryInfo dir_info, GenerationInfo gen_info) { StreamWriter sw = gen_info.OpenStream ("ObjectManager"); sw.WriteLine ("namespace GtkSharp." + Studlify (dir_info.assembly_name) + " {"); sw.WriteLine (); sw.WriteLine ("\tpublic class ObjectManager {"); sw.WriteLine (); sw.WriteLine ("\t\tstatic bool initialized = false;"); sw.WriteLine ("\t\t// Call this method from the appropriate module init function."); sw.WriteLine ("\t\tpublic static void Initialize ()"); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\tif (initialized)"); sw.WriteLine ("\t\t\t\treturn;"); sw.WriteLine (""); sw.WriteLine ("\t\t\tinitialized = true;"); foreach (string key in dir_info.objects.Keys) { if (GetExpected(key) != ((string) dir_info.objects[key])) sw.WriteLine ("\t\t\tGLib.GType.Register ({0}.GType, typeof ({0}));", dir_info.objects [key]); } sw.WriteLine ("\t\t}"); sw.WriteLine ("\t}"); sw.WriteLine ("}"); sw.Close (); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; using System.Text; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Utils; using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions { /// <summary> /// Richly represents the signature of a callsite. /// </summary> public struct CallSignature : IEquatable<CallSignature> { // TODO: invariant _infos != null ==> _argumentCount == _infos.Length /// <summary> /// Array of additional meta information about the arguments, such as named arguments. /// Null for a simple signature that's just an expression list. eg: foo(a*b,c,d) /// </summary> private readonly Argument[] _infos; /// <summary> /// Number of arguments in the signature. /// </summary> private readonly int _argumentCount; /// <summary> /// All arguments are unnamed and matched by position. /// </summary> public bool IsSimple => _infos == null; public int ArgumentCount { get { Debug.Assert(_infos == null || _infos.Length == _argumentCount); return _argumentCount; } } #region Construction public CallSignature(CallSignature signature) { _infos = signature.GetArgumentInfos(); _argumentCount = signature._argumentCount; } public CallSignature(int argumentCount) { ContractUtils.Requires(argumentCount >= 0, nameof(argumentCount)); _argumentCount = argumentCount; _infos = null; } public CallSignature(params Argument[] infos) { bool simple = true; if (infos != null) { _argumentCount = infos.Length; for (int i = 0; i < infos.Length; i++) { if (infos[i].Kind != ArgumentType.Simple) { simple = false; break; } } } else { _argumentCount = 0; } _infos = (!simple) ? infos : null; } public CallSignature(params ArgumentType[] kinds) { bool simple = true; if (kinds != null) { _argumentCount = kinds.Length; for (int i = 0; i < kinds.Length; i++) { if (kinds[i] != ArgumentType.Simple) { simple = false; break; } } } else { _argumentCount = 0; } if (!simple) { _infos = new Argument[kinds.Length]; for (int i = 0; i < kinds.Length; i++) { _infos[i] = new Argument(kinds[i]); } } else { _infos = null; } } #endregion #region IEquatable<CallSignature> Members public bool Equals(CallSignature other) { if (_infos == null) { return other._infos == null && other._argumentCount == _argumentCount; } if (other._infos == null) { return false; } if (_infos.Length != other._infos.Length) return false; for (int i = 0; i < _infos.Length; i++) { if (!_infos[i].Equals(other._infos[i])) return false; } return true; } #endregion #region Overrides public override bool Equals(object obj) => obj is CallSignature signature && Equals(signature); public static bool operator ==(CallSignature left, CallSignature right) => left.Equals(right); public static bool operator !=(CallSignature left, CallSignature right) => !left.Equals(right); public override string ToString() { if (_infos == null) { return "Simple"; } StringBuilder sb = new StringBuilder("("); for (int i = 0; i < _infos.Length; i++) { if (i > 0) { sb.Append(", "); } sb.Append(_infos[i].ToString()); } sb.Append(")"); return sb.ToString(); } public override int GetHashCode() { int h = 6551; if (_infos != null) { foreach (Argument info in _infos) { h ^= (h << 5) ^ info.GetHashCode(); } } return h; } #endregion #region Helpers public Argument[] GetArgumentInfos() { return (_infos != null) ? ArrayUtils.Copy(_infos) : CompilerHelpers.MakeRepeatedArray(Argument.Simple, _argumentCount); } public CallSignature InsertArgument(Argument info) { return InsertArgumentAt(0, info); } public CallSignature InsertArgumentAt(int index, Argument info) { if (IsSimple) { if (info.IsSimple) { return new CallSignature(_argumentCount + 1); } return new CallSignature(ArrayUtils.InsertAt(GetArgumentInfos(), index, info)); } return new CallSignature(ArrayUtils.InsertAt(_infos, index, info)); } public CallSignature RemoveFirstArgument() { return RemoveArgumentAt(0); } public CallSignature RemoveArgumentAt(int index) { if (_argumentCount == 0) { throw new InvalidOperationException(); } if (IsSimple) { return new CallSignature(_argumentCount - 1); } return new CallSignature(ArrayUtils.RemoveAt(_infos, index)); } public int IndexOf(ArgumentType kind) { if (_infos == null) { return (kind == ArgumentType.Simple && _argumentCount > 0) ? 0 : -1; } for (int i = 0; i < _infos.Length; i++) { if (_infos[i].Kind == kind) { return i; } } return -1; } public bool HasDictionaryArgument() { return IndexOf(ArgumentType.Dictionary) > -1; } public bool HasInstanceArgument() { return IndexOf(ArgumentType.Instance) > -1; } public bool HasListArgument() { return IndexOf(ArgumentType.List) > -1; } internal bool HasNamedArgument() { return IndexOf(ArgumentType.Named) > -1; } /// <summary> /// True if the OldCallAction includes an ArgumentInfo of ArgumentKind.Dictionary or ArgumentKind.Named. /// </summary> public bool HasKeywordArgument() { if (_infos != null) { foreach (Argument info in _infos) { if (info.Kind == ArgumentType.Dictionary || info.Kind == ArgumentType.Named) { return true; } } } return false; } public ArgumentType GetArgumentKind(int index) { // TODO: Contract.Requires(index >= 0 && index < _argumentCount, "index"); return _infos?[index].Kind ?? ArgumentType.Simple; } public string GetArgumentName(int index) { ContractUtils.Requires(index >= 0 && index < _argumentCount); return _infos?[index].Name; } /// <summary> /// Gets the number of positional arguments the user provided at the call site. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public int GetProvidedPositionalArgumentCount() { int result = _argumentCount; if (_infos != null) { for (int i = 0; i < _infos.Length; i++) { ArgumentType kind = _infos[i].Kind; if (kind == ArgumentType.Dictionary || kind == ArgumentType.List || kind == ArgumentType.Named) { result--; } } } return result; } public string[] GetArgumentNames() { if (_infos == null) { return ArrayUtils.EmptyStrings; } List<string> result = new List<string>(); foreach (Argument info in _infos) { if (info.Name != null) { result.Add(info.Name); } } return result.ToArray(); } public Expression CreateExpression() { if (_infos == null) { return Expression.New( typeof(CallSignature).GetConstructor(new Type[] { typeof(int) }), AstUtils.Constant(ArgumentCount) ); } Expression[] args = new Expression[_infos.Length]; for (int i = 0; i < args.Length; i++) { args[i] = _infos[i].CreateExpression(); } return Expression.New( typeof(CallSignature).GetConstructor(new Type[] { typeof(Argument[]) }), Expression.NewArrayInit(typeof(Argument), args) ); } #endregion } }
namespace SoftDemo { static class BunnyMesh { public static float[] Vertices = new float[] { -0.334392f, 0.133007f, 0.062259f, -0.350189f, 0.150354f, -0.147769f, -0.234201f, 0.343811f, -0.174307f, -0.200259f, 0.285207f, 0.093749f, 0.003520f, 0.475208f, -0.159365f, 0.001856f, 0.419203f, 0.098582f, -0.252802f, 0.093666f, 0.237538f, -0.162901f, 0.237984f, 0.206905f, 0.000865f, 0.318141f, 0.235370f, -0.414624f, 0.164083f, -0.278254f, -0.262213f, 0.357334f, -0.293246f, 0.004628f, 0.482694f, -0.338626f, -0.402162f, 0.133528f, -0.443247f, -0.243781f, 0.324275f, -0.436763f, 0.005293f, 0.437592f, -0.458332f, -0.339884f, -0.041150f, -0.668211f, -0.248382f, 0.255825f, -0.627493f, 0.006261f, 0.376103f, -0.631506f, -0.216201f, -0.126776f, -0.886936f, -0.171075f, 0.011544f, -0.881386f, -0.181074f, 0.098223f, -0.814779f, -0.119891f, 0.218786f, -0.760153f, -0.078895f, 0.276780f, -0.739281f, 0.006801f, 0.310959f, -0.735661f, -0.168842f, 0.102387f, -0.920381f, -0.104072f, 0.177278f, -0.952530f, -0.129704f, 0.211848f, -0.836678f, -0.099875f, 0.310931f, -0.799381f, 0.007237f, 0.361687f, -0.794439f, -0.077913f, 0.258753f, -0.921640f, 0.007957f, 0.282241f, -0.931680f, -0.252222f, -0.550401f, -0.557810f, -0.267633f, -0.603419f, -0.655209f, -0.446838f, -0.118517f, -0.466159f, -0.459488f, -0.093017f, -0.311341f, -0.370645f, -0.100108f, -0.159454f, -0.371984f, -0.091991f, -0.011044f, -0.328945f, -0.098269f, 0.088659f, -0.282452f, -0.018862f, 0.311501f, -0.352403f, -0.131341f, 0.144902f, -0.364126f, -0.200299f, 0.202388f, -0.283965f, -0.231869f, 0.023668f, -0.298943f, -0.155218f, 0.369716f, -0.293787f, -0.121856f, 0.419097f, -0.290163f, -0.290797f, 0.107824f, -0.264165f, -0.272849f, 0.036347f, -0.228567f, -0.372573f, 0.290309f, -0.190431f, -0.286997f, 0.421917f, -0.191039f, -0.240973f, 0.507118f, -0.287272f, -0.276431f, -0.065444f, -0.295675f, -0.280818f, -0.174200f, -0.399537f, -0.313131f, -0.376167f, -0.392666f, -0.488581f, -0.427494f, -0.331669f, -0.570185f, -0.466054f, -0.282290f, -0.618140f, -0.589220f, -0.374238f, -0.594882f, -0.323298f, -0.381071f, -0.629723f, -0.350777f, -0.382112f, -0.624060f, -0.221577f, -0.272701f, -0.566522f, 0.259157f, -0.256702f, -0.663406f, 0.286079f, -0.280948f, -0.428359f, 0.055790f, -0.184974f, -0.508894f, 0.326265f, -0.279971f, -0.526918f, 0.395319f, -0.282599f, -0.663393f, 0.412411f, -0.188329f, -0.475093f, 0.417954f, -0.263384f, -0.663396f, 0.466604f, -0.209063f, -0.663393f, 0.509344f, -0.002044f, -0.319624f, 0.553078f, -0.001266f, -0.371260f, 0.413296f, -0.219753f, -0.339762f, -0.040921f, -0.256986f, -0.282511f, -0.006349f, -0.271706f, -0.260881f, 0.001764f, -0.091191f, -0.419184f, -0.045912f, -0.114944f, -0.429752f, -0.124739f, -0.113970f, -0.382987f, -0.188540f, -0.243012f, -0.464942f, -0.242850f, -0.314815f, -0.505402f, -0.324768f, 0.002774f, -0.437526f, -0.262766f, -0.072625f, -0.417748f, -0.221440f, -0.160112f, -0.476932f, -0.293450f, 0.003859f, -0.453425f, -0.443916f, -0.120363f, -0.581567f, -0.438689f, -0.091499f, -0.584191f, -0.294511f, -0.116469f, -0.599861f, -0.188308f, -0.208032f, -0.513640f, -0.134649f, -0.235749f, -0.610017f, -0.040939f, -0.344916f, -0.622487f, -0.085380f, -0.336401f, -0.531864f, -0.212298f, 0.001961f, -0.459550f, -0.135547f, -0.058296f, -0.430536f, -0.043440f, 0.001378f, -0.449511f, -0.037762f, -0.130135f, -0.510222f, 0.079144f, 0.000142f, -0.477549f, 0.157064f, -0.114284f, -0.453206f, 0.304397f, -0.000592f, -0.443558f, 0.285401f, -0.056215f, -0.663402f, 0.326073f, -0.026248f, -0.568010f, 0.273318f, -0.049261f, -0.531064f, 0.389854f, -0.127096f, -0.663398f, 0.479316f, -0.058384f, -0.663401f, 0.372891f, -0.303961f, 0.054199f, 0.625921f, -0.268594f, 0.193403f, 0.502766f, -0.277159f, 0.126123f, 0.443289f, -0.287605f, -0.005722f, 0.531844f, -0.231396f, -0.121289f, 0.587387f, -0.253475f, -0.081797f, 0.756541f, -0.195164f, -0.137969f, 0.728011f, -0.167673f, -0.156573f, 0.609388f, -0.145917f, -0.169029f, 0.697600f, -0.077776f, -0.214247f, 0.622586f, -0.076873f, -0.214971f, 0.696301f, -0.002341f, -0.233135f, 0.622859f, -0.002730f, -0.213526f, 0.691267f, -0.003136f, -0.192628f, 0.762731f, -0.056136f, -0.201222f, 0.763806f, -0.114589f, -0.166192f, 0.770723f, -0.155145f, -0.129632f, 0.791738f, -0.183611f, -0.058705f, 0.847012f, -0.165562f, 0.001980f, 0.833386f, -0.220084f, 0.019914f, 0.768935f, -0.255730f, 0.090306f, 0.670782f, -0.255594f, 0.113833f, 0.663389f, -0.226380f, 0.212655f, 0.617740f, -0.003367f, -0.195342f, 0.799680f, -0.029743f, -0.210508f, 0.827180f, -0.003818f, -0.194783f, 0.873636f, -0.004116f, -0.157907f, 0.931268f, -0.031280f, -0.184555f, 0.889476f, -0.059885f, -0.184448f, 0.841330f, -0.135333f, -0.164332f, 0.878200f, -0.085574f, -0.170948f, 0.925547f, -0.163833f, -0.094170f, 0.897114f, -0.138444f, -0.104250f, 0.945975f, -0.083497f, -0.084934f, 0.979607f, -0.004433f, -0.146642f, 0.985872f, -0.150715f, 0.032650f, 0.884111f, -0.135892f, -0.035520f, 0.945455f, -0.070612f, 0.036849f, 0.975733f, -0.004458f, -0.042526f, 1.015670f, -0.004249f, 0.046042f, 1.003240f, -0.086969f, 0.133224f, 0.947633f, -0.003873f, 0.161605f, 0.970499f, -0.125544f, 0.140012f, 0.917678f, -0.125651f, 0.250246f, 0.857602f, -0.003127f, 0.284070f, 0.878870f, -0.159174f, 0.125726f, 0.888878f, -0.183807f, 0.196970f, 0.844480f, -0.159890f, 0.291736f, 0.732480f, -0.199495f, 0.207230f, 0.779864f, -0.206182f, 0.164608f, 0.693257f, -0.186315f, 0.160689f, 0.817193f, -0.192827f, 0.166706f, 0.782271f, -0.175112f, 0.110008f, 0.860621f, -0.161022f, 0.057420f, 0.855111f, -0.172319f, 0.036155f, 0.816189f, -0.190318f, 0.064083f, 0.760605f, -0.195072f, 0.129179f, 0.731104f, -0.203126f, 0.410287f, 0.680536f, -0.216677f, 0.309274f, 0.642272f, -0.241515f, 0.311485f, 0.587832f, -0.002209f, 0.366663f, 0.749413f, -0.088230f, 0.396265f, 0.678635f, -0.170147f, 0.109517f, 0.840784f, -0.160521f, 0.067766f, 0.830650f, -0.181546f, 0.139805f, 0.812146f, -0.180495f, 0.148568f, 0.776087f, -0.180255f, 0.129125f, 0.744192f, -0.186298f, 0.078308f, 0.769352f, -0.167622f, 0.060539f, 0.806675f, -0.189876f, 0.102760f, 0.802582f, -0.108340f, 0.455446f, 0.657174f, -0.241585f, 0.527592f, 0.669296f, -0.265676f, 0.513366f, 0.634594f, -0.203073f, 0.478550f, 0.581526f, -0.266772f, 0.642330f, 0.602061f, -0.216961f, 0.564846f, 0.535435f, -0.202210f, 0.525495f, 0.475944f, -0.193888f, 0.467925f, 0.520606f, -0.265837f, 0.757267f, 0.500933f, -0.240306f, 0.653440f, 0.463215f, -0.309239f, 0.776868f, 0.304726f, -0.271009f, 0.683094f, 0.382018f, -0.312111f, 0.671099f, 0.286687f, -0.268791f, 0.624342f, 0.377231f, -0.302457f, 0.533996f, 0.360289f, -0.263656f, 0.529310f, 0.412564f, -0.282311f, 0.415167f, 0.447666f, -0.239201f, 0.442096f, 0.495604f, -0.220043f, 0.569026f, 0.445877f, -0.001263f, 0.395631f, 0.602029f, -0.057345f, 0.442535f, 0.572224f, -0.088927f, 0.506333f, 0.529106f, -0.125738f, 0.535076f, 0.612913f, -0.126251f, 0.577170f, 0.483159f, -0.149594f, 0.611520f, 0.557731f, -0.163188f, 0.660791f, 0.491080f, -0.172482f, 0.663387f, 0.415416f, -0.160464f, 0.591710f, 0.370659f, -0.156445f, 0.536396f, 0.378302f, -0.136496f, 0.444358f, 0.425226f, -0.095564f, 0.373768f, 0.473659f, -0.104146f, 0.315912f, 0.498104f, -0.000496f, 0.384194f, 0.473817f, -0.000183f, 0.297770f, 0.401486f, -0.129042f, 0.270145f, 0.434495f, 0.000100f, 0.272963f, 0.349138f, -0.113060f, 0.236984f, 0.385554f, 0.007260f, 0.016311f, -0.883396f, 0.007865f, 0.122104f, -0.956137f, -0.032842f, 0.115282f, -0.953252f, -0.089115f, 0.108449f, -0.950317f, -0.047440f, 0.014729f, -0.882756f, -0.104458f, 0.013137f, -0.882070f, -0.086439f, -0.584866f, -0.608343f, -0.115026f, -0.662605f, -0.436732f, -0.071683f, -0.665372f, -0.606385f, -0.257884f, -0.665381f, -0.658052f, -0.272542f, -0.665381f, -0.592063f, -0.371322f, -0.665382f, -0.353620f, -0.372362f, -0.665381f, -0.224420f, -0.335166f, -0.665380f, -0.078623f, -0.225999f, -0.665375f, -0.038981f, -0.106719f, -0.665374f, -0.186351f, -0.081749f, -0.665372f, -0.292554f, 0.006943f, -0.091505f, -0.858354f, 0.006117f, -0.280985f, -0.769967f, 0.004495f, -0.502360f, -0.559799f, -0.198638f, -0.302135f, -0.845816f, -0.237395f, -0.542544f, -0.587188f, -0.270001f, -0.279489f, -0.669861f, -0.134547f, -0.119852f, -0.959004f, -0.052088f, -0.122463f, -0.944549f, -0.124463f, -0.293508f, -0.899566f, -0.047616f, -0.289643f, -0.879292f, -0.168595f, -0.529132f, -0.654931f, -0.099793f, -0.515719f, -0.645873f, -0.186168f, -0.605282f, -0.724690f, -0.112970f, -0.583097f, -0.707469f, -0.108152f, -0.665375f, -0.700408f, -0.183019f, -0.665378f, -0.717630f, -0.349529f, -0.334459f, -0.511985f, -0.141182f, -0.437705f, -0.798194f, -0.212670f, -0.448725f, -0.737447f, -0.261111f, -0.414945f, -0.613835f, -0.077364f, -0.431480f, -0.778113f, 0.005174f, -0.425277f, -0.651592f, 0.089236f, -0.431732f, -0.777093f, 0.271006f, -0.415749f, -0.610577f, 0.223981f, -0.449384f, -0.734774f, 0.153275f, -0.438150f, -0.796391f, 0.358414f, -0.335529f, -0.507649f, 0.193434f, -0.665946f, -0.715325f, 0.118363f, -0.665717f, -0.699021f, 0.123515f, -0.583454f, -0.706020f, 0.196851f, -0.605860f, -0.722345f, 0.109788f, -0.516035f, -0.644590f, 0.178656f, -0.529656f, -0.652804f, 0.061157f, -0.289807f, -0.878626f, 0.138234f, -0.293905f, -0.897958f, 0.066933f, -0.122643f, -0.943820f, 0.149571f, -0.120281f, -0.957264f, 0.280989f, -0.280321f, -0.666487f, 0.246581f, -0.543275f, -0.584224f, 0.211720f, -0.302754f, -0.843303f, 0.086966f, -0.665627f, -0.291520f, 0.110634f, -0.665702f, -0.185021f, 0.228099f, -0.666061f, -0.036201f, 0.337743f, -0.666396f, -0.074503f, 0.376722f, -0.666513f, -0.219833f, 0.377265f, -0.666513f, -0.349036f, 0.281411f, -0.666217f, -0.588670f, 0.267564f, -0.666174f, -0.654834f, 0.080745f, -0.665602f, -0.605452f, 0.122016f, -0.662963f, -0.435280f, 0.095767f, -0.585141f, -0.607228f, 0.118944f, 0.012799f, -0.880702f, 0.061944f, 0.014564f, -0.882086f, 0.104725f, 0.108156f, -0.949130f, 0.048513f, 0.115159f, -0.952753f, 0.112696f, 0.236643f, 0.386937f, 0.128177f, 0.269757f, 0.436071f, 0.102643f, 0.315600f, 0.499370f, 0.094535f, 0.373481f, 0.474824f, 0.136270f, 0.443946f, 0.426895f, 0.157071f, 0.535923f, 0.380222f, 0.161350f, 0.591224f, 0.372630f, 0.173035f, 0.662865f, 0.417531f, 0.162808f, 0.660299f, 0.493077f, 0.148250f, 0.611070f, 0.559555f, 0.125719f, 0.576790f, 0.484702f, 0.123489f, 0.534699f, 0.614440f, 0.087621f, 0.506066f, 0.530188f, 0.055321f, 0.442365f, 0.572915f, 0.219936f, 0.568361f, 0.448571f, 0.238099f, 0.441375f, 0.498528f, 0.281711f, 0.414315f, 0.451121f, 0.263833f, 0.528513f, 0.415794f, 0.303284f, 0.533081f, 0.363998f, 0.269687f, 0.623528f, 0.380528f, 0.314255f, 0.670153f, 0.290524f, 0.272023f, 0.682273f, 0.385343f, 0.311480f, 0.775931f, 0.308527f, 0.240239f, 0.652714f, 0.466159f, 0.265619f, 0.756464f, 0.504187f, 0.192562f, 0.467341f, 0.522972f, 0.201605f, 0.524885f, 0.478417f, 0.215743f, 0.564193f, 0.538084f, 0.264969f, 0.641527f, 0.605317f, 0.201031f, 0.477940f, 0.584002f, 0.263086f, 0.512567f, 0.637832f, 0.238615f, 0.526867f, 0.672237f, 0.105309f, 0.455123f, 0.658482f, 0.183993f, 0.102195f, 0.804872f, 0.161563f, 0.060042f, 0.808692f, 0.180748f, 0.077754f, 0.771600f, 0.175168f, 0.128588f, 0.746368f, 0.175075f, 0.148030f, 0.778264f, 0.175658f, 0.139265f, 0.814333f, 0.154191f, 0.067291f, 0.832578f, 0.163818f, 0.109013f, 0.842830f, 0.084760f, 0.396004f, 0.679695f, 0.238888f, 0.310760f, 0.590775f, 0.213380f, 0.308625f, 0.644905f, 0.199666f, 0.409678f, 0.683003f, 0.190143f, 0.128597f, 0.733463f, 0.184833f, 0.063516f, 0.762902f, 0.166070f, 0.035644f, 0.818261f, 0.154361f, 0.056943f, 0.857042f, 0.168542f, 0.109489f, 0.862725f, 0.187387f, 0.166131f, 0.784599f, 0.180428f, 0.160135f, 0.819438f, 0.201823f, 0.163991f, 0.695756f, 0.194206f, 0.206635f, 0.782275f, 0.155438f, 0.291260f, 0.734412f, 0.177696f, 0.196424f, 0.846693f, 0.152305f, 0.125256f, 0.890786f, 0.119546f, 0.249876f, 0.859104f, 0.118369f, 0.139643f, 0.919173f, 0.079410f, 0.132973f, 0.948652f, 0.062419f, 0.036648f, 0.976547f, 0.127847f, -0.035919f, 0.947070f, 0.143624f, 0.032206f, 0.885913f, 0.074888f, -0.085173f, 0.980577f, 0.130184f, -0.104656f, 0.947620f, 0.156201f, -0.094653f, 0.899074f, 0.077366f, -0.171194f, 0.926545f, 0.127722f, -0.164729f, 0.879810f, 0.052670f, -0.184618f, 0.842019f, 0.023477f, -0.184638f, 0.889811f, 0.022626f, -0.210587f, 0.827500f, 0.223089f, 0.211976f, 0.620493f, 0.251444f, 0.113067f, 0.666494f, 0.251419f, 0.089540f, 0.673887f, 0.214360f, 0.019258f, 0.771595f, 0.158999f, 0.001490f, 0.835374f, 0.176696f, -0.059249f, 0.849218f, 0.148696f, -0.130091f, 0.793599f, 0.108290f, -0.166528f, 0.772088f, 0.049820f, -0.201382f, 0.764454f, 0.071341f, -0.215195f, 0.697209f, 0.073148f, -0.214475f, 0.623510f, 0.140502f, -0.169461f, 0.699354f, 0.163374f, -0.157073f, 0.611416f, 0.189466f, -0.138550f, 0.730366f, 0.247593f, -0.082554f, 0.759610f, 0.227468f, -0.121982f, 0.590197f, 0.284702f, -0.006586f, 0.535347f, 0.275741f, 0.125287f, 0.446676f, 0.266650f, 0.192594f, 0.506044f, 0.300086f, 0.053287f, 0.629620f, 0.055450f, -0.663935f, 0.375065f, 0.122854f, -0.664138f, 0.482323f, 0.046520f, -0.531571f, 0.391918f, 0.024824f, -0.568450f, 0.275106f, 0.053855f, -0.663931f, 0.328224f, 0.112829f, -0.453549f, 0.305788f, 0.131265f, -0.510617f, 0.080746f, 0.061174f, -0.430716f, -0.042710f, 0.341019f, -0.532887f, -0.208150f, 0.347705f, -0.623533f, -0.081139f, 0.238040f, -0.610732f, -0.038037f, 0.211764f, -0.514274f, -0.132078f, 0.120605f, -0.600219f, -0.186856f, 0.096985f, -0.584476f, -0.293357f, 0.127621f, -0.581941f, -0.437170f, 0.165902f, -0.477425f, -0.291453f, 0.077720f, -0.417975f, -0.220519f, 0.320892f, -0.506363f, -0.320874f, 0.248214f, -0.465684f, -0.239842f, 0.118764f, -0.383338f, -0.187114f, 0.118816f, -0.430106f, -0.123307f, 0.094131f, -0.419464f, -0.044777f, 0.274526f, -0.261706f, 0.005110f, 0.259842f, -0.283292f, -0.003185f, 0.222861f, -0.340431f, -0.038210f, 0.204445f, -0.664380f, 0.513353f, 0.259286f, -0.664547f, 0.471281f, 0.185402f, -0.476020f, 0.421718f, 0.279163f, -0.664604f, 0.417328f, 0.277157f, -0.528122f, 0.400208f, 0.183069f, -0.509812f, 0.329995f, 0.282599f, -0.429210f, 0.059242f, 0.254816f, -0.664541f, 0.290687f, 0.271436f, -0.567707f, 0.263966f, 0.386561f, -0.625221f, -0.216870f, 0.387086f, -0.630883f, -0.346073f, 0.380021f, -0.596021f, -0.318679f, 0.291269f, -0.619007f, -0.585707f, 0.339280f, -0.571198f, -0.461946f, 0.400045f, -0.489778f, -0.422640f, 0.406817f, -0.314349f, -0.371230f, 0.300588f, -0.281718f, -0.170549f, 0.290866f, -0.277304f, -0.061905f, 0.187735f, -0.241545f, 0.509437f, 0.188032f, -0.287569f, 0.424234f, 0.227520f, -0.373262f, 0.293102f, 0.266526f, -0.273650f, 0.039597f, 0.291592f, -0.291676f, 0.111386f, 0.291914f, -0.122741f, 0.422683f, 0.297574f, -0.156119f, 0.373368f, 0.286603f, -0.232731f, 0.027162f, 0.364663f, -0.201399f, 0.206850f, 0.353855f, -0.132408f, 0.149228f, 0.282208f, -0.019715f, 0.314960f, 0.331187f, -0.099266f, 0.092701f, 0.375463f, -0.093120f, -0.006467f, 0.375917f, -0.101236f, -0.154882f, 0.466635f, -0.094416f, -0.305669f, 0.455805f, -0.119881f, -0.460632f, 0.277465f, -0.604242f, -0.651871f, 0.261022f, -0.551176f, -0.554667f, 0.093627f, 0.258494f, -0.920589f, 0.114248f, 0.310608f, -0.798070f, 0.144232f, 0.211434f, -0.835001f, 0.119916f, 0.176940f, -0.951159f, 0.184061f, 0.101854f, -0.918220f, 0.092431f, 0.276521f, -0.738231f, 0.133504f, 0.218403f, -0.758602f, 0.194987f, 0.097655f, -0.812476f, 0.185542f, 0.011005f, -0.879202f, 0.230315f, -0.127450f, -0.884202f, 0.260471f, 0.255056f, -0.624378f, 0.351567f, -0.042194f, -0.663976f, 0.253742f, 0.323524f, -0.433716f, 0.411612f, 0.132299f, -0.438264f, 0.270513f, 0.356530f, -0.289984f, 0.422146f, 0.162819f, -0.273130f, 0.164724f, 0.237490f, 0.208912f, 0.253806f, 0.092900f, 0.240640f, 0.203608f, 0.284597f, 0.096223f, 0.241006f, 0.343093f, -0.171396f, 0.356076f, 0.149288f, -0.143443f, 0.337656f, 0.131992f, 0.066374f }; public static int[] Indices = new int[] { 126,134,133, 342,138,134, 133,134,138, 126,342,134, 312,316,317, 169,163,162, 312,317,319, 312,319,318, 169,162,164, 169,168,163, 312,314,315, 169,164,165, 169,167,168, 312,315,316, 312,313,314, 169,165,166, 169,166,167, 312,318,313, 308,304,305, 308,305,306, 179,181,188, 177,173,175, 177,175,176, 302,293,300, 322,294,304, 188,176,175, 188,175,179, 158,177,187, 305,293,302, 305,302,306, 322,304,308, 188,181,183, 158,173,177, 293,298,300, 304,294,296, 304,296,305, 185,176,188, 185,188,183, 187,177,176, 187,176,185, 305,296,298, 305,298,293, 436,432, 28, 436, 28, 23, 434,278,431, 30,208,209, 30,209, 29, 19, 20, 24, 208,207,211, 208,211,209, 19,210,212, 433,434,431, 433,431,432, 433,432,436, 436,437,433, 277,275,276, 277,276,278, 209,210, 25, 21, 26, 24, 21, 24, 20, 25, 26, 27, 25, 27, 29, 435,439,277, 439,275,277, 432,431, 30, 432, 30, 28, 433,437,438, 433,438,435, 434,277,278, 24, 25,210, 24, 26, 25, 29, 27, 28, 29, 28, 30, 19, 24,210, 208, 30,431, 208,431,278, 435,434,433, 435,277,434, 25, 29,209, 27, 22, 23, 27, 23, 28, 26, 22, 27, 26, 21, 22, 212,210,209, 212,209,211, 207,208,278, 207,278,276, 439,435,438, 12, 9, 10, 12, 10, 13, 2, 3, 5, 2, 5, 4, 16, 13, 14, 16, 14, 17, 22, 21, 16, 13, 10, 11, 13, 11, 14, 1, 0, 3, 1, 3, 2, 15, 12, 16, 19, 18, 15, 19, 15, 16, 19, 16, 20, 9, 1, 2, 9, 2, 10, 3, 7, 8, 3, 8, 5, 16, 17, 23, 16, 23, 22, 21, 20, 16, 10, 2, 4, 10, 4, 11, 0, 6, 7, 0, 7, 3, 12, 13, 16, 451,446,445, 451,445,450, 442,440,439, 442,439,438, 442,438,441, 421,420,422, 412,411,426, 412,426,425, 408,405,407, 413, 67, 68, 413, 68,414, 391,390,412, 80,384,386, 404,406,378, 390,391,377, 390,377, 88, 400,415,375, 398,396,395, 398,395,371, 398,371,370, 112,359,358, 112,358,113, 351,352,369, 125,349,348, 345,343,342, 342,340,339, 341,335,337, 328,341,327, 331,323,333, 331,322,323, 327,318,319, 327,319,328, 315,314,324, 302,300,301, 302,301,303, 320,311,292, 285,284,289, 310,307,288, 310,288,290, 321,350,281, 321,281,282, 423,448,367, 272,273,384, 272,384,274, 264,265,382, 264,382,383, 440,442,261, 440,261,263, 252,253,254, 252,254,251, 262,256,249, 262,249,248, 228,243,242, 228, 31,243, 213,215,238, 213,238,237, 19,212,230, 224,225,233, 224,233,231, 217,218, 56, 217, 56, 54, 217,216,239, 217,239,238, 217,238,215, 218,217,215, 218,215,214, 6,102,206, 186,199,200, 197,182,180, 170,171,157, 201,200,189, 170,190,191, 170,191,192, 175,174,178, 175,178,179, 168,167,155, 122,149,158, 122,158,159, 135,153,154, 135,154,118, 143,140,141, 143,141,144, 132,133,136, 130,126,133, 124,125,127, 122,101,100, 122,100,121, 110,108,107, 110,107,109, 98, 99, 97, 98, 97, 64, 98, 64, 66, 87, 55, 57, 83, 82, 79, 83, 79, 84, 78, 74, 50, 49, 71, 41, 49, 41, 37, 49, 37, 36, 58, 44, 60, 60, 59, 58, 51, 34, 33, 39, 40, 42, 39, 42, 38, 243,240, 33, 243, 33,229, 39, 38, 6, 44, 46, 40, 55, 56, 57, 64, 62, 65, 64, 65, 66, 41, 71, 45, 75, 50, 51, 81, 79, 82, 77, 88, 73, 93, 92, 94, 68, 47, 46, 96, 97, 99, 96, 99, 95, 110,109,111, 111,112,110, 114,113,123, 114,123,124, 132,131,129, 133,137,136, 135,142,145, 145,152,135, 149,147,157, 157,158,149, 164,150,151, 153,163,168, 153,168,154, 185,183,182, 185,182,184, 161,189,190, 200,199,191, 200,191,190, 180,178,195, 180,195,196, 102,101,204, 102,204,206, 43, 48,104, 43,104,103, 216,217, 54, 216, 54, 32, 207,224,231, 230,212,211, 230,211,231, 227,232,241, 227,241,242, 235,234,241, 235,241,244, 430,248,247, 272,274,253, 272,253,252, 439,260,275, 225,224,259, 225,259,257, 269,270,407, 269,407,405, 270,269,273, 270,273,272, 273,269,268, 273,268,267, 273,267,266, 273,266,265, 273,265,264, 448,279,367, 281,350,368, 285,286,301, 290,323,310, 290,311,323, 282,281,189, 292,311,290, 292,290,291, 307,306,302, 307,302,303, 316,315,324, 316,324,329, 331,351,350, 330,334,335, 330,335,328, 341,337,338, 344,355,354, 346,345,348, 346,348,347, 364,369,352, 364,352,353, 365,363,361, 365,361,362, 376,401,402, 373,372,397, 373,397,400, 376, 92,377, 381,378,387, 381,387,385, 386, 77, 80, 390,389,412, 416,417,401, 403,417,415, 408,429,430, 419,423,418, 427,428,444, 427,444,446, 437,436,441, 450,445, 11, 450, 11, 4, 447,449, 5, 447, 5, 8, 441,438,437, 425,426,451, 425,451,452, 417,421,415, 408,407,429, 399,403,400, 399,400,397, 394,393,416, 389,411,412, 386,383,385, 408,387,378, 408,378,406, 377,391,376, 94,375,415, 372,373,374, 372,374,370, 359,111,360, 359,112,111, 113,358,349, 113,349,123, 346,343,345, 343,340,342, 338,336,144, 338,144,141, 327,341,354, 327,354,326, 331,350,321, 331,321,322, 314,313,326, 314,326,325, 300,298,299, 300,299,301, 288,287,289, 189,292,282, 287,288,303, 284,285,297, 368,280,281, 448,447,279, 274,226,255, 267,268,404, 267,404,379, 429,262,430, 439,440,260, 257,258,249, 257,249,246, 430,262,248, 234,228,242, 234,242,241, 237,238,239, 237,239,236, 15, 18,227, 15,227,229, 222,223, 82, 222, 82, 83, 214,215,213, 214,213, 81, 38,102, 6, 122,159,200, 122,200,201, 174,171,192, 174,192,194, 197,193,198, 190,170,161, 181,179,178, 181,178,180, 166,156,155, 163,153,152, 163,152,162, 120,156,149, 120,149,121, 152,153,135, 140,143,142, 135,131,132, 135,132,136, 130,129,128, 130,128,127, 100,105,119, 100,119,120, 106,104,107, 106,107,108, 91, 95, 59, 93, 94, 68, 91, 89, 92, 76, 53, 55, 76, 55, 87, 81, 78, 79, 74, 73, 49, 69, 60, 45, 58, 62, 64, 58, 64, 61, 53, 31, 32, 32, 54, 53, 42, 43, 38, 35, 36, 0, 35, 0, 1, 34, 35, 1, 34, 1, 9, 44, 40, 41, 44, 41, 45, 33,240, 51, 63, 62, 58, 63, 58, 59, 45, 71, 70, 76, 75, 51, 76, 51, 52, 86, 85, 84, 86, 84, 87, 89, 72, 73, 89, 73, 88, 91, 92, 96, 91, 96, 95, 72, 91, 60, 72, 60, 69, 104,106,105, 119,105,117, 119,117,118, 124,127,128, 117,116,129, 117,129,131, 118,117,131, 135,140,142, 146,150,152, 146,152,145, 149,122,121, 166,165,151, 166,151,156, 158,172,173, 161,160,189, 199,198,193, 199,193,191, 204,201,202, 178,174,194, 200,159,186, 109, 48, 67, 48,107,104, 216, 32,236, 216,236,239, 223,214, 81, 223, 81, 82, 33, 12, 15, 32,228,234, 32,234,236, 240, 31, 52, 256,255,246, 256,246,249, 258,263,248, 258,248,249, 275,260,259, 275,259,276, 207,276,259, 270,271,429, 270,429,407, 413,418,366, 413,366,365, 368,367,279, 368,279,280, 303,301,286, 303,286,287, 283,282,292, 283,292,291, 320,292,189, 298,296,297, 298,297,299, 318,327,326, 318,326,313, 329,330,317, 336,333,320, 326,354,353, 334,332,333, 334,333,336, 342,339,139, 342,139,138, 345,342,126, 347,357,356, 369,368,351, 363,356,357, 363,357,361, 366,367,368, 366,368,369, 375,373,400, 92, 90,377, 409,387,408, 386,385,387, 386,387,388, 412,394,391, 396,398,399, 408,406,405, 415,421,419, 415,419,414, 425,452,448, 425,448,424, 444,441,443, 448,452,449, 448,449,447, 446,444,443, 446,443,445, 250,247,261, 250,261,428, 421,422,423, 421,423,419, 427,410,250, 417,403,401, 403,402,401, 420,392,412, 420,412,425, 420,425,424, 386,411,389, 383,382,381, 383,381,385, 378,379,404, 372,371,395, 372,395,397, 371,372,370, 361,359,360, 361,360,362, 368,350,351, 349,347,348, 356,355,344, 356,344,346, 344,341,340, 344,340,343, 338,337,336, 328,335,341, 324,352,351, 324,351,331, 320,144,336, 314,325,324, 322,308,309, 310,309,307, 287,286,289, 203,280,279, 203,279,205, 297,295,283, 297,283,284, 447,205,279, 274,384, 80, 274, 80,226, 266,267,379, 266,379,380, 225,257,246, 225,246,245, 256,254,253, 256,253,255, 430,247,250, 226,235,244, 226,244,245, 232,233,244, 232,244,241, 230, 18, 19, 32, 31,228, 219,220, 86, 219, 86, 57, 226,213,235, 206, 7, 6, 122,201,101, 201,204,101, 180,196,197, 170,192,171, 200,190,189, 194,193,195, 183,181,180, 183,180,182, 155,154,168, 149,156,151, 149,151,148, 155,156,120, 145,142,143, 145,143,146, 136,137,140, 133,132,130, 128,129,116, 100,120,121, 110,112,113, 110,113,114, 66, 65, 63, 66, 63, 99, 66, 99, 98, 96, 46, 61, 89, 88, 90, 86, 87, 57, 80, 78, 81, 72, 69, 49, 67, 48, 47, 67, 47, 68, 56, 55, 53, 50, 49, 36, 50, 36, 35, 40, 39, 41, 242,243,229, 242,229,227, 6, 37, 39, 42, 47, 48, 42, 48, 43, 61, 46, 44, 45, 70, 69, 69, 70, 71, 69, 71, 49, 74, 78, 77, 83, 84, 85, 73, 74, 77, 93, 96, 92, 68, 46, 93, 95, 99, 63, 95, 63, 59, 115,108,110, 115,110,114, 125,126,127, 129,130,132, 137,133,138, 137,138,139, 148,146,143, 148,143,147, 119,118,154, 161,147,143, 165,164,151, 158,157,171, 158,171,172, 159,158,187, 159,187,186, 194,192,191, 194,191,193, 189,202,201, 182,197,184, 205, 8, 7, 48,109,107, 218,219, 57, 218, 57, 56, 207,231,211, 232,230,231, 232,231,233, 53, 52, 31, 388,411,386, 409,430,250, 262,429,254, 262,254,256, 442,444,428, 273,264,383, 273,383,384, 429,271,251, 429,251,254, 413,365,362, 67,413,360, 282,283,295, 285,301,299, 202,281,280, 284,283,291, 284,291,289, 320,189,160, 308,306,307, 307,309,308, 319,317,330, 319,330,328, 353,352,324, 332,331,333, 340,341,338, 354,341,344, 349,358,357, 349,357,347, 364,355,356, 364,356,363, 364,365,366, 364,366,369, 374,376,402, 375, 92,373, 77,389,390, 382,380,381, 389, 77,386, 393,394,412, 393,412,392, 401,394,416, 415,400,403, 411,410,427, 411,427,426, 422,420,424, 247,248,263, 247,263,261, 445,443, 14, 445, 14, 11, 449,450, 4, 449, 4, 5, 443,441, 17, 443, 17, 14, 436, 23, 17, 436, 17,441, 424,448,422, 448,423,422, 414,419,418, 414,418,413, 406,404,405, 399,397,395, 399,395,396, 420,416,392, 388,410,411, 386,384,383, 390, 88, 77, 375, 94, 92, 415,414, 68, 415, 68, 94, 370,374,402, 370,402,398, 361,357,358, 361,358,359, 125,348,126, 346,344,343, 340,338,339, 337,335,334, 337,334,336, 325,353,324, 324,331,332, 324,332,329, 323,322,309, 323,309,310, 294,295,297, 294,297,296, 289,286,285, 202,280,203, 288,307,303, 282,295,321, 67,360,111, 418,423,367, 418,367,366, 272,252,251, 272,251,271, 272,271,270, 255,253,274, 265,266,380, 265,380,382, 442,428,261, 440,263,258, 440,258,260, 409,250,410, 255,226,245, 255,245,246, 31,240,243, 236,234,235, 236,235,237, 233,225,245, 233,245,244, 220,221, 85, 220, 85, 86, 81,213,226, 81,226, 80, 7,206,205, 186,184,198, 186,198,199, 204,203,205, 204,205,206, 195,193,196, 171,174,172, 173,174,175, 173,172,174, 155,167,166, 160,161,143, 160,143,144, 119,154,155, 148,151,150, 148,150,146, 140,137,139, 140,139,141, 127,126,130, 114,124,128, 114,128,115, 117,105,106, 117,106,116, 104,105,100, 104,100,103, 59, 60, 91, 97, 96, 61, 97, 61, 64, 91, 72, 89, 87, 84, 79, 87, 79, 76, 78, 80, 77, 49, 50, 74, 60, 44, 45, 61, 44, 58, 51, 50, 35, 51, 35, 34, 39, 37, 41, 33, 34, 9, 33, 9, 12, 0, 36, 37, 0, 37, 6, 40, 46, 47, 40, 47, 42, 53, 54, 56, 65, 62, 63, 72, 49, 73, 79, 78, 75, 79, 75, 76, 52, 53, 76, 92, 89, 90, 96, 93, 46, 102,103,100, 102,100,101, 116,106,108, 116,108,115, 123,125,124, 116,115,128, 118,131,135, 140,135,136, 148,147,149, 120,119,155, 164,162,152, 164,152,150, 157,147,161, 157,161,170, 186,187,185, 186,185,184, 193,197,196, 202,203,204, 194,195,178, 198,184,197, 67,111,109, 38, 43,103, 38,103,102, 214,223,222, 214,222,221, 214,221,220, 214,220,219, 214,219,218, 213,237,235, 221,222, 83, 221, 83, 85, 15,229, 33, 227, 18,230, 227,230,232, 52, 51,240, 75, 78, 50, 408,430,409, 260,258,257, 260,257,259, 224,207,259, 268,269,405, 268,405,404, 413,362,360, 447, 8,205, 299,297,285, 189,281,202, 290,288,289, 290,289,291, 322,321,295, 322,295,294, 333,323,311, 333,311,320, 317,316,329, 320,160,144, 353,325,326, 329,332,334, 329,334,330, 339,338,141, 339,141,139, 348,345,126, 347,356,346, 123,349,125, 364,353,354, 364,354,355, 365,364,363, 376,391,394, 376,394,401, 92,376,374, 92,374,373, 377, 90, 88, 380,379,378, 380,378,381, 388,387,409, 388,409,410, 416,393,392, 399,398,402, 399,402,403, 250,428,427, 421,417,416, 421,416,420, 426,427,446, 426,446,451, 444,442,441, 452,451,450, 452,450,449 }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Principal; using Xunit; using System.Text; using System.ComponentModel; using System.Security; using System.Threading; namespace System.Diagnostics.Tests { public partial class ProcessStartInfoTests : ProcessTestBase { [Fact] public void TestEnvironmentProperty() { Assert.NotEqual(0, new Process().StartInfo.Environment.Count); ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. IDictionary<string, string> environment = psi.Environment; Assert.NotEqual(0, environment.Count); int countItems = environment.Count; environment.Add("NewKey", "NewValue"); environment.Add("NewKey2", "NewValue2"); Assert.Equal(countItems + 2, environment.Count); environment.Remove("NewKey"); Assert.Equal(countItems + 1, environment.Count); environment.Add("NewKey2", "NewValue2Overridden"); Assert.Equal("NewValue2Overridden", environment["NewKey2"]); //Clear environment.Clear(); Assert.Equal(0, environment.Count); //ContainsKey environment.Add("NewKey", "NewValue"); environment.Add("NewKey2", "NewValue2"); Assert.True(environment.ContainsKey("NewKey")); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.ContainsKey("newkey")); Assert.False(environment.ContainsKey("NewKey99")); //Iterating string result = null; int index = 0; foreach (string e1 in environment.Values.OrderBy(p => p)) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("NewValueNewValue2", result); result = null; index = 0; foreach (string e1 in environment.Keys.OrderBy(p => p)) { index++; result += e1; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (KeyValuePair<string, string> e1 in environment.OrderBy(p => p.Key)) { index++; result += e1.Key; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); //Contains Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey", "NewValue"))); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("nEwKeY", "NewValue"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey99", "NewValue99"))); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environment.Contains(new KeyValuePair<string, string>(null, "NewValue99"))); environment.Add(new KeyValuePair<string, string>("NewKey98", "NewValue98")); //Indexed string newIndexItem = environment["NewKey98"]; Assert.Equal("NewValue98", newIndexItem); //TryGetValue string stringout = null; Assert.True(environment.TryGetValue("NewKey", out stringout)); Assert.Equal("NewValue", stringout); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.True(environment.TryGetValue("NeWkEy", out stringout)); Assert.Equal("NewValue", stringout); } stringout = null; Assert.False(environment.TryGetValue("NewKey99", out stringout)); Assert.Equal(null, stringout); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { string stringout1 = null; environment.TryGetValue(null, out stringout1); }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environment.Add(null, "NewValue2")); environment.Add("NewKey2", "NewValue2OverriddenAgain"); Assert.Equal("NewValue2OverriddenAgain", environment["NewKey2"]); //Remove Item environment.Remove("NewKey98"); environment.Remove("NewKey98"); //2nd occurrence should not assert //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { environment.Remove(null); }); //"Exception not thrown with null key" Assert.Throws<KeyNotFoundException>(() => environment["1bB"]); Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey2", "NewValue2OverriddenAgain"))); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("NEWKeY2", "NewValue2OverriddenAgain"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey2", "newvalue2Overriddenagain"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("newkey2", "newvalue2Overriddenagain"))); //Use KeyValuePair Enumerator string[] results = new string[2]; var x = environment.GetEnumerator(); x.MoveNext(); results[0] = x.Current.Key + " " + x.Current.Value; x.MoveNext(); results[1] = x.Current.Key + " " + x.Current.Value; Assert.Equal(new string[] { "NewKey NewValue", "NewKey2 NewValue2OverriddenAgain" }, results.OrderBy(s => s)); //IsReadonly Assert.False(environment.IsReadOnly); environment.Add(new KeyValuePair<string, string>("NewKey3", "NewValue3")); environment.Add(new KeyValuePair<string, string>("NewKey4", "NewValue4")); //CopyTo - the order is undefined. KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10]; environment.CopyTo(kvpa, 0); KeyValuePair<string, string>[] kvpaOrdered = kvpa.OrderByDescending(k => k.Value).ToArray(); Assert.Equal("NewKey4", kvpaOrdered[0].Key); Assert.Equal("NewKey2", kvpaOrdered[2].Key); environment.CopyTo(kvpa, 6); Assert.Equal(default(KeyValuePair<string, string>), kvpa[5]); Assert.StartsWith("NewKey", kvpa[6].Key); Assert.NotEqual(kvpa[6].Key, kvpa[7].Key); Assert.StartsWith("NewKey", kvpa[7].Key); Assert.NotEqual(kvpa[7].Key, kvpa[8].Key); Assert.StartsWith("NewKey", kvpa[8].Key); //Exception not thrown with null key Assert.Throws<ArgumentOutOfRangeException>(() => { environment.CopyTo(kvpa, -1); }); //Exception not thrown with null key Assert.Throws<ArgumentException>(() => { environment.CopyTo(kvpa, 9); }); //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { KeyValuePair<string, string>[] kvpanull = null; environment.CopyTo(kvpanull, 0); }); } [Fact] public void TestEnvironmentOfChildProcess() { const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff"; Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output try { // Schedule a process to see what env vars it gets. Have it write out those variables // to its output stream so we can read them. Process p = CreateProcess(() => { Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => Convert.ToBase64String(Encoding.UTF8.GetBytes(e.Key + "=" + e.Value))))); return SuccessExitCode; }); p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); // Parse the env vars from the child process var actualEnv = new HashSet<string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None).Select(s => Encoding.UTF8.GetString(Convert.FromBase64String(s)))); // Validate against StartInfo.Environment. var startInfoEnv = new HashSet<string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value)); Assert.True(startInfoEnv.SetEquals(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", startInfoEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(startInfoEnv)))); // Validate against current process. (Profilers / code coverage tools can add own environment variables // but we start child process without them. Thus the set of variables from the child process could // be a subset of variables from current process.) var envEnv = new HashSet<string>(Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value)); Assert.True(envEnv.IsSupersetOf(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", envEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(envEnv)))); } finally { Environment.SetEnvironmentVariable(ExtraEnvVar, null); } } [PlatformSpecific(TestPlatforms.Windows)] [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.Uap, "Only UAP blocks setting ShellExecute to true")] public void UseShellExecute_GetSetWindows_Success_Uap() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.False(psi.UseShellExecute); // Calling the setter Assert.Throws<PlatformNotSupportedException>(() => { psi.UseShellExecute = true; }); psi.UseShellExecute = false; // Calling the getter Assert.False(psi.UseShellExecute, "UseShellExecute=true is not supported on onecore."); } [PlatformSpecific(TestPlatforms.Windows)] [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Desktop UseShellExecute is set to true by default")] public void UseShellExecute_GetSetWindows_Success_Netfx() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.True(psi.UseShellExecute); psi.UseShellExecute = false; Assert.False(psi.UseShellExecute); psi.UseShellExecute = true; Assert.True(psi.UseShellExecute); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.NetFramework)] public void TestUseShellExecuteProperty_SetAndGet_NotUapOrNetFX() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.False(psi.UseShellExecute); psi.UseShellExecute = true; Assert.True(psi.UseShellExecute); psi.UseShellExecute = false; Assert.False(psi.UseShellExecute); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] public void TestUseShellExecuteProperty_Redirects_NotSupported(int std) { Process p = CreateProcessLong(); p.StartInfo.UseShellExecute = true; switch (std) { case 0: p.StartInfo.RedirectStandardInput = true; break; case 1: p.StartInfo.RedirectStandardOutput = true; break; case 2: p.StartInfo.RedirectStandardError = true; break; } Assert.Throws<InvalidOperationException>(() => p.Start()); } [Fact] public void TestArgumentsProperty() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.Equal(string.Empty, psi.Arguments); psi = new ProcessStartInfo("filename", "-arg1 -arg2"); Assert.Equal("-arg1 -arg2", psi.Arguments); psi.Arguments = "-arg3 -arg4"; Assert.Equal("-arg3 -arg4", psi.Arguments); } [Theory, InlineData(true), InlineData(false)] public void TestCreateNoWindowProperty(bool value) { Process testProcess = CreateProcessLong(); try { testProcess.StartInfo.CreateNoWindow = value; testProcess.Start(); Assert.Equal(value, testProcess.StartInfo.CreateNoWindow); } finally { if (!testProcess.HasExited) testProcess.Kill(); Assert.True(testProcess.WaitForExit(WaitInMS)); } } [Fact] public void TestWorkingDirectoryProperty() { CreateDefaultProcess(); // check defaults Assert.Equal(string.Empty, _process.StartInfo.WorkingDirectory); Process p = CreateProcessLong(); p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory(); try { p.Start(); Assert.Equal(Directory.GetCurrentDirectory(), p.StartInfo.WorkingDirectory); } finally { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } [ActiveIssue(12696)] [Fact, PlatformSpecific(TestPlatforms.Windows), OuterLoop] // Uses P/Invokes, Requires admin privileges public void TestUserCredentialsPropertiesOnWindows() { string username = "test", password = "PassWord123!!"; try { Interop.NetUserAdd(username, password); } catch (Exception exc) { Console.Error.WriteLine("TestUserCredentialsPropertiesOnWindows: NetUserAdd failed: {0}", exc.Message); return; // test is irrelevant if we can't add a user } bool hasStarted = false; SafeProcessHandle handle = null; Process p = null; try { p = CreateProcessLong(); p.StartInfo.LoadUserProfile = true; p.StartInfo.UserName = username; p.StartInfo.PasswordInClearText = password; hasStarted = p.Start(); if (Interop.OpenProcessToken(p.SafeHandle, 0x8u, out handle)) { SecurityIdentifier sid; if (Interop.ProcessTokenToSid(handle, out sid)) { string actualUserName = sid.Translate(typeof(NTAccount)).ToString(); int indexOfDomain = actualUserName.IndexOf('\\'); if (indexOfDomain != -1) actualUserName = actualUserName.Substring(indexOfDomain + 1); bool isProfileLoaded = GetNamesOfUserProfiles().Any(profile => profile.Equals(username)); Assert.Equal(username, actualUserName); Assert.True(isProfileLoaded); } } } finally { IEnumerable<uint> collection = new uint[] { 0 /* NERR_Success */, 2221 /* NERR_UserNotFound */ }; Assert.Contains<uint>(Interop.NetUserDel(null, username), collection); if (handle != null) handle.Dispose(); if (hasStarted) { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } } private static List<string> GetNamesOfUserProfiles() { List<string> userNames = new List<string>(); string[] names = Registry.Users.GetSubKeyNames(); for (int i = 1; i < names.Length; i++) { try { SecurityIdentifier sid = new SecurityIdentifier(names[i]); string userName = sid.Translate(typeof(NTAccount)).ToString(); int indexofDomain = userName.IndexOf('\\'); if (indexofDomain != -1) { userName = userName.Substring(indexofDomain + 1); userNames.Add(userName); } } catch (Exception) { } } return userNames; } [Fact] public void TestEnvironmentVariables_Environment_DataRoundTrips() { ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. psi.Environment.Clear(); psi.EnvironmentVariables.Add("NewKey", "NewValue"); psi.Environment.Add("NewKey2", "NewValue2"); Assert.Equal(psi.Environment["NewKey"], psi.EnvironmentVariables["NewKey"]); Assert.Equal(psi.Environment["NewKey2"], psi.EnvironmentVariables["NewKey2"]); Assert.Equal(2, psi.EnvironmentVariables.Count); Assert.Equal(psi.Environment.Count, psi.EnvironmentVariables.Count); Assert.Throws<ArgumentException>(null, () => psi.EnvironmentVariables.Add("NewKey2", "NewValue2")); psi.EnvironmentVariables.Add("NewKey3", "NewValue3"); psi.Environment.Add("NewKey3", "NewValue3Overridden"); Assert.Equal("NewValue3Overridden", psi.Environment["NewKey3"]); psi.EnvironmentVariables.Clear(); Assert.Equal(0, psi.Environment.Count); psi.EnvironmentVariables.Add("NewKey", "NewValue"); psi.EnvironmentVariables.Add("NewKey2", "NewValue2"); // Environment and EnvironmentVariables should be equal, but have different enumeration types. IEnumerable<KeyValuePair<string, string>> allEnvironment = psi.Environment.OrderBy(k => k.Key); IEnumerable<DictionaryEntry> allDictionary = psi.EnvironmentVariables.Cast<DictionaryEntry>().OrderBy(k => k.Key); Assert.Equal(allEnvironment.Select(k => new DictionaryEntry(k.Key, k.Value)), allDictionary); psi.EnvironmentVariables.Add("NewKey3", "NewValue3"); KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[5]; psi.Environment.CopyTo(kvpa, 0); KeyValuePair<string, string>[] kvpaOrdered = kvpa.OrderByDescending(k => k.Key).ToArray(); Assert.Equal("NewKey", kvpaOrdered[2].Key); Assert.Equal("NewValue", kvpaOrdered[2].Value); psi.EnvironmentVariables.Remove("NewKey3"); Assert.False(psi.Environment.Contains(new KeyValuePair<string,string>("NewKey3", "NewValue3"))); } [PlatformSpecific(TestPlatforms.Windows)] // Test case is specific to Windows [Fact] public void Verbs_GetWithExeExtension_ReturnsExpected() { var psi = new ProcessStartInfo { FileName = $"{Process.GetCurrentProcess().ProcessName}.exe" }; if (PlatformDetection.IsNetNative) { // UapAot doesn't have RegistryKey apis available so ProcessStartInfo.Verbs returns Array<string>.Empty(). Assert.Equal(0, psi.Verbs.Length); return; } Assert.Contains("open", psi.Verbs, StringComparer.OrdinalIgnoreCase); if (PlatformDetection.IsNotWindowsNanoServer) { Assert.Contains("runas", psi.Verbs, StringComparer.OrdinalIgnoreCase); Assert.Contains("runasuser", psi.Verbs, StringComparer.OrdinalIgnoreCase); } Assert.DoesNotContain("printto", psi.Verbs, StringComparer.OrdinalIgnoreCase); Assert.DoesNotContain("closed", psi.Verbs, StringComparer.OrdinalIgnoreCase); } [Theory] [InlineData("")] [InlineData("nofileextension")] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoExtension_ReturnsEmpty(string fileName) { var info = new ProcessStartInfo { FileName = fileName }; Assert.Empty(info.Verbs); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoRegisteredExtension_ReturnsEmpty() { var info = new ProcessStartInfo { FileName = "file.nosuchextension" }; Assert.Empty(info.Verbs); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoEmptyStringKey_ReturnsEmpty() { const string Extension = ".noemptykeyextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithEmptyStringValue_ReturnsEmpty() { const string Extension = ".emptystringextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", ""); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework throws an InvalidCastException for non-string keys. See https://github.com/dotnet/corefx/issues/18187.")] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNonStringValue_ReturnsEmpty() { const string Extension = ".nonstringextension"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", 123); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithNoShellSubKey_ReturnsEmpty() { const string Extension = ".noshellsubkey"; const string FileName = "file" + Extension; using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) { if (tempKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } tempKey.Key.SetValue("", "nosuchshell"); var info = new ProcessStartInfo { FileName = FileName }; Assert.Empty(info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetWithSubkeys_ReturnsEmpty() { const string Extension = ".customregistryextension"; const string FileName = "file" + Extension; const string SubKeyValue = "customregistryextensionshell"; using (TempRegistryKey extensionKey = new TempRegistryKey(Registry.ClassesRoot, Extension)) using (TempRegistryKey shellKey = new TempRegistryKey(Registry.ClassesRoot, SubKeyValue + "\\shell")) { if (extensionKey.Key == null) { // Skip this test if the user doesn't have permission to // modify the registry. return; } extensionKey.Key.SetValue("", SubKeyValue); shellKey.Key.CreateSubKey("verb1"); shellKey.Key.CreateSubKey("NEW"); shellKey.Key.CreateSubKey("new"); shellKey.Key.CreateSubKey("verb2"); var info = new ProcessStartInfo { FileName = FileName }; Assert.Equal(new string[] { "verb1", "verb2" }, info.Verbs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Verbs_GetUnix_ReturnsEmpty() { var info = new ProcessStartInfo(); Assert.Empty(info.Verbs); } [PlatformSpecific(TestPlatforms.AnyUnix)] // Test case is specific to Unix [Fact] public void TestEnvironmentVariablesPropertyUnix(){ ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. StringDictionary environmentVariables = psi.EnvironmentVariables; Assert.NotEqual(0, environmentVariables.Count); int CountItems = environmentVariables.Count; environmentVariables.Add("NewKey", "NewValue"); environmentVariables.Add("NewKey2", "NewValue2"); Assert.Equal(CountItems + 2, environmentVariables.Count); environmentVariables.Remove("NewKey"); Assert.Equal(CountItems + 1, environmentVariables.Count); //Exception not thrown with invalid key Assert.Throws<ArgumentException>(() => { environmentVariables.Add("NewKey2", "NewValue2"); }); Assert.False(environmentVariables.ContainsKey("NewKey")); environmentVariables.Add("newkey2", "newvalue2"); Assert.True(environmentVariables.ContainsKey("newkey2")); Assert.Equal("newvalue2", environmentVariables["newkey2"]); Assert.Equal("NewValue2", environmentVariables["NewKey2"]); environmentVariables.Clear(); Assert.Equal(0, environmentVariables.Count); environmentVariables.Add("NewKey", "newvalue"); environmentVariables.Add("newkey2", "NewValue2"); Assert.False(environmentVariables.ContainsKey("newkey")); Assert.False(environmentVariables.ContainsValue("NewValue")); string result = null; int index = 0; foreach (string e1 in environmentVariables.Values) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("newvalueNewValue2", result); result = null; index = 0; foreach (string e1 in environmentVariables.Keys) { index++; result += e1; } Assert.Equal("NewKeynewkey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (DictionaryEntry e1 in environmentVariables) { index++; result += e1.Key; } Assert.Equal("NewKeynewkey2", result); Assert.Equal(2, index); //Key not found Assert.Throws<KeyNotFoundException>(() => { string stringout = environmentVariables["NewKey99"]; }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { string stringout = environmentVariables[null]; }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environmentVariables.Add(null, "NewValue2")); Assert.Throws<ArgumentException>(() => environmentVariables.Add("newkey2", "NewValue2")); //Use DictionaryEntry Enumerator var x = environmentVariables.GetEnumerator() as IEnumerator; x.MoveNext(); var y1 = (DictionaryEntry)x.Current; Assert.Equal("NewKey newvalue", y1.Key + " " + y1.Value); x.MoveNext(); y1 = (DictionaryEntry)x.Current; Assert.Equal("newkey2 NewValue2", y1.Key + " " + y1.Value); environmentVariables.Add("newkey3", "newvalue3"); KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10]; environmentVariables.CopyTo(kvpa, 0); Assert.Equal("NewKey", kvpa[0].Key); Assert.Equal("newkey3", kvpa[2].Key); Assert.Equal("newvalue3", kvpa[2].Value); string[] kvp = new string[10]; Assert.Throws<ArgumentException>(() => { environmentVariables.CopyTo(kvp, 6); }); environmentVariables.CopyTo(kvpa, 6); Assert.Equal("NewKey", kvpa[6].Key); Assert.Equal("newvalue", kvpa[6].Value); Assert.Throws<ArgumentOutOfRangeException>(() => { environmentVariables.CopyTo(kvpa, -1); }); Assert.Throws<ArgumentException>(() => { environmentVariables.CopyTo(kvpa, 9); }); Assert.Throws<ArgumentNullException>(() => { KeyValuePair<string, string>[] kvpanull = null; environmentVariables.CopyTo(kvpanull, 0); }); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("domain")] [PlatformSpecific(TestPlatforms.Windows)] public void Domain_SetWindows_GetReturnsExpected(string domain) { var info = new ProcessStartInfo { Domain = domain }; Assert.Equal(domain ?? string.Empty, info.Domain); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Domain_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.Domain); Assert.Throws<PlatformNotSupportedException>(() => info.Domain = "domain"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("filename")] public void FileName_Set_GetReturnsExpected(string fileName) { var info = new ProcessStartInfo { FileName = fileName }; Assert.Equal(fileName ?? string.Empty, info.FileName); } [Theory] [InlineData(true)] [InlineData(false)] [PlatformSpecific(TestPlatforms.Windows)] public void LoadUserProfile_SetWindows_GetReturnsExpected(bool loadUserProfile) { var info = new ProcessStartInfo { LoadUserProfile = loadUserProfile }; Assert.Equal(loadUserProfile, info.LoadUserProfile); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void LoadUserProfile_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile); Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile = false); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("passwordInClearText")] [PlatformSpecific(TestPlatforms.Windows)] public void PasswordInClearText_SetWindows_GetReturnsExpected(string passwordInClearText) { var info = new ProcessStartInfo { PasswordInClearText = passwordInClearText }; Assert.Equal(passwordInClearText, info.PasswordInClearText); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void PasswordInClearText_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText); Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText = "passwordInClearText"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void Password_SetWindows_GetReturnsExpected() { using (SecureString password = new SecureString()) { password.AppendChar('a'); var info = new ProcessStartInfo { Password = password }; Assert.Equal(password, info.Password); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Password_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.Password); Assert.Throws<PlatformNotSupportedException>(() => info.Password = new SecureString()); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("domain")] [PlatformSpecific(TestPlatforms.Windows)] public void UserName_SetWindows_GetReturnsExpected(string userName) { var info = new ProcessStartInfo { UserName = userName }; Assert.Equal(userName ?? string.Empty, info.UserName); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void UserName_GetSetUnix_ThrowsPlatformNotSupportedException() { var info = new ProcessStartInfo(); Assert.Throws<PlatformNotSupportedException>(() => info.UserName); Assert.Throws<PlatformNotSupportedException>(() => info.UserName = "username"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("verb")] public void Verb_Set_GetReturnsExpected(string verb) { var info = new ProcessStartInfo { Verb = verb }; Assert.Equal(verb ?? string.Empty, info.Verb); } [Theory] [InlineData(ProcessWindowStyle.Normal - 1)] [InlineData(ProcessWindowStyle.Maximized + 1)] public void WindowStyle_SetNoSuchWindowStyle_ThrowsInvalidEnumArgumentException(ProcessWindowStyle style) { var info = new ProcessStartInfo(); Assert.Throws<InvalidEnumArgumentException>(() => info.WindowStyle = style); } [Theory] [InlineData(ProcessWindowStyle.Hidden)] [InlineData(ProcessWindowStyle.Maximized)] [InlineData(ProcessWindowStyle.Minimized)] [InlineData(ProcessWindowStyle.Normal)] public void WindowStyle_Set_GetReturnsExpected(ProcessWindowStyle style) { var info = new ProcessStartInfo { WindowStyle = style }; Assert.Equal(style, info.WindowStyle); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("workingdirectory")] public void WorkingDirectory_Set_GetReturnsExpected(string workingDirectory) { var info = new ProcessStartInfo { WorkingDirectory = workingDirectory }; Assert.Equal(workingDirectory ?? string.Empty, info.WorkingDirectory); } [Fact(Skip = "Manual test")] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] public void StartInfo_WebPage() { ProcessStartInfo info = new ProcessStartInfo { UseShellExecute = true, FileName = @"http://www.microsoft.com" }; Process.Start(info); // Returns null after navigating browser } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] // No Notepad on Nano [MemberData(nameof(UseShellExecute))] [OuterLoop("Launches notepad")] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")] public void StartInfo_NotepadWithContent(bool useShellExecute) { string tempFile = GetTestFilePath() + ".txt"; File.WriteAllText(tempFile, $"StartInfo_NotepadWithContent({useShellExecute})"); ProcessStartInfo info = new ProcessStartInfo { UseShellExecute = useShellExecute, FileName = @"notepad.exe", Arguments = tempFile, WindowStyle = ProcessWindowStyle.Minimized }; using (var process = Process.Start(info)) { Assert.True(process != null, $"Could not start {info.FileName} {info.Arguments} UseShellExecute={info.UseShellExecute}"); try { process.WaitForInputIdle(); // Give the file a chance to load Assert.Equal("notepad", process.ProcessName); // On some Windows versions, the file extension is not included in the title Assert.StartsWith(Path.GetFileNameWithoutExtension(tempFile), process.MainWindowTitle); } finally { if (process != null && !process.HasExited) process.Kill(); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] // Does not support UseShellExecute [OuterLoop("Launches notepad")] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")] [ActiveIssue("https://github.com/dotnet/corefx/issues/20388")] public void StartInfo_TextFile_ShellExecute() { string tempFile = GetTestFilePath() + ".txt"; File.WriteAllText(tempFile, $"StartInfo_TextFile_ShellExecute"); ProcessStartInfo info = new ProcessStartInfo { UseShellExecute = true, FileName = tempFile, WindowStyle = ProcessWindowStyle.Minimized }; using (var process = Process.Start(info)) { Assert.True(process != null, $"Could not start {info.FileName} UseShellExecute={info.UseShellExecute}"); try { process.WaitForInputIdle(); // Give the file a chance to load Assert.Equal("notepad", process.ProcessName); // On some Windows versions, the file extension is not included in the title Assert.StartsWith(Path.GetFileNameWithoutExtension(tempFile), process.MainWindowTitle); } finally { if (process != null && !process.HasExited) process.Kill(); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsWindowsNanoServer))] public void ShellExecute_Nano_Fails_Start() { string tempFile = GetTestFilePath() + ".txt"; File.Create(tempFile).Dispose(); ProcessStartInfo info = new ProcessStartInfo { UseShellExecute = true, FileName = tempFile }; Assert.Throws<PlatformNotSupportedException>(() => Process.Start(info)); } public static TheoryData<bool> UseShellExecute { get { TheoryData<bool> data = new TheoryData<bool> { false }; if ( !PlatformDetection.IsUap // https://github.com/dotnet/corefx/issues/20204 && !PlatformDetection.IsWindowsNanoServer) // By design data.Add(true); return data; } } private const int ERROR_SUCCESS = 0x0; private const int ERROR_FILE_NOT_FOUND = 0x2; private const int ERROR_BAD_EXE_FORMAT = 0xC1; [MemberData(nameof(UseShellExecute))] [PlatformSpecific(TestPlatforms.Windows)] public void StartInfo_BadVerb(bool useShellExecute) { ProcessStartInfo info = new ProcessStartInfo { UseShellExecute = useShellExecute, FileName = @"foo.txt", Verb = "Zlorp" }; Assert.Equal(ERROR_FILE_NOT_FOUND, Assert.Throws<Win32Exception>(() => Process.Start(info)).NativeErrorCode); } [MemberData(nameof(UseShellExecute))] [PlatformSpecific(TestPlatforms.Windows)] public void StartInfo_BadExe(bool useShellExecute) { string tempFile = GetTestFilePath() + ".exe"; File.Create(tempFile).Dispose(); ProcessStartInfo info = new ProcessStartInfo { UseShellExecute = useShellExecute, FileName = tempFile }; int expected = ERROR_BAD_EXE_FORMAT; // Windows Nano bug see #10290 if (PlatformDetection.IsWindowsNanoServer) expected = ERROR_SUCCESS; Assert.Equal(expected, Assert.Throws<Win32Exception>(() => Process.Start(info)).NativeErrorCode); } } }
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) using System; using GooglePlayGames.Native.PInvoke; using System.Runtime.InteropServices; using GooglePlayGames.OurUtils; using System.Collections.Generic; using GooglePlayGames.Native.Cwrapper; using C = GooglePlayGames.Native.Cwrapper.RealTimeEventListenerHelper; using Types = GooglePlayGames.Native.Cwrapper.Types; using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus; namespace GooglePlayGames.Native.PInvoke { internal class RealTimeEventListenerHelper : BaseReferenceHolder { internal RealTimeEventListenerHelper(IntPtr selfPointer) : base(selfPointer) { } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeEventListenerHelper_Dispose(selfPointer); } internal RealTimeEventListenerHelper SetOnRoomStatusChangedCallback( Action<NativeRealTimeRoom> callback) { C.RealTimeEventListenerHelper_SetOnRoomStatusChangedCallback(SelfPtr(), InternalOnRoomStatusChangedCallback, ToCallbackPointer(callback)); return this; } [AOT.MonoPInvokeCallback(typeof(C.OnRoomStatusChangedCallback))] internal static void InternalOnRoomStatusChangedCallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealTimeEventListenerHelper#InternalOnRoomStatusChangedCallback", Callbacks.Type.Permanent, response, data); } internal RealTimeEventListenerHelper SetOnRoomConnectedSetChangedCallback( Action<NativeRealTimeRoom> callback) { C.RealTimeEventListenerHelper_SetOnRoomConnectedSetChangedCallback(SelfPtr(), InternalOnRoomConnectedSetChangedCallback, ToCallbackPointer(callback)); return this; } [AOT.MonoPInvokeCallback(typeof(C.OnRoomConnectedSetChangedCallback))] internal static void InternalOnRoomConnectedSetChangedCallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealTimeEventListenerHelper#InternalOnRoomConnectedSetChangedCallback", Callbacks.Type.Permanent, response, data); } internal RealTimeEventListenerHelper SetOnP2PConnectedCallback( Action<NativeRealTimeRoom, MultiplayerParticipant> callback) { C.RealTimeEventListenerHelper_SetOnP2PConnectedCallback(SelfPtr(), InternalOnP2PConnectedCallback, Callbacks.ToIntPtr(callback)); return this; } [AOT.MonoPInvokeCallback(typeof(C.OnP2PConnectedCallback))] internal static void InternalOnP2PConnectedCallback( IntPtr room, IntPtr participant, IntPtr data) { PerformRoomAndParticipantCallback( "InternalOnP2PConnectedCallback", room, participant, data); } internal RealTimeEventListenerHelper SetOnP2PDisconnectedCallback( Action<NativeRealTimeRoom, MultiplayerParticipant> callback) { C.RealTimeEventListenerHelper_SetOnP2PDisconnectedCallback(SelfPtr(), InternalOnP2PDisconnectedCallback, Callbacks.ToIntPtr(callback)); return this; } [AOT.MonoPInvokeCallback(typeof(C.OnP2PDisconnectedCallback))] internal static void InternalOnP2PDisconnectedCallback( IntPtr room, IntPtr participant, IntPtr data) { PerformRoomAndParticipantCallback( "InternalOnP2PDisconnectedCallback", room, participant, data); } internal RealTimeEventListenerHelper SetOnParticipantStatusChangedCallback( Action<NativeRealTimeRoom, MultiplayerParticipant> callback) { C.RealTimeEventListenerHelper_SetOnParticipantStatusChangedCallback(SelfPtr(), InternalOnParticipantStatusChangedCallback, Callbacks.ToIntPtr(callback)); return this; } [AOT.MonoPInvokeCallback(typeof(C.OnParticipantStatusChangedCallback))] internal static void InternalOnParticipantStatusChangedCallback( IntPtr room, IntPtr participant, IntPtr data) { PerformRoomAndParticipantCallback( "InternalOnParticipantStatusChangedCallback", room, participant, data); } internal static void PerformRoomAndParticipantCallback(string callbackName, IntPtr room, IntPtr participant, IntPtr data) { Logger.d("Entering " + callbackName); try { // This is a workaround to the fact that we're lacking proper copy constructors - // see comment below. var nativeRoom = NativeRealTimeRoom.FromPointer(room); using (var nativeParticipant = MultiplayerParticipant.FromPointer(participant)) { var callback = Callbacks.IntPtrToPermanentCallback <Action<NativeRealTimeRoom, MultiplayerParticipant>>(data); if (callback != null) { callback(nativeRoom, nativeParticipant); } } } catch (Exception e) { Logger.e("Error encountered executing " + callbackName + ". " + "Smothering to avoid passing exception into Native: " + e); } } internal RealTimeEventListenerHelper SetOnDataReceivedCallback( Action<NativeRealTimeRoom, MultiplayerParticipant, byte[], bool> callback) { IntPtr onData = Callbacks.ToIntPtr(callback); Logger.d("OnData Callback has addr: " + onData.ToInt64()); C.RealTimeEventListenerHelper_SetOnDataReceivedCallback(SelfPtr(), InternalOnDataReceived, onData); return this; } [AOT.MonoPInvokeCallback(typeof(C.OnDataReceivedCallback))] internal static void InternalOnDataReceived( IntPtr room, IntPtr participant, IntPtr data, UIntPtr dataLength, bool isReliable, IntPtr userData) { Logger.d("Entering InternalOnDataReceived: " + userData.ToInt64()); var callback = Callbacks.IntPtrToPermanentCallback <Action<NativeRealTimeRoom, MultiplayerParticipant, byte[], bool>>(userData); using (var nativeRoom = NativeRealTimeRoom.FromPointer(room)) { using (var nativeParticipant = MultiplayerParticipant.FromPointer(participant)) { if (callback == null) { return; } byte[] convertedData = null; if (dataLength.ToUInt64() != 0) { convertedData = new byte[dataLength.ToUInt32()]; Marshal.Copy(data, convertedData, 0, (int) dataLength.ToUInt32()); } try { callback(nativeRoom, nativeParticipant, convertedData, isReliable); } catch (Exception e) { Logger.e("Error encountered executing InternalOnDataReceived. " + "Smothering to avoid passing exception into Native: " + e); } } } } // This is a workaround to the fact that we're lacking proper copy constructors on the cwrapper // structs. Clients of the RealTimeEventListener need to hold long-lived references to the // room returned by the callback, but the default implementation of the utility callback method // cleans up all arguments to the callback. This can be gotten rid of when copy constructors // are present in the native sdk. private static IntPtr ToCallbackPointer(Action<NativeRealTimeRoom> callback) { Action<IntPtr> pointerReceiver = result => { NativeRealTimeRoom converted = NativeRealTimeRoom.FromPointer(result); if (callback != null) { callback(converted); } else { if (converted != null) { converted.Dispose(); } } }; return Callbacks.ToIntPtr(pointerReceiver); } internal static RealTimeEventListenerHelper Create() { return new RealTimeEventListenerHelper(C.RealTimeEventListenerHelper_Construct()); } } } #endif
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using Merlin.Testing.TypeSample; // C# has no static indexer // ref, out modifier is not valid for this[xxx] signature namespace Merlin.Testing.Indexer { public interface IReturnDouble { int this[int arg] { get; set; } } public struct StructExplicitImplementInterface : IReturnDouble { int[] array; public void Init() { array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; } int IReturnDouble.this[int arg] { get { return array[arg]; } set { array[arg] = value; } } } public class ClassExplicitImplementInterface : IReturnDouble { int[] array; public void Init() { array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; } int IReturnDouble.this[int arg] { get { return array[arg]; } set { array[arg] = value; } } } public class DerivedClassExplicitImplementInterface : ClassExplicitImplementInterface { } public struct StructImplicitImplementInterface : IReturnDouble { int[] array; public void Init() { array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; } public int this[int arg] { get { return array[arg]; } set { array[arg] = value; } } } public class ClassImplicitImplementInterface : IReturnDouble { int[] array; public void Init() { array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; } public int this[int arg] { get { return array[arg]; } set { array[arg] = value; } } } public struct StructWithIndexer { int[] array; Dictionary<string, object> dict; public void Init() { array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; dict = new Dictionary<string, object>(); } public int this[int arg] { get { return array[arg]; } set { array[arg] = value; } } public SimpleStruct this[int arg1, string arg2] { get { return (SimpleStruct)dict[arg2 + arg1.ToString()]; } set { dict[arg2 + arg1.ToString()] = value; } } public SimpleClass this[string arg1, string arg2, string arg3] { get { return (SimpleClass)dict[arg1 + arg2 + arg3]; } set { dict[arg1 + arg2 + arg3] = value; } } } public class ClassWithIndexer { int[] array; Dictionary<string, object> dict; public void Init() { array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; dict = new Dictionary<string, object>(); } public int this[int arg] { get { return array[arg]; } set { array[arg] = value; } } public SimpleStruct this[int arg1, string arg2] { get { return (SimpleStruct)dict[arg2 + arg1.ToString()]; } set { dict[arg2 + arg1.ToString()] = value; } } public SimpleClass this[string arg1, string arg2, string arg3] { get { return (SimpleClass)dict[arg1 + arg2 + arg3]; } set { dict[arg1 + arg2 + arg3] = value; } } } public class DerivedClassWithoutIndexer : ClassWithIndexer { } public class ClassWithParamsIndexer { int[] array; public void Init() { array = new int[100]; for (int i = 0; i < 100; i++) { array[i] = i; } array[0] = -100; } public int this[params int[] args] { get { int sum = 0; foreach (int x in args) { sum += x; } return array[sum]; } set { int sum = 0; foreach (int x in args) { sum += x; } array[sum] = value; } } } public class ClassWithIndexerOverloads1 { int[] array; public void Init() { array = new int[100]; for (int i = 0; i < 100; i++) { array[i] = i; } array[0] = -200; } public int this[params int[] args] { get { int sum = 0; foreach (int x in args) { sum += x; } return array[sum]; } set { int sum = 0; foreach (int x in args) { sum += x; } array[sum] = value; } } public int this[int arg1, int arg2] { get { return array[arg1 * arg2]; } set { array[arg1 * arg2] = value; } } } public class ClassWithIndexerOverloads2 { int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public int this[int arg] { get { return array[arg]; } set { array[arg] = value; } } Dictionary<string, string> dict = new Dictionary<string, string>(); public string this[string arg] { get { return dict[arg]; } set { dict[arg] = value; } } } // more overload scenarios needed public class ReadOnlyIndexer { public int this[int arg] { get { return 10; } } } public class WriteOnlyIndexer { public int this[int arg] { set { Flag.Set(arg + value); } } } public class BaseClassWithIndexer { protected int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public int this[int arg] { get { return array[arg]; } set { array[arg] = value; } } } public class DerivedClassWithNewIndexer : BaseClassWithIndexer { public new int this[int arg] { get { return array[arg] * -1; } set { array[arg] = value * 2; } } } public class DerivedClassWithNewWriteOnlyIndexer : BaseClassWithIndexer { public new int this[int arg] { set { array[arg] = value * 2; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using CsQueryControls.Demo.Areas.HelpPage.Models; namespace CsQueryControls.Demo.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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 ShiftLeftLogical128BitLaneInt161() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int16); private const int RetElementCount = VectorSize / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Vector256<Int16> _clsVar; private Vector256<Int16> _fld; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ShiftLeftLogical128BitLane( Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ShiftLeftLogical128BitLane( Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ShiftLeftLogical128BitLane( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161(); var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { if (result[0] != 2048) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 2048) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical128BitLane)}<Int16>(Vector256<Int16><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace Hydra.Framework.Conversions { // // ********************************************************************** /// <summary> /// Type related utility methods. /// </summary> // ********************************************************************** // public class ConvertType { #region Member Variables // // ********************************************************************** /// <summary> /// Type classification lists /// </summary> // ********************************************************************** // static protected Type[] m_NumericTypes = { typeof(Byte), typeof(SByte), typeof(Int16), typeof(Int32), typeof(Int64), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal), typeof(float), typeof(Byte?), typeof(SByte?), typeof(Int16?), typeof(Int32?), typeof(Int64?), typeof(UInt16?), typeof(UInt32?), typeof(UInt64?), typeof(Single?), typeof(Double?), typeof(Decimal?), typeof(float?), }; // // ********************************************************************** /// <summary> /// List of Integer Types /// </summary> // ********************************************************************** // static protected Type[] m_IntegerTypes = { typeof(Byte), typeof(SByte), typeof(Int16), typeof(Int32), typeof(Int64), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(Byte?), typeof(SByte?), typeof(Int16?), typeof(Int32?), typeof(Int64?), typeof(UInt16?), typeof(UInt32?), typeof(UInt64?) }; // // ********************************************************************** /// <summary> /// List of String Types /// </summary> // ********************************************************************** // static protected Type[] m_StringTypes = { typeof(String), typeof(Char), typeof(Char?) }; // // ********************************************************************** /// <summary> /// Lit of Boolean Types /// </summary> // ********************************************************************** // static protected Type[] m_BooleanTypes = { typeof(Boolean), typeof(Boolean?) }; // // ********************************************************************** /// <summary> /// List of Date / Time Types /// </summary> // ********************************************************************** // static protected Type[] m_DateTimeTypes = { typeof(DateTime), typeof(DateTime?) }; // // ********************************************************************** /// <summary> /// List of Guid Types /// </summary> // ********************************************************************** // static protected Type[] m_GuidTypes = { typeof(Guid), typeof(Guid?) }; #endregion #region Static Methods // // ********************************************************************** /// <summary> /// Returns true if the given type is one of numeric types. /// </summary> /// <param name="type">type to check</param> /// <returns> /// true if the given type is one of numeric types /// </returns> // ********************************************************************** // public static bool IsNumber(Type type) { return Array.IndexOf(m_NumericTypes, type) >= 0; } // // ********************************************************************** /// <summary> /// Returns true if the given type is one of integer types. /// </summary> /// <param name="type">type to check</param> /// <returns> /// true if the given type is one of integer types /// </returns> // ********************************************************************** // public static bool IsInteger(Type type) { return Array.IndexOf(m_IntegerTypes, type) >= 0; } // // ********************************************************************** /// <summary> /// Returns true if the given type is one of string types (string or char). /// </summary> /// <param name="type">type to check</param> /// <returns> /// true if the given type is one of string types /// </returns> // ********************************************************************** // public static bool IsString(Type type) { return Array.IndexOf(m_StringTypes, type) >= 0; } // // ********************************************************************** /// <summary> /// Returns true if the given type is the datetime type. /// </summary> /// <param name="type">type to check</param> /// <returns> /// true if the given type is the datetime type /// </returns> // ********************************************************************** // public static bool IsDateTime(Type type) { return Array.IndexOf(m_DateTimeTypes, type) >= 0; } // // ********************************************************************** /// <summary> /// Returns true if the given type is the boolean type. /// </summary> /// <param name="type">type to check</param> /// <returns> /// true if the given type is the boolean type /// </returns> // ********************************************************************** // public static bool IsBoolean(Type type) { return Array.IndexOf(m_BooleanTypes, type) >= 0; } // // ********************************************************************** /// <summary> /// Returns true if the given type is the GUID type. /// </summary> /// <param name="type">type to check</param> /// <returns>true if the given type is the GUID type</returns> // ********************************************************************** // public static bool IsGuid(Type type) { return Array.IndexOf(m_GuidTypes, type) >= 0; } // // ********************************************************************** /// <summary> /// Returns true if the given type is the binary type (byte array). /// </summary> /// <param name="type">type to check</param> /// <returns> /// true if the given type is the binary type /// </returns> // ********************************************************************** // public static bool IsBinary(Type type) { return type == typeof(Byte[]); } // // ********************************************************************** /// <summary> /// Returns type of the class using its name. /// </summary> /// <param name="assembly">assembly containing class</param> /// <param name="className">name of the class</param> /// <returns> /// type of the class or null if type is not found /// </returns> // ********************************************************************** // static public Type GetTypeByName(Assembly assembly, string className) { if (assembly != null && ConvertUtils.NotEmpty(className)) { try { return assembly.GetType(className); } catch { return null; } } return null; } // // ********************************************************************** /// <summary> /// Returns type of the class using its name. /// Searches all loaded assemblies. /// </summary> /// <param name="className">name of class</param> /// <returns> /// type of the class or null if type is not found /// </returns> // ********************************************************************** // static public Type GetTypeByName(string className) { Type type = GetTypeByName(Assembly.GetCallingAssembly(), className); if (type == null) type = GetTypeByName(Assembly.GetEntryAssembly(), className); if (type == null) type = GetTypeByName(Assembly.GetExecutingAssembly(), className); if (type == null) { // // Check AppDomain.GetAssemblies() // Assembly[] arr = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < arr.Length; i++) { type = GetTypeByName(arr[i], className); if (type != null) break; } } return type; } // // ********************************************************************** /// <summary> /// Returns type reference for className from the specified assembly. /// </summary> /// <param name="assemblyFolder">folder where assembly located</param> /// <param name="assemblyName">name of the assembly</param> /// <param name="className">name of the class</param> /// <returns> /// type reference for className from the specified assembly /// </returns> // ********************************************************************** // static public Type GetTypeByName(string assemblyFolder, string assemblyName, string className) { Assembly assembly = GetAssembly(assemblyFolder, assemblyName); return GetTypeByName(assembly, className); } // // ********************************************************************** /// <summary> /// Creates instance of the given type using constructor that matches with parameters. /// </summary> /// <param name="className">name of the class to create</param> /// <param name="types">constructor parameter types</param> /// <param name="parameters">constructor parameters</param> /// <returns>created object</returns> // ********************************************************************** // static public Object CreateInstance(string className, Type[] types, object[] parameters) { Type type = GetTypeByName(className); if (type == null) throw new ExClassNotFoundException(className); return CreateInstance(type, types, parameters); } // // ********************************************************************** /// <summary> /// Creates instance of the given type using constructor that matches with parameters. /// </summary> /// <param name="assemblyFolder">folder where assembly located</param> /// <param name="assemblyName">name of the assembly</param> /// <param name="className">name of the class to create</param> /// <param name="types">list of parameter types</param> /// <param name="parameters">constructor parameters</param> /// <param name="raiseException">if true exception will be raised when class could not be created, /// if false null will be returned</param> /// <returns>created object or null</returns> // ********************************************************************** // static public Object CreateInstance(string assemblyFolder, string assemblyName, string className, Type[] types, object[] parameters, bool raiseException) { Assembly assembly = GetAssembly(assemblyFolder, assemblyName, raiseException); if (assembly != null) { Type type = assembly.GetType(className); if (type == null) { if (raiseException) { throw new ExClassNotFoundException(className); } else { return null; } } return CreateInstance(type, types, parameters, raiseException); } return null; } // // ********************************************************************** /// <summary> /// Creates instance of the given type using constructor that matches with parameters. /// If it is impossible to create such instance raises an exception. /// </summary> /// <param name="assemblyFolder">folder where assembly located</param> /// <param name="assemblyName">name of the assembly</param> /// <param name="className">name of the class to create</param> /// <param name="types">list of parameter types</param> /// <param name="parameters">constructor parameters</param> /// <returns>created object</returns> // ********************************************************************** // static public Object CreateInstance(string assemblyFolder, string assemblyName, string className, Type[] types, object[] parameters) { return CreateInstance(assemblyFolder, assemblyName, className, types, parameters, true); } // // ********************************************************************** /// <summary> /// Creates instance of the given type using constructor that matches with parameters. /// If it is impossible to create such instance raises an exception. /// </summary> /// <param name="assemblyName">name of the assembly</param> /// <param name="className">name of the class to create</param> /// <param name="types">list of parameter types</param> /// <param name="parameters">constructor parameters</param> /// <returns>created object</returns> // ********************************************************************** // static public Object CreateInstance(string assemblyName, string className, Type[] types, object[] parameters) { Assembly assembly = GetAssembly(assemblyName); Type type = assembly.GetType(className); if (type == null) throw new ExClassNotFoundException(className); return CreateInstance(type, types, parameters); } // // ********************************************************************** /// <summary> /// Creates instance of the given type using constructor that matches with parameters. /// </summary> /// <param name="type">type of instance to create</param> /// <param name="types">list of parameter types</param> /// <param name="parameters">constructor parameters</param> /// <param name="raiseException">if true exception will be raised when class could not be created.</param> /// <returns>created object or null</returns> // ********************************************************************** // static public Object CreateInstance(Type type, Type[] types, object[] parameters, bool raiseException) { ConstructorInfo constructor = type.GetConstructor(types); if (constructor == null) { if (raiseException) { throw new ExConstructorNotFoundException(type, types); } else { return null; } } Object obj = constructor.Invoke(parameters); return obj; } // // ********************************************************************** /// <summary> /// Creates instance of the given type using constructor that matches with parameters. /// If it is impossible to create such instance raises an exception. /// </summary> /// <param name="type">type of instance to create</param> /// <param name="types">list of parameter types</param> /// <param name="parameters">constructor parameters</param> /// <returns>created object</returns> // ********************************************************************** // static public Object CreateInstance(Type type, Type[] types, object[] parameters) { return CreateInstance(type, types, parameters, true); } // // ********************************************************************** /// <summary> /// Creates instance of the given type using constructor that matches with parameters. /// If it is impossible to create such instance raises an exception. /// </summary> /// <param name="className">name of the class to create</param> /// <param name="parameters">constructor parameters</param> /// <returns>created object</returns> // ********************************************************************** // static public Object CreateInstance(string className, params object[] parameters) { Type[] types = new Type[parameters.Length]; for (int i = 0; i < types.Length; i++) { if (parameters[i] == null) throw new ArgumentNullException("Create Instance Parameter"); types[i] = parameters[i].GetType(); } return CreateInstance(className, types, parameters); } // // ********************************************************************** /// <summary> /// Creates instance of the given type. /// If it is impossible to create such instance raises an exception. /// </summary> /// <param name="className">class name to create instance of</param> /// <returns>created object</returns> // ********************************************************************** // static public Object CreateInstance(string className) { Type type = GetTypeByName(className); if (type == null) throw new ExClassNotFoundException(className); return CreateInstance(type); } // // ********************************************************************** /// <summary> /// Creates instance of the given type. /// </summary> /// <param name="assemblyFolder">folder where assembly located</param> /// <param name="assemblyName">name of the assembly</param> /// <param name="className">name of the class to create</param> /// <returns>created object</returns> // ********************************************************************** // static public Object CreateInstance(string assemblyFolder, string assemblyName, string className) { Assembly assembly = GetAssembly(assemblyFolder, assemblyName); Type type = assembly.GetType(className); if (type == null) throw new ExClassNotFoundException(className); return CreateInstance(type); } // // ********************************************************************** /// <summary> /// Creates instance of the given type. /// If it is impossible to create such instance raises an exception. /// </summary> /// <param name="type">type to create instance of</param> /// <returns>created object</returns> // ********************************************************************** // static public Object CreateInstance(Type type) { if (type == null) throw new ArgumentNullException("Create Instance Type Parameter"); return type.Assembly.CreateInstance(type.FullName); } // // ********************************************************************** /// <summary> /// Loads assembly from file. /// </summary> /// <param name="assemblyName">name of the file with assembly</param> /// <returns>loaded assembly</returns> // ********************************************************************** // static public Assembly GetAssembly(string assemblyName) { return GetAssembly(null, assemblyName); } // // ********************************************************************** /// <summary> /// Loads assembly from file. /// </summary> /// <param name="subFolderName">name of the folder with assembly</param> /// <param name="assemblyName">name of the assembly</param> /// <param name="raiseException">if true exception will be raised when assembly could not be loaded. /// If false returns null.</param> /// <returns>loaded assembly</returns> // ********************************************************************** // static public Assembly GetAssembly(string subFolderName, string assemblyName, bool raiseException) { return GetAssembly(ConvertPath.GetApplicationBinaryFolder(), subFolderName, assemblyName, raiseException); } // // ********************************************************************** /// <summary> /// Loads assembly from file. /// </summary> /// <param name="rootFolderName">name of the root folder with the assembly</param> /// <param name="subFolderName">name of the sub-folder with assembly</param> /// <param name="assemblyName">name of the assembly</param> /// <param name="raiseException">if true exception will be raised when assembly could not be loaded. /// If false returns null.</param> /// <returns>loaded assembly</returns> // ********************************************************************** // static public Assembly GetAssembly(string rootFolderName, string subFolderName, string assemblyName, bool raiseException) { string path = Path.Combine(rootFolderName, ConvertUtils.Nvl(subFolderName)); string fileName = Path.Combine(path, ConvertUtils.Nvl(assemblyName)); Assembly assembly = Assembly.LoadFrom(fileName); if (assembly == null && raiseException) throw new ExAssemblyNotFoundException(fileName); return assembly; } // // ********************************************************************** /// <summary> /// Loads assembly from file. /// </summary> /// <param name="subFolderName">name of the folder with assembly</param> /// <param name="assemblyName">name of the assembly</param> /// <returns>loaded assembly</returns> // ********************************************************************** // static public Assembly GetAssembly(string subFolderName, string assemblyName) { return GetAssembly(subFolderName, assemblyName, true); } // // ********************************************************************** /// <summary> /// Finds object method with specified name and parameter types. /// </summary> /// <param name="obj">obejct to find method</param> /// <param name="methodName">name of the method to find</param> /// <param name="paramTypes">array of parameter types</param> /// <returns> /// object method with specified name and parameter types /// or null if not found /// </returns> /// param&gt; // ********************************************************************** // static public MethodInfo FindMethod(object obj, string methodName, Type[] paramTypes) { Type type = obj.GetType(); MethodInfo method = null; while (method == null && type != null) { method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypes, null); type = type.BaseType; } return method; } // // ********************************************************************** /// <summary> /// Calls method of the object using reflection. /// </summary> /// <param name="obj">object to call method of</param> /// <param name="methodName">method name</param> /// <param name="types">array with parameter types</param> /// <param name="parameters">array with parameter values</param> /// <returns>value returned by method</returns> // ********************************************************************** // static public object CallMethod(object obj, string methodName, Type[] types, object[] parameters) { if (obj == null) throw new ArgumentNullException("CallMethod obj parameter"); MethodInfo methodInfo = FindMethod(obj, methodName, types); if (methodInfo == null) throw new ExMethodNotFoundException(obj, methodName); object result = methodInfo.Invoke(obj, parameters); return result; } // // ********************************************************************** /// <summary> /// Finds field in the object and returns its value. /// </summary> /// <param name="obj">object to find field in</param> /// <param name="fieldName">StateName of the field.</param> /// <returns>field value</returns> // ********************************************************************** // static public object GetFieldValue(object obj, string fieldName) { FieldInfo fieldInfo = null; Type type = obj.GetType(); while (fieldInfo == null && type != null) { fieldInfo = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); type = type.BaseType; } if (fieldInfo == null) throw new ExFieldNotFoundException(obj, fieldName); object result = fieldInfo.GetValue(obj); return result; } // // ********************************************************************** /// <summary> /// Returns true if descendant is inherited from the ancestor or the types are equal. /// </summary> /// <param name="descendant">descendant to check</param> /// <param name="ancestor">ancestor to check inheritance from</param> /// <returns> /// true if descendant is inherited from the ancestor or the types are equal /// </returns> // ********************************************************************** // static public bool IsInheritedFrom(Type descendant, Type ancestor) { return (descendant != null && ancestor != null) ? ancestor.IsAssignableFrom(descendant) : false; } // // ********************************************************************** /// <summary> /// Returns ancestor of the given type where field with the given name is /// actually defined. /// </summary> /// <param name="type">current type that has given field (inherited or declared)</param> /// <param name="fieldName">field name to find</param> /// <returns> /// ancestor of the given type where field with the given name is defined /// </returns> // ********************************************************************** // static public Type GetTypeWhereFieldDefined(Type type, string fieldName) { if (type != null && !String.IsNullOrEmpty(fieldName)) { Type parentType = type; FieldInfo fieldInfo = null; while (parentType != null && fieldInfo == null) { fieldInfo = parentType.GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (fieldInfo == null) parentType = parentType.BaseType; } return parentType; } return null; } #endregion } }
using System; using System.Collections; using Server; using Server.Items; using System.Collections.Generic; using Server.Mobiles; namespace Server.Engines.BulkOrders { [TypeAlias( "Scripts.Engines.BulkOrders.SmallBOD" )] public abstract class SmallBOD : Item { private int m_AmountCur, m_AmountMax; private Type m_Type; private int m_Number; private int m_Graphic; private bool m_RequireExceptional; private BulkMaterialType m_Material; [CommandProperty( AccessLevel.GameMaster )] public int AmountCur{ get{ return m_AmountCur; } set{ m_AmountCur = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public int AmountMax{ get{ return m_AmountMax; } set{ m_AmountMax = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public Type Type{ get{ return m_Type; } set{ m_Type = value; } } [CommandProperty( AccessLevel.GameMaster )] public int Number{ get{ return m_Number; } set{ m_Number = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public int Graphic{ get{ return m_Graphic; } set{ m_Graphic = value; } } [CommandProperty( AccessLevel.GameMaster )] public bool RequireExceptional{ get{ return m_RequireExceptional; } set{ m_RequireExceptional = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public BulkMaterialType Material{ get{ return m_Material; } set{ m_Material = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public bool Complete{ get{ return ( m_AmountCur == m_AmountMax ); } } public override int LabelNumber{ get{ return 1045151; } } // a bulk order deed [Constructable] public SmallBOD( int hue, int amountMax, Type type, int number, int graphic, bool requireExeptional, BulkMaterialType material ) : base( Core.AOS ? 0x2258 : 0x14EF ) { Weight = 1.0; Hue = hue; // Blacksmith: 0x44E; Tailoring: 0x483 LootType = LootType.Blessed; m_AmountMax = amountMax; m_Type = type; m_Number = number; m_Graphic = graphic; m_RequireExceptional = requireExeptional; m_Material = material; } public SmallBOD() : base( Core.AOS ? 0x2258 : 0x14EF ) { Weight = 1.0; LootType = LootType.Blessed; } public static BulkMaterialType GetRandomMaterial( BulkMaterialType start, double[] chances ) { double random = Utility.RandomDouble(); for ( int i = 0; i < chances.Length; ++i ) { if ( random < chances[i] ) return ( i == 0 ? BulkMaterialType.None : start + (i - 1) ); random -= chances[i]; } return BulkMaterialType.None; } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); list.Add( 1060654 ); // small bulk order if ( m_RequireExceptional ) list.Add( 1045141 ); // All items must be exceptional. if ( m_Material != BulkMaterialType.None ) list.Add( SmallBODGump.GetMaterialNumberFor( m_Material ) ); // All items must be made with x material. list.Add( 1060656, m_AmountMax.ToString() ); // amount to make: ~1_val~ list.Add( 1060658, "#{0}\t{1}", m_Number, m_AmountCur ); // ~1_val~: ~2_val~ } public override void OnDoubleClick(Mobile from) { if (IsChildOf(from.Backpack) || InSecureTrade || RootParent is PlayerVendor) from.SendGump(new SmallBODGump(from, this)); else from.SendLocalizedMessage(1045156); // You must have the deed in your backpack to use it. } public override void OnDoubleClickNotAccessible(Mobile from) { OnDoubleClick(from); } public override void OnDoubleClickSecureTrade(Mobile from) { OnDoubleClick(from); } public void BeginCombine( Mobile from ) { if ( m_AmountCur < m_AmountMax ) from.Target = new SmallBODTarget( this ); else from.SendLocalizedMessage( 1045166 ); // The maximum amount of requested items have already been combined to this deed. } public abstract List<Item> ComputeRewards( bool full ); public abstract int ComputeGold(); public abstract int ComputeFame(); public virtual void GetRewards( out Item reward, out int gold, out int fame ) { reward = null; gold = ComputeGold(); fame = ComputeFame(); List<Item> rewards = ComputeRewards( false ); if ( rewards.Count > 0 ) { reward = rewards[Utility.Random( rewards.Count )]; for ( int i = 0; i < rewards.Count; ++i ) { if ( rewards[i] != reward ) rewards[i].Delete(); } } } public static BulkMaterialType GetMaterial( CraftResource resource ) { switch ( resource ) { case CraftResource.MDullcopper: return BulkMaterialType.DullCopper; case CraftResource.MShadow: return BulkMaterialType.ShadowIron; case CraftResource.MCopper: return BulkMaterialType.Copper; case CraftResource.MBronze: return BulkMaterialType.Bronze; case CraftResource.MGold: return BulkMaterialType.Gold; case CraftResource.MAgapite: return BulkMaterialType.Agapite; case CraftResource.MVerite: return BulkMaterialType.Verite; case CraftResource.MValorite: return BulkMaterialType.Valorite; case CraftResource.SpinedLeather: return BulkMaterialType.Spined; case CraftResource.HornedLeather: return BulkMaterialType.Horned; case CraftResource.BarbedLeather: return BulkMaterialType.Barbed; } return BulkMaterialType.None; } public void EndCombine( Mobile from, object o ) { if ( o is Item && ((Item)o).IsChildOf( from.Backpack ) ) { Type objectType = o.GetType(); if ( m_AmountCur >= m_AmountMax ) { from.SendLocalizedMessage( 1045166 ); // The maximum amount of requested items have already been combined to this deed. } else if ( m_Type == null || (objectType != m_Type && !objectType.IsSubclassOf( m_Type )) || (!(o is BaseWeapon) && !(o is BaseArmor) && !(o is BaseClothing)) ) { from.SendLocalizedMessage( 1045169 ); // The item is not in the request. } else { BulkMaterialType material = BulkMaterialType.None; if ( o is BaseArmor ) material = GetMaterial( ((BaseArmor)o).Resource ); else if ( o is BaseClothing ) material = GetMaterial( ((BaseClothing)o).Resource ); if ( m_Material >= BulkMaterialType.DullCopper && m_Material <= BulkMaterialType.Valorite && material != m_Material ) { from.SendLocalizedMessage( 1045168 ); // The item is not made from the requested ore. } else if ( m_Material >= BulkMaterialType.Spined && m_Material <= BulkMaterialType.Barbed && material != m_Material ) { from.SendLocalizedMessage( 1049352 ); // The item is not made from the requested leather type. } else { bool isExceptional = false; if ( o is BaseWeapon ) isExceptional = ( ((BaseWeapon)o).Quality == WeaponQuality.Exceptional ); else if ( o is BaseArmor ) isExceptional = ( ((BaseArmor)o).Quality == ArmorQuality.Exceptional ); else if ( o is BaseClothing ) isExceptional = ( ((BaseClothing)o).Quality == ClothingQuality.Exceptional ); if ( m_RequireExceptional && !isExceptional ) { from.SendLocalizedMessage( 1045167 ); // The item must be exceptional. } else { ((Item)o).Delete(); ++AmountCur; from.SendLocalizedMessage( 1045170 ); // The item has been combined with the deed. from.SendGump( new SmallBODGump( from, this ) ); if ( m_AmountCur < m_AmountMax ) BeginCombine( from ); } } } } else { from.SendLocalizedMessage( 1045158 ); // You must have the item in your backpack to target it. } } public SmallBOD( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version writer.Write( m_AmountCur ); writer.Write( m_AmountMax ); writer.Write( m_Type == null ? null : m_Type.FullName ); writer.Write( m_Number ); writer.Write( m_Graphic ); writer.Write( m_RequireExceptional ); writer.Write( (int) m_Material ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 0: { m_AmountCur = reader.ReadInt(); m_AmountMax = reader.ReadInt(); string type = reader.ReadString(); if ( type != null ) m_Type = ScriptCompiler.FindTypeByFullName( type ); m_Number = reader.ReadInt(); m_Graphic = reader.ReadInt(); m_RequireExceptional = reader.ReadBool(); m_Material = (BulkMaterialType)reader.ReadInt(); break; } } if ( Weight == 0.0 ) Weight = 1.0; if ( Core.AOS && ItemID == 0x14EF ) ItemID = 0x2258; if ( Parent == null && Map == Map.Internal && Location == Point3D.Zero ) Delete(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; namespace LinFx.Linq; public interface IAsyncQueryableExecuter { #region Contains Task<bool> ContainsAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] T item, CancellationToken cancellationToken = default); #endregion #region Any/All Task<bool> AnyAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<bool> AnyAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); Task<bool> AllAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); #endregion #region Count/LongCount Task<int> CountAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<int> CountAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); Task<long> LongCountAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<long> LongCountAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); #endregion #region First/FirstOrDefault Task<T> FirstAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<T> FirstAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); Task<T> FirstOrDefaultAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<T> FirstOrDefaultAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); #endregion #region Last/LastOrDefault Task<T> LastAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<T> LastAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); Task<T> LastOrDefaultAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<T> LastOrDefaultAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); #endregion #region Single/SingleOrDefault Task<T> SingleAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<T> SingleAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); Task<T> SingleOrDefaultAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<T> SingleOrDefaultAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, bool>> predicate, CancellationToken cancellationToken = default); #endregion #region Min Task<T> MinAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<TResult> MinAsync<T, TResult>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, TResult>> selector, CancellationToken cancellationToken = default); #endregion #region Max Task<T> MaxAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<TResult> MaxAsync<T, TResult>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, TResult>> selector, CancellationToken cancellationToken = default); #endregion #region Sum Task<decimal> SumAsync( [NotNull] IQueryable<decimal> source, CancellationToken cancellationToken = default); Task<decimal?> SumAsync( [NotNull] IQueryable<decimal?> source, CancellationToken cancellationToken = default); Task<decimal> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, decimal>> selector, CancellationToken cancellationToken = default); Task<decimal?> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, decimal?>> selector, CancellationToken cancellationToken = default); Task<int> SumAsync( [NotNull] IQueryable<int> source, CancellationToken cancellationToken = default); Task<int?> SumAsync( [NotNull] IQueryable<int?> source, CancellationToken cancellationToken = default); Task<int> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, int>> selector, CancellationToken cancellationToken = default); Task<int?> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, int?>> selector, CancellationToken cancellationToken = default); Task<long> SumAsync( [NotNull] IQueryable<long> source, CancellationToken cancellationToken = default); Task<long?> SumAsync( [NotNull] IQueryable<long?> source, CancellationToken cancellationToken = default); Task<long> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, long>> selector, CancellationToken cancellationToken = default); Task<long?> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, long?>> selector, CancellationToken cancellationToken = default); Task<double> SumAsync( [NotNull] IQueryable<double> source, CancellationToken cancellationToken = default); Task<double?> SumAsync( [NotNull] IQueryable<double?> source, CancellationToken cancellationToken = default); Task<double> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, double>> selector, CancellationToken cancellationToken = default); Task<double?> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, double?>> selector, CancellationToken cancellationToken = default); Task<float> SumAsync( [NotNull] IQueryable<float> source, CancellationToken cancellationToken = default); Task<float?> SumAsync( [NotNull] IQueryable<float?> source, CancellationToken cancellationToken = default); Task<float> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, float>> selector, CancellationToken cancellationToken = default); Task<float?> SumAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, float?>> selector, CancellationToken cancellationToken = default); #endregion #region Average Task<decimal> AverageAsync( [NotNull] IQueryable<decimal> source, CancellationToken cancellationToken = default); Task<decimal?> AverageAsync( [NotNull] IQueryable<decimal?> source, CancellationToken cancellationToken = default); Task<decimal> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, decimal>> selector, CancellationToken cancellationToken = default); Task<decimal?> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, decimal?>> selector, CancellationToken cancellationToken = default); Task<double> AverageAsync( [NotNull] IQueryable<int> source, CancellationToken cancellationToken = default); Task<double?> AverageAsync( [NotNull] IQueryable<int?> source, CancellationToken cancellationToken = default); Task<double> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, int>> selector, CancellationToken cancellationToken = default); Task<double?> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, int?>> selector, CancellationToken cancellationToken = default); Task<double> AverageAsync( [NotNull] IQueryable<long> source, CancellationToken cancellationToken = default); Task<double?> AverageAsync( [NotNull] IQueryable<long?> source, CancellationToken cancellationToken = default); Task<double> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, long>> selector, CancellationToken cancellationToken = default); Task<double?> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, long?>> selector, CancellationToken cancellationToken = default); Task<double> AverageAsync( [NotNull] IQueryable<double> source, CancellationToken cancellationToken = default); Task<double?> AverageAsync( [NotNull] IQueryable<double?> source, CancellationToken cancellationToken = default); Task<double> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, double>> selector, CancellationToken cancellationToken = default); Task<double?> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, double?>> selector, CancellationToken cancellationToken = default); Task<float> AverageAsync( [NotNull] IQueryable<float> source, CancellationToken cancellationToken = default); Task<float?> AverageAsync( [NotNull] IQueryable<float?> source, CancellationToken cancellationToken = default); Task<float> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, float>> selector, CancellationToken cancellationToken = default); Task<float?> AverageAsync<T>( [NotNull] IQueryable<T> queryable, [NotNull] Expression<Func<T, float?>> selector, CancellationToken cancellationToken = default); #endregion #region ToList/Array Task<List<T>> ToListAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); Task<T[]> ToArrayAsync<T>( [NotNull] IQueryable<T> queryable, CancellationToken cancellationToken = default); #endregion }
// Copyright (c) 2014 Christian Crowhurst. All rights reserved. // see LICENSE using CcAcca.CacheAbstraction.Statistics; using NUnit.Framework; namespace CcAcca.CacheAbstraction.Test.Statistics { [TestFixture] public class CachHitRatioCacheStatisticExamples : CacheStatisticExamplesBase { private IStatisticsCache _cache; [SetUp] public void TestInitialise() { _cache = CreateCacheWith(new CacheHitRatioCacheStatistic()); } [Test] public void ShouldBeNullBeforeCacheUsed() { var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.Null); } [Test] public void GetCacheItem_Miss() { // when _cache.GetCacheItem<object>("key1"); // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(0m)); } [Test] public void GetCacheItem_Hit() { // given _cache.AddOrUpdate("key1", new object()); // when _cache.GetCacheItem<object>("key1"); // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(1m)); } [Test] public void Contains_Miss() { // when _cache.Contains("key1"); // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(0m)); } [Test] public void Contains_Hit() { // given _cache.AddOrUpdate("key1", new object()); // when _cache.Contains("key1"); // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(1m)); } [Test] public void GetCacheItem_MixtureOfHitsAndMisses() { // given, when _cache.AddOrUpdate("key1", new object()); _cache.GetCacheItem<object>("key1"); // hit _cache.GetCacheItem<object>("key1"); // hit _cache.GetCacheItem<object>("key2"); // miss // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(0.6667m)); } [Test] public void Contains_MixtureOfHitsAndMisses() { // given, when _cache.AddOrUpdate("key1", new object()); _cache.Contains("key1"); // hit _cache.Contains("key1"); // hit _cache.Contains("key2"); // miss // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(0.6667m)); } [Test] public void GetCacheItem_Contains_MixtureOfHitsAndMisses() { // given, when _cache.AddOrUpdate("key1", new object()); _cache.GetCacheItem<object>("key1"); // hit _cache.GetCacheItem<object>("key1"); // hit _cache.GetCacheItem<object>("key2"); // miss _cache.Contains("key1"); // hit _cache.Contains("key1"); // hit _cache.Contains("key2"); // miss // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(0.6667m)); } [Test] public void Remove_ShouldNotInfluenceResult() { // given _cache.AddOrUpdate("key1", new object()); _cache.GetCacheItem<object>("key1"); _cache.GetCacheItem<object>("key2"); // when _cache.Remove("key1"); // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(0.5m)); } [Test] public void GetOrAdd_Miss() { // when _cache.GetOrAdd("key1", _ => new object()); // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(0m)); } [Test] public void GetOrAdd_Hit() { // given _cache.AddOrUpdate("key1", new object()); // when _cache.GetOrAdd("key1", _ => new object()); // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(1m)); } [Test] public void GetOrAdd_MixOfHitsAndMisses() { // given _cache.AddOrUpdate("key1", new object()); // when _cache.GetOrAdd("key1", _ => new object()); // hit _cache.GetOrAdd("key1", _ => new object()); // hit // note: GetOrAdd internally calls GetCacheItem twice if item not already in cache _cache.GetOrAdd("key2", _ => new object()); // miss x2 // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.EqualTo(0.5m)); } [Test] public void FlushShouldResetToZero() { // given _cache.AddOrUpdate("key1", new object()); _cache.GetOrAdd("key1", _ => new object()); // when _cache.Flush(); // then var ratio = _cache.Statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio); Assert.That(ratio, Is.Null); } } }
using System; using System.Data; using System.Data.SqlClient; using Rainbow.Framework.Settings; using Rainbow.Framework.Web.UI.WebControls; using Rainbow.Framework.Data; namespace Rainbow.Framework.Content.Data { /// <summary> /// IBS Portal FAQ module /// (c)2002 by Christopher S Judd, CDP &amp; Horizons, LLC /// Moved into Rainbow by Jakob Hansen, [email protected] /// </summary> public class FAQsDB { /// <summary> /// The AddFAQ function is used to ADD FAQs to the Database /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="question">The question.</param> /// <param name="answer">The answer.</param> /// <returns></returns> public int AddFAQ(int moduleID, int itemID, string userName, string question, string answer) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_AddFAQ", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterQuestion = new SqlParameter("@Question", SqlDbType.NVarChar, 500); parameterQuestion.Value = question; myCommand.Parameters.Add(parameterQuestion); //Changed to Ntext from NVarChar, 4000 SqlParameter parameterAnswer = new SqlParameter("@Answer", SqlDbType.NText); parameterAnswer.Value = answer; myCommand.Parameters.Add(parameterAnswer); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return Convert.ToInt32(parameterItemID.Value); } /// <summary> /// The GetFAQ function is used to get all the FAQs in the module /// </summary> /// <param name="moduleID">moduleID</param> /// <returns>A DataSet</returns> public DataSet GetFAQ(int moduleID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlDataAdapter myCommand = new SqlDataAdapter("rb_GetFAQ", myConnection); myCommand.SelectCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.SelectCommand.Parameters.Add(parameterModuleID); // Create and Fill the DataSet DataSet myDataSet = new DataSet(); try { myCommand.Fill(myDataSet); } finally { myConnection.Close(); } // return the DataSet return myDataSet; } /// <summary> /// The GetSingleFAQ function is used to Get a single FAQ /// from the database for display/edit /// </summary> /// <param name="itemID">itemID</param> /// <returns>A SqlDataReader</returns> public SqlDataReader GetSingleFAQ(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSingleFAQ", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // return the datareader return result; } /// <summary> /// The DeleteFAQ function is used to remove FAQs from the Database /// </summary> /// <param name="itemID">itemID</param> public void DeleteFAQ(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DeleteFAQ", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } /// <summary> /// The UpdateFAQ function is used to update changes to the FAQs /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="question">The question.</param> /// <param name="answer">The answer.</param> public void UpdateFAQ(int moduleID, int itemID, string userName, string question, string answer) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_UpdateFAQ", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterQuestion = new SqlParameter("@Question", SqlDbType.NVarChar, 500); parameterQuestion.Value = question; myCommand.Parameters.Add(parameterQuestion); // Changed to NText from NVarChar, 4000 SqlParameter parameterAnswer = new SqlParameter("@Answer", SqlDbType.NText); parameterAnswer.Value = answer; myCommand.Parameters.Add(parameterAnswer); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } } }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Zumo.WindowsPhone8.Test; using Microsoft.WindowsAzure.MobileServices; using Newtonsoft.Json.Linq; using System.IO.IsolatedStorage; namespace Microsoft.Azure.Zumo.WindowsPhone8.CSharp.Test { public class ZumoServiceTests : TestBase { /// <summary> /// Verify we have an installation ID created whenever we use a ZUMO /// service. /// </summary> [TestMethod] public void InstallationId() { MobileServiceClient service = new MobileServiceClient("http://test.com"); string settings = IsolatedStorageSettings.ApplicationSettings["MobileServices.Installation.config"] as string; string id = JValue.Parse(settings).Get("applicationInstallationId").AsString(); Assert.IsNotNull(id); } [TestMethod] public void Construction() { string appUrl = "http://www.test.com/"; string appKey = "secret..."; MobileServiceClient service = new MobileServiceClient(new Uri(appUrl), appKey); Assert.AreEqual(appUrl, service.ApplicationUri.ToString()); Assert.AreEqual(appKey, service.ApplicationKey); service = new MobileServiceClient(appUrl, appKey); Assert.AreEqual(appUrl, service.ApplicationUri.ToString()); Assert.AreEqual(appKey, service.ApplicationKey); service = new MobileServiceClient(new Uri(appUrl)); Assert.AreEqual(appUrl, service.ApplicationUri.ToString()); Assert.AreEqual(null, service.ApplicationKey); service = new MobileServiceClient(appUrl); Assert.AreEqual(appUrl, service.ApplicationUri.ToString()); Assert.AreEqual(null, service.ApplicationKey); Uri none = null; Throws<ArgumentNullException>(() => new MobileServiceClient(none)); Throws<FormatException>(() => new MobileServiceClient("not a valid uri!!!@#!@#")); } [AsyncTestMethod] public async Task WithFilter() { string appUrl = "http://www.test.com/"; string appKey = "secret..."; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(new Uri(appUrl), appKey) .WithFilter(hijack); // Ensure properties are copied over Assert.AreEqual(appUrl, service.ApplicationUri.ToString()); Assert.AreEqual(appKey, service.ApplicationKey); // Set the filter to return an empty array hijack.Response.Content = new JArray().ToString(); JToken response = await service.GetTable("foo").ReadAsync("bar"); // Verify the filter was in the loop Assert.StartsWith(hijack.Request.Uri.ToString(), appUrl); Throws<ArgumentNullException>(() => service.WithFilter(null)); } [AsyncTestMethod] public async Task LoginAsync() { TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...") .WithFilter(hijack); // Send back a successful login response hijack.Response.Content = new JObject() .Set("authenticationToken", "rhubarb") .Set("user", new JObject() .Set("userId", "123456")).ToString(); MobileServiceUser current = await service.LoginAsync("donkey"); Assert.IsNotNull(current); Assert.AreEqual("123456", current.UserId); Assert.EndsWith(hijack.Request.Uri.ToString(), "login"); string input = JToken.Parse(hijack.Request.Content).Get("authenticationToken").AsString(); Assert.AreEqual("donkey", input); Assert.AreEqual("POST", hijack.Request.Method); Assert.AreSame(current, service.CurrentUser); // Verify that the user token is sent with each request JToken response = await service.GetTable("foo").ReadAsync("bar"); Assert.AreEqual("rhubarb", hijack.Request.Headers["X-ZUMO-AUTH"]); // Verify error cases ThrowsAsync<ArgumentNullException>(async () => await service.LoginAsync(null)); ThrowsAsync<ArgumentException>(async () => await service.LoginAsync("")); // Send back a failure and ensure it throws hijack.Response.Content = new JObject().Set("error", "login failed").ToString(); hijack.Response.StatusCode = 401; ThrowsAsync<InvalidOperationException>(async () => { current = await service.LoginAsync("donkey"); }); } [AsyncTestMethod] public async Task Logout() { TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...") .WithFilter(hijack); // Send back a successful login response hijack.Response.Content = new JObject() .Set("authenticationToken", "rhubarb") .Set("user", new JObject() .Set("userId", "123456")).ToString(); MobileServiceUser current = await service.LoginAsync("donkey"); Assert.IsNotNull(service.CurrentUser); service.Logout(); Assert.IsNull(service.CurrentUser); } [AsyncTestMethod] public async Task StandardRequestFormat() { string appUrl = "http://www.test.com"; string appKey = "secret..."; string collection = "tests"; string query = "$filter=id eq 12"; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(appUrl, appKey) .WithFilter(hijack); hijack.Response.Content = new JArray() .Append(new JObject().Set("id", 12).Set("value", "test")) .ToString(); JToken response = await service.GetTable(collection).ReadAsync(query); Assert.IsNotNull(hijack.Request.Headers["X-ZUMO-INSTALLATION-ID"]); Assert.AreEqual("secret...", hijack.Request.Headers["X-ZUMO-APPLICATION"]); Assert.AreEqual("application/json", hijack.Request.Accept); } [AsyncTestMethod] public async Task ErrorMessageConstruction() { string appUrl = "http://www.test.com"; string appKey = "secret..."; string collection = "tests"; string query = "$filter=id eq 12"; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(appUrl, appKey) .WithFilter(hijack); // Verify the error message is correctly pulled out hijack.Response.Content = new JObject() .Set("error", "error message") .Set("other", "donkey") .ToString(); hijack.Response.StatusCode = 401; hijack.Response.StatusDescription = "YOU SHALL NOT PASS."; try { JToken response = await service.GetTable(collection).ReadAsync(query); } catch (InvalidOperationException ex) { Assert.Equals(ex.Message, "error message"); } // Verify all of the exception parameters hijack.Response.Content = new JObject() .Set("error", "error message") .Set("other", "donkey") .ToString(); hijack.Response.StatusCode = 401; hijack.Response.StatusDescription = "YOU SHALL NOT PASS."; try { JToken response = await service.GetTable(collection).ReadAsync(query); } catch (MobileServiceInvalidOperationException ex) { Assert.Equals(ex.Message, "error message"); Assert.AreEqual((int)HttpStatusCode.Unauthorized, ex.Response.StatusCode); Assert.Contains(ex.Response.Content, "donkey"); Assert.StartsWith(ex.Request.Uri.ToString(), appUrl); Assert.AreEqual("YOU SHALL NOT PASS.", ex.Response.StatusDescription); } // If no error message in the response, we'll use the // StatusDescription instead hijack.Response.Content = new JObject() .Set("other", "donkey") .ToString(); try { JToken response = await service.GetTable(collection).ReadAsync(query); } catch (InvalidOperationException ex) { Assert.Equals("The request could not be completed. (YOU SHALL NOT PASS).", ex.Message); } } public class Person { public long Id { get; set; } public string Name { get; set; } } [AsyncTestMethod] public async Task ReadAsync() { string appUrl = "http://www.test.com"; string appKey = "secret..."; string collection = "tests"; string query = "$filter=id eq 12"; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(appUrl, appKey) .WithFilter(hijack); hijack.Response.Content = new JArray() .Append(new JObject().Set("id", 12).Set("value", "test")) .ToString(); JToken response = await service.GetTable(collection).ReadAsync(query); Assert.Contains(hijack.Request.Uri.ToString(), collection); Assert.EndsWith(hijack.Request.Uri.ToString(), query); ThrowsAsync<ArgumentNullException>(async () => await service.GetTable(null).ReadAsync(query)); ThrowsAsync<ArgumentException>(async () => await service.GetTable("").ReadAsync(query)); } [AsyncTestMethod] public async Task ReadAsyncGeneric() { string appUrl = "http://www.test.com"; string appKey = "secret..."; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(appUrl, appKey) .WithFilter(hijack); hijack.Response.Content = new JArray() .Append(new JObject().Set("id", 12).Set("Name", "Bob")) .ToString(); IMobileServiceTable<Person> table = service.GetTable<Person>(); List<Person> people = await table.Where(p => p.Id == 12).ToListAsync(); Assert.AreEqual(1, people.Count); Assert.AreEqual(12L, people[0].Id); Assert.AreEqual("Bob", people[0].Name); } [AsyncTestMethod] public async Task LookupAsync() { string appUrl = "http://www.test.com"; string appKey = "secret..."; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(appUrl, appKey) .WithFilter(hijack); hijack.Response.Content = new JObject() .Set("id", 12) .Set("Name", "Bob") .ToString(); IMobileServiceTable<Person> table = service.GetTable<Person>(); Person bob = await table.LookupAsync(12); Assert.AreEqual(12L, bob.Id); Assert.AreEqual("Bob", bob.Name); hijack.Response.StatusCode = 404; bool thrown = false; try { bob = await table.LookupAsync(12); } catch (InvalidOperationException) { thrown = true; } Assert.IsTrue(thrown, "Exception should be thrown on a 404!"); } [AsyncTestMethod] public async Task InsertAsync() { string appUrl = "http://www.test.com"; string appKey = "secret..."; string collection = "tests"; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(appUrl, appKey) .WithFilter(hijack); JObject obj = new JObject().Set("value", "new") as JObject; hijack.Response.Content = new JObject().Set("id", 12).Set("value", "new").ToString(); await service.GetTable(collection).InsertAsync(obj); Assert.AreEqual(12, obj.Get("id").AsInteger()); Assert.Contains(hijack.Request.Uri.ToString(), collection); ThrowsAsync<ArgumentNullException>( async () => await service.GetTable(collection).InsertAsync(null)); // Verify we throw if ID is set on both JSON and strongly typed // instances ThrowsAsync<ArgumentException>( async () => await service.GetTable(collection).InsertAsync( new JObject().Set("id", 15) as JObject)); ThrowsAsync<ArgumentException>( async () => await service.GetTable<Person>().InsertAsync( new Person() { Id = 15 })); } [TestMethod] public void InsertAsyncThrowsIfIdExists() { string appUrl = "http://www.test.com"; string collection = "tests"; MobileServiceClient service = new MobileServiceClient(appUrl); // Verify we throw if ID is set on both JSON and strongly typed // instances ThrowsAsync<ArgumentException>( async () => await service.GetTable(collection).InsertAsync( new JObject().Set("id", 15) as JObject)); ThrowsAsync<ArgumentException>( async () => await service.GetTable<Person>().InsertAsync( new Person() { Id = 15 })); } [AsyncTestMethod] public async Task UpdateAsync() { string appUrl = "http://www.test.com"; string appKey = "secret..."; string collection = "tests"; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(appUrl, appKey) .WithFilter(hijack); JObject obj = new JObject().Set("id", 12).Set("value", "new") as JObject; hijack.Response.Content = new JObject() .Set("id", 12) .Set("value", "new") .Set("other", "123") .ToString(); IMobileServiceTable table = service.GetTable(collection); await table.UpdateAsync(obj); Assert.AreEqual("123", obj.Get("other").AsString()); Assert.Contains(hijack.Request.Uri.ToString(), collection); ThrowsAsync<ArgumentNullException>(async () => await table.UpdateAsync(null)); ThrowsAsync<ArgumentException>(async () => await table.UpdateAsync(new JObject())); } [AsyncTestMethod] public async Task DeleteAsync() { string appUrl = "http://www.test.com"; string appKey = "secret..."; string collection = "tests"; TestServiceFilter hijack = new TestServiceFilter(); MobileServiceClient service = new MobileServiceClient(appUrl, appKey) .WithFilter(hijack); JObject obj = new JObject().Set("id", 12).Set("value", "new") as JObject; IMobileServiceTable table = service.GetTable(collection); await table.DeleteAsync(obj); Assert.Contains(hijack.Request.Uri.ToString(), collection); ThrowsAsync<ArgumentNullException>(async () => await table.DeleteAsync(null)); ThrowsAsync<ArgumentException>(async () => await table.DeleteAsync(new JObject())); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.DiaSymReader; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class HoistedStateMachineLocalTests : ExpressionCompilerTestBase { private const string asyncLambdaSourceTemplate = @" using System; using System.Threading.Tasks; public class D {{ private double t; public {0} void M(char u) {{ int x = 1; Func<char, Task<int>> f = async ch => {1}; }} }} "; private const string genericAsyncLambdaSourceTemplate = @" using System; using System.Threading.Tasks; public class D<T> {{ private T t; public {0} void M<U>(U u) {{ int x = 1; Func<char, Task<int>> f = async ch => {1}; }} }} "; [Fact] public void Iterator() { var source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { #line 500 DummySequencePoint(); { #line 550 int x = 0; yield return x; x++; #line 600 } #line 650 DummySequencePoint(); { #line 700 int x = 0; yield return x; x++; #line 750 } #line 800 DummySequencePoint(); } static void DummySequencePoint() { } } "; var expectedError = "error CS0103: The name 'x' does not exist in the current context"; var expectedIlTemplate = @" {{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__0.{0}"" IL_0006: ret }} "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { EvaluationContext context; CompilationTestData testData; string error; context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 500); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 550); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__1")); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 600); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__1")); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 650); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 700); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__2")); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 750); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__2")); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 800); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); }); } [Fact] public void Async() { var source = @" using System.Threading.Tasks; class C { static async Task M() { #line 500 DummySequencePoint(); { #line 550 int x = 0; await M(); x++; #line 600 } #line 650 DummySequencePoint(); { #line 700 int x = 0; await M(); x++; #line 750 } #line 800 DummySequencePoint(); } static void DummySequencePoint() { } } "; var expectedError = "error CS0103: The name 'x' does not exist in the current context"; var expectedIlTemplate = @" {{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<M>d__0 V_2, int V_3, System.Runtime.CompilerServices.TaskAwaiter V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__0.{0}"" IL_0006: ret }} "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { EvaluationContext context; CompilationTestData testData; string error; context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 500); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 550); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__1")); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 600); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__1")); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 650); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 700); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__2")); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 750); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__2")); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 800); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Instance_CaptureNothing() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "1"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Instance_CaptureLocal() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "x"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D.<>c__DisplayClass1_0.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch", "x"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Instance_CaptureParameter() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "u.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); testData = new CompilationTestData(); context.CompileExpression("u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""char D.<>c__DisplayClass1_0.u"" IL_000b: ret } "); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch", "u"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Instance_CaptureLambdaParameter() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "ch.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Instance_CaptureThis() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "t.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D D.<<M>b__1_0>d.<>4__this"" IL_0006: ldfld ""double D.t"" IL_000b: ret } "); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "this", "ch"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Instance_CaptureThisAndLocal() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "x + t.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""D D.<>c__DisplayClass1_0.<>4__this"" IL_000b: ldfld ""double D.t"" IL_0010: ret } "); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D.<>c__DisplayClass1_0.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "this", "ch", "x"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Static_CaptureNothing() { var source = string.Format(asyncLambdaSourceTemplate, "static", "1"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Static_CaptureLocal() { var source = string.Format(asyncLambdaSourceTemplate, "static", "x"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D.<>c__DisplayClass1_0.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch", "x"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Static_CaptureParameter() { var source = string.Format(asyncLambdaSourceTemplate, "static", "u.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D.t'", error); testData = new CompilationTestData(); context.CompileExpression("u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""char D.<>c__DisplayClass1_0.u"" IL_000b: ret } "); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch", "u"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void AsyncLambda_Static_CaptureLambdaParameter() { var source = string.Format(asyncLambdaSourceTemplate, "static", "ch.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Instance_CaptureNothing() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "1"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__1.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__1<U>.<<M>b__1_0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Instance_CaptureLocal() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "x"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D<T>.<>c__DisplayClass1_0<U>.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "x", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Instance_CaptureParameter() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "u.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); testData = new CompilationTestData(); context.CompileExpression("u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""U D<T>.<>c__DisplayClass1_0<U>.u"" IL_000b: ret } "); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "u", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Instance_CaptureLambdaParameter() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "ch.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__1.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__1<U>.<<M>b__1_0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Instance_CaptureThis() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "t.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T> D<T>.<<M>b__1_0>d<U>.<>4__this"" IL_0006: ldfld ""T D<T>.t"" IL_000b: ret } "); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<<M>b__1_0>d<U>.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "this", "ch", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Instance_CaptureThisAndLocal() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "x + t.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""D<T> D<T>.<>c__DisplayClass1_0<U>.<>4__this"" IL_000b: ldfld ""T D<T>.t"" IL_0010: ret } "); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D<T>.<>c__DisplayClass1_0<U>.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "this", "ch", "x", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Static_CaptureNothing() { var source = string.Format(genericAsyncLambdaSourceTemplate, "static", "1"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__1.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D<T>.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__1<U>.<<M>b__1_0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Static_CaptureLocal() { var source = string.Format(genericAsyncLambdaSourceTemplate, "static", "x"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D<T>.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D<T>.<>c__DisplayClass1_0<U>.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "x", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Static_CaptureParameter() { var source = string.Format(genericAsyncLambdaSourceTemplate, "static", "u.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D<T>.t'", error); testData = new CompilationTestData(); context.CompileExpression("u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""U D<T>.<>c__DisplayClass1_0<U>.u"" IL_000b: ret } "); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "u", "<>TypeVariables"); }); } [WorkItem(1112496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112496")] [Fact] public void GenericAsyncLambda_Static_CaptureLambdaParameter() { var source = string.Format(genericAsyncLambdaSourceTemplate, "static", "ch.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "D.<>c__1.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D<T>.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__1<U>.<<M>b__1_0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "<>TypeVariables"); }); } [WorkItem(1134746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1134746")] [Fact] public void CacheInvalidation() { var source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { #line 100 int x = 1; yield return x; { #line 200 int y = x + 1; yield return y; } } }"; var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, "C.<M>d__0.MoveNext", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber: 100); var context = EvaluationContext.CreateMethodContext( default(CSharpMetadataContext), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken); string error; context.CompileExpression("x", out error); Assert.Null(error); context.CompileExpression("y", out error); Assert.Equal("error CS0103: The name 'y' does not exist in the current context", error); ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber: 200); context = EvaluationContext.CreateMethodContext( new CSharpMetadataContext(blocks, context), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken); context.CompileExpression("x", out error); Assert.Null(error); context.CompileExpression("y", out error); Assert.Null(error); }); } private static string[] GetLocalNames(EvaluationContext context) { string unused; var locals = new ArrayBuilder<LocalAndMethod>(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out unused, testData: null); return locals.Select(l => l.LocalName).ToArray(); } } }
#region Header /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (c) 2007-2008 James Nies and NArrange contributors. * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *<author>James Nies</author> *<contributor>Justin Dearing</contributor> *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #endregion Header namespace NArrange.Core { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using NArrange.Core.CodeElements; using NArrange.Core.Configuration; /// <summary> /// Code arranger. /// </summary> public sealed class CodeArranger : ICodeArranger { #region Fields /// <summary> /// Arranger chain collection synch lock. /// </summary> private readonly object _codeArrangeChainLock = new object(); /// <summary> /// Code configuration. /// </summary> private readonly CodeConfiguration _configuration; /// <summary> /// Arranger chain collection. /// </summary> private ChainElementArranger _elementArrangerChain; #endregion Fields #region Constructors /// <summary> /// Creates a new code arranger with the specified configuration. /// </summary> /// <param name="configuration">Configuration to use for arranging code members.</param> public CodeArranger(CodeConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException("configuration"); } // Clone the configuration information so we don't have to worry about it // changing during processing. _configuration = configuration.Clone() as CodeConfiguration; } #endregion Constructors #region Properties /// <summary> /// Gets the arranger chain. /// </summary> private ChainElementArranger ArrangerChain { get { if (_elementArrangerChain == null) { lock (_codeArrangeChainLock) { if (_elementArrangerChain == null) { _elementArrangerChain = new ChainElementArranger(); foreach (ConfigurationElement configuration in _configuration.Elements) { IElementArranger elementArranger = ElementArrangerFactory.CreateElementArranger( configuration, _configuration); if (elementArranger != null) { _elementArrangerChain.AddArranger(elementArranger); } } } } } return _elementArrangerChain; } } #endregion Properties #region Methods /// <summary> /// Arranges the code elements according to the configuration supplied /// in the constructor. /// </summary> /// <param name="originalElements">Original elements</param> /// <returns>An arranged collection of code elements.</returns> public ReadOnlyCollection<ICodeElement> Arrange(ReadOnlyCollection<ICodeElement> originalElements) { GroupElement rootElement = new GroupElement(); if (originalElements != null) { List<ICodeElement> elements = new List<ICodeElement>(); NamespaceElement firstNamespace = null; for (int elementIndex = 0; elementIndex < originalElements.Count; elementIndex++) { ICodeElement element = originalElements[elementIndex]; ICodeElement elementClone = element.Clone() as ICodeElement; elements.Add(elementClone); if (firstNamespace == null) { Action<ICodeElement> findFirstNamespace = delegate(ICodeElement processElement) { if (firstNamespace == null) { NamespaceElement namespaceElement = processElement as NamespaceElement; if (namespaceElement != null) { firstNamespace = namespaceElement; } } }; ElementUtilities.ProcessElementTree(elementClone, findFirstNamespace); } } MoveUsings(elements, firstNamespace); foreach (ICodeElement element in elements) { ArrangerChain.ArrangeElement(rootElement, element); } } List<ICodeElement> arranged = new List<ICodeElement>(rootElement.Children); foreach (ICodeElement arrangedElement in arranged) { // Remove the root element as the parent. arrangedElement.Parent = null; } return arranged.AsReadOnly(); } /// <summary> /// Moves using directives if configured to do so. /// </summary> /// <param name="elements">List of top-level code elements.</param> /// <param name="namespaceElement">Namespace namespace to use when moving usings.</param> private void MoveUsings(List<ICodeElement> elements, NamespaceElement namespaceElement) { CodeLevel moveUsingsTo = _configuration.Formatting.Usings.MoveTo; List<ICodeElement> tempElements; if (moveUsingsTo != CodeLevel.None && namespaceElement != null) { if (moveUsingsTo == CodeLevel.Namespace) { tempElements = new List<ICodeElement>(elements); for (int elementIndex = 0; elementIndex < tempElements.Count; elementIndex++) { UsingElement usingElement = tempElements[elementIndex] as UsingElement; if (usingElement != null && usingElement.IsMovable) { if (elements.Contains(usingElement)) { elements.Remove(usingElement); } tempElements.Remove(usingElement); namespaceElement.InsertChild(0, usingElement); elementIndex--; } else { if (tempElements[elementIndex] is RegionElement || tempElements[elementIndex] is GroupElement) { tempElements.AddRange(tempElements[elementIndex].Children); } else if (tempElements[elementIndex] is ConditionDirectiveElement) { ConditionDirectiveElement condition = tempElements[elementIndex] as ConditionDirectiveElement; while (condition != null) { if (namespaceElement.Parent == condition) { tempElements.AddRange(tempElements[elementIndex].Children); break; } condition = condition.ElseCondition; } } } } } else if (moveUsingsTo == CodeLevel.File) { tempElements = new List<ICodeElement>(); for (int elementIndex = 0; elementIndex < namespaceElement.Children.Count; elementIndex++) { UsingElement usingElement = namespaceElement.Children[elementIndex] as UsingElement; if (usingElement != null && usingElement.IsMovable) { namespaceElement.RemoveChild(usingElement); elements.Insert(0, usingElement); elementIndex--; } else if (namespaceElement.Children[elementIndex] is RegionElement || namespaceElement.Children[elementIndex] is GroupElement) { foreach (ICodeElement childElement in namespaceElement.Children[elementIndex].Children) { if (childElement is UsingElement || childElement is RegionElement || childElement is GroupElement) { tempElements.Add(childElement); } } } } for (int elementIndex = 0; elementIndex < tempElements.Count; elementIndex++) { UsingElement usingElement = tempElements[elementIndex] as UsingElement; if (usingElement != null && usingElement.IsMovable) { tempElements.Remove(usingElement); elements.Insert(0, usingElement); elementIndex--; } else if (tempElements[elementIndex] is RegionElement || tempElements[elementIndex] is GroupElement) { tempElements.AddRange(tempElements[elementIndex].Children); } } } else { throw new ArgumentOutOfRangeException( string.Format( "Unknown code level '{0}'.", moveUsingsTo)); } } } #endregion Methods } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Accounts.V1.Credential; namespace Twilio.Tests.Rest.Accounts.V1.Credential { [TestFixture] public class AwsTest : TwilioTest { [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Accounts, "/v1/Credentials/AWS", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { AwsResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"credentials\": [],\"meta\": {\"first_page_url\": \"https://accounts.twilio.com/v1/Credentials/AWS?PageSize=50&Page=0\",\"key\": \"credentials\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://accounts.twilio.com/v1/Credentials/AWS?PageSize=50&Page=0\"}}" )); var response = AwsResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"credentials\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-31T04:00:00Z\",\"date_updated\": \"2015-07-31T04:00:00Z\",\"friendly_name\": \"friendly_name\",\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://accounts.twilio.com/v1/Credentials/AWS/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"meta\": {\"first_page_url\": \"https://accounts.twilio.com/v1/Credentials/AWS?PageSize=50&Page=0\",\"key\": \"credentials\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://accounts.twilio.com/v1/Credentials/AWS?PageSize=50&Page=0\"}}" )); var response = AwsResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Accounts, "/v1/Credentials/AWS", "" ); request.AddPostParam("Credentials", Serialize("AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { AwsResource.Create("AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-31T04:00:00Z\",\"date_updated\": \"2015-07-31T04:00:00Z\",\"friendly_name\": \"friendly_name\",\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://accounts.twilio.com/v1/Credentials/AWS/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = AwsResource.Create("AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Accounts, "/v1/Credentials/AWS/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { AwsResource.Fetch("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-31T04:00:00Z\",\"date_updated\": \"2015-07-31T04:00:00Z\",\"friendly_name\": \"friendly_name\",\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://accounts.twilio.com/v1/Credentials/AWS/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = AwsResource.Fetch("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Accounts, "/v1/Credentials/AWS/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { AwsResource.Update("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-31T04:00:00Z\",\"date_updated\": \"2015-07-31T04:00:00Z\",\"friendly_name\": \"friendly_name\",\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://accounts.twilio.com/v1/Credentials/AWS/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = AwsResource.Update("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Accounts, "/v1/Credentials/AWS/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { AwsResource.Delete("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = AwsResource.Delete("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } } }
// 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.AcceptanceTestsBodyComplex { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Http; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestComplexTestService : ServiceClient<AutoRestComplexTestService>, IAutoRestComplexTestService { /// <summary> /// The base URI of the service. /// </summary> public System.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> /// API ID. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets the IBasicOperations. /// </summary> public virtual IBasicOperations Basic { get; private set; } /// <summary> /// Gets the IPrimitive. /// </summary> public virtual IPrimitive Primitive { get; private set; } /// <summary> /// Gets the IArray. /// </summary> public virtual IArray Array { get; private set; } /// <summary> /// Gets the IDictionary. /// </summary> public virtual IDictionary Dictionary { get; private set; } /// <summary> /// Gets the IInheritance. /// </summary> public virtual IInheritance Inheritance { get; private set; } /// <summary> /// Gets the IPolymorphism. /// </summary> public virtual IPolymorphism Polymorphism { get; private set; } /// <summary> /// Gets the IPolymorphicrecursive. /// </summary> public virtual IPolymorphicrecursive Polymorphicrecursive { get; private set; } /// <summary> /// Gets the IReadonlyproperty. /// </summary> public virtual IReadonlyproperty Readonlyproperty { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestComplexTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestComplexTestService(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestComplexTestService 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> public AutoRestComplexTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestComplexTestService 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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestComplexTestService(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestComplexTestService 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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestComplexTestService(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Basic = new BasicOperations(this); Primitive = new Primitive(this); Array = new Array(this); Dictionary = new Dictionary(this); Inheritance = new Inheritance(this); Polymorphism = new Polymorphism(this); Polymorphicrecursive = new Polymorphicrecursive(this); Readonlyproperty = new Readonlyproperty(this); BaseUri = new System.Uri("http://localhost"); ApiVersion = "2014-04-01-preview"; 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() } }; DeserializationSettings = new JsonSerializerSettings { 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 PolymorphicSerializeJsonConverter<Fish>("fishtype")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Fish>("fishtype")); CustomInitialize(); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using NetTopologySuite.IO; namespace DotSpatial.Data { /// <summary> /// A reader that reads features from WKB text. /// </summary> public static class WkbFeatureReader { #region Fields private static ByteOrder endian; #endregion #region Methods /// <summary> /// Given the array of bytes, this reverses the bytes based on size. So if size if 4, the /// reversal will flip uints of 4 bytes at a time. /// </summary> /// <param name="data">Data that gets reversed.</param> /// <param name="size">Number of bytes that will be flipped together.</param> public static void CheckEndian(byte[] data, int size) { if ((endian == ByteOrder.LittleEndian) == BitConverter.IsLittleEndian) return; int count = data.Length / size; for (int i = 0; i < count; i++) { byte[] temp = new byte[size]; Array.Copy(data, i * size, temp, 0, size); Array.Reverse(temp); Array.Copy(temp, 0, data, i * size, size); } } /// <summary> /// Since WKB can in fact store different kinds of shapes, this will split out /// each type of shape into a different featureset. If all the shapes are /// the same kind of feature, thre will only be one list of feature types. /// </summary> /// <param name="data">Data to get the feature sets from.</param> /// <returns>The feature sets gotten from the data.</returns> public static FeatureSetPack GetFeatureSets(byte[] data) { MemoryStream ms = new MemoryStream(data); return GetFeatureSets(ms); } /// <summary> /// Gets a FeatureSetPack from the WKB /// </summary> /// <param name="data">Data to get the feature sets from.</param> /// <returns>The feature sets gotten from the data.</returns> public static FeatureSetPack GetFeatureSets(Stream data) { FeatureSetPack result = new FeatureSetPack(); while (data.Position < data.Length) { ReadFeature(data, result); } result.StopEditing(); return result; } /// <summary> /// Reads the specified number of doubles. /// </summary> /// <param name="data">Data to read the double from.</param> /// <param name="count">Number of doubles that should be read.</param> /// <returns>The doubles that were read.</returns> public static double[] ReadDouble(Stream data, int count) { byte[] vals = new byte[8 * count]; data.Read(vals, 0, count * 8); CheckEndian(vals, 8); double[] result = new double[count]; Buffer.BlockCopy(vals, 0, result, 0, count * 8); return result; } /// <summary> /// Reads only a single geometry into a feature. This may be a multi-part geometry. /// </summary> /// <param name="data">The data to read the features from.</param> /// <param name="results">FeatureSetPack the read features get added to.</param> public static void ReadFeature(Stream data, FeatureSetPack results) { endian = (ByteOrder)data.ReadByte(); WKBGeometryTypes type = (WKBGeometryTypes)ReadInt32(data); switch (type) { case WKBGeometryTypes.WKBPoint: ReadPoint(data, results); return; case WKBGeometryTypes.WKBLineString: ReadLineString(data, results); return; case WKBGeometryTypes.WKBPolygon: ReadPolygon(data, results); break; case WKBGeometryTypes.WKBMultiPoint: ReadMultiPoint(data, results); break; case WKBGeometryTypes.WKBMultiLineString: ReadMultiLineString(data, results); break; case WKBGeometryTypes.WKBMultiPolygon: ReadMultiPolygon(data, results); break; case WKBGeometryTypes.WKBGeometryCollection: ReadGeometryCollection(data, results); break; } } /// <summary> /// Reads an int from the stream. /// </summary> /// <param name="data">The raw byte data.</param> /// <returns>The int that was read.</returns> public static int ReadInt32(Stream data) { byte[] vals = new byte[4]; data.Read(vals, 0, 4); CheckEndian(vals, 4); return BitConverter.ToInt32(vals, 0); } /// <summary> /// Reads ints from the stream. /// </summary> /// <param name="data">The raw byte data.</param> /// <param name="count">The count of integers, not bytes.</param> /// <returns>The ints that were read.</returns> public static int[] ReadInt32(Stream data, int count) { byte[] vals = new byte[4 * count]; data.Read(vals, 0, 4 * count); CheckEndian(vals, 4); int[] result = new int[count]; Buffer.BlockCopy(vals, 0, result, 0, count * 4); return result; } /// <summary> /// Reads a point from the data. This assumes that the byte order and shapetype have already been read. /// </summary> /// <param name="data">Data to read the point from.</param> /// <returns>The read point as shape.</returns> public static Shape ReadPoint(Stream data) { Shape result = new Shape { Range = new ShapeRange(FeatureType.Point) }; PartRange prt = new PartRange(FeatureType.Point) { NumVertices = 1 }; result.Range.Parts.Add(prt); result.Vertices = ReadDouble(data, 2); return result; } /// <summary> /// Reads only a single geometry into a feature. This may be a multi-part geometry, /// but cannot be a mixed part geometry. Anything that registers as "geometryCollection" /// will trigger an exception. /// </summary> /// <param name="data">The data to read from.</param> /// <returns>The shape that was read.</returns> public static Shape ReadShape(Stream data) { return ReadShape(data, FeatureType.Unspecified); } /// <summary> /// Attempts to read in an entry to the specified feature type. If the feature type does not match /// the geometry type, this will return null. (A Point geometry will be accepted by MultiPoint /// feature type, but not the other way arround. Either way, this will advance the reader /// through the shape feature. Using the Unspecified will always return the shape it reads, /// or null in the case of mixed feature collections which are not supported. /// </summary> /// <param name="data">Data that contains the WKB feature.</param> /// <param name="featureType">The feature type.</param> /// <returns>The resulting shape.</returns> public static Shape ReadShape(Stream data, FeatureType featureType) { endian = (ByteOrder)data.ReadByte(); WKBGeometryTypes type = (WKBGeometryTypes)ReadInt32(data); Shape result; switch (type) { case WKBGeometryTypes.WKBPoint: result = ReadPoint(data); if (featureType == FeatureType.Point || featureType == FeatureType.MultiPoint || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBLineString: result = ReadLineString(data); if (featureType == FeatureType.Line || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBPolygon: result = ReadPolygon(data); if (featureType == FeatureType.Polygon || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBMultiPoint: result = ReadMultiPoint(data); if (featureType == FeatureType.MultiPoint || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBMultiLineString: result = ReadMultiLineString(data); if (featureType == FeatureType.Line || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBMultiPolygon: result = ReadMultiPolygon(data); if (featureType == FeatureType.Polygon || featureType == FeatureType.Unspecified) { return result; } return null; case WKBGeometryTypes.WKBGeometryCollection: throw new ArgumentException("Mixed shape type collections are not supported by this method."); } return null; } /// <summary> /// Calculates the area and if the area is negative, this is considered a hole. /// </summary> /// <param name="coords">Coordinates whose direction gets checked.</param> /// <returns>Boolean, true if this has a negative area and should be thought of as a hole</returns> private static bool IsCounterClockwise(double[] coords) { double area = 0; for (int i = 0; i < coords.Length / 2; i++) { double x1 = coords[i * 2]; double y1 = coords[(i * 2) + 1]; double x2, y2; if (i == (coords.Length / 2) - 1) { x2 = coords[0]; y2 = coords[1]; } else { x2 = coords[(i + 1) * 2]; y2 = coords[((i + 1) * 2) + 1]; } double trapArea = (x1 * y2) - (x2 * y1); area += trapArea; } return area >= 0; } private static void ReadGeometryCollection(Stream data, FeatureSetPack results) { int numGeometries = ReadInt32(data); // Don't worry about "multi-parting" these. Simply create a separate shape // entry for every single geometry here since we have to split out the features // based on feature type. (currently we don't have a mixed feature type for drawing.) for (int i = 0; i < numGeometries; i++) { endian = (ByteOrder)data.ReadByte(); WKBGeometryTypes type = (WKBGeometryTypes)ReadInt32(data); switch (type) { case WKBGeometryTypes.WKBPoint: ReadPoint(data, results); return; case WKBGeometryTypes.WKBLineString: ReadLineString(data, results); return; case WKBGeometryTypes.WKBPolygon: ReadPolygon(data, results); break; case WKBGeometryTypes.WKBMultiPoint: ReadMultiPoint(data, results); break; case WKBGeometryTypes.WKBMultiLineString: ReadMultiLineString(data, results); break; case WKBGeometryTypes.WKBMultiPolygon: ReadMultiPolygon(data, results); break; case WKBGeometryTypes.WKBGeometryCollection: ReadGeometryCollection(data, results); break; } } } private static Shape ReadLineString(Stream data) { Shape result = new Shape(FeatureType.Line); int count = ReadInt32(data); double[] coords = ReadDouble(data, 2 * count); PartRange lPrt = new PartRange(FeatureType.Line) { NumVertices = count }; result.Range.Parts.Add(lPrt); result.Vertices = coords; return result; } private static void ReadLineString(Stream data, FeatureSetPack results) { int count = ReadInt32(data); double[] coords = ReadDouble(data, 2 * count); ShapeRange lShp = new ShapeRange(FeatureType.Line); PartRange lPrt = new PartRange(FeatureType.Line) { NumVertices = count }; lShp.Parts.Add(lPrt); results.Add(coords, lShp); } private static Shape ReadMultiLineString(Stream data) { Shape result = new Shape(FeatureType.Line); int numLineStrings = ReadInt32(data); List<double[]> strings = new List<double[]>(); int partOffset = 0; for (int iString = 0; iString < numLineStrings; iString++) { // Each of these needs to read a full WKBLineString data.Seek(5, SeekOrigin.Current); // ignore header int numPoints = ReadInt32(data); double[] coords = ReadDouble(data, 2 * numPoints); PartRange lPrt = new PartRange(FeatureType.Line) { PartOffset = partOffset, NumVertices = numPoints }; result.Range.Parts.Add(lPrt); partOffset += coords.Length / 2; strings.Add(coords); } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in strings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } result.Vertices = allVertices; return result; } private static void ReadMultiLineString(Stream data, FeatureSetPack results) { int numLineStrings = ReadInt32(data); ShapeRange shp = new ShapeRange(FeatureType.Line); List<double[]> strings = new List<double[]>(); int partOffset = 0; for (int iString = 0; iString < numLineStrings; iString++) { // Each of these needs to read a full WKBLineString data.Seek(5, SeekOrigin.Current); // ignore header int numPoints = ReadInt32(data); double[] coords = ReadDouble(data, 2 * numPoints); PartRange lPrt = new PartRange(FeatureType.Line) { PartOffset = partOffset, NumVertices = numPoints }; shp.Parts.Add(lPrt); partOffset += coords.Length / 2; strings.Add(coords); } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in strings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } results.Add(allVertices, shp); } /// <summary> /// Reads one multipoint shape from a data stream. /// (this assumes that the two bytes (endian and type) have already been read. /// </summary> /// <param name="data">The data to read from.</param> /// <returns>The multipoint that was read as shape.</returns> private static Shape ReadMultiPoint(Stream data) { Shape result = new Shape(FeatureType.MultiPoint); int count = ReadInt32(data); PartRange prt = new PartRange(FeatureType.MultiPoint) { NumVertices = count }; result.Range.Parts.Add(prt); double[] vertices = new double[count * 2]; for (int iPoint = 0; iPoint < count; iPoint++) { data.ReadByte(); // ignore endian ReadInt32(data); // ignore geometry type double[] coord = ReadDouble(data, 2); Array.Copy(coord, 0, vertices, iPoint * 2, 2); } result.Vertices = vertices; return result; } private static void ReadMultiPoint(Stream data, FeatureSetPack results) { int count = ReadInt32(data); ShapeRange sr = new ShapeRange(FeatureType.MultiPoint); PartRange prt = new PartRange(FeatureType.MultiPoint) { NumVertices = count }; sr.Parts.Add(prt); double[] vertices = new double[count * 2]; for (int iPoint = 0; iPoint < count; iPoint++) { data.ReadByte(); // ignore endian ReadInt32(data); // ignore geometry type double[] coord = ReadDouble(data, 2); Array.Copy(coord, 0, vertices, iPoint * 2, 2); } results.Add(vertices, sr); } private static Shape ReadMultiPolygon(Stream data) { Shape result = new Shape(FeatureType.Polygon); int numPolygons = ReadInt32(data); List<double[]> rings = new List<double[]>(); int partOffset = 0; for (int iPoly = 0; iPoly < numPolygons; iPoly++) { data.Seek(5, SeekOrigin.Current); // endian and geometry type int numRings = ReadInt32(data); for (int iRing = 0; iRing < numRings; iRing++) { int numPoints = ReadInt32(data); // ring structures are like a linestring without the final point. double[] coords = ReadDouble(data, 2 * numPoints); if (iRing == 0) { // By shapefile standard, the shell should be clockwise if (IsCounterClockwise(coords)) coords = ReverseCoords(coords); } else { // By shapefile standard, the holes should be counter clockwise. if (!IsCounterClockwise(coords)) coords = ReverseCoords(coords); } PartRange lPrt = new PartRange(FeatureType.Polygon) { PartOffset = partOffset, NumVertices = numPoints }; result.Range.Parts.Add(lPrt); partOffset += coords.Length / 2; rings.Add(coords); } } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in rings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } result.Vertices = allVertices; return result; } private static void ReadMultiPolygon(Stream data, FeatureSetPack results) { int numPolygons = ReadInt32(data); ShapeRange lShp = new ShapeRange(FeatureType.Polygon); List<double[]> rings = new List<double[]>(); int partOffset = 0; for (int iPoly = 0; iPoly < numPolygons; iPoly++) { data.Seek(5, SeekOrigin.Current); // endian and geometry type int numRings = ReadInt32(data); for (int iRing = 0; iRing < numRings; iRing++) { int numPoints = ReadInt32(data); // ring structures are like a linestring without the final point. double[] coords = ReadDouble(data, 2 * numPoints); if (iRing == 0) { // By shapefile standard, the shell should be clockwise if (IsCounterClockwise(coords)) coords = ReverseCoords(coords); } else { // By shapefile standard, the holes should be counter clockwise. if (!IsCounterClockwise(coords)) coords = ReverseCoords(coords); } PartRange lPrt = new PartRange(FeatureType.Polygon) { PartOffset = partOffset, NumVertices = numPoints }; lShp.Parts.Add(lPrt); partOffset += coords.Length / 2; rings.Add(coords); } } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in rings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } results.Add(allVertices, lShp); } /// <summary> /// This assumes that the byte order and shapetype have already been read. /// </summary> /// <param name="data">The data to read from.</param> /// <param name="results">The featureSetPack the read point gets added to.</param> private static void ReadPoint(Stream data, FeatureSetPack results) { ShapeRange sr = new ShapeRange(FeatureType.MultiPoint); PartRange prt = new PartRange(FeatureType.MultiPoint) { NumVertices = 1 }; sr.Parts.Add(prt); double[] coord = ReadDouble(data, 2); results.Add(coord, sr); } private static Shape ReadPolygon(Stream data) { Shape result = new Shape(FeatureType.Polygon); int numRings = ReadInt32(data); List<double[]> rings = new List<double[]>(); int partOffset = 0; for (int iRing = 0; iRing < numRings; iRing++) { int numPoints = ReadInt32(data); // ring structures are like a linestring without the final point. double[] coords = ReadDouble(data, 2 * numPoints); if (iRing == 0) { // By shapefile standard, the shell should be clockwise if (IsCounterClockwise(coords)) coords = ReverseCoords(coords); } else { // By shapefile standard, the holes should be counter clockwise. if (!IsCounterClockwise(coords)) coords = ReverseCoords(coords); } PartRange lPrt = new PartRange(FeatureType.Polygon) { PartOffset = partOffset, NumVertices = numPoints }; result.Range.Parts.Add(lPrt); partOffset += coords.Length / 2; rings.Add(coords); } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in rings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } result.Vertices = allVertices; return result; } private static void ReadPolygon(Stream data, FeatureSetPack results) { int numRings = ReadInt32(data); ShapeRange lShp = new ShapeRange(FeatureType.Polygon); List<double[]> rings = new List<double[]>(); int partOffset = 0; for (int iRing = 0; iRing < numRings; iRing++) { int numPoints = ReadInt32(data); // ring structures are like a linestring without the final point. double[] coords = ReadDouble(data, 2 * numPoints); if (iRing == 0) { // By shapefile standard, the shell should be clockwise if (IsCounterClockwise(coords)) coords = ReverseCoords(coords); } else { // By shapefile standard, the holes should be counter clockwise. if (!IsCounterClockwise(coords)) coords = ReverseCoords(coords); } PartRange lPrt = new PartRange(FeatureType.Polygon) { PartOffset = partOffset, NumVertices = numPoints }; lShp.Parts.Add(lPrt); partOffset += coords.Length / 2; rings.Add(coords); } double[] allVertices = new double[partOffset * 2]; int offset = 0; foreach (double[] ring in rings) { Array.Copy(ring, 0, allVertices, offset, ring.Length); offset += ring.Length; } results.Add(allVertices, lShp); } /// <summary> /// Fix introduced by [email protected]. 3/11/2010 /// Using Array.Reverse does not work because it has the unwanted effect of flipping /// the X and Y values. /// </summary> /// <param name="coords">The double precision XY coordinate array of vertices</param> /// <returns>The double array in reverse order.</returns> private static double[] ReverseCoords(double[] coords) { int numCoords = coords.Length; double[] newCoords = new double[numCoords]; for (int i = numCoords - 1; i >= 0; i -= 2) { newCoords[i - 1] = coords[numCoords - i - 1]; // X newCoords[i] = coords[numCoords - i]; // Y } return newCoords; } #endregion } }
//--------------------------------------------------------------------------- // // File: InkCanvas.cs // // Description: // Defines a Canvas-like class which is used by InkCanvas for the layout. // // Features: // // History: // 02/02/2006 waynezen: Ported from the old InnerCanvas. // // Copyright (C) 2001 by Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace MS.Internal.Controls { /// <summary> /// A subclass of Panel which does layout for InkCanvas. /// </summary> internal class InkCanvasInnerCanvas : Panel { //------------------------------------------------------ // // Cnostructors // //------------------------------------------------------ #region Constructors internal InkCanvasInnerCanvas(InkCanvas inkCanvas) { Debug.Assert(inkCanvas != null); _inkCanvas = inkCanvas; } // No default constructor private InkCanvasInnerCanvas() { } #endregion Constructors //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Override OnVisualChildrenChanged /// </summary> /// <param name="visualAdded"></param> /// <param name="visualRemoved"></param> protected internal override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved) { base.OnVisualChildrenChanged(visualAdded, visualRemoved); UIElement removedElement = visualRemoved as UIElement; // If there is an element being removed, we should make sure to update our selected elements list.. if ( removedElement != null ) { InkCanvas.InkCanvasSelection.RemoveElement(removedElement); } //resurface this on the containing InkCanvas InkCanvas.RaiseOnVisualChildrenChanged(visualAdded, visualRemoved); } /// <summary> /// Override of <seealso cref="FrameworkElement.MeasureOverride" /> /// The code is similar to Canvas.MeasureOverride. The only difference we have is that /// InkCanvasInnerCanvas does report the size based on its children's sizes. /// </summary> /// <param name="constraint">Constraint size.</param> /// <returns>Computed desired size.</returns> protected override Size MeasureOverride(Size constraint) { Size childConstraint = new Size(Double.PositiveInfinity, Double.PositiveInfinity); Size newSize = new Size(); foreach ( UIElement child in InternalChildren ) { if ( child == null ) { continue; } child.Measure(childConstraint); // NOTICE-2006/02/03-WAYNEZEN, // We only honor Left and/or Top property for the measure. // For Right/Bottom, only the child.Width/Height will be used. Those properties will be used by the arrange // but not the measure. double left = (double)InkCanvas.GetLeft(child); if ( !DoubleUtil.IsNaN(left) ) { newSize.Width = Math.Max(newSize.Width, left + child.DesiredSize.Width); } else { newSize.Width = Math.Max(newSize.Width, child.DesiredSize.Width); } double top = (double)InkCanvas.GetTop(child); if ( !DoubleUtil.IsNaN(top) ) { newSize.Height = Math.Max(newSize.Height, top + child.DesiredSize.Height); } else { newSize.Height = Math.Max(newSize.Height, child.DesiredSize.Height); } } return newSize; } /// <summary> /// Canvas computes a position for each of its children taking into account their margin and /// attached Canvas properties: Top, Left. /// /// Canvas will also arrange each of its children. /// This code is same as the Canvas'. /// </summary> /// <param name="arrangeSize">Size that Canvas will assume to position children.</param> protected override Size ArrangeOverride(Size arrangeSize) { //Canvas arranges children at their DesiredSize. //This means that Margin on children is actually respected and added //to the size of layout partition for a child. //Therefore, is Margin is 10 and Left is 20, the child's ink will start at 30. foreach ( UIElement child in InternalChildren ) { if ( child == null ) { continue; } double x = 0; double y = 0; //Compute offset of the child: //If Left is specified, then Right is ignored //If Left is not specified, then Right is used //If both are not there, then 0 double left = (double)InkCanvas.GetLeft(child); if ( !DoubleUtil.IsNaN(left) ) { x = left; } else { double right = (double)InkCanvas.GetRight(child); if ( !DoubleUtil.IsNaN(right) ) { x = arrangeSize.Width - child.DesiredSize.Width - right; } } double top = (double)InkCanvas.GetTop(child); if ( !DoubleUtil.IsNaN(top) ) { y = top; } else { double bottom = (double)InkCanvas.GetBottom(child); if ( !DoubleUtil.IsNaN(bottom) ) { y = arrangeSize.Height - child.DesiredSize.Height - bottom; } } child.Arrange(new Rect(new Point(x, y), child.DesiredSize)); } return arrangeSize; } /// <summary> /// OnChildDesiredSizeChanged /// </summary> /// <param name="child"></param> protected override void OnChildDesiredSizeChanged(UIElement child) { base.OnChildDesiredSizeChanged(child); // Invalid InkCanvasInnerCanvas' measure. InvalidateMeasure(); } /// <summary> /// Override CreateUIElementCollection method. /// The logical parent of InnerCanvas will be set to InkCanvas instead. /// </summary> /// <param name="logicalParent"></param> /// <returns></returns> protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent) { // Replace the logical parent of the InnerCanvas children with our InkCanvas. return base.CreateUIElementCollection(_inkCanvas); } /// <summary> /// Returns LogicalChildren /// </summary> protected internal override IEnumerator LogicalChildren { get { // InnerCanvas won't have any logical children publicly. return EmptyEnumerator.Instance; } } /// <summary> /// The overridden GetLayoutClip method /// </summary> /// <returns>Geometry to use as additional clip if ClipToBounds=true</returns> protected override Geometry GetLayoutClip(Size layoutSlotSize) { // NTRAID:WINDOWSOS#1516798-2006/02/17-WAYNEZEN // By default an FE will clip its content if the ink size exceeds the layout size (the final arrange size). // Since we are auto growing, the ink size is same as the desired size. So it ends up the strokes will be clipped // regardless ClipToBounds is set or not. // We override the GetLayoutClip method so that we can bypass the default layout clip if ClipToBounds is set to false. if ( ClipToBounds ) { return base.GetLayoutClip(layoutSlotSize); } else return null; } #endregion Protected Methods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// Hit test on the children /// </summary> /// <param name="point"></param> /// <returns></returns> internal UIElement HitTestOnElements(Point point) { UIElement hitElement = null; // Do hittest. HitTestResult hitTestResult = VisualTreeHelper.HitTest(this, point); // Now find out which element is hit if there is a result. if ( hitTestResult != null ) { Visual visual = hitTestResult.VisualHit as Visual; System.Windows.Media.Media3D.Visual3D visual3D = hitTestResult.VisualHit as System.Windows.Media.Media3D.Visual3D; DependencyObject currentObject = null; if ( visual != null ) { currentObject = visual; } else if ( visual3D != null ) { currentObject = visual3D; } while ( currentObject != null ) { DependencyObject parent = VisualTreeHelper.GetParent(currentObject); if ( parent == InkCanvas.InnerCanvas ) { // Break when we hit the inner canvas in the visual tree. hitElement = currentObject as UIElement; Debug.Assert(Children.Contains(hitElement), "The hit element should be a child of InnerCanvas."); break; } else { currentObject = parent; } } } return hitElement; } /// <summary> /// Returns the private logical children /// </summary> internal IEnumerator PrivateLogicalChildren { get { // Return the logical children of the base - Canvas return base.LogicalChildren; } } /// <summary> /// Returns the associated InkCanvas /// </summary> internal InkCanvas InkCanvas { get { return _inkCanvas; } } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // The host InkCanvas private InkCanvas _inkCanvas; #endregion Private Fields } }
//----------------------------------------------------------------------- // <copyright file="SharedAccessSignatureHelper.cs" company="Microsoft"> // Copyright 2011 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. // </copyright> // <summary> // Contains code for the SharedAccessSignatureHelper.cs class. // </summary> //----------------------------------------------------------------------- namespace Microsoft.WindowsAzure { using System; using System.Collections.Specialized; using System.Globalization; using System.Web; using Microsoft.WindowsAzure.StorageClient; using Microsoft.WindowsAzure.StorageClient.Protocol; /// <summary> /// Contains helper methods for implementing shared access signatures. /// </summary> internal static class SharedAccessSignatureHelper { /// <summary> /// Get the signature hash embedded inside the Shared Access Signature. /// </summary> /// <param name="policy">The shared access policy to hash.</param> /// <param name="groupPolicyIdentifier">An optional identifier for the policy.</param> /// <param name="resourceName">The canonical resource string, unescaped.</param> /// <param name="client">The client whose credentials are to be used for signing.</param> /// <returns>The signed hash.</returns> internal static string GetSharedAccessSignatureHashImpl( SharedAccessPolicy policy, string groupPolicyIdentifier, string resourceName, CloudBlobClient client) { CommonUtils.AssertNotNull("policy", policy); CommonUtils.AssertNotNullOrEmpty("resourceName", resourceName); CommonUtils.AssertNotNull("client", client); ////StringToSign = signedpermissions + "\n" //// signedstart + "\n" //// signedexpiry + "\n" //// canonicalizedresource + "\n" //// signedidentifier ////HMAC-SHA256(URL.Decode(UTF8.Encode(StringToSign))) string stringToSign = string.Format( "{0}\n{1}\n{2}\n{3}\n{4}", SharedAccessPolicy.PermissionsToString(policy.Permissions), GetDateTimeOrEmpty(policy.SharedAccessStartTime), GetDateTimeOrEmpty(policy.SharedAccessExpiryTime), resourceName, groupPolicyIdentifier); string signature = client.Credentials.ComputeHmac(stringToSign); return signature; } /// <summary> /// Get the complete query builder for creating the Shared Access Signature query. /// </summary> /// <param name="policy">The shared access policy to hash.</param> /// <param name="groupPolicyIdentifier">An optional identifier for the policy.</param> /// <param name="resourceType">Either "b" for blobs or "c" for containers.</param> /// <param name="signature">The signature to use.</param> /// <returns>The finished query builder.</returns> internal static UriQueryBuilder GetShareAccessSignatureImpl( SharedAccessPolicy policy, string groupPolicyIdentifier, string resourceType, string signature) { CommonUtils.AssertNotNull("policy", policy); CommonUtils.AssertNotNullOrEmpty("resourceType", resourceType); CommonUtils.AssertNotNull("signature", signature); UriQueryBuilder builder = new UriQueryBuilder(); // FUTURE blob for blob and container for container string permissions = SharedAccessPolicy.PermissionsToString(policy.Permissions); if (String.IsNullOrEmpty(permissions)) { permissions = null; } AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, GetDateTimeOrNull(policy.SharedAccessStartTime)); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, GetDateTimeOrNull(policy.SharedAccessExpiryTime)); builder.Add(Constants.QueryConstants.SignedResource, resourceType); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIdentifier, groupPolicyIdentifier); AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature); return builder; } /// <summary> /// Converts the specified value to either a string representation or <see cref="String.Empty"/>. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A string representing the specified value.</returns> internal static string GetDateTimeOrEmpty(DateTime? value) { string result = GetDateTimeOrNull(value) ?? string.Empty; return result; } /// <summary> /// Converts the specified value to either a string representation or <c>null</c>. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A string representing the specified value.</returns> internal static string GetDateTimeOrNull(DateTime? value) { string result = value != null ? value.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") : null; return result; } /// <summary> /// Escapes and adds the specified name/value pair to the query builder if it is not null. /// </summary> /// <param name="builder">The builder to add the value to.</param> /// <param name="name">The name of the pair.</param> /// <param name="value">The value to be escaped.</param> internal static void AddEscapedIfNotNull(UriQueryBuilder builder, string name, string value) { if (value != null) { builder.Add(name, value); } } /// <summary> /// Parses the query. /// </summary> /// <param name="queryParameters">The query parameters.</param> /// <param name="credentials">The credentials.</param> internal static void ParseQuery(NameValueCollection queryParameters, out StorageCredentialsSharedAccessSignature credentials) { string signature = null; string signedStart = null; string signedExpiry = null; string signedResource = null; string sigendPermissions = null; string signedIdentifier = null; string signedVersion = null; bool sasParameterFound = false; credentials = null; foreach (var key in queryParameters.AllKeys) { switch (key.ToLower()) { case Constants.QueryConstants.SignedStart: signedStart = queryParameters[key]; sasParameterFound = true; break; case Constants.QueryConstants.SignedExpiry: signedExpiry = queryParameters[key]; sasParameterFound = true; break; case Constants.QueryConstants.SignedPermissions: sigendPermissions = queryParameters[key]; sasParameterFound = true; break; case Constants.QueryConstants.SignedResource: signedResource = queryParameters[key]; sasParameterFound = true; break; case Constants.QueryConstants.SignedIdentifier: signedIdentifier = queryParameters[key]; sasParameterFound = true; break; case Constants.QueryConstants.Signature: signature = queryParameters[key]; sasParameterFound = true; break; case Constants.QueryConstants.SignedVersion: signedVersion = queryParameters[key]; sasParameterFound = true; break; default: break; //// string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.InvalidQueryParametersInsideBlobAddress, key.ToLower()); //// throw new ArgumentException(errorMessage); } } if (sasParameterFound) { if (signature == null || signedResource == null) { string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.MissingMandatoryParamtersForSAS); throw new ArgumentException(errorMessage); } UriQueryBuilder builder = new UriQueryBuilder(); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, signedStart); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, signedExpiry); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, sigendPermissions); builder.Add(Constants.QueryConstants.SignedResource, signedResource); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIdentifier, signedIdentifier); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedVersion, signedVersion); AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature); string token = builder.ToString(); credentials = new StorageCredentialsSharedAccessSignature(token); } } } }
// GtkSharp.Generation.GObjectVM.cs - GObject specific part of VM creation // // Author: Christian Hoff <[email protected]> // // Copyright (c) 2007 Novell, Inc. // Copyright (c) 2009 Christian Hoff // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GtkSharp.Generation { using System; using System.Collections; using System.IO; using System.Xml; public class GObjectVM : VirtualMethod { protected string class_struct_name; const bool force_glue_generation = false; public GObjectVM (XmlElement elem, ObjectBase container_type) : base (elem, container_type) { parms.HideData = false; this.Protection = "protected"; class_struct_name = container_type.ClassStructName; } // Some types don't install headers. In that case, the glue code will not compile. bool BlockGlue { get { return elem.GetAttribute ("block_glue") == "1"; } } protected override string CallString { get { return String.Format ("{0} ({1})", IsStatic ? this.CName + "_handler" : "On" + this.Name, call.ToString ()); } } public void Generate (GenerationInfo gen_info, ObjectBase implementor) { if (!CanGenerate (gen_info, implementor)) throw new NotSupportedException (String.Format ("Cannot generate virtual method {0}.{1}. Make sure a writable glue path was provided to the generator.", container_type.Name, this.CallString)); GenerateOverride (gen_info, implementor); GenerateCallback (gen_info.Writer, implementor); if (!IsStatic) GenerateUnmanagedInvocation (gen_info, implementor); } protected virtual bool CanGenerate (GenerationInfo gen_info, ObjectBase implementor) { if (implementor != null || this.CName.Length == 0 || CodeType == VMCodeType.None || (CodeType == VMCodeType.Glue && !gen_info.GlueEnabled)) return false; else return true; } enum VMCodeType { None, Managed, Glue } VMCodeType CodeType { get { if (!(container_type as ObjectBase).CanGenerateClassStruct || force_glue_generation) { if (BlockGlue) return VMCodeType.None; else return VMCodeType.Glue; } else return VMCodeType.Managed; } } enum VMOverrideType { Unspecified, DeclaringClass, ImplementingClass } /* There are basically two types of static virtual methods: * 1. VMs overridden in the declaring class (e.g. AtkUtil vms): * The VM is overridden in the class in which it is declared and not in the derived classes. In that case, the GAPI generates a static XYZHandler property * in the declaring class. * 2. VMs overridden in derived classes (e.g. GIO is_supported vms): * As with nonstatic vms, this VM type hooks into the class structure field of derived classes. This type is currently unsupported as it is rarely used * and we would need anonymous methods for the callback (we are using only *one* callback method; the callback does not know to which type that method call * has to be redirected). */ VMOverrideType OverrideType { get { if (IsStatic) { switch (elem.GetAttribute ("override_in")) { case "declaring_class": return VMOverrideType.DeclaringClass; case "implementing_class": return VMOverrideType.ImplementingClass; default: return VMOverrideType.Unspecified; } } else return VMOverrideType.ImplementingClass; } } protected virtual void GenerateOverride (GenerationInfo gen_info, ObjectBase implementor) { if (CodeType == VMCodeType.Glue) GenerateOverride_glue (gen_info); else GenerateOverride_managed (gen_info.Writer); } protected virtual void GenerateUnmanagedInvocation (GenerationInfo gen_info, ObjectBase implementor) { if (CodeType == VMCodeType.Glue) GenerateUnmanagedInvocation_glue (gen_info); else GenerateUnmanagedInvocation_managed (gen_info); } protected void GenerateOverrideBody (StreamWriter sw) { sw.WriteLine ("\t\tstatic {0}NativeDelegate {0}_cb_delegate;", Name); sw.WriteLine ("\t\tstatic " + Name + "NativeDelegate " + Name + "VMCallback {"); sw.WriteLine ("\t\t\tget {"); sw.WriteLine ("\t\t\t\tif ({0}_cb_delegate == null)", Name); sw.WriteLine ("\t\t\t\t\t{0}_cb_delegate = new {0}NativeDelegate ({0}_cb);", Name); sw.WriteLine ("\t\t\t\treturn {0}_cb_delegate;", Name); sw.WriteLine ("\t\t\t}"); sw.WriteLine ("\t\t}"); sw.WriteLine (); if (IsStatic) { sw.WriteLine ("\t\tpublic delegate {0} {1}Delegate ({2});", retval.CSType, Name, Signature.ToString ()); sw.WriteLine ("\t\tstatic {0}Delegate {1}_handler;", Name, CName); sw.WriteLine (); sw.WriteLine ("\t\tpublic static " + Name + "Delegate " + Name + "Handler {"); sw.WriteLine ("\t\t\tset {"); sw.WriteLine ("\t\t\t\t{0}_handler = value;", CName); sw.WriteLine ("\t\t\t\tOverride{0} ((GLib.GType) typeof ({1}), value == null ? null : {0}VMCallback);", Name, container_type.Name); sw.WriteLine ("\t\t\t}"); sw.WriteLine ("\t\t}"); } else { sw.WriteLine ("\t\tstatic void Override{0} (GLib.GType gtype)", this.Name); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\tOverride{0} (gtype, {0}VMCallback);", this.Name); sw.WriteLine ("\t\t}"); } sw.WriteLine (); sw.WriteLine ("\t\tstatic void Override{0} (GLib.GType gtype, {0}NativeDelegate callback)", this.Name); sw.WriteLine ("\t\t{"); } protected void GenerateOverride_managed (StreamWriter sw) { GenerateOverrideBody (sw); // Override VM; class_offset var is generated by object generatable sw.WriteLine ("\t\t\t{0} class_iface = GetClassStruct (gtype, false);", class_struct_name); sw.WriteLine ("\t\t\tclass_iface.{0} = callback;", this.Name); sw.WriteLine ("\t\t\tOverrideClassStruct (gtype, class_iface);"); sw.WriteLine ("\t\t}"); sw.WriteLine (); } protected void GenerateMethodBody (StreamWriter sw, ClassBase implementor) { sw.WriteLine ("\t\t[GLib.DefaultSignalHandler(Type=typeof(" + (implementor != null ? implementor.QualifiedName : container_type.QualifiedName) + "), ConnectionMethod=\"Override" + this.Name +"\")]"); sw.Write ("\t\t{0} ", this.Protection); if (this.modifiers != "") sw.Write ("{0} ", this.modifiers); sw.WriteLine ("virtual {0} On{1} ({2})", retval.CSType, this.Name, Signature.ToString ()); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\t{0}Internal{1} ({2});", retval.IsVoid ? "" : "return ", this.Name, Signature.GetCallString (false)); sw.WriteLine ("\t\t}"); sw.WriteLine (); // This method is to be invoked from existing VM implementations in the .customs sw.WriteLine ("\t\tprivate {0} Internal{1} ({2})", retval.CSType, this.Name, Signature.ToString ()); sw.WriteLine ("\t\t{"); } void GenerateUnmanagedInvocation_managed (GenerationInfo gen_info) { StreamWriter sw = gen_info.Writer; string native_call = "this.Handle"; if (parms.Count > 0) native_call += ", " + Body.GetCallString (false); this.GenerateMethodBody (sw, null); // Find the first unmanaged ancestor sw.WriteLine ("\t\t\t{0}NativeDelegate unmanaged = GetClassStruct (GTypeExtensions.GetThresholdType (this.LookupGType ()), true).{0};", this.Name); sw.Write ("\t\t\tif (unmanaged == null) "); if (parms.HasOutParam) sw.WriteLine ("throw new InvalidOperationException (\"No base method to invoke\");"); else if (retval.IsVoid) sw.WriteLine ("return;"); else sw.WriteLine ("return {0};", retval.DefaultValue); sw.WriteLine (); Body.Initialize (gen_info); sw.Write ("\t\t\t"); if (!retval.IsVoid) sw.Write ("{0} __result = ", retval.MarshalType); sw.WriteLine ("unmanaged ({0});", native_call); Body.Finish (gen_info.Writer, ""); if(!retval.IsVoid) sw.WriteLine ("\t\t\treturn {0};", retval.FromNative ("__result")); sw.WriteLine ("\t\t}"); sw.WriteLine (); } /* old glue code. This code is to be used if * a) the generated api file is version 1 * b) an old Mono version(< 2.4) is being used * Punt it when we drop support for the parser version 1. */ private string CastFromInt (string type) { return type != "int" ? "(" + type + ") " : ""; } private string GlueSignature { get { string[] glue_params = new string [this.IsStatic ? parms.Count + 1 : parms.Count + 2]; glue_params [0] = class_struct_name + " *class_struct"; if (!IsStatic) glue_params [1] = container_type.CName + "* inst"; for (int i = 0; i < parms.Count; i++) glue_params [i + (IsStatic ? 1 : 2)] = parms [i].CType.Replace ("const-", "const ") + " " + parms [i].Name; return String.Join (", ", glue_params); } } private string DefaultGlueValue { get { if (retval.IGen is EnumGen) return String.Format ("({0}) 0", retval.CType); string val = retval.DefaultValue; switch (val) { case "null": return "NULL"; case "false": return "FALSE"; case "true": return "TRUE"; case "GLib.GType.None": return "G_TYPE_NONE"; default: return val; } } } void GenerateOverride_glue (GenerationInfo gen_info) { StreamWriter glue = gen_info.GlueWriter; StreamWriter sw = gen_info.Writer; string glue_name = String.Format ("{0}sharp_{1}_override_{2}", container_type.NS.ToLower ().Replace (".", "_"), container_type.Name.ToLower (), CName); sw.WriteLine ("\t\t[DllImport (\"{0}\")]", gen_info.GluelibName); sw.WriteLine ("\t\tstatic extern void {0} (IntPtr class_struct, {1}NativeDelegate cb);", glue_name, Name); sw.WriteLine (); glue.WriteLine ("void {0} ({1} *class_struct, gpointer cb);\n", glue_name, class_struct_name); glue.WriteLine ("void\n{0} ({1} *class_struct, gpointer cb)", glue_name, class_struct_name); glue.WriteLine ("{"); glue.WriteLine ("\tclass_struct->{0} = cb;", CName); glue.WriteLine ("}"); glue.WriteLine (); GenerateOverrideBody (sw); sw.WriteLine ("\t\t\t{0} (gtype.ClassPtr, callback);", glue_name); sw.WriteLine ("\t\t}"); sw.WriteLine (); } void GenerateUnmanagedInvocation_glue (GenerationInfo gen_info) { StreamWriter glue = gen_info.GlueWriter; string glue_name = String.Format ("{0}sharp_{1}_invoke_{2}", container_type.NS.ToLower ().Replace (".", "_"), container_type.Name.ToLower (), CName); glue.WriteLine ("{0} {1} ({2});\n", retval.CType.Replace ("const-", "const "), glue_name, GlueSignature); glue.WriteLine ("{0}\n{1} ({2})", retval.CType.Replace ("const-", "const "), glue_name, GlueSignature); glue.WriteLine ("{"); glue.Write ("\tif (class_struct->{0})\n\t\t", CName); if (!retval.IsVoid) glue.Write ("return "); string[] call_args = new string [IsStatic ? parms.Count : parms.Count + 1]; if (!IsStatic) call_args [0] = "inst"; for (int i = 0; i < parms.Count; i++) call_args [IsStatic ? i : i + 1] = parms[i].Name; glue.WriteLine ("(* class_struct->{0}) ({1});", CName, String.Join (", ", call_args)); if (!retval.IsVoid) glue.WriteLine ("\treturn " + DefaultGlueValue + ";"); glue.WriteLine ("}"); glue.WriteLine (); StreamWriter sw = gen_info.Writer; sw.WriteLine ("\t\t[DllImport (\"{0}\")]", gen_info.GluelibName); sw.Write ("\t\tstatic extern {0} {1} (IntPtr class_struct", retval.MarshalType, glue_name); if (!IsStatic) sw.Write (", IntPtr inst"); if (parms.Count > 0) sw.Write (", {0}", parms.ImportSignature); sw.WriteLine (");"); sw.WriteLine (); GenerateMethodBody (sw, null); Body.Initialize (gen_info, false, false, String.Empty); string glue_call_string = "GTypeExtensions.GetClassPtr (GTypeExtensions.GetThresholdType (this.LookupGType ()))"; if (!IsStatic) glue_call_string += ", Handle"; if (parms.Count > 0) glue_call_string += ", " + Body.GetCallString (false); sw.Write ("\t\t\t"); if (!retval.IsVoid) sw.Write ("{0} __result = ", retval.MarshalType); sw.WriteLine ("{0} ({1});", glue_name, glue_call_string); Body.Finish (gen_info.Writer, ""); if(!retval.IsVoid) sw.WriteLine ("\t\t\treturn {0};", retval.FromNative ("__result")); sw.WriteLine ("\t\t}"); sw.WriteLine (); } public override bool Validate () { if (!base.Validate ()) return false; bool is_valid = true; if (this.IsStatic) { switch (OverrideType) { case VMOverrideType.Unspecified: Console.Write ("Static virtual methods can only be generated if you provide info on how to override this method via the metadata "); is_valid = false; break; case VMOverrideType.ImplementingClass: Console.Write ("Overriding static virtual methods in the implementing class is not supported yet "); is_valid = false; break; } } if (!is_valid) Console.WriteLine (" (in virtual method {0}.{1})", container_type.QualifiedName, this.Name); return is_valid; } } }
/* * 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.Data; using System.Reflection; using System.Collections.Generic; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.MySQL { /// <summary> /// A MySQL Interface for the Asset Server /// </summary> public class MySQLAssetData : AssetDataBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private MySQLManager _dbConnection; #region IPlugin Members /// <summary> /// <para>Initialises Asset interface</para> /// <para> /// <list type="bullet"> /// <item>Loads and initialises the MySQL storage plugin.</item> /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item> /// <item>Check for migration</item> /// </list> /// </para> /// </summary> /// <param name="connect">connect string</param> override public void Initialise(string connect) { // TODO: This will let you pass in the connect string in // the config, though someone will need to write that. if (connect == String.Empty) { // This is old seperate config file m_log.Warn("no connect string, using old mysql_connection.ini instead"); Initialise(); } else { _dbConnection = new MySQLManager(connect); } // This actually does the roll forward assembly stuff Assembly assem = GetType().Assembly; Migration m = new Migration(_dbConnection.Connection, assem, "AssetStore"); m.Update(); } /// <summary> /// <para>Initialises Asset interface</para> /// <para> /// <list type="bullet"> /// <item>Loads and initialises the MySQL storage plugin</item> /// <item>uses the obsolete mysql_connection.ini</item> /// </list> /// </para> /// </summary> /// <remarks>DEPRECATED and shouldn't be used</remarks> public override void Initialise() { IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); string hostname = GridDataMySqlFile.ParseFileReadValue("hostname"); string database = GridDataMySqlFile.ParseFileReadValue("database"); string username = GridDataMySqlFile.ParseFileReadValue("username"); string password = GridDataMySqlFile.ParseFileReadValue("password"); string pooling = GridDataMySqlFile.ParseFileReadValue("pooling"); string port = GridDataMySqlFile.ParseFileReadValue("port"); _dbConnection = new MySQLManager(hostname, database, username, password, pooling, port); } public override void Dispose() { } /// <summary> /// Database provider version /// </summary> override public string Version { get { return _dbConnection.getVersion(); } } /// <summary> /// The name of this DB provider /// </summary> override public string Name { get { return "MySQL Asset storage engine"; } } #endregion #region IAssetDataPlugin Members /// <summary> /// Fetch Asset <paramref name="assetID"/> from database /// </summary> /// <param name="assetID">Asset UUID to fetch</param> /// <returns>Return the asset</returns> /// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks> override public AssetBase GetAsset(UUID assetID) { AssetBase asset = null; lock (_dbConnection) { _dbConnection.CheckConnection(); using (MySqlCommand cmd = new MySqlCommand( "SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id", _dbConnection.Connection)) { cmd.Parameters.AddWithValue("?id", assetID.ToString()); try { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { asset = new AssetBase(); asset.Data = (byte[])dbReader["data"]; asset.Description = (string)dbReader["description"]; asset.FullID = assetID; string local = dbReader["local"].ToString(); if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase)) asset.Local = true; else asset.Local = false; asset.Name = (string)dbReader["name"]; asset.Type = (sbyte)dbReader["assetType"]; asset.Temporary = Convert.ToBoolean(dbReader["temporary"]); } } } catch (Exception e) { m_log.ErrorFormat( "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString() + Environment.NewLine + "Reconnecting", assetID); _dbConnection.Reconnect(); } } } return asset; } /// <summary> /// Create an asset in database, or update it if existing. /// </summary> /// <param name="asset">Asset UUID to create</param> /// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks> override public void StoreAsset(AssetBase asset) { lock (_dbConnection) { _dbConnection.CheckConnection(); MySqlCommand cmd = new MySqlCommand( "replace INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, data)" + "VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?data)", _dbConnection.Connection); string assetName = asset.Name; if (asset.Name.Length > 64) { assetName = asset.Name.Substring(0, 64); m_log.Warn("[ASSET DB]: Name field truncated from " + asset.Name.Length + " to " + assetName.Length + " characters on add"); } string assetDescription = asset.Description; if (asset.Description.Length > 64) { assetDescription = asset.Description.Substring(0, 64); m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on add"); } // need to ensure we dispose try { using (cmd) { // create unix epoch time int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow); cmd.Parameters.AddWithValue("?id", asset.ID); cmd.Parameters.AddWithValue("?name", assetName); cmd.Parameters.AddWithValue("?description", assetDescription); cmd.Parameters.AddWithValue("?assetType", asset.Type); cmd.Parameters.AddWithValue("?local", asset.Local); cmd.Parameters.AddWithValue("?temporary", asset.Temporary); cmd.Parameters.AddWithValue("?create_time", now); cmd.Parameters.AddWithValue("?access_time", now); cmd.Parameters.AddWithValue("?data", asset.Data); cmd.ExecuteNonQuery(); cmd.Dispose(); } } catch (Exception e) { m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset {0} with name \"{1}\". Attempting reconnect. Error: {2}", asset.FullID, asset.Name, e.Message); _dbConnection.Reconnect(); } } } private void UpdateAccessTime(AssetBase asset) { // Writing to the database every time Get() is called on an asset is killing us. Seriously. -jph return; lock (_dbConnection) { _dbConnection.CheckConnection(); MySqlCommand cmd = new MySqlCommand("update assets set access_time=?access_time where id=?id", _dbConnection.Connection); // need to ensure we dispose try { using (cmd) { // create unix epoch time int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow); cmd.Parameters.AddWithValue("?id", asset.ID); cmd.Parameters.AddWithValue("?access_time", now); cmd.ExecuteNonQuery(); cmd.Dispose(); } } catch (Exception e) { m_log.ErrorFormat( "[ASSETS DB]: " + "MySql failure updating access_time for asset {0} with name {1}" + Environment.NewLine + e.ToString() + Environment.NewLine + "Attempting reconnection", asset.FullID, asset.Name); _dbConnection.Reconnect(); } } } /// <summary> /// check if the asset UUID exist in database /// </summary> /// <param name="uuid">The asset UUID</param> /// <returns>true if exist.</returns> override public bool ExistsAsset(UUID uuid) { bool assetExists = false; lock (_dbConnection) { _dbConnection.CheckConnection(); using (MySqlCommand cmd = new MySqlCommand( "SELECT id FROM assets WHERE id=?id", _dbConnection.Connection)) { cmd.Parameters.AddWithValue("?id", uuid.ToString()); try { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) assetExists = true; } } catch (Exception e) { m_log.ErrorFormat( "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString() + Environment.NewLine + "Attempting reconnection", uuid); _dbConnection.Reconnect(); } } } return assetExists; } /// <summary> /// Returns a list of AssetMetadata objects. The list is a subset of /// the entire data set offset by <paramref name="start" /> containing /// <paramref name="count" /> elements. /// </summary> /// <param name="start">The number of results to discard from the total data set.</param> /// <param name="count">The number of rows the returned list should contain.</param> /// <returns>A list of AssetMetadata objects.</returns> public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { List<AssetMetadata> retList = new List<AssetMetadata>(count); lock (_dbConnection) { _dbConnection.CheckConnection(); MySqlCommand cmd = new MySqlCommand("SELECT name,description,assetType,temporary,id FROM assets LIMIT ?start, ?count", _dbConnection.Connection); cmd.Parameters.AddWithValue("?start", start); cmd.Parameters.AddWithValue("?count", count); try { using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { AssetMetadata metadata = new AssetMetadata(); metadata.Name = (string) dbReader["name"]; metadata.Description = (string) dbReader["description"]; metadata.Type = (sbyte) dbReader["assetType"]; metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]); // Not sure if this is correct. metadata.FullID = new UUID((string) dbReader["id"]); // Current SHA1s are not stored/computed. metadata.SHA1 = new byte[] {}; retList.Add(metadata); } } } catch (Exception e) { m_log.Error("[ASSETS DB]: MySql failure fetching asset set" + Environment.NewLine + e.ToString() + Environment.NewLine + "Attempting reconnection"); _dbConnection.Reconnect(); } } return retList; } #endregion } }
using System; using System.Collections.Generic; using System.Threading; using Hydra.Framework.Actors.Exceptions; namespace Hydra.Framework.Actors.CommandQueues { /// <summary> /// Asynchronous Command Queue /// </summary> public class AsyncCommandQueue : ICommandQueue { #region Member Variables private readonly List<Action> actionCollection = new List<Action>(); private readonly int limit; private readonly int enqueueWaitInterval; private readonly object mutex = new object(); private bool enabled = true; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="AsyncCommandQueue"/> class. /// </summary> /// <param name="limit">The limit.</param> /// <param name="waitTime">The wait time.</param> public AsyncCommandQueue(int limit, int waitTime) { this.limit = limit; this.enqueueWaitInterval = waitTime; } #endregion #region Properties /// <summary> /// Gets the command limit. /// </summary> /// <value>The command limit.</value> public int CommandLimit { get { return limit; } } /// <summary> /// Gets the enqueue wait time. /// </summary> /// <value>The enqueue wait time.</value> public int EnqueueWaitTime { get { return enqueueWaitInterval; } } #endregion #region Public Methods /// <summary> /// Adds an action to the end of the command queue /// </summary> /// <param name="action">The action.</param> public void Enqueue(Action action) { lock (mutex) { if (!SpaceAvailable(1)) return; actionCollection.Add(action); Monitor.PulseAll(mutex); } } /// <summary> /// Adds a range of actions to the end of the command queue /// </summary> /// <param name="actionCollection">The collection of actions.</param> public void EnqueueAll(List<Action> actionCollection) { lock (mutex) { if (!SpaceAvailable(actionCollection.Count)) return; this.actionCollection.AddRange(actionCollection); Monitor.PulseAll(mutex); } } /// <summary> /// Runs the command queue on the callers thread. Does not return until the queue is /// disabled. /// </summary> public void Run() { while (ExecuteAvailableActions()) { // TOOD: Need to support quantum slice and wait periods so that the CPU does not spin } } /// <summary> /// Disables the command queue, losing all commands that are present in the queue /// </summary> public void Disable() { lock (mutex) { enabled = false; Monitor.PulseAll(mutex); } } /// <summary> /// Actionses the available. /// </summary> /// <returns></returns> public bool ActionsAvailable() { while (actionCollection.Count == 0 && enabled) { Monitor.Wait(mutex); } return enabled; } /// <summary> /// Executes the available actions. /// </summary> /// <returns></returns> public bool ExecuteAvailableActions() { Action[] actions = DequeueAll(); if (actions == null) return false; foreach (var action in actions) { if (enabled == false) break; action(); } return true; } #endregion #region Private Methods /// <summary> /// Dequeues all. /// </summary> /// <returns></returns> private Action[] DequeueAll() { lock (mutex) { if (ActionsAvailable()) { Action[] results = actionCollection.ToArray(); actionCollection.Clear(); Monitor.PulseAll(mutex); return results; } return null; } } /// <summary> /// Spaces the available. /// </summary> /// <param name="needed">The needed.</param> /// <returns></returns> private bool SpaceAvailable(int needed) { if (!enabled) return false; if (limit <= 0 || actionCollection.Count + needed <= limit) return true; if (enqueueWaitInterval <= 0) throw new QueueFullException(actionCollection.Count); Monitor.Wait(mutex, enqueueWaitInterval); if (!enabled) return false; if (limit > 0 && actionCollection.Count + needed > limit) throw new QueueFullException(actionCollection.Count); return true; } #endregion } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using VSLangProj; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default. /// Set this attribute to false on Properties that should not be visible for Automation. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class AutomationBrowsableAttribute : System.Attribute { public AutomationBrowsableAttribute(bool browsable) { this.browsable = browsable; } public bool Browsable { get { return this.browsable; } } private bool browsable; } /// <summary> /// To create your own localizable node properties, subclass this and add public properties /// decorated with your own localized display name, category and description attributes. /// </summary> [ComVisible(true)] public class NodeProperties : LocalizableProperties, ISpecifyPropertyPages, IVsGetCfgProvider, IVsSpecifyProjectDesignerPages, IVsBrowseObject { #region fields private HierarchyNode node; #endregion #region properties [Browsable(false)] [AutomationBrowsable(true)] public object Node { get { return this.node; } } internal HierarchyNode HierarchyNode { get { return this.node; } } /// <summary> /// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned. /// </summary> [Browsable(false)] [AutomationBrowsable(false)] public virtual string Name { get { return this.node.Caption; } } #endregion #region ctors internal NodeProperties(HierarchyNode node) { Utilities.ArgumentNotNull("node", node); this.node = node; } #endregion #region ISpecifyPropertyPages methods public virtual void GetPages(CAUUID[] pages) { this.GetCommonPropertyPages(pages); } #endregion #region IVsSpecifyProjectDesignerPages /// <summary> /// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent. /// </summary> /// <param name="pages">The pages to return.</param> /// <returns></returns> public virtual int GetProjectDesignerPages(CAUUID[] pages) { this.GetCommonPropertyPages(pages); return VSConstants.S_OK; } #endregion #region IVsGetCfgProvider methods public virtual int GetCfgProvider(out IVsCfgProvider p) { p = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsBrowseObject methods /// <summary> /// Maps back to the hierarchy or project item object corresponding to the browse object. /// </summary> /// <param name="hier">Reference to the hierarchy object.</param> /// <param name="itemid">Reference to the project item.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) { Utilities.CheckNotNull(node); hier = node.ProjectMgr.GetOuterInterface<IVsHierarchy>(); itemid = this.node.ID; return VSConstants.S_OK; } #endregion #region overridden methods /// <summary> /// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base /// </summary> /// <returns>Caption of Hierarchy node instance</returns> public override string GetComponentName() { string caption = this.HierarchyNode.Caption; if (string.IsNullOrEmpty(caption)) { return base.GetComponentName(); } else { return caption; } } #endregion #region helper methods protected string GetProperty(string name, string def) { string a = this.HierarchyNode.ItemNode.GetMetadata(name); return (a == null) ? def : a; } protected void SetProperty(string name, string value) { this.HierarchyNode.ItemNode.SetMetadata(name, value); } /// <summary> /// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support /// configuration independent properties. /// </summary> /// <param name="pages">The pages to return.</param> private void GetCommonPropertyPages(CAUUID[] pages) { // We do not check whether the supportsProjectDesigner is set to false on the ProjectNode. // We rely that the caller knows what to call on us. Utilities.ArgumentNotNull("pages", pages); if (pages.Length == 0) { throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages"); } // Only the project should show the property page the rest should show the project properties. if (this.node != null && (this.node is ProjectNode)) { // Retrieve the list of guids from hierarchy properties. // Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy string guidsList = String.Empty; IVsHierarchy hierarchy = HierarchyNode.ProjectMgr.GetOuterInterface<IVsHierarchy>(); object variant = null; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant)); guidsList = (string)variant; Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList); if (guids == null || guids.Length == 0) { pages[0] = new CAUUID(); pages[0].cElems = 0; } else { pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids); } } else { pages[0] = new CAUUID(); pages[0].cElems = 0; } } #endregion #region ExtenderSupport [Browsable(false)] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CATID")] public virtual string ExtenderCATID { get { Guid catid = this.HierarchyNode.ProjectMgr.GetCATIDForType(this.GetType()); if (Guid.Empty.CompareTo(catid) == 0) { return null; } return catid.ToString("B"); } } [Browsable(false)] public object ExtenderNames() { EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.HierarchyNode.GetService(typeof(EnvDTE.ObjectExtenders)); Utilities.CheckNotNull(extenderService, "Could not get the ObjectExtenders object from the services exposed by this property object"); return extenderService.GetExtenderNames(this.ExtenderCATID, this); } public object Extender(string extenderName) { EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.HierarchyNode.GetService(typeof(EnvDTE.ObjectExtenders)); Utilities.CheckNotNull(extenderService, "Could not get the ObjectExtenders object from the services exposed by this property object"); return extenderService.GetExtender(this.ExtenderCATID, extenderName, this); } #endregion } [ComVisible(true)] public class FileNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] public virtual string FileName { get { return this.HierarchyNode.Caption; } set { this.HierarchyNode.SetEditLabel(value); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public string FullPath { get { return this.HierarchyNode.Url; } } #region non-browsable properties - used for automation only [Browsable(false)] public string URL { get { return this.HierarchyNode.Url; } } [Browsable(false)] public string Extension { get { return Path.GetExtension(this.HierarchyNode.Caption); } } #endregion #endregion #region ctors internal FileNodeProperties(HierarchyNode node) : base(node) { } #endregion public override string GetClassName() { return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture); } } [ComVisible(true)] public class ExcludedFileNodeProperties : FileNodeProperties { internal ExcludedFileNodeProperties(HierarchyNode node) : base(node) { } [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.BuildAction)] [SRDescriptionAttribute(SR.BuildActionDescription)] [TypeConverter(typeof(BuildActionTypeConverter))] public prjBuildAction BuildAction { get { return prjBuildAction.prjBuildActionNone; } } } [ComVisible(true)] public class IncludedFileNodeProperties : FileNodeProperties { internal IncludedFileNodeProperties(HierarchyNode node) : base(node) { } [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.BuildAction)] [SRDescriptionAttribute(SR.BuildActionDescription)] [TypeConverter(typeof(BuildActionTypeConverter))] public prjBuildAction BuildAction { get { return (prjBuildAction)BuildActionTypeConverter.Instance.ConvertFromString(HierarchyNode.ItemNode.ItemTypeName); } set { this.HierarchyNode.ItemNode.ItemTypeName = BuildActionTypeConverter.Instance.ConvertToString(value); } } [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.Publish)] [SRDescriptionAttribute(SR.PublishDescription)] public bool Publish { get { var publish = this.HierarchyNode.ItemNode.GetMetadata("Publish"); if (String.IsNullOrEmpty(publish)) { if (this.HierarchyNode.ItemNode.ItemTypeName == "Compile") { return true; } return false; } return Convert.ToBoolean(publish); } set { this.HierarchyNode.ItemNode.SetMetadata("Publish", value.ToString()); } } [Browsable(false)] public string SourceControlStatus { get { // remove STATEICON_ and return rest of enum return HierarchyNode.StateIconIndex.ToString().Substring(10); } } } [ComVisible(true)] public class LinkFileNodeProperties : FileNodeProperties { internal LinkFileNodeProperties(HierarchyNode node) : base(node) { } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] [ReadOnly(true)] public override string FileName { get { return this.HierarchyNode.Caption; } set { throw new InvalidOperationException(); } } } [ComVisible(true)] public class DependentFileNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] public virtual string FileName { get { return this.HierarchyNode.Caption; } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public string FullPath { get { return this.HierarchyNode.Url; } } #endregion #region ctors internal DependentFileNodeProperties(HierarchyNode node) : base(node) { } #endregion public override string GetClassName() { return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture); } } class BuildActionTypeConverter : StringConverter { internal static readonly BuildActionTypeConverter Instance = new BuildActionTypeConverter(); public BuildActionTypeConverter() { } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { switch((prjBuildAction)value) { case prjBuildAction.prjBuildActionCompile: return "Compile"; case prjBuildAction.prjBuildActionContent: return "Content"; case prjBuildAction.prjBuildActionNone: return "None"; } } return base.ConvertTo(context, culture, value, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string strVal = (string)value; if (strVal.Equals("Compile", StringComparison.OrdinalIgnoreCase)) { return prjBuildAction.prjBuildActionCompile; } else if (strVal.Equals("Content", StringComparison.OrdinalIgnoreCase)) { return prjBuildAction.prjBuildActionContent; } else if (strVal.Equals("None", StringComparison.OrdinalIgnoreCase)) { return prjBuildAction.prjBuildActionNone; } } return base.ConvertFrom(context, culture, value); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new[] { prjBuildAction.prjBuildActionNone, prjBuildAction.prjBuildActionCompile, prjBuildAction.prjBuildActionContent }); } } [ComVisible(true)] public class ProjectNodeProperties : NodeProperties, EnvDTE80.IInternalExtenderProvider { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.ProjectFolder)] [SRDescriptionAttribute(SR.ProjectFolderDescription)] [AutomationBrowsable(false)] public string ProjectFolder { get { return this.Node.ProjectMgr.ProjectFolder; } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.ProjectFile)] [SRDescriptionAttribute(SR.ProjectFileDescription)] [AutomationBrowsable(false)] public string ProjectFile { get { return this.Node.ProjectMgr.ProjectFile; } set { this.Node.ProjectMgr.ProjectFile = value; } } #region non-browsable properties - used for automation only [Browsable(false)] public string Guid { get { return this.Node.ProjectMgr.ProjectIDGuid.ToString(); } } [Browsable(false)] public string FileName { get { return this.Node.ProjectMgr.ProjectFile; } set { this.Node.ProjectMgr.ProjectFile = value; } } [Browsable(false)] public string FullPath { get { return CommonUtils.NormalizeDirectoryPath(this.Node.ProjectMgr.ProjectFolder); } } #endregion #endregion #region ctors internal ProjectNodeProperties(ProjectNode node) : base(node) { } internal new ProjectNode Node { get { return (ProjectNode)base.Node; } } #endregion #region overridden methods /// <summary> /// ICustomTypeDescriptor.GetEditor /// To enable the "Property Pages" button on the properties browser /// the browse object (project properties) need to be unmanaged /// or it needs to provide an editor of type ComponentEditor. /// </summary> /// <param name="editorBaseType">Type of the editor</param> /// <returns>Editor</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The service provider is used by the PropertiesEditorLauncher")] public override object GetEditor(Type editorBaseType) { // Override the scenario where we are asked for a ComponentEditor // as this is how the Properties Browser calls us if (editorBaseType == typeof(ComponentEditor)) { IOleServiceProvider sp; ErrorHandler.ThrowOnFailure(Node.ProjectMgr.GetSite(out sp)); return new PropertiesEditorLauncher(new ServiceProvider(sp)); } return base.GetEditor(editorBaseType); } public override int GetCfgProvider(out IVsCfgProvider p) { if (this.Node != null && this.Node.ProjectMgr != null) { return this.Node.ProjectMgr.GetCfgProvider(out p); } return base.GetCfgProvider(out p); } public override string GetClassName() { return SR.GetString(SR.ProjectProperties, CultureInfo.CurrentUICulture); } #endregion #region IInternalExtenderProvider Members bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject) { EnvDTE80.IInternalExtenderProvider outerHierarchy = Node.GetOuterInterface<EnvDTE80.IInternalExtenderProvider>(); if (outerHierarchy != null) { return outerHierarchy.CanExtend(extenderCATID, extenderName, extendeeObject); } return false; } object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie) { EnvDTE80.IInternalExtenderProvider outerHierarchy = Node.GetOuterInterface<EnvDTE80.IInternalExtenderProvider>(); if (outerHierarchy != null) { return outerHierarchy.GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie); } return null; } object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject) { return null; } #endregion } [ComVisible(true)] public class FolderNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FolderName)] [SRDescriptionAttribute(SR.FolderNameDescription)] public string FolderName { get { return this.HierarchyNode.Caption; } set { UIThread.Instance.RunSync(() => { this.HierarchyNode.SetEditLabel(value); this.HierarchyNode.ProjectMgr.ReDrawNode(HierarchyNode, UIHierarchyElement.Caption); }); } } #region properties - used for automation only [Browsable(false)] [AutomationBrowsable(true)] public string FileName { get { return this.HierarchyNode.Caption; } set { UIThread.Instance.RunSync(() => { this.HierarchyNode.SetEditLabel(value); this.HierarchyNode.ProjectMgr.ReDrawNode(HierarchyNode, UIHierarchyElement.Caption); }); } } [Browsable(false)] [AutomationBrowsable(true)] public string FullPath { get { return CommonUtils.NormalizeDirectoryPath(this.HierarchyNode.GetMkDocument()); } } #endregion #endregion #region ctors internal FolderNodeProperties(HierarchyNode node) : base(node) { } #endregion public override string GetClassName() { return SR.GetString(SR.FolderProperties, CultureInfo.CurrentUICulture); } } [CLSCompliant(false), ComVisible(true)] public class ReferenceNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.RefName)] [SRDescriptionAttribute(SR.RefNameDescription)] [Browsable(true)] [AutomationBrowsable(true)] public override string Name { get { return this.HierarchyNode.Caption; } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.CopyToLocal)] [SRDescriptionAttribute(SR.CopyToLocalDescription)] public bool CopyToLocal { get { string copyLocal = this.GetProperty(ProjectFileConstants.Private, "False"); if (copyLocal == null || copyLocal.Length == 0) return true; return bool.Parse(copyLocal); } set { this.SetProperty(ProjectFileConstants.Private, value.ToString()); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public virtual string FullPath { get { return this.HierarchyNode.Url; } } #endregion #region ctors internal ReferenceNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.ReferenceProperties, CultureInfo.CurrentUICulture); } #endregion } [ComVisible(true)] public class ProjectReferencesProperties : ReferenceNodeProperties { #region ctors internal ProjectReferencesProperties(ProjectReferenceNode node) : base(node) { } #endregion #region overriden methods public override string FullPath { get { return ((ProjectReferenceNode)Node).ReferencedProjectOutputPath; } } #endregion } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.MathUtils; using osu.Framework.Platform; using osu.Framework.Screens; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Overlays.Settings; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.AccountCreation { public class ScreenEntry : AccountCreationScreen { private ErrorTextFlowContainer usernameDescription; private ErrorTextFlowContainer emailAddressDescription; private ErrorTextFlowContainer passwordDescription; private OsuTextBox usernameTextBox; private OsuTextBox emailTextBox; private OsuPasswordTextBox passwordTextBox; private IAPIProvider api; private ShakeContainer registerShake; private IEnumerable<Drawable> characterCheckText; private OsuTextBox[] textboxes; private ProcessingOverlay processingOverlay; private GameHost host; [BackgroundDependencyLoader] private void load(OsuColour colours, IAPIProvider api, GameHost host) { this.api = api; this.host = host; InternalChildren = new Drawable[] { new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Padding = new MarginPadding(20), Spacing = new Vector2(0, 10), Children = new Drawable[] { new OsuSpriteText { Margin = new MarginPadding { Vertical = 10 }, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Font = OsuFont.GetFont(size: 20), Text = "Let's create an account!", }, usernameTextBox = new OsuTextBox { PlaceholderText = "username", RelativeSizeAxes = Axes.X, TabbableContentContainer = this }, usernameDescription = new ErrorTextFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y }, emailTextBox = new OsuTextBox { PlaceholderText = "email address", RelativeSizeAxes = Axes.X, TabbableContentContainer = this }, emailAddressDescription = new ErrorTextFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y }, passwordTextBox = new OsuPasswordTextBox { PlaceholderText = "password", RelativeSizeAxes = Axes.X, TabbableContentContainer = this, }, passwordDescription = new ErrorTextFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y }, new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { registerShake = new ShakeContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Child = new SettingsButton { Text = "Register", Margin = new MarginPadding { Vertical = 20 }, Action = performRegistration } } } }, }, }, processingOverlay = new ProcessingOverlay { Alpha = 0 } }; textboxes = new[] { usernameTextBox, emailTextBox, passwordTextBox }; usernameDescription.AddText("This will be your public presence. No profanity, no impersonation. Avoid exposing your own personal details, too!"); emailAddressDescription.AddText("Will be used for notifications, account verification and in the case you forget your password. No spam, ever."); emailAddressDescription.AddText(" Make sure to get it right!", cp => cp.Font = cp.Font.With(Typeface.Exo, weight: FontWeight.Bold)); passwordDescription.AddText("At least "); characterCheckText = passwordDescription.AddText("8 characters long"); passwordDescription.AddText(". Choose something long but also something you will remember, like a line from your favourite song."); passwordTextBox.Current.ValueChanged += password => { characterCheckText.ForEach(s => s.Colour = password.NewValue.Length == 0 ? Color4.White : Interpolation.ValueAt(password.NewValue.Length, Color4.OrangeRed, Color4.YellowGreen, 0, 8, Easing.In)); }; } protected override void Update() { base.Update(); if (host?.OnScreenKeyboardOverlapsGameWindow != true && !textboxes.Any(t => t.HasFocus)) focusNextTextbox(); } public override void OnEntering(IScreen last) { base.OnEntering(last); processingOverlay.Hide(); } private void performRegistration() { if (focusNextTextbox()) { registerShake.Shake(); return; } usernameDescription.ClearErrors(); emailAddressDescription.ClearErrors(); passwordDescription.ClearErrors(); processingOverlay.Show(); Task.Run(() => { bool success; RegistrationRequest.RegistrationRequestErrors errors = null; try { errors = api.CreateAccount(emailTextBox.Text, usernameTextBox.Text, passwordTextBox.Text); success = errors == null; } catch (Exception) { success = false; } Schedule(() => { if (!success) { if (errors != null) { usernameDescription.AddErrors(errors.User.Username); emailAddressDescription.AddErrors(errors.User.Email); passwordDescription.AddErrors(errors.User.Password); } else { passwordDescription.AddErrors(new[] { "Something happened... but we're not sure what." }); } registerShake.Shake(); processingOverlay.Hide(); return; } api.Login(emailTextBox.Text, passwordTextBox.Text); }); }); } private bool focusNextTextbox() { var nextTextbox = nextUnfilledTextbox(); if (nextTextbox != null) { Schedule(() => GetContainingInputManager().ChangeFocus(nextTextbox)); return true; } return false; } private OsuTextBox nextUnfilledTextbox() => textboxes.FirstOrDefault(t => string.IsNullOrEmpty(t.Text)); } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERLevel { /// <summary> /// C03Level11Child (editable child object).<br/> /// This is a generated base class of <see cref="C03Level11Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="C02Level1"/> collection. /// </remarks> [Serializable] public partial class C03Level11Child : BusinessBase<C03Level11Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_Child_Name, "Level_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1 Child Name. /// </summary> /// <value>The Level_1_1 Child Name.</value> public string Level_1_1_Child_Name { get { return GetProperty(Level_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C03Level11Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="C03Level11Child"/> object.</returns> internal static C03Level11Child NewC03Level11Child() { return DataPortal.CreateChild<C03Level11Child>(); } /// <summary> /// Factory method. Loads a <see cref="C03Level11Child"/> object, based on given parameters. /// </summary> /// <param name="cParentID1">The CParentID1 parameter of the C03Level11Child to fetch.</param> /// <returns>A reference to the fetched <see cref="C03Level11Child"/> object.</returns> internal static C03Level11Child GetC03Level11Child(int cParentID1) { return DataPortal.FetchChild<C03Level11Child>(cParentID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C03Level11Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private C03Level11Child() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C03Level11Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C03Level11Child"/> object from the database, based on given criteria. /// </summary> /// <param name="cParentID1">The CParent ID1.</param> protected void Child_Fetch(int cParentID1) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetC03Level11Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CParentID1", cParentID1).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, cParentID1); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C03Level11Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_Child_NameProperty, dr.GetString("Level_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="C03Level11Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddC03Level11Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="C03Level11Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(C02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateC03Level11Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="C03Level11Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(C02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteC03Level11Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
//------------------------------------------------------------------------------ // <license file="XMLName.cs"> // // The use and distribution terms for this software are contained in the file // named 'LICENSE', which can be found in the resources directory of this // distribution. // // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // </license> //------------------------------------------------------------------------------ using System; using System.Xml; using System.Text; namespace EcmaScript.NET.Types.E4X { internal class XMLName : IRef { internal String uri; internal String localName; private XMLObject xmlObject; internal bool IsAttributeName; internal bool IsDescendants; public XMLName (string uri, string localName) { this.uri = uri; this.localName = localName; } public void BindTo (XMLObject obj) { if (obj == null) throw new ArgumentNullException ("obj"); if (xmlObject != null) throw new ArgumentException ("Already bound to an xml object."); this.xmlObject = obj; } public object Get (Context cx) { if (xmlObject == null) throw ScriptRuntime.UndefReadError (Undefined.Value, ToString ()); return xmlObject.GetXMLProperty (this); } public object Set (Context cx, object value) { if (xmlObject == null) throw ScriptRuntime.UndefWriteError (this, ToString (), value); xmlObject.PutXMLProperty (this, value); return value; } public bool Has (Context cx) { throw new Exception ("The method or operation is not implemented."); } public bool Delete (Context cx) { throw new Exception ("The method or operation is not implemented."); } internal bool Matches (XmlNode node) { if (uri != null && !uri.Equals (node.NamespaceURI)) return false; if (localName != null && localName != "*" && !localName.Equals (node.LocalName)) return false; return true; } public override string ToString () { StringBuilder buff = new StringBuilder (); if (IsDescendants) buff.Append (".."); if (IsAttributeName) buff.Append ('@'); if (uri == null) { buff.Append ('*'); if (localName.Equals ("*")) { return buff.ToString (); } } else { buff.Append ('"').Append (uri).Append ('"'); } buff.Append (':').Append (localName); return buff.ToString (); } internal static XMLName Parse (XMLLib lib, Context cx, Object value) { XMLName result; if (value is XMLName) { result = (XMLName)value; } else if (value is String) { String str = (String)value; long test = ScriptRuntime.testUint32String (str); if (test >= 0) { ScriptRuntime.storeUint32Result (cx, test); result = null; } else { result = Parse (lib, cx, str); } } else if (CliHelper.IsNumber (value)) { double d = ScriptConvert.ToNumber (value); long l = (long)d; if (l == d && 0 <= l && l <= 0xFFFFFFFFL) { ScriptRuntime.storeUint32Result (cx, l); result = null; } else { throw XMLLib.BadXMLName (value); } } else if (value is QName) { QName qname = (QName)value; String uri = qname.Uri; bool number = false; result = null; if (uri != null && uri.Length == 0) { // Only in this case qname.toString() can resemble uint32 long test = ScriptRuntime.testUint32String (uri); if (test >= 0) { ScriptRuntime.storeUint32Result (cx, test); number = true; } } if (!number) { result = XMLName.FormProperty (uri, qname.LocalName); } } else if (value is Boolean || value == Undefined.Value || value == null) { throw XMLLib.BadXMLName (value); } else { String str = ScriptConvert.ToString (value); long test = ScriptRuntime.testUint32String (str); if (test >= 0) { ScriptRuntime.storeUint32Result (cx, test); result = null; } else { result = Parse (lib, cx, str); } } return result; } internal static XMLName FormStar () { return new XMLName (null, "*"); } internal static XMLName FormProperty (string uri, string localName) { return new XMLName (uri, localName); } internal static XMLName Parse (XMLLib lib, Context cx, string name) { if (name == null) throw new ArgumentNullException ("name"); int l = name.Length; if (l != 0) { char firstChar = name [0]; if (firstChar == '*') { if (l == 1) { return FormStar (); } } else if (firstChar == '@') { XMLName xmlName = FormProperty ("", name.Substring (1)); xmlName.IsAttributeName = true; return xmlName; } } String uri = lib.GetDefaultNamespaceURI (cx); return XMLName.FormProperty (uri, name); } } }