context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using Odachi.Extensions.Reflection.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace Odachi.Extensions.Reflection { public static class AwaitableExtensions { private static Dictionary<Type, AwaiterEntry?> _awaiterCache = new Dictionary<Type, AwaiterEntry?>(); private static Dictionary<Type, AwaitableEntry?> _awaitableCache = new Dictionary<Type, AwaitableEntry?>(); private static AwaiterEntry? GetAwaiterEntry(Type type) { if (_awaiterCache.TryGetValue(type, out var result)) { return result; } lock (_awaiterCache) { if (_awaiterCache.TryGetValue(type, out result)) { return result; } var interfaces = type.GetInterfaces(); // must implement INotifyCompletion if (!interfaces.Any(t => t == typeof(INotifyCompletion))) { return _awaiterCache[type] = null; } var notifyCompetitionMap = type.GetTypeInfo().GetRuntimeInterfaceMap(typeof(INotifyCompletion)); var onCompletedMethod = notifyCompetitionMap.InterfaceMethods.Single(m => m.Name.Equals("OnCompleted", StringComparison.OrdinalIgnoreCase) && m.ReturnType == typeof(void) && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(Action) ); // may implement ICriticalNotifyCompletion var unsafeOnCompletedMethod = default(MethodInfo); if (interfaces.Any(t => t == typeof(ICriticalNotifyCompletion))) { var criticalNotifyCompetitionMap = type.GetTypeInfo().GetRuntimeInterfaceMap(typeof(ICriticalNotifyCompletion)); unsafeOnCompletedMethod = criticalNotifyCompetitionMap.InterfaceMethods.Single(m => m.Name.Equals("UnsafeOnCompleted", StringComparison.OrdinalIgnoreCase) && m.ReturnType == typeof(void) && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(Action) ); } // must have `bool IsCompleted { get; }` property var isCompletedProperty = type.GetRuntimeProperty("IsCompleted"); if (isCompletedProperty == null || isCompletedProperty.PropertyType != typeof(bool)) { return _awaiterCache[type] = null; } var isCompletedMethod = isCompletedProperty.GetGetMethod(); if (isCompletedMethod == null || isCompletedMethod.ReturnType != typeof(bool)) { return _awaiterCache[type] = null; } // must have `void | T GetResult()` method var getResultMethod = type.GetRuntimeMethod("GetResult", Array.Empty<Type>()); if (getResultMethod == null || getResultMethod.GetParameters().Length > 0) { return _awaiterCache[type] = null; } return _awaiterCache[type] = new AwaiterEntry() { OnCompletedMethod = onCompletedMethod, UnsafeOnCompletedMethod = unsafeOnCompletedMethod, IsCompletedMethod = isCompletedMethod, GetResultMethod = getResultMethod, }; } } private static AwaitableEntry? GetAwaitableEntry(Type type) { if (_awaitableCache.TryGetValue(type, out var result)) { return result; } lock (_awaitableCache) { if (_awaitableCache.TryGetValue(type, out result)) { return result; } var getAwaiterMethod = type.GetMethod("GetAwaiter", BindingFlags.Public | BindingFlags.Instance); if (getAwaiterMethod == null || getAwaiterMethod.GetParameters().Length > 0) { return _awaitableCache[type] = null; } if (!IsAwaiter(getAwaiterMethod.ReturnType)) { return _awaitableCache[type] = null; } return _awaitableCache[type] = new AwaitableEntry() { GetAwaiterMethod = getAwaiterMethod, }; } } /// <summary> /// Returns whether type is an awaiter. /// </summary> public static bool IsAwaiter(this Type type) { return GetAwaiterEntry(type) != null; } /// <summary> /// Returns an awaiter for given target. /// </summary> public static Awaiter GetAwaiter(this Type type, object target) { var entry = GetAwaiterEntry(type); if (entry == null) throw new InvalidOperationException($"Type '{type.FullName}' is not an awaiter"); return new Awaiter(target, entry.OnCompletedMethod, entry.UnsafeOnCompletedMethod, entry.IsCompletedMethod, entry.GetResultMethod); } /// <summary> /// Returns whether type is an awaitable. Note that this doesn't currently support extensions implementing `GetAwaiter`. /// </summary> public static bool IsAwaitable(this Type type) { return GetAwaitableEntry(type) != null; } /// <summary> /// Returns an awaiter for given target. /// </summary> public static Awaitable GetAwaitable(this Type type, object target) { var entry = GetAwaitableEntry(type); if (entry == null) throw new InvalidOperationException($"Type '{type.FullName}' is not an awaitable"); return new Awaitable(target, entry.GetAwaiterMethod); } /// <summary> /// Returns result type of awaitable. /// </summary> public static Type GetAwaitedType(this Type type) { var awaitableEntry = GetAwaitableEntry(type); if (awaitableEntry == null) throw new InvalidOperationException($"Type '{type.FullName}' is not an awaitable"); var awaiterType = awaitableEntry.GetAwaiterMethod.ReturnType; var awaiterEntry = GetAwaiterEntry(awaiterType); if (awaiterEntry == null) throw new InvalidOperationException($"Type '{awaiterType.FullName}' is not an awaiter"); return awaiterEntry.GetResultMethod.ReturnType; } /// <summary> /// Invokes given method and returns awaitable. /// </summary> public static Awaitable InvokeAsync(this MethodInfo method, object target, object[] parameters) { var result = method.Invoke(target, parameters); if (result == null) return default(Awaitable); var resultType = result.GetType(); if (!resultType.IsAwaitable()) return Awaitable.FromValue(result); return resultType.GetAwaitable(result); } #region Nested type: AwaiterEntry private class AwaiterEntry { #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public MethodInfo OnCompletedMethod { get; set; } public MethodInfo? UnsafeOnCompletedMethod { get; set; } public MethodInfo IsCompletedMethod { get; set; } public MethodInfo GetResultMethod { get; set; } #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. } #endregion #region Nested type: AwaitableEntry private class AwaitableEntry { #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public MethodInfo GetAwaiterMethod { get; set; } #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. } #endregion } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; namespace Aurora.Framework { public interface IEventArgs { IScene Scene { get; set; } IClientAPI Sender { get; set; } } /// <summary> /// ChatFromViewer Arguments /// </summary> public class OSChatMessage : EventArgs, IEventArgs { protected int m_channel; protected string m_from; protected UUID m_fromID; protected string m_message; protected Vector3 m_position; protected float m_range; protected IScene m_scene; protected IClientAPI m_sender; protected ISceneChildEntity m_senderObject; protected UUID m_toAgentID; protected ChatTypeEnum m_type; public OSChatMessage() { m_position = new Vector3(); } /// <summary> /// The message sent by the user /// </summary> public string Message { get { return m_message; } set { m_message = value; } } /// <summary> /// The type of message, eg say, shout, broadcast. /// </summary> public ChatTypeEnum Type { get { return m_type; } set { m_type = value; } } /// <summary> /// Which channel was this message sent on? Different channels may have different listeners. Public chat is on channel zero. /// </summary> public int Channel { get { return m_channel; } set { m_channel = value; } } /// <summary> /// How far should this chat go? -1 is default range for the type /// </summary> public float Range { get { return m_range; } set { m_range = value; } } /// <summary> /// The position of the sender at the time of the message broadcast. /// </summary> public Vector3 Position { get { return m_position; } set { m_position = value; } } /// <summary> /// The name of the sender (needed for scripts) /// </summary> public string From { get { return m_from; } set { m_from = value; } } /// <summary> /// The object responsible for sending the message, or null. /// </summary> public ISceneChildEntity SenderObject { get { return m_senderObject; } set { m_senderObject = value; } } public UUID SenderUUID { get { return m_fromID; } set { m_fromID = value; } } public UUID ToAgentID { get { return m_toAgentID; } set { m_toAgentID = value; } } #region IEventArgs Members /// TODO: Sender and SenderObject should just be Sender and of /// type IChatSender /// <summary> /// The client responsible for sending the message, or null. /// </summary> public IClientAPI Sender { get { return m_sender; } set { m_sender = value; } } ///<summary> ///</summary> public IScene Scene { get { return m_scene; } set { m_scene = value; } } #endregion public OSChatMessage Copy() { OSChatMessage message = new OSChatMessage { Channel = Channel, From = From, Message = Message, Position = Position, Range = Range, Scene = Scene, Sender = Sender, SenderObject = SenderObject, SenderUUID = SenderUUID, Type = Type, ToAgentID = ToAgentID }; return message; } public override string ToString() { return m_message; } public Dictionary<string, object> ToKVP() { Dictionary<string, object> kvp = new Dictionary<string, object>(); kvp["Message"] = Message; kvp["Type"] = (int) Type; kvp["Channel"] = Channel; kvp["Range"] = Range; kvp["Position"] = Position; kvp["From"] = From; kvp["SenderUUID"] = SenderUUID; kvp["ToAgentID"] = ToAgentID; return kvp; } public void FromKVP(Dictionary<string, object> kvp) { Message = kvp["Message"].ToString(); Type = ((ChatTypeEnum) int.Parse(kvp["Type"].ToString())); Channel = int.Parse(kvp["Channel"].ToString()); Range = float.Parse(kvp["Range"].ToString()); Position = Vector3.Parse(kvp["Position"].ToString()); From = kvp["From"].ToString(); SenderUUID = UUID.Parse(kvp["SenderUUID"].ToString()); ToAgentID = UUID.Parse(kvp["ToAgentID"].ToString()); } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using Unpacker.Mythic; namespace Unpacker.Spying { public class Spy : IDisposable { private Process m_Process; private IntPtr m_hProcess; private NativeMethods.CONTEXT m_ContextBuffer; private NativeMethods.DEBUG_EVENT_EXCEPTION m_DEventBuffer; private bool m_ToStop; private ManualResetEvent m_Stopped; private bool SafeToStop { get { lock ( this ) return m_ToStop; } set { lock ( this ) m_ToStop = value; } } private bool ProcessTerminated { get { return m_Process.HasExited; } } public Spy() { m_ContextBuffer = new NativeMethods.CONTEXT(); m_ContextBuffer.ContextFlags = NativeMethods.ContextFlags.CONTEXT_CONTROL | NativeMethods.ContextFlags.CONTEXT_INTEGER; m_DEventBuffer = new NativeMethods.DEBUG_EVENT_EXCEPTION(); m_ToStop = false; m_Stopped = new ManualResetEvent( true ); } private static byte[] Signature = new byte[] { 0xC9, 0xC3, 0x8B, 0x45, 0x10, 0x89, 0x30, 0xEB }; private byte[] m_Buffer = new byte[ ScanRange ]; private const uint StartAddress = 0x665000; private const uint EndAddress = 0x675000; private const uint ScanRange = EndAddress - StartAddress; private uint m_Address; private uint FindBreakpoint() { m_Buffer = ReadProcessMemory( StartAddress, ScanRange ); for ( int i = 0; i < m_Buffer.Length - Signature.Length; i ++ ) { int j; for ( j = 0; j < Signature.Length; j ++ ) { if ( m_Buffer[ i + j ] != Signature[ j ] ) break; } if ( j == 8 ) return (uint) ( StartAddress + i ); } return 0; } public void Init( string path ) { string pathDir = Path.GetDirectoryName( path ); NativeMethods.STARTUPINFO startupInfo = new NativeMethods.STARTUPINFO(); NativeMethods.PROCESS_INFORMATION processInfo; if ( !NativeMethods.CreateProcess( path, null, IntPtr.Zero, IntPtr.Zero, false, NativeMethods.CreationFlag.DEBUG_PROCESS, IntPtr.Zero, pathDir, ref startupInfo, out processInfo ) ) throw new Win32Exception(); NativeMethods.CloseHandle( processInfo.hThread ); m_Process = Process.GetProcessById( (int)processInfo.dwProcessId ); m_hProcess = processInfo.hProcess; m_Address = FindBreakpoint(); if ( m_Address == 0 ) throw new Exception( "Cannot find hash function!" ); InitBreakpoints(); } public void Init( Process process ) { uint id = (uint)process.Id; m_Process = process; m_hProcess = NativeMethods.OpenProcess( NativeMethods.DesiredAccessProcess.PROCESS_ALL_ACCESS, false, id ); if ( m_hProcess == IntPtr.Zero ) throw new Win32Exception(); if ( !NativeMethods.DebugActiveProcess( id ) ) throw new Win32Exception(); m_Address = FindBreakpoint(); if ( m_Address == 0 ) throw new Exception( "Cannot find hash function!" ); InitBreakpoints(); } private void InitBreakpoints() { m_OrCode = AddBreakpoint( m_Address ); } private byte[] m_OrCode; private static readonly byte[] BreakCode = { 0xCC }; private static ASCIIEncoding Encoding = new ASCIIEncoding(); private byte[] AddBreakpoint( uint address ) { byte[] orOpCode = ReadProcessMemory( address, 1 ); WriteProcessMemory( address, BreakCode ); return orOpCode; } private void RemoveBreakpoints() { WriteProcessMemory( m_Address, m_OrCode ); } public void MainLoop() { m_Stopped.Reset(); try { while ( !SafeToStop && !ProcessTerminated ) { if ( NativeMethods.WaitForDebugEvent( ref m_DEventBuffer, 1000 ) ) { if ( m_DEventBuffer.dwDebugEventCode == NativeMethods.DebugEventCode.EXCEPTION_DEBUG_EVENT ) { uint address = (uint)m_DEventBuffer.u.Exception.ExceptionRecord.ExceptionAddress.ToInt32(); if ( address == m_Address ) { SpyAddress( m_DEventBuffer.dwThreadId, address ); continue; } } ContinueDebugEvent( m_DEventBuffer.dwThreadId ); } } } finally { EndSpy(); } } private void SpyAddress( uint threadId, uint address ) { IntPtr hThread = NativeMethods.OpenThread( NativeMethods.DesiredAccessThread.THREAD_GET_CONTEXT | NativeMethods.DesiredAccessThread.THREAD_SET_CONTEXT, false, threadId ); GetThreadContext( hThread, ref m_ContextBuffer ); byte[] data = ReadProcessMemory( m_ContextBuffer.Ecx, 8 ); long hash = ( (long) BitConverter.ToUInt32( data, 4 ) << 32 ) | BitConverter.ToUInt32( data, 0 ); if ( HashDictionary.Contains( hash ) ) { uint pointer = m_ContextBuffer.Edi - 1; uint length = m_ContextBuffer.Ebx & 0xFFFF; string name = Encoding.GetString( ReadProcessMemory( pointer, length ) ); HashDictionary.Set( hash, name ); } #region Breakpoint Recovery WriteProcessMemory( address, m_OrCode ); m_ContextBuffer.Eip--; m_ContextBuffer.EFlags |= 0x100; // Single step SetThreadContext( hThread, ref m_ContextBuffer ); ContinueDebugEvent( threadId ); if ( !NativeMethods.WaitForDebugEvent( ref m_DEventBuffer, uint.MaxValue ) ) throw new Win32Exception(); WriteProcessMemory( address, BreakCode ); GetThreadContext( hThread, ref m_ContextBuffer ); m_ContextBuffer.EFlags &= ~0x100u; // End single step SetThreadContext( hThread, ref m_ContextBuffer ); #endregion NativeMethods.CloseHandle( hThread ); ContinueDebugEvent( threadId ); } private byte[] ReadProcessMemory( uint address, uint length ) { byte[] buffer = new byte[length]; IntPtr ptrAddr = new IntPtr( address ); uint read; NativeMethods.ReadProcessMemory( m_hProcess, ptrAddr, buffer, length, out read ); if ( read != length ) throw new Win32Exception(); return buffer; } private void WriteProcessMemory( uint address, byte[] data ) { uint length = (uint)data.Length; IntPtr ptrAddr = new IntPtr( address ); uint written; NativeMethods.WriteProcessMemory( m_hProcess, ptrAddr, data, length, out written ); if ( written != length ) throw new Win32Exception(); NativeMethods.FlushInstructionCache( m_hProcess, ptrAddr, length ); } private void ContinueDebugEvent( uint threadId ) { if ( !NativeMethods.ContinueDebugEvent( (uint)m_Process.Id, threadId, NativeMethods.ContinueStatus.DBG_CONTINUE ) ) throw new Win32Exception(); } private void GetThreadContext( IntPtr hThread, ref NativeMethods.CONTEXT context ) { if ( !NativeMethods.GetThreadContext( hThread, ref context ) ) throw new Win32Exception(); } private void SetThreadContext( IntPtr hThread, ref NativeMethods.CONTEXT context ) { if ( !NativeMethods.SetThreadContext( hThread, ref context ) ) throw new Win32Exception(); } public void Dispose() { if ( !SafeToStop ) { SafeToStop = true; m_Stopped.WaitOne(); m_Stopped.Close(); } } private void EndSpy() { try { RemoveBreakpoints(); NativeMethods.DebugActiveProcessStop( (uint)m_Process.Id ); NativeMethods.CloseHandle( m_hProcess ); } catch { } m_Stopped.Set(); } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace BooksOnline.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), NormalizedName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), NormalizedEmail = table.Column<string>(nullable: true), NormalizedUserName = table.Column<string>(nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Diagnostics; using System.IO; using System.Text; using System.Windows.Forms; using Axiom.MathLib; using Multiverse.CollisionLib; namespace CollisionLibTest { public partial class CollisionTestForm : Form { public CollisionTestForm() { InitializeComponent(); } private void FourCollisionsButton_Click(object sender, EventArgs e) { CollisionAPI API = new CollisionAPI(); // Create some obstacles, at 4 corners of a square List<CollisionShape> shapes = new List<CollisionShape>(); CollisionSphere sphere = new CollisionSphere(new Vector3(0f, 0f, 2f), 1f); shapes.Add(sphere); API.AddCollisionShape(sphere, 1); CollisionCapsule capsule = new CollisionCapsule(new Vector3(10f,0f,0f), new Vector3(10f,0f,4f), 1f); shapes.Add(capsule); API.AddCollisionShape(capsule, 2); // Now, an AABB CollisionAABB aabb = new CollisionAABB(new Vector3(9.5f,9.5f,0f), new Vector3(10.5f,10.5f,4f)); shapes.Add(aabb); API.AddCollisionShape(aabb, 3); CollisionOBB obb = new CollisionOBB(new Vector3(0f,10f,2), new Vector3[3] { new Vector3(1f,0f,0f), new Vector3(0f,1f,0f), new Vector3(0f,0f,1f)}, new Vector3(1f, 1f, 1f)); shapes.Add(obb); API.AddCollisionShape(obb, 4); FileStream f = new FileStream("C:\\Junk\\DumpSphereTree.txt", FileMode.Create, FileAccess.Write); StreamWriter writer = new StreamWriter(f); API.DumpSphereTree(writer); API.SphereTreeRoot.VerifySphereTree(); // Now a moving object capsule in the center of the square CollisionCapsule moCap = new CollisionCapsule(new Vector3(5f,5f,0f), new Vector3(5f,5f,4f), 1f); // Remember where the moving object started Vector3 start = moCap.center; // Move the moving object toward each of the obstacles foreach (CollisionShape s in shapes) { moCap.AddDisplacement(start - moCap.center); MoveToObject(writer, API, s, moCap); } writer.Close(); } private void MoveToObject(StreamWriter stream, CollisionAPI API, CollisionShape collisionShape, CollisionShape movingShape) { stream.Write("\n\n\nEntering MoveToObject\n"); // Create a MovingObject, and add movingShape to it MovingObject mo = new MovingObject(); API.AddPartToMovingObject(mo, movingShape); // Move movingObject 1 foot at a time toward the sphere Vector3 toShape = collisionShape.center - movingShape.center; stream.Write(string.Format("movingShape {0}\n", movingShape.ToString())); stream.Write(string.Format("collisionShape {0}\nDisplacement Vector {1}\n", collisionShape.ToString(), toShape.ToString())); // We'll certainly get there before steps expires int steps = (int)Math.Ceiling(toShape.Length); // 1 foot step in the right direction Vector3 stepVector = toShape.ToNormalized(); stream.Write(string.Format("Steps {0}, stepVector {1}\n", steps, stepVector.ToString())); bool hitIt = false; // Loop til we smack into something CollisionParms parms = new CollisionParms(); for (int i=0; i<steps; i++) { // Move 1 foot; if returns true, we hit something hitIt = (API.TestCollision (mo, stepVector, parms)); stream.Write(string.Format("i = {0}, hitIt = {1}, movingShape.center = {2}\n", i, hitIt, movingShape.center.ToString())); if (hitIt) { stream.Write(string.Format("collidingPart {0}\nblockingObstacle {1}\n, normPart {2}, normObstacle {3}\n", parms.part.ToString(), parms.obstacle.ToString(), parms.normPart.ToString(), parms.normObstacle.ToString())); return; } stream.Write("\n"); } Debug.Assert(hitIt, "Didn't hit the obstacle"); } private Vector3 RandomPoint(Random rand, float coordRange) { return new Vector3(coordRange * (float)rand.NextDouble(), coordRange * (float)rand.NextDouble(), coordRange * (float)rand.NextDouble()); } private float RandomFloat(Random rand, float range) { return range * (float)rand.NextDouble(); } // All vector coords are positive private Vector3 RandomRelativeVector(Random rand, Vector3 p, float range) { Vector3 q = Vector3.Zero; for (int i=0; i<3; i++) { q[i] = p[i] + RandomFloat(rand, range); } return q; } private float RandomAngle(Random rand) { return RandomFloat(rand, (float)Math.PI); } private Vector3[] RandomAxes(Random rand) { Matrix3 m = Matrix3.Identity; m.FromEulerAnglesXYZ(RandomAngle(rand), RandomAngle(rand), RandomAngle(rand)); return new Vector3[3] { m.GetColumn(0), m.GetColumn(1), m.GetColumn(2)}; } private CollisionShape RandomObject(Random rand, float coordRange, float objectSizeRange) { Vector3 p = Vector3.Zero; switch((int)Math.Ceiling(4.0f * (float)rand.NextDouble())) { default: case 0: return new CollisionSphere(RandomPoint(rand, coordRange), RandomFloat(rand, objectSizeRange)); case 1: p = RandomPoint(rand, coordRange); return new CollisionCapsule(p, RandomRelativeVector(rand, p, objectSizeRange), RandomFloat(rand, objectSizeRange)); case 2: p = RandomPoint(rand, coordRange); return new CollisionAABB(p, RandomRelativeVector(rand, p, objectSizeRange)); case 3: p = RandomPoint(rand, coordRange); return new CollisionOBB(p, RandomAxes(rand), RandomPoint(rand, objectSizeRange)); } } private void GenerateRandomObjects(StreamWriter stream, CollisionAPI API, Random rand, int count, int handleStart, float coordRange, float objectSizeRange) { // Set the seed to make the sequence deterministic for (int i=0; i<count; i++) { CollisionShape shape = RandomObject(rand, coordRange, objectSizeRange); //stream.Write(string.Format("\nAdding (i={0}) shape {1}", i, shape.ToString())); //stream.Flush(); API.AddCollisionShape(shape, (i + handleStart)); //API.DumpSphereTree(stream); //stream.Flush(); API.SphereTreeRoot.VerifySphereTree(); } } private void RandomSpheresButton_Click(object sender, EventArgs e) { const int iterations = 20; const int objects = 10; const float coordRange = 1000.0f; const float objectSizeRange = 20.0f; CollisionAPI API = new CollisionAPI(); Random rand = new Random((int)3141526); FileStream f = new FileStream("C:\\Junk\\RandomSphereTree.txt", FileMode.Create, FileAccess.Write); StreamWriter stream = new StreamWriter(f); // Create and delete many randomly-placed collision // objects, periodically verifying the sphere tree for (int i=0; i<iterations; i++) { stream.Write("//////////////////////////////////////////////////////////////////////\n\n"); stream.Write(string.Format("Creation Iteration {0}, adding {1} objects, object size range {2}, coordinate range {3}\n\n", i, objects, objectSizeRange, coordRange)); GenerateRandomObjects(stream, API, rand, objects, 0, coordRange, objectSizeRange); stream.Write(string.Format("\n\nAfter iteration {0}:\n\n", i)); API.DumpSphereTree(stream); stream.Flush(); API.SphereTreeRoot.VerifySphereTree(); } for (int i=0; i<objects; i++) { stream.Write("\n\n//////////////////////////////////////////////////////////////////////\n\n"); stream.Write(string.Format("Deleting shapes with handle {0}\n\n", i)); API.RemoveCollisionShapesWithHandle(i); API.DumpSphereTree(stream); stream.Flush(); API.SphereTreeRoot.VerifySphereTree(); } stream.Close(); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Registrasi_FISAddBaru : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["RegistrasiFIS"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>"; btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>"; GetListStatus(); GetListStatusPerkawinan(); GetListAgama(); GetListPendidikan(); GetListJenisPenjamin(); GetListHubungan(); txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); GetNomorRegistrasi(); GetNomorTunggu(); GetListKelompokPemeriksaan(); GetListSatuanKerja(); GetListSatuanKerjaPenjamin(); } } public void GetListStatus() { string StatusId = ""; SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status(); DataTable dt = myObj.GetList(); cmbStatusPasien.Items.Clear(); int i = 0; cmbStatusPasien.Items.Add(""); cmbStatusPasien.Items[i].Text = ""; cmbStatusPasien.Items[i].Value = ""; cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = ""; cmbStatusPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPasien.Items.Add(""); cmbStatusPasien.Items[i].Text = dr["Nama"].ToString(); cmbStatusPasien.Items[i].Value = dr["Id"].ToString(); cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusId) { cmbStatusPasien.SelectedIndex = i; cmbStatusPenjamin.SelectedIndex = i; } i++; } } public void GetListPangkatPasien() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPasien.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPasien.Items.Clear(); int i = 0; cmbPangkatPasien.Items.Add(""); cmbPangkatPasien.Items[i].Text = ""; cmbPangkatPasien.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPasien.Items.Add(""); cmbPangkatPasien.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPasien.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPasien.SelectedIndex = i; } i++; } } public void GetListPangkatPenjamin() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPenjamin.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPenjamin.Items.Clear(); int i = 0; cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = ""; cmbPangkatPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPenjamin.SelectedIndex = i; } i++; } } public void GetNomorTunggu() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 34; // Fisiterapi myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString(); } public void GetListStatusPerkawinan() { string StatusPerkawinanId = ""; BkNet.DataAccess.StatusPerkawinan myObj = new BkNet.DataAccess.StatusPerkawinan(); DataTable dt = myObj.GetList(); cmbStatusPerkawinan.Items.Clear(); int i = 0; cmbStatusPerkawinan.Items.Add(""); cmbStatusPerkawinan.Items[i].Text = ""; cmbStatusPerkawinan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPerkawinan.Items.Add(""); cmbStatusPerkawinan.Items[i].Text = dr["Nama"].ToString(); cmbStatusPerkawinan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusPerkawinanId) cmbStatusPerkawinan.SelectedIndex = i; i++; } } public void GetListAgama() { string AgamaId = ""; BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama(); DataTable dt = myObj.GetList(); cmbAgama.Items.Clear(); int i = 0; cmbAgama.Items.Add(""); cmbAgama.Items[i].Text = ""; cmbAgama.Items[i].Value = ""; cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = ""; cmbAgamaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbAgama.Items.Add(""); cmbAgama.Items[i].Text = dr["Nama"].ToString(); cmbAgama.Items[i].Value = dr["Id"].ToString(); cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == AgamaId) cmbAgama.SelectedIndex = i; i++; } } public void GetListPendidikan() { string PendidikanId = ""; BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan(); DataTable dt = myObj.GetList(); cmbPendidikan.Items.Clear(); int i = 0; cmbPendidikan.Items.Add(""); cmbPendidikan.Items[i].Text = ""; cmbPendidikan.Items[i].Value = ""; cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = ""; cmbPendidikanPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPendidikan.Items.Add(""); cmbPendidikan.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikan.Items[i].Value = dr["Id"].ToString(); cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PendidikanId) cmbPendidikan.SelectedIndex = i; i++; } } public void GetListJenisPenjamin() { string JenisPenjaminId = ""; SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin(); DataTable dt = myObj.GetList(); cmbJenisPenjamin.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbJenisPenjamin.Items.Add(""); cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == JenisPenjaminId) cmbJenisPenjamin.SelectedIndex = i; i++; } } public void GetListHubungan() { string HubunganId = ""; SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan(); DataTable dt = myObj.GetList(); cmbHubungan.Items.Clear(); int i = 0; cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = ""; cmbHubungan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = dr["Nama"].ToString(); cmbHubungan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == HubunganId) cmbHubungan.SelectedIndex = i; i++; } } public void GetNomorRegistrasi() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 34;//FIS myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNoRegistrasi.Text = myObj.GetNomorRegistrasi(); } public void GetListKelompokPemeriksaan() { SIMRS.DataAccess.RS_KelompokPemeriksaan myObj = new SIMRS.DataAccess.RS_KelompokPemeriksaan(); myObj.JenisPemeriksaanId = 4;//FIS DataTable dt = myObj.GetListByJenisPemeriksaanId(); cmbKelompokPemeriksaan.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbKelompokPemeriksaan.Items.Add(""); cmbKelompokPemeriksaan.Items[i].Text = dr["Nama"].ToString(); cmbKelompokPemeriksaan.Items[i].Value = dr["Id"].ToString(); i++; } cmbKelompokPemeriksaan.SelectedIndex = 0; GetListPemeriksaan(); } public DataSet GetDataPemeriksaan() { DataSet ds = new DataSet(); if (Session["dsLayananFIS"] != null) ds = (DataSet)Session["dsLayananFIS"]; else { SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); myObj.PoliklinikId = 34;// FIS DataTable myData = myObj.SelectAllWPoliklinikIdLogic(); ds.Tables.Add(myData); Session.Add("dsLayananFIS", ds); } return ds; } public void GetListPemeriksaan() { DataSet ds = new DataSet(); ds = GetDataPemeriksaan(); lstRefPemeriksaan.DataTextField = "Nama"; lstRefPemeriksaan.DataValueField = "Id"; DataView dv = ds.Tables[0].DefaultView; if (cmbKelompokPemeriksaan.Text!="") dv.RowFilter = " KelompokPemeriksaanId = " + cmbKelompokPemeriksaan.SelectedItem.Value; lstRefPemeriksaan.DataSource = dv; lstRefPemeriksaan.DataBind(); } public void OnSave(Object sender, EventArgs e) { lblError.Text = ""; if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return; } string noRM1 = txtNoRM.Text.Replace("_",""); string noRM2 = noRM1.Replace(".",""); if (noRM2 == "") { lblError.Text = "Nomor Rekam Medis Harus diisi"; return; } else if (noRM2.Length < 5) { lblError.Text = "Nomor Rekam Medis Harus diisi dengan benar"; return; } //if(noRM1.Substring(noRM1.LastIndexOf(".")) == "") SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien(); //txtNoRM.Text = txtNoRM1.Text + "." + txtNoRM2.Text + "." + txtNoRM3.Text; myPasien.PasienId = 0; myPasien.NoRM = txtNoRM.Text.Replace("_", ""); myPasien.Nama = txtNama.Text; if (cmbStatusPasien.SelectedIndex > 0) myPasien.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value); if (cmbPangkatPasien.SelectedIndex > 0) myPasien.PangkatId = int.Parse(cmbPangkatPasien.SelectedItem.Value); myPasien.NoAskes = txtNoASKES.Text; myPasien.NoKTP = txtNoKTP.Text; myPasien.GolDarah = txtGolDarah.Text; myPasien.NRP = txtNrpPasien.Text; myPasien.Jabatan = txtJabatanPasien.Text; //myPasien.Kesatuan = txtKesatuanPasien.Text; myPasien.Kesatuan = cmbSatuanKerja.SelectedItem.ToString(); myPasien.AlamatKesatuan = txtAlamatKesatuanPasien.Text; myPasien.TempatLahir = txtTempatLahir.Text; if (txtTanggalLahir.Text != "") myPasien.TanggalLahir = DateTime.Parse(txtTanggalLahir.Text); myPasien.Alamat = txtAlamatPasien.Text; myPasien.Telepon = txtTeleponPasien.Text; if (cmbJenisKelamin.SelectedIndex > 0) myPasien.JenisKelamin = cmbJenisKelamin.SelectedItem.Value; if (cmbStatusPerkawinan.SelectedIndex > 0) myPasien.StatusPerkawinanId = int.Parse(cmbStatusPerkawinan.SelectedItem.Value); if (cmbAgama.SelectedIndex > 0) myPasien.AgamaId = int.Parse(cmbAgama.SelectedItem.Value); if (cmbPendidikan.SelectedIndex > 0) myPasien.PendidikanId = int.Parse(cmbPendidikan.SelectedItem.Value); myPasien.Pekerjaan = txtPekerjaan.Text; myPasien.AlamatKantor = txtAlamatKantorPasien.Text; myPasien.TeleponKantor = txtTeleponKantorPasien.Text; myPasien.Keterangan = txtKeteranganPasien.Text; myPasien.CreatedBy = UserId; myPasien.CreatedDate = DateTime.Now; if (myPasien.IsExist()) { lblError.Text = myPasien.ErrorMessage.ToString(); return; } else { myPasien.Insert(); int PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex > 0) { //Input Data Penjamin SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin(); myPenj.PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex == 1) { myPenj.Nama = txtNamaPenjamin.Text; if (cmbHubungan.SelectedIndex > 0) myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value); myPenj.Umur = txtUmurPenjamin.Text; myPenj.Alamat = txtAlamatPenjamin.Text; myPenj.Telepon = txtTeleponPenjamin.Text; if (cmbAgamaPenjamin.SelectedIndex > 0) myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value); if (cmbPendidikanPenjamin.SelectedIndex > 0) myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value); if (cmbPangkatPenjamin.SelectedIndex > 0) myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value); myPenj.NoKTP = txtNoKTPPenjamin.Text; myPenj.GolDarah = txtGolDarahPenjamin.Text; myPenj.NRP = txtNRPPenjamin.Text; //myPenj.Kesatuan = txtKesatuanPenjamin.Text; myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString(); myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text; myPenj.Keterangan = txtKeteranganPenjamin.Text; } else { myPenj.Nama = txtNamaPerusahaan.Text; myPenj.NamaKontak = txtNamaKontak.Text; myPenj.Alamat = txtAlamatPerusahaan.Text; myPenj.Telepon = txtTeleponPerusahaan.Text; myPenj.Fax = txtFAXPerusahaan.Text; } myPenj.CreatedBy = UserId; myPenj.CreatedDate = DateTime.Now; myPenj.Insert(); PenjaminId = (int)myPenj.PenjaminId; } //Input Data Registrasi SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.RegistrasiId = 0; myReg.PasienId = myPasien.PasienId; GetNomorRegistrasi(); myReg.NoRegistrasi = txtNoRegistrasi.Text; myReg.JenisRegistrasiId = 1; myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text); myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value); if (PenjaminId != 0) myReg.PenjaminId = PenjaminId; myReg.CreatedBy = UserId; myReg.CreatedDate = DateTime.Now; //myReg.NoUrut = txtNoUrut.Text; myReg.Insert(); //Input Data Rawat Jalan SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan(); myRJ.RawatJalanId = 0; myRJ.RegistrasiId = myReg.RegistrasiId; myRJ.PoliklinikId = 34;// FIS myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); GetNomorTunggu(); if (txtNomorTunggu.Text != "" ) myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text); myRJ.Status = 0;//Baru daftar myRJ.CreatedBy = UserId; myRJ.CreatedDate = DateTime.Now; myRJ.Insert(); ////Input Data Layanan SIMRS.DataAccess.RS_RJLayanan myLayanan = new SIMRS.DataAccess.RS_RJLayanan(); SIMRS.DataAccess.RS_Layanan myTarif = new SIMRS.DataAccess.RS_Layanan(); if (lstPemeriksaan.Items.Count > 0) { string[] kellay; string[] Namakellay; DataTable dt; for (int i = 0; i < lstPemeriksaan.Items.Count; i++) { myLayanan.RJLayananId = 0; myLayanan.RawatJalanId = myRJ.RawatJalanId; myLayanan.JenisLayananId = 3; kellay = lstPemeriksaan.Items[i].Value.Split('|'); Namakellay = lstPemeriksaan.Items[i].Text.Split(':'); myLayanan.KelompokLayananId = 2; myLayanan.LayananId = int.Parse(kellay[1]); myLayanan.NamaLayanan = Namakellay[1]; myTarif.Id = int.Parse(kellay[1]); dt = myTarif.GetTarifRIByLayananId(0); if (dt.Rows.Count > 0) myLayanan.Tarif = dt.Rows[0]["Tarif"].ToString() != "" ? (Decimal)dt.Rows[0]["Tarif"] : 0; else myLayanan.Tarif = 0; myLayanan.JumlahSatuan = double.Parse("1"); myLayanan.Discount = 0; myLayanan.BiayaTambahan = 0; myLayanan.JumlahTagihan = myLayanan.Tarif; myLayanan.Keterangan = ""; myLayanan.CreatedBy = UserId; myLayanan.CreatedDate = DateTime.Now; myLayanan.Insert(); } } //================= string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("FISView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId); } } public void OnCancel(Object sender, EventArgs e) { string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("FISList.aspx?CurrentPage=" + CurrentPage); } protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e) { if (cmbJenisPenjamin.SelectedIndex == 1) { tblPenjaminKeluarga.Visible = true; tblPenjaminPerusahaan.Visible = false; } else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3) { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = true; } else { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = false; } } protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { GetNomorTunggu(); GetNomorRegistrasi(); } protected void cmbStatusPasien_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPasien(); } protected void cmbStatusPenjamin_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPenjamin(); } protected void cmbKelompokPemeriksaan_SelectedIndexChanged(object sender, EventArgs e) { GetListPemeriksaan(); } protected void btnAddPemeriksaan_Click(object sender, EventArgs e) { if (lstRefPemeriksaan.SelectedIndex != -1) { int i = lstPemeriksaan.Items.Count; bool exist = false; string selectValue = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; for (int j = 0; j < i; j++) { if (lstPemeriksaan.Items[j].Value == selectValue) { exist = true; break; } } if (!exist) { ListItem newItem = new ListItem(); newItem.Text = cmbKelompokPemeriksaan.SelectedItem.Text + ": " + lstRefPemeriksaan.SelectedItem.Text; newItem.Value = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; lstPemeriksaan.Items.Add(newItem); } } } protected void btnRemovePemeriksaan_Click(object sender, EventArgs e) { if (lstPemeriksaan.SelectedIndex != -1) { lstPemeriksaan.Items.RemoveAt(lstPemeriksaan.SelectedIndex); } } protected void btnCek_Click(object sender, EventArgs e) { SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien(); myPasien.NoRM = txtNoRM.Text.Replace("_", ""); if (myPasien.IsExistRM()) { lblCek.Text = "No.RM sudah terpakai"; return; } else { lblCek.Text = "No.RM belum terpakai"; return; } } public void GetListSatuanKerja() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerja.Items.Clear(); int i = 0; cmbSatuanKerja.Items.Add(""); cmbSatuanKerja.Items[i].Text = ""; cmbSatuanKerja.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerja.Items.Add(""); cmbSatuanKerja.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerja.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) cmbSatuanKerja.SelectedIndex = i; i++; } } public void GetListSatuanKerjaPenjamin() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerjaPenjamin.Items.Clear(); int i = 0; cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = ""; cmbSatuanKerjaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) cmbSatuanKerjaPenjamin.SelectedIndex = i; i++; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="BiddingSeasonalityAdjustmentServiceClient"/> instances.</summary> public sealed partial class BiddingSeasonalityAdjustmentServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>. /// </summary> /// <returns>A new instance of the default <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>.</returns> public static BiddingSeasonalityAdjustmentServiceSettings GetDefault() => new BiddingSeasonalityAdjustmentServiceSettings(); /// <summary> /// Constructs a new <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> object with default settings. /// </summary> public BiddingSeasonalityAdjustmentServiceSettings() { } private BiddingSeasonalityAdjustmentServiceSettings(BiddingSeasonalityAdjustmentServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateBiddingSeasonalityAdjustmentsSettings = existing.MutateBiddingSeasonalityAdjustmentsSettings; OnCopy(existing); } partial void OnCopy(BiddingSeasonalityAdjustmentServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BiddingSeasonalityAdjustmentServiceClient.MutateBiddingSeasonalityAdjustments</c> and /// <c>BiddingSeasonalityAdjustmentServiceClient.MutateBiddingSeasonalityAdjustmentsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateBiddingSeasonalityAdjustmentsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> object.</returns> public BiddingSeasonalityAdjustmentServiceSettings Clone() => new BiddingSeasonalityAdjustmentServiceSettings(this); } /// <summary> /// Builder class for <see cref="BiddingSeasonalityAdjustmentServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class BiddingSeasonalityAdjustmentServiceClientBuilder : gaxgrpc::ClientBuilderBase<BiddingSeasonalityAdjustmentServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public BiddingSeasonalityAdjustmentServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public BiddingSeasonalityAdjustmentServiceClientBuilder() { UseJwtAccessWithScopes = BiddingSeasonalityAdjustmentServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref BiddingSeasonalityAdjustmentServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BiddingSeasonalityAdjustmentServiceClient> task); /// <summary>Builds the resulting client.</summary> public override BiddingSeasonalityAdjustmentServiceClient Build() { BiddingSeasonalityAdjustmentServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<BiddingSeasonalityAdjustmentServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<BiddingSeasonalityAdjustmentServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private BiddingSeasonalityAdjustmentServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return BiddingSeasonalityAdjustmentServiceClient.Create(callInvoker, Settings); } private async stt::Task<BiddingSeasonalityAdjustmentServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return BiddingSeasonalityAdjustmentServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => BiddingSeasonalityAdjustmentServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => BiddingSeasonalityAdjustmentServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => BiddingSeasonalityAdjustmentServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>BiddingSeasonalityAdjustmentService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage bidding seasonality adjustments. /// </remarks> public abstract partial class BiddingSeasonalityAdjustmentServiceClient { /// <summary> /// The default endpoint for the BiddingSeasonalityAdjustmentService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default BiddingSeasonalityAdjustmentService scopes.</summary> /// <remarks> /// The default BiddingSeasonalityAdjustmentService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> using the default /// credentials, endpoint and settings. To specify custom credentials or other settings, use /// <see cref="BiddingSeasonalityAdjustmentServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns> /// The task representing the created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>. /// </returns> public static stt::Task<BiddingSeasonalityAdjustmentServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new BiddingSeasonalityAdjustmentServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> using the default /// credentials, endpoint and settings. To specify custom credentials or other settings, use /// <see cref="BiddingSeasonalityAdjustmentServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>.</returns> public static BiddingSeasonalityAdjustmentServiceClient Create() => new BiddingSeasonalityAdjustmentServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>.</param> /// <returns>The created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>.</returns> internal static BiddingSeasonalityAdjustmentServiceClient Create(grpccore::CallInvoker callInvoker, BiddingSeasonalityAdjustmentServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient = new BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient(callInvoker); return new BiddingSeasonalityAdjustmentServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC BiddingSeasonalityAdjustmentService client</summary> public virtual BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </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 MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, st::CancellationToken cancellationToken) => MutateBiddingSeasonalityAdjustmentsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose seasonality adjustments are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual seasonality adjustments. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateBiddingSeasonalityAdjustments(new MutateBiddingSeasonalityAdjustmentsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose seasonality adjustments are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual seasonality adjustments. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateBiddingSeasonalityAdjustmentsAsync(new MutateBiddingSeasonalityAdjustmentsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose seasonality adjustments are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual seasonality adjustments. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, st::CancellationToken cancellationToken) => MutateBiddingSeasonalityAdjustmentsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>BiddingSeasonalityAdjustmentService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage bidding seasonality adjustments. /// </remarks> public sealed partial class BiddingSeasonalityAdjustmentServiceClientImpl : BiddingSeasonalityAdjustmentServiceClient { private readonly gaxgrpc::ApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse> _callMutateBiddingSeasonalityAdjustments; /// <summary> /// Constructs a client wrapper for the BiddingSeasonalityAdjustmentService service, with the specified gRPC /// client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> used within this client. /// </param> public BiddingSeasonalityAdjustmentServiceClientImpl(BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient, BiddingSeasonalityAdjustmentServiceSettings settings) { GrpcClient = grpcClient; BiddingSeasonalityAdjustmentServiceSettings effectiveSettings = settings ?? BiddingSeasonalityAdjustmentServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateBiddingSeasonalityAdjustments = clientHelper.BuildApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse>(grpcClient.MutateBiddingSeasonalityAdjustmentsAsync, grpcClient.MutateBiddingSeasonalityAdjustments, effectiveSettings.MutateBiddingSeasonalityAdjustmentsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateBiddingSeasonalityAdjustments); Modify_MutateBiddingSeasonalityAdjustmentsApiCall(ref _callMutateBiddingSeasonalityAdjustments); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateBiddingSeasonalityAdjustmentsApiCall(ref gaxgrpc::ApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse> call); partial void OnConstruction(BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient, BiddingSeasonalityAdjustmentServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC BiddingSeasonalityAdjustmentService client</summary> public override BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient GrpcClient { get; } partial void Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref MutateBiddingSeasonalityAdjustmentsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </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 MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref request, ref callSettings); return _callMutateBiddingSeasonalityAdjustments.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes seasonality adjustments. /// Operation statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref request, ref callSettings); return _callMutateBiddingSeasonalityAdjustments.Async(request, callSettings); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Net; using DotVVM.Framework.Compilation.ControlTree.Resolved; using DotVVM.Framework.Compilation.Parser; using DotVVM.Framework.Compilation.Parser.Dothtml.Parser; using DotVVM.Framework.Controls; using DotVVM.Framework.Controls.Infrastructure; using DotVVM.Framework.Runtime; using DotVVM.Framework.Compilation.Parser.Binding.Tokenizer; using DotVVM.Framework.Compilation.Parser.Binding.Parser; using DotVVM.Framework.Compilation.Binding; using DotVVM.Framework.Utils; using System.Collections.ObjectModel; using DotVVM.Framework.Binding; using System.Diagnostics.CodeAnalysis; using DotVVM.Framework.Compilation.ViewCompiler; using DotVVM.Framework.ResourceManagement; namespace DotVVM.Framework.Compilation.ControlTree { /// <summary> /// An abstract base class for control tree resolver. /// </summary> public abstract class ControlTreeResolverBase : IControlTreeResolver { protected readonly IControlResolver controlResolver; protected readonly IAbstractTreeBuilder treeBuilder; protected readonly DotvvmResourceRepository? resourceRepo; protected Lazy<IControlResolverMetadata> rawLiteralMetadata; protected Lazy<IControlResolverMetadata> literalMetadata; protected Lazy<IControlResolverMetadata> placeholderMetadata; /// <summary> /// Initializes a new instance of the <see cref="ControlTreeResolverBase"/> class. /// </summary> public ControlTreeResolverBase(IControlResolver controlResolver, IAbstractTreeBuilder treeBuilder, DotvvmResourceRepository? resourceRepo) { this.controlResolver = controlResolver; this.treeBuilder = treeBuilder; this.resourceRepo = resourceRepo; rawLiteralMetadata = new Lazy<IControlResolverMetadata>(() => controlResolver.ResolveControl(new ResolvedTypeDescriptor(typeof(RawLiteral)))); literalMetadata = new Lazy<IControlResolverMetadata>(() => controlResolver.ResolveControl(new ResolvedTypeDescriptor(typeof(Literal)))); placeholderMetadata = new Lazy<IControlResolverMetadata>(() => controlResolver.ResolveControl(new ResolvedTypeDescriptor(typeof(PlaceHolder)))); } public static HashSet<string> SingleValueDirectives = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ParserConstants.BaseTypeDirective, ParserConstants.MasterPageDirective, ParserConstants.ResourceTypeDirective, ParserConstants.ViewModelDirectiveName }; /// <summary> /// Resolves the control tree. /// </summary> public virtual IAbstractTreeRoot ResolveTree(DothtmlRootNode root, string fileName) { var directives = ProcessDirectives(root); var wrapperType = ResolveWrapperType(directives, fileName); var viewModelType = ResolveViewModelType(directives, root, fileName); var namespaceImports = ResolveNamespaceImports(directives, root); var injectedServices = ResolveInjectDirectives(directives); IAbstractControlBuilderDescriptor? masterPage = null; if (directives.TryGetValue(ParserConstants.MasterPageDirective, out var masterPageDirective)) { masterPage = ResolveMasterPage(fileName, masterPageDirective.First()); } var viewModule = ResolveImportedViewModules(AssignViewModuleId(masterPage), directives, isMarkupControl: !wrapperType.IsEqualTo(ResolvedTypeDescriptor.Create(typeof(DotvvmView)))); // We need to call BuildControlMetadata instead of ResolveControl. The control builder for the control doesn't have to be compiled yet so the // metadata would be incomplete and ResolveControl caches them internally. BuildControlMetadata just builds the metadata and the control is // actually resolved when the control builder is ready and the metadata are complete. var viewMetadata = controlResolver.BuildControlMetadata(CreateControlType(wrapperType, fileName)); var dataContextTypeStack = CreateDataContextTypeStack(viewModelType, null, namespaceImports, new BindingExtensionParameter[] { new CurrentMarkupControlExtensionParameter(wrapperType), new BindingPageInfoExtensionParameter(), new BindingApiExtensionParameter(), }.Concat(injectedServices) .Concat(viewModule is null ? new BindingExtensionParameter[0] : new[] { viewModule.Value.extensionParameter }).ToArray()); var view = treeBuilder.BuildTreeRoot(this, viewMetadata, root, dataContextTypeStack, directives, masterPage); view.FileName = fileName; if (viewModule.HasValue) { treeBuilder.AddProperty( view, treeBuilder.BuildPropertyValue(Internal.ReferencedViewModuleInfoProperty, viewModule.Value.resource, null), out _ ); } ValidateMasterPage(view, masterPage, masterPageDirective?.First()); ResolveRootContent(root, view, viewMetadata); return view; } /// <summary> /// Resolves the content of the root node. /// </summary> protected virtual void ResolveRootContent(DothtmlRootNode root, IAbstractControl view, IControlResolverMetadata viewMetadata) { // WORKAROUND: // if there is a control in root of a MarkupControl that has DataContext assigned, it will not find the data context space, because the space of DataContext property does not include the control itself and the space of MarkupControl also does not include the MarkupControl. And because the MarkupControl is a direct parent of the DataContext-bound control there is no space in between. if (viewMetadata.Type.IsAssignableTo(new ResolvedTypeDescriptor(typeof(DotvvmMarkupControl)))) { var placeHolder = this.treeBuilder.BuildControl( this.controlResolver.ResolveControl(new ResolvedTypeDescriptor(typeof(PlaceHolder))), view.DothtmlNode, view.DataContextTypeStack ); this.treeBuilder.AddChildControl(view, placeHolder); view = placeHolder; viewMetadata = placeHolder.Metadata; } ResolveControlContentImmediately(view, root.Content); } /// <summary> /// Resolves the view model for the root node. /// </summary> protected virtual ITypeDescriptor? ResolveViewModelType(IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> directives, DothtmlRootNode root, string fileName) { if (!directives.ContainsKey(ParserConstants.ViewModelDirectiveName) || directives[ParserConstants.ViewModelDirectiveName].Count == 0) { root.AddError($"The @viewModel directive is missing in the page '{fileName}'!"); return null; } var viewmodelDirective = (IAbstractViewModelDirective)directives[ParserConstants.ViewModelDirectiveName].First(); if (viewmodelDirective?.ResolvedType is object && viewmodelDirective.ResolvedType.IsAssignableTo(new ResolvedTypeDescriptor(typeof(DotvvmBindableObject)))) { root.AddError($"The @viewModel directive cannot contain type that derives from DotvvmBindableObject!"); return null; } return viewmodelDirective?.ResolvedType; } protected virtual IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> ProcessDirectives(DothtmlRootNode root) { var directives = new Dictionary<string, IReadOnlyList<IAbstractDirective>>(StringComparer.OrdinalIgnoreCase); foreach (var directiveGroup in root.Directives.GroupBy(d => d.Name, StringComparer.OrdinalIgnoreCase)) { if (SingleValueDirectives.Contains(directiveGroup.Key) && directiveGroup.Count() > 1) { foreach (var d in directiveGroup) { ProcessDirective(d); d.AddError($"Directive '{d.Name}' cannot be present multiple times."); } directives[directiveGroup.Key] = ImmutableList.Create(ProcessDirective(directiveGroup.First())); } else { directives[directiveGroup.Key] = directiveGroup.Select(ProcessDirective).ToImmutableList(); } } return new ReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>>(directives); } protected virtual ImmutableList<InjectedServiceExtensionParameter> ResolveInjectDirectives(IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> directives) => directives.Values.SelectMany(d => d).OfType<IAbstractServiceInjectDirective>() .Where(d => d.Type != null) .Select(d => new InjectedServiceExtensionParameter(d.NameSyntax.Name, d.Type!)) .ToImmutableList(); private (JsExtensionParameter extensionParameter, ViewModuleReferenceInfo resource)? ResolveImportedViewModules(string id, IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> directives, bool isMarkupControl) { if (!directives.TryGetValue(ParserConstants.ViewModuleDirective, out var moduleDirectives)) return null; var resources = moduleDirectives .Cast<IAbstractViewModuleDirective>() .Select(x => { if (this.resourceRepo is object && x.DothtmlNode is object) { var resource = this.resourceRepo.FindResource(x.ImportedResourceName); var node = (x.DothtmlNode as DothtmlDirectiveNode)?.ValueNode ?? x.DothtmlNode; if (resource is null) node.AddError($"Cannot find resource named '{x.ImportedResourceName}' referenced by the @js directive!"); else if (!(resource is ScriptModuleResource)) node.AddError($"The resource named '{x.ImportedResourceName}' referenced by the @js directive must be of the ScriptModuleResource type!"); } return x.ImportedResourceName; }) .ToArray(); return (new JsExtensionParameter(id, isMarkupControl), new ViewModuleReferenceInfo(id, resources, isMarkupControl)); } protected virtual string AssignViewModuleId(IAbstractControlBuilderDescriptor? masterPage) { var numberOfMasterPages = 0; while (masterPage != null) { masterPage = masterPage.MasterPage; numberOfMasterPages += 1; } return "p" + numberOfMasterPages; } protected abstract IAbstractControlBuilderDescriptor? ResolveMasterPage(string currentFile, IAbstractDirective masterPageDirective); protected virtual void ValidateMasterPage(IAbstractTreeRoot root, IAbstractControlBuilderDescriptor? masterPage, IAbstractDirective? masterPageDirective) { if (masterPage == null) return; var viewModel = root.DataContextTypeStack.DataContextType; if (masterPage.DataContextType is ResolvedTypeDescriptor typeDescriptor && typeDescriptor.Type == typeof(UnknownTypeSentinel)) { masterPageDirective!.DothtmlNode!.AddError("Could not resolve the type of viewmodel for the specified master page. " + $"This usually means that there is an error with the @viewModel directive in the master page file: \"{masterPage.FileName}\". " + $"Make sure that the provided viewModel type is correct and visible for DotVVM."); } else if (!masterPage.DataContextType.IsAssignableFrom(viewModel)) { masterPageDirective!.DothtmlNode!.AddError($"The viewmodel {viewModel.Name} is not assignable to the viewmodel of the master page {masterPage.DataContextType.Name}."); } } protected virtual ImmutableList<NamespaceImport> ResolveNamespaceImports(IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> directives, DothtmlRootNode root) => ResolveNamespaceImportsCore(directives).ToImmutableList(); private IEnumerable<NamespaceImport> ResolveNamespaceImportsCore(IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> directives) => directives.Values.SelectMany(d => d).OfType<IAbstractImportDirective>() .Where(d => !d.HasError) .Select(d => new NamespaceImport(d.NameSyntax.ToDisplayString(), d.AliasSyntax.As<IdentifierNameBindingParserNode>()?.Name)); /// <summary> /// Processes the parser node and builds a control. /// </summary> public IAbstractControl? ProcessNode(IAbstractTreeNode parent, DothtmlNode node, IControlResolverMetadata parentMetadata, IDataContextStack dataContext) { try { if (node is DothtmlBindingNode) { // binding in text return ProcessBindingInText(node, dataContext); } else if (node is DotHtmlCommentNode commentNode) { // HTML comment return ProcessHtmlComment(node, dataContext, commentNode); } else if (node is DothtmlLiteralNode literalNode) { // text content return ProcessText(node, parentMetadata, dataContext, literalNode); } else if (node is DothtmlElementNode element) { // HTML element return ProcessObjectElement(element, dataContext); } else { throw new NotSupportedException($"The node of type '{node.GetType()}' is not supported!"); } } catch (DotvvmCompilationException ex) { if (ex.Tokens == null) { ex.Tokens = node.Tokens; ex.ColumnNumber = node.Tokens.First().ColumnNumber; ex.LineNumber = node.Tokens.First().LineNumber; } if (!LogError(ex, node)) throw; else return null; } catch (Exception ex) { if (!LogError(ex, node)) throw new DotvvmCompilationException("", ex, node.Tokens); else return null; } } protected virtual bool LogError(Exception exception, DothtmlNode node) { return false; } private IAbstractControl ProcessText(DothtmlNode node, IControlResolverMetadata parentMetadata, IDataContextStack dataContext, DothtmlLiteralNode literalNode) { var whitespace = string.IsNullOrWhiteSpace(literalNode.Value); string text; if (literalNode.Escape) { text = WebUtility.HtmlEncode(literalNode.Value); } else { text = literalNode.Value; } var literal = treeBuilder.BuildControl(rawLiteralMetadata.Value, node, dataContext); literal.ConstructorParameters = new object[] { text.Replace("\r\n", "\n"), literalNode.Value.Replace("\r\n", "\n"), BoxingUtils.Box(whitespace) }; return literal; } private IAbstractControl ProcessHtmlComment(DothtmlNode node, IDataContextStack dataContext, DotHtmlCommentNode commentNode) { var text = commentNode.IsServerSide ? "" : "<!--" + commentNode.Value + "-->"; var literal = treeBuilder.BuildControl(rawLiteralMetadata.Value, node, dataContext); literal.ConstructorParameters = new object[] { text.Replace("\r\n", "\n"), "", BoxingUtils.True }; return literal; } private IAbstractControl ProcessBindingInText(DothtmlNode node, IDataContextStack dataContext) { var bindingNode = (DothtmlBindingNode)node; var literal = treeBuilder.BuildControl(literalMetadata.Value, node, dataContext); var textBinding = ProcessBinding(bindingNode, dataContext, Literal.TextProperty); var textProperty = treeBuilder.BuildPropertyBinding(Literal.TextProperty, textBinding, null); treeBuilder.AddProperty(literal, textProperty, out _); // this can't fail var renderSpanElement = treeBuilder.BuildPropertyValue(Literal.RenderSpanElementProperty, BoxingUtils.False, null); treeBuilder.AddProperty(literal, renderSpanElement, out _); return literal; } /// <summary> /// Processes the HTML element that represents a new object. /// </summary> private IAbstractControl ProcessObjectElement(DothtmlElementNode element, IDataContextStack dataContext) { // build control var controlMetadata = controlResolver.ResolveControl(element.TagPrefix, element.TagName, out var constructorParameters); if (controlMetadata == null) { controlMetadata = controlResolver.ResolveControl("", element.TagName, out constructorParameters).NotNull(); constructorParameters = new[] { element.FullTagName }; element.AddError($"The control <{element.FullTagName}> could not be resolved! Make sure that the tagPrefix is registered in DotvvmConfiguration.Markup.Controls collection!"); } var control = treeBuilder.BuildControl(controlMetadata, element, dataContext); control.ConstructorParameters = constructorParameters; // resolve data context var dataContextAttribute = element.Attributes.FirstOrDefault(a => a.AttributeName == "DataContext"); if (dataContextAttribute != null) { ProcessAttribute(DotvvmBindableObject.DataContextProperty, dataContextAttribute, control, dataContext); } if (control.TryGetProperty(DotvvmBindableObject.DataContextProperty, out var dataContextProperty) && dataContextProperty is IAbstractPropertyBinding { Binding: var dataContextBinding } ) { if (dataContextBinding?.ResultType != null) { dataContext = CreateDataContextTypeStack(dataContextBinding.ResultType, parentDataContextStack: dataContext); } else { dataContext = CreateDataContextTypeStack(null, dataContext); } control.DataContextTypeStack = dataContext; } if (controlMetadata.DataContextConstraint != null && dataContext != null && !controlMetadata.DataContextConstraint.IsAssignableFrom(dataContext.DataContextType)) { ((DothtmlNode?)dataContextAttribute ?? element) .AddError($"The control '{controlMetadata.Type.Name}' requires a DataContext of type '{controlMetadata.DataContextConstraint.FullName}'!"); } ProcessAttributeProperties(control, element.Attributes.Where(a => a.AttributeName != "DataContext").ToArray(), dataContext!); // process control contents ProcessControlContent(control, element.Content); var unknownContent = control.Content.Where(c => !c.Metadata.Type.IsAssignableTo(new ResolvedTypeDescriptor(typeof(DotvvmControl)))); foreach (var unknownControl in unknownContent) { unknownControl.DothtmlNode!.AddError($"The control '{ unknownControl.Metadata.Type.FullName }' does not inherit from DotvvmControl and thus cannot be used in content."); } return control; } /// <summary> /// Processes the binding node. /// </summary> public IAbstractBinding ProcessBinding(DothtmlBindingNode node, IDataContextStack? context, IPropertyDescriptor property) { var bindingOptions = controlResolver.ResolveBinding(node.Name); if (bindingOptions == null) { node.NameNode.AddError($"Binding {node.Name} could not be resolved."); bindingOptions = controlResolver.ResolveBinding("value").NotNull(); // just try it as with value binding } if (context?.NamespaceImports.Length > 0) bindingOptions = bindingOptions.AddImports(context.NamespaceImports); return CompileBinding(node, bindingOptions, context!, property); } protected virtual IAbstractDirective ProcessDirective(DothtmlDirectiveNode directiveNode) { if (string.Equals(ParserConstants.ImportNamespaceDirective, directiveNode.Name) || string.Equals(ParserConstants.ResourceNamespaceDirective, directiveNode.Name)) { return ProcessImportDirective(directiveNode); } else if (string.Equals(ParserConstants.ViewModelDirectiveName, directiveNode.Name, StringComparison.OrdinalIgnoreCase)) { return ProcessViewModelDirective(directiveNode); } else if (string.Equals(ParserConstants.BaseTypeDirective, directiveNode.Name, StringComparison.OrdinalIgnoreCase)) { return ProcessBaseTypeDirective(directiveNode); } else if (string.Equals(ParserConstants.ServiceInjectDirective, directiveNode.Name, StringComparison.OrdinalIgnoreCase)) { return ProcessServiceInjectDirective(directiveNode); } else if (string.Equals(ParserConstants.ViewModuleDirective, directiveNode.Name, StringComparison.OrdinalIgnoreCase)) { return ProcessViewModuleDirective(directiveNode); } return treeBuilder.BuildDirective(directiveNode); } protected virtual IAbstractDirective ProcessViewModelDirective(DothtmlDirectiveNode directiveNode) { return this.treeBuilder.BuildViewModelDirective(directiveNode, ParseDirectiveTypeName(directiveNode)); } protected virtual IAbstractDirective ProcessBaseTypeDirective(DothtmlDirectiveNode directiveNode) { return this.treeBuilder.BuildBaseTypeDirective(directiveNode, ParseDirectiveTypeName(directiveNode)); } protected virtual BindingParserNode ParseDirectiveTypeName(DothtmlDirectiveNode directiveNode) { var tokenizer = new BindingTokenizer(); tokenizer.Tokenize(directiveNode.ValueNode.Text); var parser = new BindingParser() { Tokens = tokenizer.Tokens }; var valueSyntaxRoot = parser.ReadDirectiveTypeName(); if (!parser.OnEnd()) { directiveNode.AddError($"Unexpected token: {parser.Peek()?.Text}."); } return valueSyntaxRoot; } protected BindingParserNode ParseImportDirectiveValue(DothtmlDirectiveNode directiveNode) { var tokenizer = new BindingTokenizer(); tokenizer.Tokenize(directiveNode.ValueNode.Text); var parser = new BindingParser() { Tokens = tokenizer.Tokens }; var result = parser.ReadDirectiveValue(); if (!parser.OnEnd()) directiveNode.AddError($"Unexpected token: {parser.Peek()?.Text}."); return result; } protected virtual IAbstractDirective ProcessImportDirective(DothtmlDirectiveNode directiveNode) { var valueSyntaxRoot = ParseImportDirectiveValue(directiveNode); BindingParserNode? alias = null; BindingParserNode? name = null; if (valueSyntaxRoot is BinaryOperatorBindingParserNode assignment) { alias = assignment.FirstExpression; name = assignment.SecondExpression; } else { name = valueSyntaxRoot; } return treeBuilder.BuildImportDirective(directiveNode, alias, name); } protected virtual IAbstractDirective ProcessServiceInjectDirective(DothtmlDirectiveNode directiveNode) { var valueSyntaxRoot = ParseImportDirectiveValue(directiveNode); if (valueSyntaxRoot is BinaryOperatorBindingParserNode assignment) { var name = assignment.FirstExpression as SimpleNameBindingParserNode; if (name == null) { directiveNode.AddError($"Identifier expected on the left side of the assignment."); name = new SimpleNameBindingParserNode("service"); } var type = assignment.SecondExpression; return treeBuilder.BuildServiceInjectDirective(directiveNode, name, type); } else { directiveNode.AddError($"Assignment operation expected - the correct form is `@{ParserConstants.ServiceInjectDirective} myStringService = ISomeService<string>`"); return treeBuilder.BuildServiceInjectDirective(directiveNode, new SimpleNameBindingParserNode("service"), valueSyntaxRoot); } } protected virtual IAbstractDirective ProcessViewModuleDirective(DothtmlDirectiveNode directiveNode) { return treeBuilder.BuildViewModuleDirective(directiveNode, modulePath: directiveNode.Value, resourceName: directiveNode.Value); } static HashSet<string> treatBindingAsHardCodedValue = new HashSet<string> { "resource" }; private void ProcessAttributeProperties(IAbstractControl control, DothtmlAttributeNode[] nodes, IDataContextStack dataContext) { var doneAttributes = new HashSet<DothtmlAttributeNode>(); string getName(DothtmlAttributeNode n) => n.AttributePrefix == null ? n.AttributeName : n.AttributePrefix + ":" + n.AttributeName; void resolveAttribute(DothtmlAttributeNode attribute) { var name = getName(attribute); if (!doneAttributes.Add(attribute)) return; var property = controlResolver.FindProperty(control.Metadata, name, MappingMode.Attribute); if (property == null) { attribute.AddError($"The control '{control.Metadata.Type}' does not have a property '{attribute.AttributeName}' and does not allow HTML attributes!"); } else { var dependsOn = property.DataContextChangeAttributes.SelectMany(c => c.PropertyDependsOn); foreach (var p in dependsOn.SelectMany(t => nodes.Where(n => t == getName(n)))) resolveAttribute(p); ProcessAttribute(property, attribute, control, dataContext); } } // set properties from attributes foreach (var attr in nodes) { resolveAttribute(attr); } } /// <summary> /// Processes the attribute node. /// </summary> private void ProcessAttribute(IPropertyDescriptor property, DothtmlAttributeNode attribute, IAbstractControl control, IDataContextStack dataContext) { dataContext = GetDataContextChange(dataContext, control, property); if (!property.MarkupOptions.MappingMode.HasFlag(MappingMode.Attribute)) { attribute.AddError($"The property '{property.FullName}' cannot be used as a control attribute!"); return; } // set the property if (attribute.ValueNode == null) { // implicitly set boolean property if (property.PropertyType.IsEqualTo(new ResolvedTypeDescriptor(typeof(bool))) || property.PropertyType.IsEqualTo(new ResolvedTypeDescriptor(typeof(bool?)))) { if (!treeBuilder.AddProperty(control, treeBuilder.BuildPropertyValue(property, BoxingUtils.True, attribute), out var error)) attribute.AddError(error); } else if (property.MarkupOptions.AllowAttributeWithoutValue) { if (!treeBuilder.AddProperty(control, treeBuilder.BuildPropertyValue(property, (property as DotVVM.Framework.Binding.DotvvmProperty)?.DefaultValue, attribute), out var error)) attribute.AddError(error); } else attribute.AddError($"The attribute '{property.Name}' on the control '{control.Metadata.Type.FullName}' must have a value!"); } else if (attribute.ValueNode is DothtmlValueBindingNode valueBindingNode) { // binding var bindingNode = valueBindingNode.BindingNode; if (!treatBindingAsHardCodedValue.Contains(bindingNode.Name)) { if (!property.MarkupOptions.AllowBinding) attribute.ValueNode.AddError($"The property '{ property.FullName }' cannot contain {bindingNode.Name} binding."); } var binding = ProcessBinding(bindingNode, dataContext, property); var bindingProperty = treeBuilder.BuildPropertyBinding(property, binding, attribute); if (!treeBuilder.AddProperty(control, bindingProperty, out var error)) attribute.AddError(error); } else { // hard-coded value in markup if (!property.MarkupOptions.AllowHardCodedValue) { attribute.ValueNode.AddError($"The property '{ property.FullName }' cannot contain hard coded value."); } var textValue = (DothtmlValueTextNode)attribute.ValueNode; var value = ConvertValue(WebUtility.HtmlDecode(textValue.Text), property.PropertyType); var propertyValue = treeBuilder.BuildPropertyValue(property, value, attribute); if (!treeBuilder.AddProperty(control, propertyValue, out var error)) attribute.AddError(error); } } /// <summary> /// Processes the content of the control node. /// </summary> public void ProcessControlContent(IAbstractControl control, IEnumerable<DothtmlNode> nodes) { var content = new List<DothtmlNode>(); bool properties = true; foreach (var node in nodes) { var element = node as DothtmlElementNode; if (element != null && properties) { var property = controlResolver.FindProperty(control.Metadata, element.TagName, MappingMode.InnerElement); if (property != null && string.IsNullOrEmpty(element.TagPrefix) && property.MarkupOptions.MappingMode.HasFlag(MappingMode.InnerElement)) { content.Clear(); if (!treeBuilder.AddProperty(control, ProcessElementProperty(control, property, element.Content, element), out var error)) element.AddError(error); foreach (var attr in element.Attributes) attr.AddError("Attributes can't be set on element property."); } else { content.Add(node); if (node.IsNotEmpty()) { properties = false; } } } else { content.Add(node); } } if (control.Metadata.DefaultContentProperty is IPropertyDescriptor contentProperty) { // don't assign the property, when content is empty if (content.All(c => !c.IsNotEmpty())) return; if (control.HasProperty(contentProperty)) { foreach (var c in content) if (c.IsNotEmpty()) c.AddError($"Property { contentProperty.FullName } was already set."); } else { if (!treeBuilder.AddProperty(control, ProcessElementProperty(control, contentProperty, content, null), out var error)) content.First().AddError(error); } } else { if (!control.Metadata.IsContentAllowed) { foreach (var item in content) { if (item.IsNotEmpty()) { var compositeControlHelp = control.Metadata.Type.IsAssignableTo(new ResolvedTypeDescriptor (typeof(CompositeControl))) ? " CompositeControls don't allow content by default and Content or ContentTemplate property is missing on this control." : ""; item.AddError($"Content not allowed inside {control.Metadata.Type.Name}.{compositeControlHelp}"); } } } else ResolveControlContentImmediately(control, content); } } /// <summary> /// Resolves the content of the control immediately during the parsing. /// Override this method if you need lazy loading of tree node contents. /// </summary> protected virtual void ResolveControlContentImmediately(IAbstractControl control, List<DothtmlNode> content) { var dataContext = GetDataContextChange(control.DataContextTypeStack, control, null); foreach (var node in content) { var child = ProcessNode(control, node, control.Metadata, dataContext); if (child != null) { treeBuilder.AddChildControl(control, child); if (!child.Metadata.Type.IsAssignableTo(ResolvedTypeDescriptor.Create(typeof(DotvvmControl)))) node.AddError($"Content control must inherit from DotvvmControl, but {child.Metadata.Type} doesn't."); } } } /// <summary> /// Processes the element which contains property value. /// </summary> private IAbstractPropertySetter ProcessElementProperty(IAbstractControl control, IPropertyDescriptor property, IEnumerable<DothtmlNode> elementContent, DothtmlElementNode? propertyWrapperElement) { IEnumerable<IAbstractControl> filterByType(ITypeDescriptor type, IEnumerable<IAbstractControl> controls) => FilterOrError(controls, c => c is object && c.Metadata.Type.IsAssignableTo(type), c => { // empty nodes are only filtered, non-empty nodes cause errors if (c.DothtmlNode.IsNotEmpty()) c.DothtmlNode.AddError($"Control type {c.Metadata.Type.FullName} can't be used in collection of type {type.FullName}."); }); // resolve data context var dataContext = control.DataContextTypeStack; dataContext = GetDataContextChange(dataContext, control, property); // the element is a property if (IsTemplateProperty(property)) { // template return treeBuilder.BuildPropertyTemplate(property, ProcessTemplate(control, elementContent, dataContext), propertyWrapperElement); } else if (IsCollectionProperty(property)) { var collectionType = GetCollectionType(property); // collection of elements var collection = elementContent.Select(childObject => ProcessNode(control, childObject, control.Metadata, dataContext)!); if (collectionType != null) { collection = filterByType(collectionType, collection); } return treeBuilder.BuildPropertyControlCollection(property, collection.ToArray(), propertyWrapperElement); } else if (property.PropertyType.IsEqualTo(new ResolvedTypeDescriptor(typeof(string)))) { // string property var strings = FilterNodes<DothtmlLiteralNode>(elementContent, property); var value = string.Concat(strings.Select(s => s.Value)); return treeBuilder.BuildPropertyValue(property, value, propertyWrapperElement); } else if (IsControlProperty(property)) { var children = filterByType(property.PropertyType, elementContent.Select(childObject => ProcessNode(control, childObject, control.Metadata, dataContext)!)).ToArray(); if (children.Length > 1) { // try with the empty nodes are excluded children = children.Where(c => c.DothtmlNode.IsNotEmpty()).ToArray(); if (children.Length > 1) { foreach (var c in children.Skip(1)) c.DothtmlNode!.AddError($"The property '{property.MarkupOptions.Name}' can have only one child element!"); } } if (children.Length >= 1) { return treeBuilder.BuildPropertyControl(property, children[0], propertyWrapperElement); } else { return treeBuilder.BuildPropertyControl(property, null, propertyWrapperElement); } } else { control.DothtmlNode!.AddError($"The property '{property.FullName}' is not supported!"); return treeBuilder.BuildPropertyValue(property, null, propertyWrapperElement); } } /// <summary> /// Processes the template contents. /// </summary> private List<IAbstractControl> ProcessTemplate(IAbstractTreeNode parent, IEnumerable<DothtmlNode> elementContent, IDataContextStack dataContext) { var content = elementContent.Select(e => ProcessNode(parent, e, placeholderMetadata.Value, dataContext)!).Where(e => e != null); return content.ToList(); } protected IEnumerable<T> FilterOrError<T>(IEnumerable<T> controls, Predicate<T> predicate, Action<T> errorAction) { foreach (var item in controls) { if (predicate(item)) yield return item; else errorAction(item); } } /// <summary> /// Gets the inner property elements and makes sure that no other content is present. /// </summary> private IEnumerable<TNode> FilterNodes<TNode>(IEnumerable<DothtmlNode> nodes, IPropertyDescriptor property) where TNode : DothtmlNode { foreach (var child in nodes) { if (child is TNode) { yield return (TNode)child; } else if (child.IsNotEmpty()) { child.AddError($"Content is not allowed inside the property '{property.FullName}'! (Conflicting node: Node {child.GetType().Name})"); } } } /// <summary> /// Resolves the type of the wrapper. /// </summary> private ITypeDescriptor ResolveWrapperType(IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> directives, string fileName) { var wrapperType = GetDefaultWrapperType(fileName); var baseControlDirective = !directives.ContainsKey(ParserConstants.BaseTypeDirective) ? null : (IAbstractBaseTypeDirective?)directives[ParserConstants.BaseTypeDirective].SingleOrDefault(); if (baseControlDirective != null) { var baseType = baseControlDirective.ResolvedType; if (baseType == null) { baseControlDirective.DothtmlNode!.AddError($"The type '{baseControlDirective.Value}' specified in baseType directive was not found!"); } else if (!baseType.IsAssignableTo(new ResolvedTypeDescriptor(typeof(DotvvmMarkupControl)))) { baseControlDirective.DothtmlNode!.AddError("Markup controls must derive from DotvvmMarkupControl class!"); wrapperType = baseType; } else { wrapperType = baseType; } } return wrapperType; } /// <summary> /// Gets the default type of the wrapper for the view. /// </summary> private ITypeDescriptor GetDefaultWrapperType(string fileName) { ITypeDescriptor wrapperType; if (fileName.EndsWith(".dotcontrol", StringComparison.Ordinal)) { wrapperType = new ResolvedTypeDescriptor(typeof(DotvvmMarkupControl)); } else { wrapperType = new ResolvedTypeDescriptor(typeof(DotvvmView)); } return wrapperType; } protected virtual bool IsCollectionProperty(IPropertyDescriptor property) { return property.PropertyType.IsAssignableTo(new ResolvedTypeDescriptor(typeof(ICollection))); } protected virtual ITypeDescriptor? GetCollectionType(IPropertyDescriptor property) { return property.PropertyType.TryGetArrayElementOrIEnumerableType(); } protected virtual bool IsTemplateProperty(IPropertyDescriptor property) { return property.PropertyType.IsAssignableTo(new ResolvedTypeDescriptor(typeof(ITemplate))); } protected virtual bool IsControlProperty(IPropertyDescriptor property) { return property.PropertyType.IsAssignableTo(new ResolvedTypeDescriptor(typeof(DotvvmControl))); } /// <summary> /// Gets the data context change behavior for the specified control property. /// </summary> [return: NotNullIfNotNull("dataContext")] protected virtual IDataContextStack? GetDataContextChange(IDataContextStack dataContext, IAbstractControl control, IPropertyDescriptor? property) { if (dataContext == null) return null; var manipulationAttribute = property != null ? property.DataContextManipulationAttribute : control.Metadata.DataContextManipulationAttribute; if (manipulationAttribute != null) { return manipulationAttribute.ChangeStackForChildren(dataContext, control, property!, (parent, changeType) => CreateDataContextTypeStack(changeType, parentDataContextStack: parent)); } var attributes = property != null ? property.DataContextChangeAttributes : control.Metadata.DataContextChangeAttributes; if (attributes == null || attributes.Length == 0) return dataContext; try { var (type, extensionParameters) = ApplyContextChange(dataContext, attributes, control, property); if (type == null) return dataContext; else return CreateDataContextTypeStack(type, parentDataContextStack: dataContext, extensionParameters: extensionParameters.ToArray()); } catch (Exception exception) { var node = property != null && control.TryGetProperty(property, out var v) ? v.DothtmlNode : control.DothtmlNode; node?.AddError($"Could not compute the type of DataContext: {exception}"); return CreateDataContextTypeStack(null, parentDataContextStack: dataContext); } } public static (ITypeDescriptor? type, List<BindingExtensionParameter> extensionParameters) ApplyContextChange(IDataContextStack dataContext, DataContextChangeAttribute[] attributes, IAbstractControl control, IPropertyDescriptor? property) { var type = dataContext.DataContextType; var extensionParameters = new List<BindingExtensionParameter>(); foreach (var attribute in attributes.OrderBy(a => a.Order)) { if (type == null) break; extensionParameters.AddRange(attribute.GetExtensionParameters(type)); type = attribute.GetChildDataContextType(type, dataContext, control, property); } return (type, extensionParameters); } /// <summary> /// Creates the IControlType identification of the control. /// </summary> protected abstract IControlType CreateControlType(ITypeDescriptor wrapperType, string virtualPath); /// <summary> /// Creates the data context type stack object. /// </summary> protected abstract IDataContextStack CreateDataContextTypeStack(ITypeDescriptor? viewModelType, IDataContextStack? parentDataContextStack = null, IReadOnlyList<NamespaceImport>? imports = null, IReadOnlyList<BindingExtensionParameter>? extensionParameters = null); /// <summary> /// Converts the value to the property type. /// </summary> protected abstract object? ConvertValue(string value, ITypeDescriptor propertyType); /// <summary> /// Compiles the binding. /// </summary> protected abstract IAbstractBinding CompileBinding(DothtmlBindingNode node, BindingParserOptions bindingOptions, IDataContextStack context, IPropertyDescriptor property); } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using Moq; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Auxiliary; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Securities; using QuantConnect.Util; namespace QuantConnect.Tests.Engine.DataFeeds { [TestFixture, Parallelizable(ParallelScope.All)] public class SubscriptionUtilsTests { private Security _security; private SubscriptionDataConfig _config; private IFactorFileProvider _factorFileProvider; [SetUp] public void SetUp() { _security = new Security(Symbols.SPY, SecurityExchangeHours.AlwaysOpen(TimeZones.Utc), new Cash(Currencies.USD, 0, 0), SymbolProperties.GetDefault(Currencies.USD), new IdentityCurrencyConverter(Currencies.USD), RegisteredSecurityDataTypesProvider.Null, new SecurityCache()); _config = new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork, true, true, false); _factorFileProvider = TestGlobals.FactorFileProvider; } [Test] public void SubscriptionIsDisposed() { var dataPoints = 10; var enumerator = new TestDataEnumerator { MoveNextTrueCount = dataPoints }; var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, DateTime.UtcNow, Time.EndOfTime ), enumerator, _factorFileProvider, false); var count = 0; while (enumerator.MoveNextTrueCount > 8) { if (count++ > 100) { Assert.Fail($"Timeout waiting for producer. {enumerator.MoveNextTrueCount}"); } Thread.Sleep(1); } subscription.DisposeSafely(); Assert.IsFalse(subscription.MoveNext()); } [Test] public void ThrowingEnumeratorStackDisposesOfSubscription() { var enumerator = new TestDataEnumerator { MoveNextTrueCount = 10, ThrowException = true}; var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, DateTime.UtcNow, Time.EndOfTime ), enumerator, _factorFileProvider, false); var count = 0; while (enumerator.MoveNextTrueCount != 9) { if (count++ > 100) { Assert.Fail("Timeout waiting for producer"); } Thread.Sleep(1); } Assert.IsFalse(subscription.MoveNext()); Assert.IsTrue(subscription.EndOfStream); // enumerator is disposed by the producer count = 0; while (!enumerator.Disposed) { if (count++ > 100) { Assert.Fail("Timeout waiting for producer"); } Thread.Sleep(1); } } [Test] // This unit tests reproduces GH 3885 where the consumer hanged forever public void ConsumerDoesNotHang() { for (var i = 0; i < 10000; i++) { var dataPoints = 10; var enumerator = new TestDataEnumerator {MoveNextTrueCount = dataPoints}; var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, DateTime.UtcNow, Time.EndOfTime ), enumerator, _factorFileProvider, false); for (var j = 0; j < dataPoints; j++) { Assert.IsTrue(subscription.MoveNext()); } Assert.IsFalse(subscription.MoveNext()); subscription.DisposeSafely(); } } [Test] public void PriceScaleFirstFillForwardBar() { var referenceTime = new DateTime(2020, 08, 06); var point = new Tick(referenceTime, Symbols.SPY, 1, 2); var point2 = point.Clone(true); point2.Time = referenceTime; var point3 = point.Clone(false); point3.Time = referenceTime.AddDays(1); ; var enumerator = new List<BaseData> { point2, point3 }.GetEnumerator(); var factorFileProfider = new Mock<IFactorFileProvider>(); var factorFile = new CorporateFactorProvider(_security.Symbol.Value, new[] { new CorporateFactorRow(referenceTime, 0.5m, 1), new CorporateFactorRow(referenceTime.AddDays(1), 1m, 1) }, referenceTime); factorFileProfider.Setup(s => s.Get(It.IsAny<Symbol>())).Returns(factorFile); var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, referenceTime, Time.EndOfTime ), enumerator, factorFileProfider.Object, true); Assert.IsTrue(subscription.MoveNext()); // we do expect it to pick up the prev factor file scale Assert.AreEqual(1, (subscription.Current.Data as Tick).AskPrice); Assert.IsTrue((subscription.Current.Data as Tick).IsFillForward); Assert.IsTrue(subscription.MoveNext()); Assert.AreEqual(2, (subscription.Current.Data as Tick).AskPrice); Assert.IsFalse((subscription.Current.Data as Tick).IsFillForward); subscription.DisposeSafely(); } [Test] public void PriceScaleDoesNotUpdateForFillForwardBar() { var referenceTime = new DateTime(2020, 08, 06); var point = new Tick(referenceTime, Symbols.SPY, 1, 2); var point2 = point.Clone(true); point2.Time = referenceTime.AddDays(1); var point3 = point.Clone(false); point3.Time = referenceTime.AddDays(2); ; var enumerator = new List<BaseData> { point, point2, point3 }.GetEnumerator(); var factorFileProfider = new Mock<IFactorFileProvider>(); var factorFile = new CorporateFactorProvider(_security.Symbol.Value, new[] { new CorporateFactorRow(referenceTime, 0.5m, 1), new CorporateFactorRow(referenceTime.AddDays(1), 1m, 1) }, referenceTime); factorFileProfider.Setup(s => s.Get(It.IsAny<Symbol>())).Returns(factorFile); var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, referenceTime, Time.EndOfTime ), enumerator, factorFileProfider.Object, true); Assert.IsTrue(subscription.MoveNext()); Assert.AreEqual(1, (subscription.Current.Data as Tick).AskPrice); Assert.IsFalse((subscription.Current.Data as Tick).IsFillForward); Assert.IsTrue(subscription.MoveNext()); Assert.AreEqual(1, (subscription.Current.Data as Tick).AskPrice); Assert.IsTrue((subscription.Current.Data as Tick).IsFillForward); Assert.IsTrue(subscription.MoveNext()); Assert.AreEqual(2, (subscription.Current.Data as Tick).AskPrice); Assert.IsFalse((subscription.Current.Data as Tick).IsFillForward); subscription.DisposeSafely(); } [TestCase(typeof(TradeBar), true)] [TestCase(typeof(OpenInterest), false)] [TestCase(typeof(QuoteBar), false)] public void SubscriptionEmitsAuxData(Type typeOfConfig, bool shouldReceiveAuxData) { var config = new SubscriptionDataConfig(typeOfConfig, _security.Symbol, Resolution.Hour, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var totalPoints = 8; var time = new DateTime(2010, 1, 1); var enumerator = Enumerable.Range(0, totalPoints).Select(x => new Delisting { Time = time.AddHours(x) }).GetEnumerator(); var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, config, DateTime.UtcNow, Time.EndOfTime ), enumerator, _factorFileProvider, false); // Test our subscription stream to see if it emits the aux data it should be filtered // by the SubscriptionUtils produce function if the config isn't for a TradeBar int dataReceivedCount = 0; while (subscription.MoveNext()) { dataReceivedCount++; if (subscription.Current != null && subscription.Current.Data.DataType == MarketDataType.Auxiliary) { Assert.IsTrue(shouldReceiveAuxData); } } // If it should receive aux data it should have emitted all points // otherwise none should have been emitted if (shouldReceiveAuxData) { Assert.AreEqual(totalPoints, dataReceivedCount); } else { Assert.AreEqual(0, dataReceivedCount); } } private class TestDataEnumerator : IEnumerator<BaseData> { public bool ThrowException { get; set; } public bool Disposed { get; set; } public int MoveNextTrueCount { get; set; } public void Dispose() { Disposed = true; } public bool MoveNext() { Current = new Tick(DateTime.UtcNow,Symbols.SPY, 1, 2); var result = --MoveNextTrueCount >= 0; if (ThrowException) { throw new Exception("TestDataEnumerator.MoveNext()"); } return result; } public void Reset() { } public BaseData Current { get; set; } object IEnumerator.Current => Current; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Locality.Areas.HelpPage.ModelDescriptions; using Locality.Areas.HelpPage.Models; namespace Locality.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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.Globalization; using System.Runtime.CompilerServices; /// <summary> /// Convert.ToString(System.Int64,System.Int32) /// </summary> public class ConvertToString21 { public static int Main() { ConvertToString21 testObj = new ConvertToString21(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Int64,System.Int32)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify value is -123 and radix is 2,8,10 or 16... "; string c_TEST_ID = "P001"; Int64 int64Value = -123; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "1111111111111111111111111111111111111111111111111111111110000101"; radix = 2; String resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "1777777777777777777605"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "-123"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "ffffffffffffff85"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify value is Int64.MaxValue and radix is 2,8,10 or 16... "; string c_TEST_ID = "P002"; Int64 int64Value = Int64.MaxValue; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "111111111111111111111111111111111111111111111111111111111111111"; radix = 2; String resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "777777777777777777777"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "9223372036854775807"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "7fffffffffffffff"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify value is Int64.MinValue and radix is 2,8,10 or 16... "; string c_TEST_ID = "P003"; Int64 int64Value = Int64.MinValue; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "1000000000000000000000000000000000000000000000000000000000000000"; radix = 2; String resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "1000000000000000000000"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "-9223372036854775808"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "8000000000000000"; errorDesc = ""; resValue = Convert.ToString(int64Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int64Value, radix); TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("015", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region NegativeTesting public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: the radix is 32..."; const string c_TEST_ID = "N001"; Int32 int32Value = TestLibrary.Generator.GetInt32(-55); int radix = 32; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToString(int32Value, radix); TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected ." + DataString(int32Value, radix)); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + DataString(int32Value, radix)); retVal = false; } return retVal; } #endregion #region Help Methods private string DataString(Int64 int64Value, int radix) { string str; str = string.Format("\n[int64Value value]\n \"{0}\"", int64Value); str += string.Format("\n[radix value ]\n {0}", radix); return str; } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for PagingOperations. /// </summary> public static partial class PagingOperationsExtensions { /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetSinglePages(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetSinglePagesAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetSinglePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> public static IPage<Product> GetMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions)) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesAsync(clientRequestId, pagingGetMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that includes a nextLink in odata format that has 10 /// pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> public static IPage<Product> GetOdataMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions)) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetOdataMultiplePagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink in odata format that has 10 /// pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetOdataMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOdataMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pagingGetMultiplePagesWithOffsetOptions'> /// Additional parameters for the operation /// </param> /// <param name='clientRequestId'> /// </param> public static IPage<Product> GetMultiplePagesWithOffset(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string)) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesWithOffsetAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pagingGetMultiplePagesWithOffsetOptions'> /// Additional parameters for the operation /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesWithOffsetAsync(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesWithOffsetWithHttpMessagesAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePagesRetryFirst(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesRetryFirstAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesRetryFirstWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which the /// 2nd call fails first with 500. The client should retry and finish all 10 /// pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePagesRetrySecond(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which the /// 2nd call fails first with 500. The client should retry and finish all 10 /// pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesRetrySecondAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesRetrySecondWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetSinglePagesFailure(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetSinglePagesFailureAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetSinglePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePagesFailure(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesFailureAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePagesFailureUri(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesFailureUriAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesFailureUriWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> public static IPage<Product> GetMultiplePagesFragmentNextLink(this IPagingOperations operations, string apiVersion, string tenant) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFragmentNextLinkAsync(apiVersion, tenant), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesFragmentNextLinkAsync(this IPagingOperations operations, string apiVersion, string tenant, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesFragmentNextLinkWithHttpMessagesAsync(apiVersion, tenant, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that doesn't return a full URL, just a fragment with /// parameters grouped /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> public static IPage<Product> GetMultiplePagesFragmentWithGroupingNextLink(this IPagingOperations operations, CustomParameterGroup customParameterGroup) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFragmentWithGroupingNextLinkAsync(customParameterGroup), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that doesn't return a full URL, just a fragment with /// parameters grouped /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesFragmentWithGroupingNextLinkAsync(this IPagingOperations operations, CustomParameterGroup customParameterGroup, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesFragmentWithGroupingNextLinkWithHttpMessagesAsync(customParameterGroup, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='nextLink'> /// Next link for list operation. /// </param> public static IPage<Product> NextFragment(this IPagingOperations operations, string apiVersion, string tenant, string nextLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).NextFragmentAsync(apiVersion, tenant, nextLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> NextFragmentAsync(this IPagingOperations operations, string apiVersion, string tenant, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.NextFragmentWithHttpMessagesAsync(apiVersion, tenant, nextLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> public static IPage<Product> NextFragmentWithGrouping(this IPagingOperations operations, string nextLink, CustomParameterGroup customParameterGroup) { return Task.Factory.StartNew(s => ((IPagingOperations)s).NextFragmentWithGroupingAsync(nextLink, customParameterGroup), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> NextFragmentWithGroupingAsync(this IPagingOperations operations, string nextLink, CustomParameterGroup customParameterGroup, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.NextFragmentWithGroupingWithHttpMessagesAsync(nextLink, customParameterGroup, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Product> GetSinglePagesNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetSinglePagesNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetSinglePagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> public static IPage<Product> GetMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions)) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that includes a nextLink in odata format that has 10 /// pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> public static IPage<Product> GetOdataMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions)) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetOdataMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink in odata format that has 10 /// pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetOdataMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOdataMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesWithOffsetNextOptions'> /// Additional parameters for the operation /// </param> public static IPage<Product> GetMultiplePagesWithOffsetNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions)) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesWithOffsetNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesWithOffsetNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesWithOffsetNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Product> GetMultiplePagesRetryFirstNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesRetryFirstNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which the /// 2nd call fails first with 500. The client should retry and finish all 10 /// pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Product> GetMultiplePagesRetrySecondNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which the /// 2nd call fails first with 500. The client should retry and finish all 10 /// pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesRetrySecondNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Product> GetSinglePagesFailureNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetSinglePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetSinglePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Product> GetMultiplePagesFailureNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Product> GetMultiplePagesFailureUriNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesFailureUriNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetMultiplePagesFailureUriNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Ported from mt19937-64.c, which contains this copyright header: /* Copyright (C) 2004, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Numerics; using System.Runtime.InteropServices; namespace AirBreather.Random { public struct MT19937_64State : IEquatable<MT19937_64State>, IRandomGeneratorState { internal ulong[] data; internal int idx; public MT19937_64State(ulong seed) { this.data = new ulong[312]; this.data[0] = seed; for (int i = 1; i < 312; ++i) { ulong prev = this.data[i - 1]; this.data[i] = unchecked((6364136223846793005 * (prev ^ (prev >> 62))) + (ulong)i); } this.idx = 312; } public MT19937_64State(MT19937_64State copyFrom) { this.idx = copyFrom.idx; if (copyFrom.data == null) { this.data = null; } else { this.data = new ulong[312]; copyFrom.data.CopyTo(this.data); } } // TODO: our cousins in other languages allow seeding by multiple input values... support that too. public bool IsValid => StateIsValid(this); private static bool StateIsValid(MT19937_64State state) { if (state.data == null) { return false; } if (!state.idx.IsInRange(0, 313)) { return false; } int end = 312 - (312 % Vector<ulong>.Count); Vector<ulong> accumulatorVector = Vector<ulong>.Zero; for (int i = 0; i < end; i += Vector<ulong>.Count) { accumulatorVector |= new Vector<ulong>(state.data, i); } ulong accumulator = 0; for (int i = end; i < 312; ++i) { accumulator |= state.data[i]; } for (int i = 0; i < Vector<ulong>.Count; ++i) { accumulator |= accumulatorVector[i]; } return accumulator != 0; } public static bool Equals(MT19937_64State first, MT19937_64State second) { if (first.idx != second.idx) { return false; } bool firstIsDefault = first.data == null; bool secondIsDefault = second.data == null; if (firstIsDefault != secondIsDefault) { return false; } if (firstIsDefault) { return true; } int end = 312 - (312 % Vector<ulong>.Count); Vector<ulong> accumulatorVector = Vector<ulong>.Zero; for (int i = 0; i < end; i += Vector<ulong>.Count) { accumulatorVector |= (new Vector<ulong>(first.data, i) ^ new Vector<ulong>(second.data, i)); } ulong accumulator = 0; for (int i = end; i < 312; ++i) { accumulator |= (first.data[i] ^ second.data[i]); } for (int i = 0; i < Vector<ulong>.Count; ++i) { accumulator |= accumulatorVector[i]; } return accumulator == 0; } public static int GetHashCode(MT19937_64State state) { int hashCode = HashCode.Seed; hashCode = hashCode.HashWith(state.idx); if (state.data == null) { return hashCode; } int end = 312 - (312 % Vector<ulong>.Count); Vector<ulong> accumulatorVector = Vector<ulong>.Zero; for (int i = 0; i < end; i += Vector<ulong>.Count) { accumulatorVector ^= new Vector<ulong>(state.data, i); } ulong accumulator = 0; for (int i = end; i < 312; ++i) { accumulator ^= state.data[i]; } for (int i = 0; i < Vector<ulong>.Count; ++i) { accumulator ^= accumulatorVector[i]; } return hashCode.HashWith(accumulator); } public static bool operator ==(MT19937_64State first, MT19937_64State second) => Equals(first, second); public static bool operator !=(MT19937_64State first, MT19937_64State second) => !Equals(first, second); public override bool Equals(object obj) => obj is MT19937_64State && Equals(this, (MT19937_64State)obj); public bool Equals(MT19937_64State other) => Equals(this, other); public override int GetHashCode() => GetHashCode(this); public override string ToString() => $"{nameof(MT19937_64State)}[]"; } public sealed class MT19937_64Generator : IRandomGenerator<MT19937_64State> { /// <summary> /// The size of each "chunk" of bytes that can be generated at a time. /// </summary> public static readonly int ChunkSize = sizeof(ulong); /// <inheritdoc /> [ExcludeFromCodeCoverage] int IRandomGenerator<MT19937_64State>.ChunkSize => ChunkSize; /// <inheritdoc /> public unsafe MT19937_64State FillBuffer(MT19937_64State state, Span<byte> buffer) { if (buffer.Length % ChunkSize != 0) { throw new ArgumentException("Length must be a multiple of ChunkSize.", nameof(buffer)); } if (!state.IsValid) { throw new ArgumentException("State is not valid; use the parameterized constructor to initialize a new instance with the given seed values.", nameof(state)); } state = new MT19937_64State(state); fixed (ulong* fData = state.data) fixed (byte* fbuf = &MemoryMarshal.GetReference(buffer)) { // count has already been validated to be a multiple of ChunkSize, // and we assume index is OK too, so we can do this fanciness without fear. for (ulong* pbuf = (ulong*)fbuf, pend = pbuf + (buffer.Length / ChunkSize); pbuf < pend; ++pbuf) { if (state.idx == 312) { Twist(fData); state.idx = 0; } ulong x = fData[state.idx++]; x ^= (x >> 29) & 0x5555555555555555; x ^= (x << 17) & 0x71D67FFFEDA60000; x ^= (x << 37) & 0xFFF7EEE000000000; x ^= (x >> 43); *pbuf = x; } } return state; } private static unsafe void Twist(ulong* vals) { const ulong Upper33 = 0xFFFFFFFF80000000; const ulong Lower31 = 0x000000007FFFFFFF; for (int curr = 0; curr < 312; ++curr) { int near = (curr + 1) % 312; int far = (curr + 156) % 312; ulong x = vals[curr] & Upper33; ulong y = vals[near] & Lower31; ulong z = vals[far] ^ ((x | y) >> 1); vals[curr] = z ^ ((y & 1) * 0xB5026F5AA96619E9); } } } }
using UnityEngine; namespace UnitySampleAssets.Vehicles.Car { [RequireComponent(typeof (CarController))] public class CarAIControl : MonoBehaviour { // This script provides input to the car controller in the same way that the user control script does. // As such, it is really 'driving' the car, with no special physics or animation tricks to make the car behave properly. // "wandering" is used to give the cars a more human, less robotic feel. They can waver slightly // in speed and direction while driving towards their target. [SerializeField] [Range(0, 1)] private float cautiousSpeedFactor = 0.05f;// percentage of max speed to use when being maximally cautious [SerializeField] [Range(0, 180)] private float cautiousMaxAngle = 50f;// angle of approaching corner to treat as warranting maximum caution [SerializeField] private float cautiousMaxDistance = 100f;// distance at which distance-based cautiousness begins [SerializeField] private float cautiousAngularVelocityFactor = 30f;// how cautious the AI should be when considering its own current angular velocity (i.e. easing off acceleration if spinning!) [SerializeField] private float steerSensitivity = 0.05f;// how sensitively the AI uses steering input to turn to the desired direction [SerializeField] private float accelSensitivity = 0.04f;// How sensitively the AI uses the accelerator to reach the current desired speed [SerializeField] private float brakeSensitivity = 1f;// How sensitively the AI uses the brake to reach the current desired speed [SerializeField] private float lateralWanderDistance = 3f;// how far the car will wander laterally towards its target [SerializeField] private float lateralWanderSpeed = 0.1f; // how fast the lateral wandering will fluctuate [SerializeField] [Range(0, 1)] public float accelWanderAmount = 0.1f;// how much the cars acceleration will wander [SerializeField] private float accelWanderSpeed = 0.1f;// how fast the cars acceleration wandering will fluctuate [SerializeField] private BrakeCondition brakeCondition = BrakeCondition.TargetDistance;// what should the AI consider when accelerating/braking? [SerializeField] private bool driving = false; // whether the AI is currently actively driving or stopped. [SerializeField] private Transform target; // 'target' the target object to aim for. [SerializeField] private bool stopWhenTargetReached; // should we stop driving when we reach the target? [SerializeField] private float reachTargetThreshold = 2;// proximity to target to consider we 'reached' it, and stop driving. public enum BrakeCondition { NeverBrake,// the car simply accelerates at full throttle all the time. TargetDirectionDifference,// the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners. TargetDistance,// the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to // head for a stationary target and come to rest when it arrives there. } private float randomPerlin;// A random value for the car to base its wander on (so that AI cars don't all wander in the same pattern) private CarController carController; // Reference to actual car controller we are controlling // if this AI car collides with another car, it can take evasive action for a short duration: private float avoidOtherCarTime; // time until which to avoid the car we recently collided with private float avoidOtherCarSlowdown; // how much to slow down due to colliding with another car, whilst avoiding private float avoidPathOffset;// direction (-1 or 1) in which to offset path to avoid other car, whilst avoiding private void Awake() { // get the car controller reference carController = GetComponent<CarController>(); // give the random perlin a random value randomPerlin = Random.value*100; } private void FixedUpdate() { if (target == null || !driving) { // Car should not be moving, // (so use accel/brake to get to zero speed) float accel = Mathf.Clamp(-carController.CurrentSpeed, -1, 1); carController.Move(0, accel); } else { Vector3 fwd = transform.forward; if (rigidbody.velocity.magnitude > carController.MaxSpeed*0.1f) { fwd = rigidbody.velocity; } float desiredSpeed = carController.MaxSpeed; // now it's time to decide if we should be slowing down... switch (brakeCondition) { case BrakeCondition.TargetDirectionDifference: { // the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners. // check out the angle of our target compared to the current direction of the car float approachingCornerAngle = Vector3.Angle(target.forward, fwd); // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle float spinningAngle = rigidbody.angularVelocity.magnitude*cautiousAngularVelocityFactor; // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount float cautiousnessRequired = Mathf.InverseLerp(0, cautiousMaxAngle, Mathf.Max(spinningAngle, approachingCornerAngle)); desiredSpeed = Mathf.Lerp(carController.MaxSpeed, carController.MaxSpeed*cautiousSpeedFactor, cautiousnessRequired); break; } case BrakeCondition.TargetDistance: { // the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to // head for a stationary target and come to rest when it arrives there. // check out the distance to target Vector3 delta = target.position - transform.position; float distanceCautiousFactor = Mathf.InverseLerp(cautiousMaxDistance, 0, delta.magnitude); // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle float spinningAngle = rigidbody.angularVelocity.magnitude*cautiousAngularVelocityFactor; // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount float cautiousnessRequired = Mathf.Max( Mathf.InverseLerp(0, cautiousMaxAngle, spinningAngle), distanceCautiousFactor); desiredSpeed = Mathf.Lerp(carController.MaxSpeed, carController.MaxSpeed*cautiousSpeedFactor, cautiousnessRequired); break; } case BrakeCondition.NeverBrake: break; // blarg! } // Evasive action due to collision with other cars: // our target position starts off as the 'real' target position Vector3 offsetTargetPos = target.position; // if are we currently taking evasive action to prevent being stuck against another car: if (Time.time < avoidOtherCarTime) { // slow down if necessary (if we were behind the other car when collision occured) desiredSpeed *= avoidOtherCarSlowdown; // and veer towards the side of our path-to-target that is away from the other car offsetTargetPos += target.right*avoidPathOffset; } else { // no need for evasive action, we can just wander across the path-to-target in a random way, // which can help prevent AI from seeming too uniform and robotic in their driving offsetTargetPos += target.right* (Mathf.PerlinNoise(Time.time*lateralWanderSpeed, randomPerlin)*2 - 1)* lateralWanderDistance; } // use different sensitivity depending on whether accelerating or braking: float accelBrakeSensitivity = (desiredSpeed < carController.CurrentSpeed) ? brakeSensitivity : accelSensitivity; // decide the actual amount of accel/brake input to achieve desired speed. float accel = Mathf.Clamp((desiredSpeed - carController.CurrentSpeed)*accelBrakeSensitivity, -1, 1); // add acceleration 'wander', which also prevents AI from seeming too uniform and robotic in their driving // i.e. increasing the accel wander amount can introduce jostling and bumps between AI cars in a race accel *= (1 - accelWanderAmount) + (Mathf.PerlinNoise(Time.time*accelWanderSpeed, randomPerlin)*accelWanderAmount); // calculate the local-relative position of the target, to steer towards Vector3 localTarget = transform.InverseTransformPoint(offsetTargetPos); // work out the local angle towards the target float targetAngle = Mathf.Atan2(localTarget.x, localTarget.z)*Mathf.Rad2Deg; // get the amount of steering needed to aim the car towards the target float steer = Mathf.Clamp(targetAngle*steerSensitivity, -1, 1)*Mathf.Sign(carController.CurrentSpeed); // feed input to the car controller. carController.Move(steer, accel); // if appropriate, stop driving when we're close enough to the target. if (stopWhenTargetReached && localTarget.magnitude < reachTargetThreshold) { driving = false; } } } private void OnCollisionStay(Collision col) { // detect collision against other cars, so that we can take evasive action if (col.rigidbody != null) { var otherAI = col.rigidbody.GetComponent<CarAIControl>(); if (otherAI != null) { // we'll take evasive action for 1 second avoidOtherCarTime = Time.time + 1; // but who's in front?... if (Vector3.Angle(transform.forward, otherAI.transform.position - transform.position) < 90) { // the other ai is in front, so it is only good manners that we ought to brake... avoidOtherCarSlowdown = 0.5f; } else { // we're in front! ain't slowing down for anybody... avoidOtherCarSlowdown = 1; } // both cars should take evasive action by driving along an offset from the path centre, // away from the other car var otherCarLocalDelta = transform.InverseTransformPoint(otherAI.transform.position); float otherCarAngle = Mathf.Atan2(otherCarLocalDelta.x, otherCarLocalDelta.z); avoidPathOffset = lateralWanderDistance*-Mathf.Sign(otherCarAngle); } } } public void SetTarget(Transform target) { this.target = target; driving = true; } } }
// 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.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Navigation; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.Log; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text.Differencing; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PreviewPane { internal partial class PreviewPane : UserControl, IDisposable { private static readonly string s_dummyThreeLineTitle = 'A' + Environment.NewLine + 'A' + Environment.NewLine + 'A'; private static readonly Size s_infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity); private readonly string _errorId; private readonly bool _telemetry; private readonly IServiceProvider _serviceProvider; private bool _isExpanded; private double _heightForThreeLineTitle; private IWpfDifferenceViewer _previewDiffViewer; public PreviewPane(Image severityIcon, string id, string title, string helpMessage, string description, string helpLink, bool telemetry, object previewContent, IServiceProvider serviceProvider) { InitializeComponent(); InitializeHyperlinkStyles(); if ((severityIcon != null) && !string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(title)) { HeaderStackPanel.Visibility = Visibility.Visible; SeverityIconBorder.Child = severityIcon; // Set the initial title text to three lines worth so that we can measure the pixel height // that WPF requires to render three lines of text under the current font and DPI settings. TitleRun.Text = s_dummyThreeLineTitle; TitleTextBlock.Measure(availableSize: s_infiniteSize); _heightForThreeLineTitle = TitleTextBlock.DesiredSize.Height; // Now set the actual title text. TitleRun.Text = title; Uri helpUri; if (BrowserHelper.TryGetUri(helpLink, out helpUri)) { InitializeDiagnosticIdHyperLink(id, helpUri, bingLink: false); } else { InitializeDiagnosticIdHyperLink(id, BrowserHelper.CreateBingQueryUri(id, helpMessage), bingLink: true); } if (!string.IsNullOrWhiteSpace(description)) { DescriptionParagraph.Inlines.Add(description); } } InitializePreviewElement(previewContent); _serviceProvider = serviceProvider; _errorId = id; // save permission whether we are allowed to save data as it is or not. _telemetry = telemetry; } private void InitializePreviewElement(object previewContent) { FrameworkElement previewElement = null; if (previewContent is IWpfDifferenceViewer) { _previewDiffViewer = previewContent as IWpfDifferenceViewer; previewElement = _previewDiffViewer.VisualElement; PreviewDockPanel.Background = _previewDiffViewer.InlineView.Background; } else if (previewContent is string) { previewElement = GetPreviewForString(previewContent as string); } else if (previewContent is FrameworkElement) { previewElement = previewContent as FrameworkElement; } if (previewElement != null) { HeaderSeparator.Visibility = Visibility.Visible; PreviewDockPanel.Visibility = Visibility.Visible; PreviewScrollViewer.Content = previewElement; previewElement.VerticalAlignment = VerticalAlignment.Top; previewElement.HorizontalAlignment = HorizontalAlignment.Left; } // 1. Width of the header section should not exceed the width of the preview content. // In other words, the text we put in the header at the top of the preview pane // should not cause the preview pane itself to grow wider than the width required to // display the preview content at the bottom of the pane. // 2. Adjust the height of the header section so that it displays only three lines worth // by default. AdjustWidthAndHeight(previewElement); } private void InitializeHyperlinkStyles() { this.IdHyperlink.SetVSHyperLinkStyle(); this.LearnMoreHyperlink.SetVSHyperLinkStyle(); } private void InitializeDiagnosticIdHyperLink(string id, Uri helpUri, bool bingLink) { IdHyperlink.Inlines.Add(id); IdHyperlink.NavigateUri = helpUri; IdHyperlink.IsEnabled = true; LearnMoreHyperlink.Inlines.Add(string.Format(ServicesVSResources.LearnMoreLinkText, id)); LearnMoreHyperlink.NavigateUri = helpUri; } public static Border GetPreviewForString(string previewContent, bool useItalicFontStyle = false, bool centerAlignTextHorizontally = false) { var textBlock = new TextBlock() { Margin = new Thickness(5), VerticalAlignment = VerticalAlignment.Center, Text = previewContent, TextWrapping = TextWrapping.Wrap, }; if (useItalicFontStyle) { textBlock.FontStyle = FontStyles.Italic; } if (centerAlignTextHorizontally) { textBlock.TextAlignment = TextAlignment.Center; } var preview = new Border() { Width = 400, MinHeight = 75, Child = textBlock }; return preview; } // This method adjusts the width of the header section to match that of the preview content // thereby ensuring that the preview pane itself is never wider than the preview content. // This method also adjusts the height of the header section so that it displays only three lines // worth by default. private void AdjustWidthAndHeight(FrameworkElement previewElement) { var headerStackPanelWidth = double.PositiveInfinity; var titleTextBlockHeight = double.PositiveInfinity; if (previewElement == null) { HeaderStackPanel.Measure(availableSize: s_infiniteSize); headerStackPanelWidth = HeaderStackPanel.DesiredSize.Width; TitleTextBlock.Measure(availableSize: s_infiniteSize); titleTextBlockHeight = TitleTextBlock.DesiredSize.Height; } else { PreviewDockPanel.Measure(availableSize: new Size(previewElement.Width, double.PositiveInfinity)); headerStackPanelWidth = PreviewDockPanel.DesiredSize.Width; if (IsNormal(headerStackPanelWidth)) { TitleTextBlock.Measure(availableSize: new Size(headerStackPanelWidth, double.PositiveInfinity)); titleTextBlockHeight = TitleTextBlock.DesiredSize.Height; } } if (IsNormal(headerStackPanelWidth)) { HeaderStackPanel.Width = headerStackPanelWidth; } // If the pixel height required to render the complete title in the // TextBlock is larger than that required to render three lines worth, // then trim the contents of the TextBlock with an ellipsis at the end and // display the expander button that will allow users to view the full text. if (HasDescription || (IsNormal(titleTextBlockHeight) && (titleTextBlockHeight > _heightForThreeLineTitle))) { TitleTextBlock.MaxHeight = _heightForThreeLineTitle; TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis; ExpanderToggleButton.Visibility = Visibility.Visible; if (_isExpanded) { ExpanderToggleButton.IsChecked = true; } } } private static bool IsNormal(double size) { return size > 0 && !double.IsNaN(size) && !double.IsInfinity(size); } private bool HasDescription { get { return DescriptionParagraph.Inlines.Count > 0; } } #region IDisposable Implementation private bool _disposedValue = false; // VS editor will call Dispose at which point we should Close() the embedded IWpfDifferenceViewer. protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing && (_previewDiffViewer != null) && !_previewDiffViewer.IsClosed) { _previewDiffViewer.Close(); } } _disposedValue = true; } void IDisposable.Dispose() { Dispose(true); } #endregion private void LearnMoreHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { if (e.Uri == null) { return; } BrowserHelper.StartBrowser(_serviceProvider, e.Uri); e.Handled = true; var hyperlink = sender as Hyperlink; if (hyperlink == null) { return; } DiagnosticLogger.LogHyperlink(hyperlink.Name ?? "Preview", _errorId, HasDescription, _telemetry, e.Uri.AbsoluteUri); } private void ExpanderToggleButton_CheckedChanged(object sender, RoutedEventArgs e) { if (ExpanderToggleButton.IsChecked ?? false) { TitleTextBlock.MaxHeight = double.PositiveInfinity; TitleTextBlock.TextTrimming = TextTrimming.None; if (HasDescription) { DescriptionDockPanel.Visibility = Visibility.Visible; if (LearnMoreHyperlink.NavigateUri != null) { LearnMoreTextBlock.Visibility = Visibility.Visible; LearnMoreHyperlink.IsEnabled = true; } } _isExpanded = true; } else { TitleTextBlock.MaxHeight = _heightForThreeLineTitle; TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis; DescriptionDockPanel.Visibility = Visibility.Collapsed; _isExpanded = 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. // namespace System.Reflection.Emit { using System; using System.Collections.Generic; using CultureInfo = System.Globalization.CultureInfo; using System.Reflection; using System.Security; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; public sealed class DynamicMethod : MethodInfo { private RuntimeType[] m_parameterTypes; internal IRuntimeMethodInfo m_methodHandle; private RuntimeType m_returnType; private DynamicILGenerator m_ilGenerator; private DynamicILInfo m_DynamicILInfo; private bool m_fInitLocals; private RuntimeModule m_module; internal bool m_skipVisibility; internal RuntimeType m_typeOwner; // can be null // We want the creator of the DynamicMethod to control who has access to the // DynamicMethod (just like we do for delegates). However, a user can get to // the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc. // If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would // not be able to bound access to the DynamicMethod. Hence, we need to ensure that // we do not allow direct use of RTDynamicMethod. private RTDynamicMethod m_dynMethod; // needed to keep the object alive during jitting // assigned by the DynamicResolver ctor internal DynamicResolver m_resolver; internal bool m_restrictedSkipVisibility; // The context when the method was created. We use this to do the RestrictedMemberAccess checks. // These checks are done when the method is compiled. This can happen at an arbitrary time, // when CreateDelegate or Invoke is called, or when another DynamicMethod executes OpCodes.Call. // We capture the creation context so that we can do the checks against the same context, // irrespective of when the method gets compiled. Note that the DynamicMethod does not know when // it is ready for use since there is not API which indictates that IL generation has completed. private static volatile InternalModuleBuilder s_anonymouslyHostedDynamicMethodsModule; private static readonly object s_anonymouslyHostedDynamicMethodsModuleLock = new object(); // // class initialization (ctor and init) // private DynamicMethod() { } public DynamicMethod(string name, Type returnType, Type[] parameterTypes) { Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, // owner null, // m false, // skipVisibility true); } public DynamicMethod(string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility) { Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, // owner null, // m restrictedSkipVisibility, true); } public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Module m) { if (m == null) throw new ArgumentNullException(nameof(m)); Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, // owner m, // m false, // skipVisibility false); } public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) { if (m == null) throw new ArgumentNullException(nameof(m)); Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, // owner m, // m skipVisibility, false); } public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) { if (m == null) throw new ArgumentNullException(nameof(m)); Init(name, attributes, callingConvention, returnType, parameterTypes, null, // owner m, // m skipVisibility, false); } public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) { if (owner == null) throw new ArgumentNullException(nameof(owner)); Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, // owner null, // m false, // skipVisibility false); } public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) { if (owner == null) throw new ArgumentNullException(nameof(owner)); Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, // owner null, // m skipVisibility, false); } public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) { if (owner == null) throw new ArgumentNullException(nameof(owner)); Init(name, attributes, callingConvention, returnType, parameterTypes, owner, // owner null, // m skipVisibility, false); } // helpers for intialization static private void CheckConsistency(MethodAttributes attributes, CallingConventions callingConvention) { // only static public for method attributes if ((attributes & ~MethodAttributes.MemberAccessMask) != MethodAttributes.Static) throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); if ((attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); Contract.EndContractBlock(); // only standard or varargs supported if (callingConvention != CallingConventions.Standard && callingConvention != CallingConventions.VarArgs) throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); // vararg is not supported at the moment if (callingConvention == CallingConventions.VarArgs) throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); } // We create a transparent assembly to host DynamicMethods. Since the assembly does not have any // non-public fields (or any fields at all), it is a safe anonymous assembly to host DynamicMethods [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod private static RuntimeModule GetDynamicMethodsModule() { if (s_anonymouslyHostedDynamicMethodsModule != null) return s_anonymouslyHostedDynamicMethodsModule; lock (s_anonymouslyHostedDynamicMethodsModuleLock) { if (s_anonymouslyHostedDynamicMethodsModule != null) return s_anonymouslyHostedDynamicMethodsModule; ConstructorInfo transparencyCtor = typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes); CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, Array.Empty<Object>()); List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>(); assemblyAttributes.Add(transparencyAttribute); AssemblyName assemblyName = new AssemblyName("Anonymously Hosted DynamicMethods Assembly"); StackCrawlMark stackMark = StackCrawlMark.LookForMe; AssemblyBuilder assembly = AssemblyBuilder.InternalDefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run, ref stackMark, assemblyAttributes); AppDomain.PublishAnonymouslyHostedDynamicMethodsAssembly(assembly.GetNativeHandle()); // this always gets the internal module. s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assembly.ManifestModule; } return s_anonymouslyHostedDynamicMethodsModule; } private unsafe void Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] signature, Type owner, Module m, bool skipVisibility, bool transparentMethod) { DynamicMethod.CheckConsistency(attributes, callingConvention); // check and store the signature if (signature != null) { m_parameterTypes = new RuntimeType[signature.Length]; for (int i = 0; i < signature.Length; i++) { if (signature[i] == null) throw new ArgumentException(SR.Arg_InvalidTypeInSignature); m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType; if (m_parameterTypes[i] == null || !(m_parameterTypes[i] is RuntimeType) || m_parameterTypes[i] == (RuntimeType)typeof(void)) throw new ArgumentException(SR.Arg_InvalidTypeInSignature); } } else { m_parameterTypes = Array.Empty<RuntimeType>(); } // check and store the return value m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType; if ((m_returnType == null) || !(m_returnType is RuntimeType) || m_returnType.IsByRef) throw new NotSupportedException(SR.Arg_InvalidTypeInRetType); if (transparentMethod) { Debug.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods"); m_module = GetDynamicMethodsModule(); if (skipVisibility) { m_restrictedSkipVisibility = true; } } else { Debug.Assert(m != null || owner != null, "Constructor should ensure that either m or owner is set"); Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly"); Debug.Assert(m == null || owner == null, "m and owner cannot both be set"); if (m != null) m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects. else { RuntimeType rtOwner = null; if (owner != null) rtOwner = owner.UnderlyingSystemType as RuntimeType; if (rtOwner != null) { if (rtOwner.HasElementType || rtOwner.ContainsGenericParameters || rtOwner.IsGenericParameter || rtOwner.IsInterface) throw new ArgumentException(SR.Argument_InvalidTypeForDynamicMethod); m_typeOwner = rtOwner; m_module = rtOwner.GetRuntimeModule(); } } m_skipVisibility = skipVisibility; } // initialize remaining fields m_ilGenerator = null; m_fInitLocals = true; m_methodHandle = null; if (name == null) throw new ArgumentNullException(nameof(name)); m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention); } // // Delegate and method creation // public sealed override Delegate CreateDelegate(Type delegateType) { if (m_restrictedSkipVisibility) { // Compile the method since accessibility checks are done as part of compilation. GetMethodDescriptor(); System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle); } MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, null, GetMethodDescriptor()); // stash this MethodInfo by brute force. d.StoreDynamicMethod(GetMethodInfo()); return d; } public sealed override Delegate CreateDelegate(Type delegateType, Object target) { if (m_restrictedSkipVisibility) { // Compile the method since accessibility checks are done as part of compilation GetMethodDescriptor(); System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle); } MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, target, GetMethodDescriptor()); // stash this MethodInfo by brute force. d.StoreDynamicMethod(GetMethodInfo()); return d; } // This is guaranteed to return a valid handle internal unsafe RuntimeMethodHandle GetMethodDescriptor() { if (m_methodHandle == null) { lock (this) { if (m_methodHandle == null) { if (m_DynamicILInfo != null) m_DynamicILInfo.GetCallableMethod(m_module, this); else { if (m_ilGenerator == null || m_ilGenerator.ILOffset == 0) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadEmptyMethodBody, Name)); m_ilGenerator.GetCallableMethod(m_module, this); } } } } return new RuntimeMethodHandle(m_methodHandle); } // // MethodInfo api. They mostly forward to RTDynamicMethod // public override String ToString() { return m_dynMethod.ToString(); } public override String Name { get { return m_dynMethod.Name; } } public override Type DeclaringType { get { return m_dynMethod.DeclaringType; } } public override Type ReflectedType { get { return m_dynMethod.ReflectedType; } } public override Module Module { get { return m_dynMethod.Module; } } // we cannot return a MethodHandle because we cannot track it via GC so this method is off limits public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInDynamicMethod); } } public override MethodAttributes Attributes { get { return m_dynMethod.Attributes; } } public override CallingConventions CallingConvention { get { return m_dynMethod.CallingConvention; } } public override MethodInfo GetBaseDefinition() { return this; } [Pure] public override ParameterInfo[] GetParameters() { return m_dynMethod.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dynMethod.GetMethodImplementationFlags(); } // // Security transparency accessors // // Since the dynamic method may not be JITed yet, we don't always have the runtime method handle // which is needed to determine the official runtime transparency status of the dynamic method. We // fall back to saying that the dynamic method matches the transparency of its containing module // until we get a JITed version, since dynamic methods cannot have attributes of their own. // public override bool IsSecurityCritical { get { return true; } } public override bool IsSecuritySafeCritical { get { return false; } } public override bool IsSecurityTransparent { get { return false; } } public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) throw new NotSupportedException(SR.NotSupported_CallToVarArg); Contract.EndContractBlock(); // // We do not demand any permission here because the caller already has access // to the current DynamicMethod object, and it could just as easily emit another // Transparent DynamicMethod to call the current DynamicMethod. // RuntimeMethodHandle method = GetMethodDescriptor(); // ignore obj since it's a static method // create a signature object Signature sig = new Signature( this.m_methodHandle, m_parameterTypes, m_returnType, CallingConvention); // verify arguments int formalCount = sig.Arguments.Length; int actualCount = (parameters != null) ? parameters.Length : 0; if (formalCount != actualCount) throw new TargetParameterCountException(SR.Arg_ParmCnt); // if we are here we passed all the previous checks. Time to look at the arguments bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; Object retValue = null; if (actualCount > 0) { Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, false, wrapExceptions); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; } else { retValue = RuntimeMethodHandle.InvokeMethod(null, null, sig, false, wrapExceptions); } GC.KeepAlive(this); return retValue; } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_dynMethod.GetCustomAttributes(attributeType, inherit); } public override Object[] GetCustomAttributes(bool inherit) { return m_dynMethod.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_dynMethod.IsDefined(attributeType, inherit); } public override Type ReturnType { get { return m_dynMethod.ReturnType; } } public override ParameterInfo ReturnParameter { get { return m_dynMethod.ReturnParameter; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return m_dynMethod.ReturnTypeCustomAttributes; } } // // DynamicMethod specific methods // public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String parameterName) { if (position < 0 || position > m_parameterTypes.Length) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); position--; // it's 1 based. 0 is the return value if (position >= 0) { RuntimeParameterInfo[] parameters = m_dynMethod.LoadParameters(); parameters[position].SetName(parameterName); parameters[position].SetAttributes(attributes); } return null; } public ILGenerator GetILGenerator() { return GetILGenerator(64); } public ILGenerator GetILGenerator(int streamSize) { if (m_ilGenerator == null) { byte[] methodSignature = SignatureHelper.GetMethodSigHelper( null, CallingConvention, ReturnType, null, null, m_parameterTypes, null, null).GetSignature(true); m_ilGenerator = new DynamicILGenerator(this, methodSignature, streamSize); } return m_ilGenerator; } public bool InitLocals { get { return m_fInitLocals; } set { m_fInitLocals = value; } } // // Internal API // internal MethodInfo GetMethodInfo() { return m_dynMethod; } ////////////////////////////////////////////////////////////////////////////////////////////// // RTDynamicMethod // // this is actually the real runtime instance of a method info that gets used for invocation // We need this so we never leak the DynamicMethod out via an exception. // This way the DynamicMethod creator is the only one responsible for DynamicMethod access, // and can control exactly who gets access to it. // internal sealed class RTDynamicMethod : MethodInfo { internal DynamicMethod m_owner; private RuntimeParameterInfo[] m_parameters; private String m_name; private MethodAttributes m_attributes; private CallingConventions m_callingConvention; // // ctors // private RTDynamicMethod() { } internal RTDynamicMethod(DynamicMethod owner, String name, MethodAttributes attributes, CallingConventions callingConvention) { m_owner = owner; m_name = name; m_attributes = attributes; m_callingConvention = callingConvention; } // // MethodInfo api // public override String ToString() { return ReturnType.FormatTypeName() + " " + FormatNameAndSig(); } public override String Name { get { return m_name; } } public override Type DeclaringType { get { return null; } } public override Type ReflectedType { get { return null; } } public override Module Module { get { return m_owner.m_module; } } public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInDynamicMethod); } } public override MethodAttributes Attributes { get { return m_attributes; } } public override CallingConventions CallingConvention { get { return m_callingConvention; } } public override MethodInfo GetBaseDefinition() { return this; } [Pure] public override ParameterInfo[] GetParameters() { ParameterInfo[] privateParameters = LoadParameters(); ParameterInfo[] parameters = new ParameterInfo[privateParameters.Length]; Array.Copy(privateParameters, 0, parameters, 0, privateParameters.Length); return parameters; } public override MethodImplAttributes GetMethodImplementationFlags() { return MethodImplAttributes.IL | MethodImplAttributes.NoInlining; } public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { // We want the creator of the DynamicMethod to control who has access to the // DynamicMethod (just like we do for delegates). However, a user can get to // the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc. // If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would // not be able to bound access to the DynamicMethod. Hence, we do not allow // direct use of RTDynamicMethod. throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "this"); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) return new Object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) }; else return Array.Empty<Object>(); } public override Object[] GetCustomAttributes(bool inherit) { // support for MethodImplAttribute PCA return new Object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) }; } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) return true; else return false; } public override bool IsSecurityCritical { get { return m_owner.IsSecurityCritical; } } public override bool IsSecuritySafeCritical { get { return m_owner.IsSecuritySafeCritical; } } public override bool IsSecurityTransparent { get { return m_owner.IsSecurityTransparent; } } public override Type ReturnType { get { return m_owner.m_returnType; } } public override ParameterInfo ReturnParameter { get { return null; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return GetEmptyCAHolder(); } } // // private implementation // internal RuntimeParameterInfo[] LoadParameters() { if (m_parameters == null) { Type[] parameterTypes = m_owner.m_parameterTypes; RuntimeParameterInfo[] parameters = new RuntimeParameterInfo[parameterTypes.Length]; for (int i = 0; i < parameterTypes.Length; i++) parameters[i] = new RuntimeParameterInfo(this, null, parameterTypes[i], i); if (m_parameters == null) // should we interlockexchange? m_parameters = parameters; } return m_parameters; } // private implementation of CA for the return type private ICustomAttributeProvider GetEmptyCAHolder() { return new EmptyCAHolder(); } /////////////////////////////////////////////////// // EmptyCAHolder private class EmptyCAHolder : ICustomAttributeProvider { internal EmptyCAHolder() { } Object[] ICustomAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit) { return Array.Empty<Object>(); } Object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit) { return Array.Empty<Object>(); } bool ICustomAttributeProvider.IsDefined(Type attributeType, bool inherit) { return false; } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Asset { /// <summary> /// Cenome memory asset cache. /// </summary> /// <remarks> /// <para> /// Cache is enabled by setting "AssetCaching" configuration to value "CenomeMemoryAssetCache". /// When cache is successfully enable log should have message /// "[ASSET CACHE]: Cenome asset cache enabled (MaxSize = XXX bytes, MaxCount = XXX, ExpirationTime = XXX)". /// </para> /// <para> /// Cache's size is limited by two parameters: /// maximal allowed size in bytes and maximal allowed asset count. When new asset /// is added to cache that have achieved either size or count limitation, cache /// will automatically remove less recently used assets from cache. Additionally /// asset's lifetime is controlled by expiration time. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Configuration</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>MaxSize</term> /// <description>Maximal size of the cache in bytes. Default value: 128MB (134 217 728 bytes).</description> /// </item> /// <item> /// <term>MaxCount</term> /// <description>Maximal count of assets stored to cache. Default value: 4096 assets.</description> /// </item> /// <item> /// <term>ExpirationTime</term> /// <description>Asset's expiration time in minutes. Default value: 30 minutes.</description> /// </item> /// </list> /// </para> /// </remarks> /// <example> /// Enabling Cenome Asset Cache: /// <code> /// [Modules] /// AssetCaching = "CenomeMemoryAssetCache" /// </code> /// Setting size and expiration time limitations: /// <code> /// [AssetCache] /// ; 256 MB (default: 134217728) /// MaxSize = 268435456 /// ; How many assets it is possible to store cache (default: 4096) /// MaxCount = 16384 /// ; Expiration time - 1 hour (default: 30 minutes) /// ExpirationTime = 60 /// </code> /// </example> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CenomeMemoryAssetCache")] public class CenomeMemoryAssetCache : IImprovedAssetCache, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Cache's default maximal asset count. /// </summary> /// <remarks> /// <para> /// Assuming that average asset size is about 32768 bytes. /// </para> /// </remarks> public const int DefaultMaxCount = 4096; /// <summary> /// Default maximal size of the cache in bytes /// </summary> /// <remarks> /// <para> /// 128MB = 128 * 1024^2 = 134 217 728 bytes. /// </para> /// </remarks> public const long DefaultMaxSize = 134217728; /// <summary> /// Asset's default expiration time in the cache. /// </summary> public static readonly TimeSpan DefaultExpirationTime = TimeSpan.FromMinutes(30.0); /// <summary> /// Cache object. /// </summary> private ICnmCache<string, AssetBase> m_cache; /// <summary> /// Count of cache commands /// </summary> private int m_cachedCount; /// <summary> /// How many gets before dumping statistics /// </summary> /// <remarks> /// If 0 or less, then disabled. /// </remarks> private int m_debugEpoch; /// <summary> /// Is Cenome asset cache enabled. /// </summary> private bool m_enabled; /// <summary> /// Count of get requests /// </summary> private int m_getCount; /// <summary> /// How many hits /// </summary> private int m_hitCount; /// <summary> /// Initialize asset cache module, with custom parameters. /// </summary> /// <param name="maximalSize"> /// Cache's maximal size in bytes. /// </param> /// <param name="maximalCount"> /// Cache's maximal count of assets. /// </param> /// <param name="expirationTime"> /// Asset's expiration time. /// </param> protected void Initialize(long maximalSize, int maximalCount, TimeSpan expirationTime) { if (maximalSize <= 0 || maximalCount <= 0) { //m_log.Debug("[ASSET CACHE]: Cenome asset cache is not enabled."); m_enabled = false; return; } if (expirationTime <= TimeSpan.Zero) { // Disable expiration time expirationTime = TimeSpan.MaxValue; } // Create cache and add synchronization wrapper over it m_cache = CnmSynchronizedCache<string, AssetBase>.Synchronized(new CnmMemoryCache<string, AssetBase>( maximalSize, maximalCount, expirationTime)); m_enabled = true; m_log.DebugFormat( "[ASSET CACHE]: Cenome asset cache enabled (MaxSize = {0} bytes, MaxCount = {1}, ExpirationTime = {2})", maximalSize, maximalCount, expirationTime); } #region IImprovedAssetCache Members public bool Check(string id) { AssetBase asset; // XXX:This is probably not an efficient implementation. return m_cache.TryGetValue(id, out asset); } /// <summary> /// Cache asset. /// </summary> /// <param name="asset"> /// The asset that is being cached. /// </param> public void Cache(AssetBase asset) { if (asset != null) { // m_log.DebugFormat("[CENOME ASSET CACHE]: Caching asset {0}", asset.ID); long size = asset.Data != null ? asset.Data.Length : 1; m_cache.Set(asset.ID, asset, size); m_cachedCount++; } } /// <summary> /// Clear asset cache. /// </summary> public void Clear() { m_cache.Clear(); } /// <summary> /// Expire (remove) asset stored to cache. /// </summary> /// <param name="id"> /// The expired asset's id. /// </param> public void Expire(string id) { m_cache.Remove(id); } /// <summary> /// Get asset stored /// </summary> /// <param name="id"> /// The asset's id. /// </param> /// <returns> /// Asset if it is found from cache; otherwise <see langword="null"/>. /// </returns> /// <remarks> /// <para> /// Caller should always check that is return value <see langword="null"/>. /// Cache doesn't guarantee in any situation that asset is stored to it. /// </para> /// </remarks> public AssetBase Get(string id) { m_getCount++; AssetBase assetBase; if (m_cache.TryGetValue(id, out assetBase)) m_hitCount++; if (m_getCount == m_debugEpoch) { m_log.DebugFormat( "[ASSET CACHE]: Cached = {0}, Get = {1}, Hits = {2}%, Size = {3} bytes, Avg. A. Size = {4} bytes", m_cachedCount, m_getCount, ((double) m_hitCount / m_getCount) * 100.0, m_cache.Size, m_cache.Size / m_cache.Count); m_getCount = 0; m_hitCount = 0; m_cachedCount = 0; } // if (null == assetBase) // m_log.DebugFormat("[CENOME ASSET CACHE]: Asset {0} not in cache", id); return assetBase; } #endregion #region ISharedRegionModule Members /// <summary> /// Gets region module's name. /// </summary> public string Name { get { return "CenomeMemoryAssetCache"; } } public Type ReplaceableInterface { get { return null; } } /// <summary> /// New region is being added to server. /// </summary> /// <param name="scene"> /// Region's scene. /// </param> public void AddRegion(Scene scene) { if (m_enabled) scene.RegisterModuleInterface<IImprovedAssetCache>(this); } /// <summary> /// Close region module. /// </summary> public void Close() { if (m_enabled) { m_enabled = false; m_cache.Clear(); m_cache = null; } } /// <summary> /// Initialize region module. /// </summary> /// <param name="source"> /// Configuration source. /// </param> public void Initialise(IConfigSource source) { m_cache = null; m_enabled = false; IConfig moduleConfig = source.Configs[ "Modules" ]; if (moduleConfig == null) return; string name = moduleConfig.GetString("AssetCaching"); //m_log.DebugFormat("[XXX] name = {0} (this module's name: {1}", name, Name); if (name != Name) return; long maxSize = DefaultMaxSize; int maxCount = DefaultMaxCount; TimeSpan expirationTime = DefaultExpirationTime; IConfig assetConfig = source.Configs["AssetCache"]; if (assetConfig != null) { // Get optional configurations maxSize = assetConfig.GetLong("MaxSize", DefaultMaxSize); maxCount = assetConfig.GetInt("MaxCount", DefaultMaxCount); expirationTime = TimeSpan.FromMinutes(assetConfig.GetInt("ExpirationTime", (int)DefaultExpirationTime.TotalMinutes)); // Debugging purposes only m_debugEpoch = assetConfig.GetInt("DebugEpoch", 0); } Initialize(maxSize, maxCount, expirationTime); } /// <summary> /// Initialization post handling. /// </summary> /// <remarks> /// <para> /// Modules can use this to initialize connection with other modules. /// </para> /// </remarks> public void PostInitialise() { } /// <summary> /// Region has been loaded. /// </summary> /// <param name="scene"> /// Region's scene. /// </param> /// <remarks> /// <para> /// This is needed for all module types. Modules will register /// Interfaces with scene in AddScene, and will also need a means /// to access interfaces registered by other modules. Without /// this extra method, a module attempting to use another modules' /// interface would be successful only depending on load order, /// which can't be depended upon, or modules would need to resort /// to ugly kludges to attempt to request interfaces when needed /// and unnecessary caching logic repeated in all modules. /// The extra function stub is just that much cleaner. /// </para> /// </remarks> public void RegionLoaded(Scene scene) { } /// <summary> /// Region is being removed. /// </summary> /// <param name="scene"> /// Region scene that is being removed. /// </param> public void RemoveRegion(Scene scene) { } #endregion } }
// 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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// OriginsOperations operations. /// </summary> internal partial class OriginsOperations : Microsoft.Rest.IServiceOperations<CdnManagementClient>, IOriginsOperations { /// <summary> /// Initializes a new instance of the OriginsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal OriginsOperations(CdnManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the CdnManagementClient /// </summary> public CdnManagementClient Client { get; private set; } /// <summary> /// Lists the existing CDN origins within an endpoint. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Origin>>> ListByEndpointWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (profileName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "profileName"); } if (endpointName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "endpointName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("profileName", profileName); tracingParameters.Add("endpointName", endpointName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListByEndpoint", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName)); _url = _url.Replace("{endpointName}", System.Uri.EscapeDataString(endpointName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Origin>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Origin>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets an existing CDN origin within an endpoint. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Origin>> GetWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string originName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (profileName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "profileName"); } if (endpointName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "endpointName"); } if (originName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "originName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("profileName", profileName); tracingParameters.Add("endpointName", endpointName); tracingParameters.Add("originName", originName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName)); _url = _url.Replace("{endpointName}", System.Uri.EscapeDataString(endpointName)); _url = _url.Replace("{originName}", System.Uri.EscapeDataString(originName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Origin>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Origin>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates an existing CDN origin within an endpoint. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> /// <param name='originUpdateProperties'> /// Origin properties /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Origin>> UpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Send Request Microsoft.Rest.Azure.AzureOperationResponse<Origin> _response = await BeginUpdateWithHttpMessagesAsync( resourceGroupName, profileName, endpointName, originName, originUpdateProperties, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Updates an existing CDN origin within an endpoint. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> /// <param name='originUpdateProperties'> /// Origin properties /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Origin>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (profileName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "profileName"); } if (endpointName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "endpointName"); } if (originName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "originName"); } if (originUpdateProperties == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "originUpdateProperties"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("profileName", profileName); tracingParameters.Add("endpointName", endpointName); tracingParameters.Add("originName", originName); tracingParameters.Add("originUpdateProperties", originUpdateProperties); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName)); _url = _url.Replace("{endpointName}", System.Uri.EscapeDataString(endpointName)); _url = _url.Replace("{originName}", System.Uri.EscapeDataString(originName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(originUpdateProperties != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(originUpdateProperties, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Origin>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Origin>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Origin>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the existing CDN origins within an endpoint. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Origin>>> ListByEndpointNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListByEndpointNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Origin>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Origin>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using Android.Content; using Android.Database; using Android.Graphics; using Android.OS; using Android.Provider; using Xamarin.Media; namespace Xamarin.Contacts { public class Contact { public Contact() { } internal Contact (string id, bool isAggregate, ContentResolver content) { this.content = content; IsAggregate = isAggregate; Id = id; } public string Id { get; private set; } public bool IsAggregate { get; private set; } public string DisplayName { get; set; } public string Prefix { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string Nickname { get; set; } public string Suffix { get; set; } internal List<Relationship> relationships = new List<Relationship>(); public IEnumerable<Relationship> Relationships { get { return this.relationships; } set { this.relationships = new List<Relationship> (value); } } internal List<Address> addresses = new List<Address>(); public IEnumerable<Address> Addresses { get { return this.addresses; } set { this.addresses = new List<Address> (value); } } internal List<InstantMessagingAccount> instantMessagingAccounts = new List<InstantMessagingAccount>(); public IEnumerable<InstantMessagingAccount> InstantMessagingAccounts { get { return this.instantMessagingAccounts; } set { this.instantMessagingAccounts = new List<InstantMessagingAccount> (value); } } internal List<Website> websites = new List<Website>(); public IEnumerable<Website> Websites { get { return this.websites; } set { this.websites = new List<Website> (value); } } internal List<Organization> organizations = new List<Organization>(); public IEnumerable<Organization> Organizations { get { return this.organizations; } set { this.organizations = new List<Organization> (value); } } internal List<Note> notes = new List<Note>(); public IEnumerable<Note> Notes { get { return this.notes; } set { this.notes = new List<Note> (value); } } internal List<Email> emails = new List<Email>(); public IEnumerable<Email> Emails { get { return this.emails; } set { this.emails = new List<Email> (value); } } internal List<Phone> phones = new List<Phone>(); public IEnumerable<Phone> Phones { get { return this.phones; } set { this.phones = new List<Phone> (value); } } public Bitmap GetThumbnail() { byte[] data = GetThumbnailBytes(); return (data == null) ? null : BitmapFactory.DecodeByteArray (data, 0, data.Length); } public Task<MediaFile> SaveThumbnailAsync (string path) { if (path == null) throw new ArgumentNullException ("path"); return Task.Factory.StartNew (() => { byte[] bytes = GetThumbnailBytes(); if (bytes == null) return null; File.WriteAllBytes (path, bytes); return new MediaFile (path, deletePathOnDispose: false); }); } byte[] GetThumbnailBytes() { string lookupColumn = (IsAggregate) ? ContactsContract.ContactsColumns.LookupKey : ContactsContract.RawContactsColumns.ContactId; ICursor c = null; try { c = this.content.Query (ContactsContract.Data.ContentUri, new[] { ContactsContract.CommonDataKinds.Photo.PhotoColumnId, ContactsContract.DataColumns.Mimetype }, lookupColumn + "=? AND " + ContactsContract.DataColumns.Mimetype + "=?", new[] { Id, ContactsContract.CommonDataKinds.Photo.ContentItemType }, null); while (c.MoveToNext()) { byte[] tdata = c.GetBlob (c.GetColumnIndex (ContactsContract.CommonDataKinds.Photo.PhotoColumnId)); if (tdata != null) return tdata; } } finally { if (c != null) c.Close(); } return null; } private readonly ContentResolver content; } }
// 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.Collections.Generic; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.MethodInfos; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; using Internal.Reflection.Augments; using EnumInfo = Internal.Runtime.Augments.EnumInfo; using IRuntimeImplementedType = Internal.Reflection.Core.NonPortable.IRuntimeImplementedType; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // Abstract base class for all TypeInfo's implemented by the runtime. // // This base class performs several services: // // - Provides default implementations whenever possible. Some of these // return the "common" error result for narrowly applicable properties (such as those // that apply only to generic parameters.) // // - Inverts the DeclaredMembers/DeclaredX relationship (DeclaredMembers is auto-implemented, others // are overriden as abstract. This ordering makes more sense when reading from metadata.) // // - Overrides many "NotImplemented" members in TypeInfo with abstracts so failure to implement // shows up as build error. // [DebuggerDisplay("{_debugName}")] internal abstract partial class RuntimeTypeInfo : TypeInfo, ITraceableTypeMember, ICloneable, IRuntimeImplementedType { protected RuntimeTypeInfo() { } public abstract override bool IsTypeDefinition { get; } public abstract override bool IsGenericTypeDefinition { get; } protected abstract override bool HasElementTypeImpl(); protected abstract override bool IsArrayImpl(); public abstract override bool IsSZArray { get; } public abstract override bool IsVariableBoundArray { get; } protected abstract override bool IsByRefImpl(); protected abstract override bool IsPointerImpl(); public abstract override bool IsGenericParameter { get; } public abstract override bool IsConstructedGenericType { get; } public abstract override bool IsByRefLike { get; } public abstract override Assembly Assembly { get; } public sealed override string AssemblyQualifiedName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_AssemblyQualifiedName(this); #endif string fullName = FullName; if (fullName == null) // Some Types (such as generic parameters) return null for FullName by design. return null; string assemblyName = InternalFullNameOfAssembly; return fullName + ", " + assemblyName; } } public sealed override Type AsType() { return this; } public sealed override Type BaseType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_BaseType(this); #endif // If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata. RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) { RuntimeTypeHandle baseTypeHandle; if (ReflectionCoreExecution.ExecutionEnvironment.TryGetBaseType(typeHandle, out baseTypeHandle)) return Type.GetTypeFromHandle(baseTypeHandle); } Type baseType = BaseTypeWithoutTheGenericParameterQuirk; if (baseType != null && baseType.IsGenericParameter) { // Desktop quirk: a generic parameter whose constraint is another generic parameter reports its BaseType as System.Object // unless that other generic parameter has a "class" constraint. GenericParameterAttributes genericParameterAttributes = baseType.GenericParameterAttributes; if (0 == (genericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint)) baseType = CommonRuntimeTypes.Object; } return baseType; } } public abstract override bool ContainsGenericParameters { get; } public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; } // // Left unsealed as generic parameter types must override. // public override MethodBase DeclaringMethod { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } // // Equals()/GetHashCode() // // RuntimeTypeInfo objects are interned to preserve the app-compat rule that Type objects (which are the same as TypeInfo objects) // can be compared using reference equality. // // We use weak pointers to intern the objects. This means we can use instance equality to implement Equals() but we cannot use // the instance hashcode to implement GetHashCode() (otherwise, the hash code will not be stable if the TypeInfo is released and recreated.) // Thus, we override and seal Equals() here but defer to a flavor-specific hash code implementation. // public sealed override bool Equals(object obj) { return object.ReferenceEquals(this, obj); } public sealed override bool Equals(Type o) { return object.ReferenceEquals(this, o); } public sealed override int GetHashCode() { return InternalGetHashCode(); } public abstract override string FullName { get; } // // Left unsealed as generic parameter types must override. // public override GenericParameterAttributes GenericParameterAttributes { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } // // Left unsealed as generic parameter types must override this. // public override int GenericParameterPosition { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } public sealed override Type[] GenericTypeArguments { get { return InternalRuntimeGenericTypeArguments.CloneTypeArray(); } } public sealed override MemberInfo[] GetDefaultMembers() { string defaultMemberName = GetDefaultMemberName(); return defaultMemberName != null ? GetMember(defaultMemberName) : Array.Empty<MemberInfo>(); } public sealed override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_InterfaceMap); } // // Implements the correct GUID behavior for all "constructed" types (i.e. returning an all-zero GUID.) Left unsealed // so that RuntimeNamedTypeInfo can override. // public override Guid GUID { get { return Guid.Empty; } } public abstract override bool HasSameMetadataDefinitionAs(MemberInfo other); public sealed override IEnumerable<Type> ImplementedInterfaces { get { LowLevelListWithIList<Type> result = new LowLevelListWithIList<Type>(); bool done = false; // If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata. RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) { IEnumerable<RuntimeTypeHandle> implementedInterfaces = ReflectionCoreExecution.ExecutionEnvironment.TryGetImplementedInterfaces(typeHandle); if (implementedInterfaces != null) { done = true; foreach (RuntimeTypeHandle th in implementedInterfaces) { result.Add(Type.GetTypeFromHandle(th)); } } } if (!done) { TypeContext typeContext = this.TypeContext; Type baseType = this.BaseTypeWithoutTheGenericParameterQuirk; if (baseType != null) result.AddRange(baseType.GetInterfaces()); foreach (QTypeDefRefOrSpec directlyImplementedInterface in this.TypeRefDefOrSpecsForDirectlyImplementedInterfaces) { Type ifc = directlyImplementedInterface.Resolve(typeContext); if (result.Contains(ifc)) continue; result.Add(ifc); foreach (Type indirectIfc in ifc.GetInterfaces()) { if (result.Contains(indirectIfc)) continue; result.Add(indirectIfc); } } } return result.AsNothingButIEnumerable(); } } public sealed override bool IsAssignableFrom(TypeInfo typeInfo) => IsAssignableFrom((Type)typeInfo); public sealed override bool IsAssignableFrom(Type c) { if (c == null) return false; if (object.ReferenceEquals(c, this)) return true; c = c.UnderlyingSystemType; Type typeInfo = c; RuntimeTypeInfo toTypeInfo = this; if (typeInfo == null || !typeInfo.IsRuntimeImplemented()) return false; // Desktop compat: If typeInfo is null, or implemented by a different Reflection implementation, return "false." RuntimeTypeInfo fromTypeInfo = typeInfo.CastToRuntimeTypeInfo(); if (toTypeInfo.Equals(fromTypeInfo)) return true; RuntimeTypeHandle toTypeHandle = toTypeInfo.InternalTypeHandleIfAvailable; RuntimeTypeHandle fromTypeHandle = fromTypeInfo.InternalTypeHandleIfAvailable; bool haveTypeHandles = !(toTypeHandle.IsNull() || fromTypeHandle.IsNull()); if (haveTypeHandles) { // If both types have type handles, let MRT handle this. It's not dependent on metadata. if (ReflectionCoreExecution.ExecutionEnvironment.IsAssignableFrom(toTypeHandle, fromTypeHandle)) return true; // Runtime IsAssignableFrom does not handle casts from generic type definitions: always returns false. For those, we fall through to the // managed implementation. For everyone else, return "false". // // Runtime IsAssignableFrom does not handle pointer -> UIntPtr cast. if (!(fromTypeInfo.IsGenericTypeDefinition || fromTypeInfo.IsPointer)) return false; } // If we got here, the types are open, or reduced away, or otherwise lacking in type handles. Perform the IsAssignability check in managed code. return Assignability.IsAssignableFrom(this, typeInfo); } public sealed override bool IsEnum { get { return 0 != (Classification & TypeClassification.IsEnum); } } public sealed override MemberTypes MemberType { get { if (IsPublic || IsNotPublic) return MemberTypes.TypeInfo; else return MemberTypes.NestedType; } } // // Left unsealed as there are so many subclasses. Need to be overriden by EcmaFormatRuntimeNamedTypeInfo and RuntimeConstructedGenericTypeInfo // public abstract override int MetadataToken { get; } public sealed override Module Module { get { return Assembly.ManifestModule; } } public abstract override string Namespace { get; } public sealed override Type[] GenericTypeParameters { get { return RuntimeGenericTypeParameters.CloneTypeArray(); } } // // Left unsealed as array types must override this. // public override int GetArrayRank() { Debug.Assert(!IsArray); throw new ArgumentException(SR.Argument_HasToBeArrayClass); } public sealed override Type GetElementType() { return InternalRuntimeElementType; } // // Left unsealed as generic parameter types must override. // public override Type[] GetGenericParameterConstraints() { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } // // Left unsealed as IsGenericType types must override this. // public override Type GetGenericTypeDefinition() { Debug.Assert(!IsGenericType); throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); } public sealed override Type MakeArrayType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeArrayType(this); #endif // Do not implement this as a call to MakeArrayType(1) - they are not interchangable. MakeArrayType() returns a // vector type ("SZArray") while MakeArrayType(1) returns a multidim array of rank 1. These are distinct types // in the ECMA model and in CLR Reflection. return this.GetArrayType(); } public sealed override Type MakeArrayType(int rank) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeArrayType(this, rank); #endif if (rank <= 0) throw new IndexOutOfRangeException(); return this.GetMultiDimArrayType(rank); } public sealed override Type MakeByRefType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeByRefType(this); #endif return this.GetByRefType(); } public sealed override Type MakeGenericType(params Type[] typeArguments) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeGenericType(this, typeArguments); #endif if (typeArguments == null) throw new ArgumentNullException(nameof(typeArguments)); if (!IsGenericTypeDefinition) throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); // We intentionally don't validate the number of arguments or their suitability to the generic type's constraints. // In a pay-for-play world, this can cause needless MissingMetadataExceptions. There is no harm in creating // the Type object for an inconsistent generic type - no EEType will ever match it so any attempt to "invoke" it // will throw an exception. RuntimeTypeInfo[] runtimeTypeArguments = new RuntimeTypeInfo[typeArguments.Length]; for (int i = 0; i < typeArguments.Length; i++) { RuntimeTypeInfo runtimeTypeArgument = typeArguments[i] as RuntimeTypeInfo; if (runtimeTypeArgument == null) { if (typeArguments[i] == null) throw new ArgumentNullException(); else throw new PlatformNotSupportedException(SR.PlatformNotSupported_MakeGenericType); // "PlatformNotSupported" because on desktop, passing in a foreign type is allowed and creates a RefEmit.TypeBuilder } // Desktop compatibility: Treat generic type definitions as a constructed generic type using the generic parameters as type arguments. if (runtimeTypeArgument.IsGenericTypeDefinition) runtimeTypeArgument = runtimeTypeArgument.GetConstructedGenericType(runtimeTypeArgument.RuntimeGenericTypeParameters); if (runtimeTypeArgument.IsByRefLike) throw new TypeLoadException(SR.CannotUseByRefLikeTypeInInstantiation); runtimeTypeArguments[i] = runtimeTypeArgument; } return this.GetConstructedGenericType(runtimeTypeArguments); } public sealed override Type MakePointerType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakePointerType(this); #endif return this.GetPointerType(); } public sealed override Type DeclaringType { get { return this.InternalDeclaringType; } } public sealed override string Name { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Name(this); #endif Type rootCauseForFailure = null; string name = InternalGetNameIfAvailable(ref rootCauseForFailure); if (name == null) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(rootCauseForFailure); return name; } } public sealed override Type ReflectedType { get { // Desktop compat: For types, ReflectedType == DeclaringType. Nested types are always looked up as BindingFlags.DeclaredOnly was passed. // For non-nested types, the concept of a ReflectedType doesn't even make sense. return DeclaringType; } } public abstract override StructLayoutAttribute StructLayoutAttribute { get; } public abstract override string ToString(); public sealed override RuntimeTypeHandle TypeHandle { get { RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) return typeHandle; // If a constructed type doesn't have an type handle, it's either because the reducer tossed it (in which case, // we would thrown a MissingMetadataException when attempting to construct the type) or because one of // component types contains open type parameters. Since we eliminated the first case, it must be the second. // Throwing PlatformNotSupported since the desktop does, in fact, create type handles for open types. if (HasElementType || IsConstructedGenericType || IsGenericParameter) throw new PlatformNotSupportedException(SR.PlatformNotSupported_NoTypeHandleForOpenTypes); // If got here, this is a "plain old type" that has metadata but no type handle. We can get here if the only // representation of the type is in the native metadata and there's no EEType at the runtime side. // If you squint hard, this is a missing metadata situation - the metadata is missing on the runtime side - and // the action for the user to take is the same: go mess with RD.XML. throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override Type UnderlyingSystemType { get { return this; } } protected abstract override TypeAttributes GetAttributeFlagsImpl(); protected sealed override TypeCode GetTypeCodeImpl() { return ReflectionAugments.GetRuntimeTypeCode(this); } protected abstract int InternalGetHashCode(); protected sealed override bool IsCOMObjectImpl() { return ReflectionCoreExecution.ExecutionEnvironment.IsCOMObject(this); } protected sealed override bool IsPrimitiveImpl() { return 0 != (Classification & TypeClassification.IsPrimitive); } protected sealed override bool IsValueTypeImpl() { return 0 != (Classification & TypeClassification.IsValueType); } String ITraceableTypeMember.MemberName { get { string name = InternalNameIfAvailable; return name ?? string.Empty; } } Type ITraceableTypeMember.ContainingType { get { return this.InternalDeclaringType; } } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // a base class and interface list based on its constraints. // internal virtual RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { return null; } } internal EnumInfo EnumInfo => Cache.EnumInfo; internal abstract Type InternalDeclaringType { get; } // // Return the full name of the "defining assembly" for the purpose of computing TypeInfo.AssemblyQualifiedName; // internal abstract string InternalFullNameOfAssembly { get; } public abstract override string InternalGetNameIfAvailable(ref Type rootCauseForFailure); // // Left unsealed as HasElement types must override this. // internal virtual RuntimeTypeInfo InternalRuntimeElementType { get { Debug.Assert(!HasElementType); return null; } } // // Left unsealed as constructed generic types must override this. // internal virtual RuntimeTypeInfo[] InternalRuntimeGenericTypeArguments { get { Debug.Assert(!IsConstructedGenericType); return Array.Empty<RuntimeTypeInfo>(); } } internal abstract RuntimeTypeHandle InternalTypeHandleIfAvailable { get; } internal bool IsDelegate { get { return 0 != (Classification & TypeClassification.IsDelegate); } } // // Returns true if it's possible to ask for a list of members and the base type without triggering a MissingMetadataException. // internal abstract bool CanBrowseWithoutMissingMetadataExceptions { get; } // // The non-public version of TypeInfo.GenericTypeParameters (does not array-copy.) // internal virtual RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { Debug.Assert(!(this is RuntimeNamedTypeInfo)); return Array.Empty<RuntimeTypeInfo>(); } } // // Normally returns empty: Overridden by array types to return constructors. // internal virtual IEnumerable<RuntimeConstructorInfo> SyntheticConstructors { get { return Empty<RuntimeConstructorInfo>.Enumerable; } } // // Normally returns empty: Overridden by array types to return the "Get" and "Set" methods. // internal virtual IEnumerable<RuntimeMethodInfo> SyntheticMethods { get { return Empty<RuntimeMethodInfo>.Enumerable; } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // // If you override this method, there is no need to override BaseTypeWithoutTheGenericParameterQuirk. // internal virtual QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { return QTypeDefRefOrSpec.Null; } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal virtual QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { return Array.Empty<QTypeDefRefOrSpec>(); } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal virtual TypeContext TypeContext { get { return new TypeContext(null, null); } } // // Note: This can be (and is) called multiple times. We do not do this work in the constructor as calling ToString() // in the constructor causes some serious recursion issues. // internal void EstablishDebugName() { bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled; #if DEBUG populateDebugNames = true; #endif if (!populateDebugNames) return; if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. String debugName; #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) debugName = this.GetTraceString(); // If tracing on, call this.GetTraceString() which only gives you useful strings when metadata is available but doesn't pollute the ETW trace. else #endif debugName = this.ToString(); if (debugName == null) debugName = ""; _debugName = debugName; } return; } // // This internal method implements BaseType without the following desktop quirk: // // class Foo<X,Y> // where X:Y // where Y:MyReferenceClass // // The desktop reports "X"'s base type as "System.Object" rather than "Y", even though it does // report any interfaces that are in MyReferenceClass's interface list. // // This seriously messes up the implementation of RuntimeTypeInfo.ImplementedInterfaces which assumes // that it can recover the transitive interface closure by combining the directly mentioned interfaces and // the BaseType's own interface closure. // // To implement this with the least amount of code smell, we'll implement the idealized version of BaseType here // and make the special-case adjustment in the public version of BaseType. // // If you override this method, there is no need to overrride TypeRefDefOrSpecForBaseType. // // This method is left unsealed so that RuntimeCLSIDTypeInfo can override. // internal virtual Type BaseTypeWithoutTheGenericParameterQuirk { get { QTypeDefRefOrSpec baseTypeDefRefOrSpec = TypeRefDefOrSpecForBaseType; RuntimeTypeInfo baseType = null; if (!baseTypeDefRefOrSpec.IsValid) { baseType = baseTypeDefRefOrSpec.Resolve(this.TypeContext); } return baseType; } } private string GetDefaultMemberName() { Type defaultMemberAttributeType = typeof(DefaultMemberAttribute); for (Type type = this; type != null; type = type.BaseType) { foreach (CustomAttributeData attribute in type.CustomAttributes) { if (attribute.AttributeType == defaultMemberAttributeType) { // NOTE: Neither indexing nor cast can fail here. Any attempt to use fewer than 1 argument // or a non-string argument would correctly trigger MissingMethodException before // we reach here as that would be an attempt to reference a non-existent DefaultMemberAttribute // constructor. Debug.Assert(attribute.ConstructorArguments.Count == 1 && attribute.ConstructorArguments[0].Value is string); string memberName = (string)(attribute.ConstructorArguments[0].Value); return memberName; } } } return null; } // // Returns a latched set of flags indicating the value of IsValueType, IsEnum, etc. // private TypeClassification Classification { get { if (_lazyClassification == 0) { TypeClassification classification = TypeClassification.Computed; Type baseType = this.BaseType; if (baseType != null) { Type enumType = CommonRuntimeTypes.Enum; Type valueType = CommonRuntimeTypes.ValueType; if (baseType.Equals(enumType)) classification |= TypeClassification.IsEnum | TypeClassification.IsValueType; if (baseType.Equals(CommonRuntimeTypes.MulticastDelegate)) classification |= TypeClassification.IsDelegate; if (baseType.Equals(valueType) && !(this.Equals(enumType))) { classification |= TypeClassification.IsValueType; foreach (Type primitiveType in ReflectionCoreExecution.ExecutionDomain.PrimitiveTypes) { if (this.Equals(primitiveType)) { classification |= TypeClassification.IsPrimitive; break; } } } } _lazyClassification = classification; } return _lazyClassification; } } [Flags] private enum TypeClassification { Computed = 0x00000001, // Always set (to indicate that the lazy evaluation has occurred) IsValueType = 0x00000002, IsEnum = 0x00000004, IsPrimitive = 0x00000008, IsDelegate = 0x00000010, } object ICloneable.Clone() { return this; } private volatile TypeClassification _lazyClassification; private String _debugName; } }
// 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 CompareEqualInt32() { var test = new SimpleBinaryOpTest__CompareEqualInt32(); 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(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (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 class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualInt32 testClass) { var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqualInt32 testClass) { fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx2.CompareEqual( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqualInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public SimpleBinaryOpTest__CompareEqualInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.CompareEqual( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.CompareEqual( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.CompareEqual( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int32>* pClsVar1 = &_clsVar1) fixed (Vector256<Int32>* pClsVar2 = &_clsVar2) { var result = Avx2.CompareEqual( Avx.LoadVector256((Int32*)(pClsVar1)), Avx.LoadVector256((Int32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareEqualInt32(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareEqualInt32(); fixed (Vector256<Int32>* pFld1 = &test._fld1) fixed (Vector256<Int32>* pFld2 = &test._fld2) { var result = Avx2.CompareEqual( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx2.CompareEqual( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.CompareEqual( Avx.LoadVector256((Int32*)(&test._fld1)), Avx.LoadVector256((Int32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] == right[0]) ? unchecked((int)(-1)) : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((int)(-1)) : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = 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.Diagnostics.Contracts; using System.Numerics.Hashing; namespace System.Drawing { /// <summary> /// <para> /// Stores the location and size of a rectangular region. /// </para> /// </summary> [Serializable] public struct Rectangle : IEquatable<Rectangle> { public static readonly Rectangle Empty = new Rectangle(); private int _x; private int _y; private int _width; private int _height; /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Rectangle'/> /// class with the specified location and size. /// </para> /// </summary> public Rectangle(int x, int y, int width, int height) { _x = x; _y = y; _width = width; _height = height; } /// <summary> /// <para> /// Initializes a new instance of the Rectangle class with the specified location /// and size. /// </para> /// </summary> public Rectangle(Point location, Size size) { _x = location.X; _y = location.Y; _width = size.Width; _height = size.Height; } /// <summary> /// Creates a new <see cref='System.Drawing.Rectangle'/> with /// the specified location and size. /// </summary> public static Rectangle FromLTRB(int left, int top, int right, int bottom) => new Rectangle(left, top, unchecked(right - left), unchecked(bottom - top)); /// <summary> /// <para> /// Gets or sets the coordinates of the /// upper-left corner of the rectangular region represented by this <see cref='System.Drawing.Rectangle'/>. /// </para> /// </summary> public Point Location { get { return new Point(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets the size of this <see cref='System.Drawing.Rectangle'/>. /// </summary> public Size Size { get { return new Size(Width, Height); } set { Width = value.Width; Height = value.Height; } } /// <summary> /// Gets or sets the x-coordinate of the /// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.Rectangle'/>. /// </summary> public int X { get { return _x; } set { _x = value; } } /// <summary> /// Gets or sets the y-coordinate of the /// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.Rectangle'/>. /// </summary> public int Y { get { return _y; } set { _y = value; } } /// <summary> /// Gets or sets the width of the rectangular /// region defined by this <see cref='System.Drawing.Rectangle'/>. /// </summary> public int Width { get { return _width; } set { _width = value; } } /// <summary> /// Gets or sets the width of the rectangular /// region defined by this <see cref='System.Drawing.Rectangle'/>. /// </summary> public int Height { get { return _height; } set { _height = value; } } /// <summary> /// <para> /// Gets the x-coordinate of the upper-left corner of the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> public int Left => X; /// <summary> /// <para> /// Gets the y-coordinate of the upper-left corner of the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>. /// </para> /// </summary> public int Top => Y; /// <summary> /// <para> /// Gets the x-coordinate of the lower-right corner of the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>. /// </para> /// </summary> public int Right => unchecked(X + Width); /// <summary> /// <para> /// Gets the y-coordinate of the lower-right corner of the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>. /// </para> /// </summary> public int Bottom => unchecked(Y + Height); /// <summary> /// <para> /// Tests whether this <see cref='System.Drawing.Rectangle'/> has a <see cref='System.Drawing.Rectangle.Width'/> /// or a <see cref='System.Drawing.Rectangle.Height'/> of 0. /// </para> /// </summary> public bool IsEmpty => _height == 0 && _width == 0 && _x == 0 && _y == 0; /// <summary> /// <para> /// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.Rectangle'/> with /// the same location and size of this Rectangle. /// </para> /// </summary> public override bool Equals(object obj) => obj is Rectangle && Equals((Rectangle)obj); public bool Equals(Rectangle other) => this == other; /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.Rectangle'/> /// objects have equal location and size. /// </para> /// </summary> public static bool operator ==(Rectangle left, Rectangle right) => left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height; /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.Rectangle'/> /// objects differ in location or size. /// </para> /// </summary> public static bool operator !=(Rectangle left, Rectangle right) => !(left == right); /// <summary> /// Converts a RectangleF to a Rectangle by performing a ceiling operation on /// all the coordinates. /// </summary> public static Rectangle Ceiling(RectangleF value) { unchecked { return new Rectangle( (int)Math.Ceiling(value.X), (int)Math.Ceiling(value.Y), (int)Math.Ceiling(value.Width), (int)Math.Ceiling(value.Height)); } } /// <summary> /// Converts a RectangleF to a Rectangle by performing a truncate operation on /// all the coordinates. /// </summary> public static Rectangle Truncate(RectangleF value) { unchecked { return new Rectangle( (int)value.X, (int)value.Y, (int)value.Width, (int)value.Height); } } /// <summary> /// Converts a RectangleF to a Rectangle by performing a round operation on /// all the coordinates. /// </summary> public static Rectangle Round(RectangleF value) { unchecked { return new Rectangle( (int)Math.Round(value.X), (int)Math.Round(value.Y), (int)Math.Round(value.Width), (int)Math.Round(value.Height)); } } /// <summary> /// <para> /// Determines if the specified point is contained within the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(int x, int y) => X <= x && x < X + Width && Y <= y && y < Y + Height; /// <summary> /// <para> /// Determines if the specified point is contained within the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(Point pt) => Contains(pt.X, pt.Y); /// <summary> /// <para> /// Determines if the rectangular region represented by /// <paramref name="rect"/> is entirely contained within the rectangular region represented by /// this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(Rectangle rect) => (X <= rect.X) && (rect.X + rect.Width <= X + Width) && (Y <= rect.Y) && (rect.Y + rect.Height <= Y + Height); public override int GetHashCode() => HashHelpers.Combine(HashHelpers.Combine(HashHelpers.Combine(X, Y), Width), Height); /// <summary> /// <para> /// Inflates this <see cref='System.Drawing.Rectangle'/> /// by the specified amount. /// </para> /// </summary> public void Inflate(int width, int height) { unchecked { X -= width; Y -= height; Width += 2 * width; Height += 2 * height; } } /// <summary> /// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount. /// </summary> public void Inflate(Size size) => Inflate(size.Width, size.Height); /// <summary> /// <para> /// Creates a <see cref='System.Drawing.Rectangle'/> /// that is inflated by the specified amount. /// </para> /// </summary> public static Rectangle Inflate(Rectangle rect, int x, int y) { Rectangle r = rect; r.Inflate(x, y); return r; } /// <summary> Creates a Rectangle that represents the intersection between this Rectangle and rect. /// </summary> public void Intersect(Rectangle rect) { Rectangle result = Intersect(rect, this); X = result.X; Y = result.Y; Width = result.Width; Height = result.Height; } /// <summary> /// Creates a rectangle that represents the intersection between a and /// b. If there is no intersection, null is returned. /// </summary> public static Rectangle Intersect(Rectangle a, Rectangle b) { int x1 = Math.Max(a.X, b.X); int x2 = Math.Min(a.X + a.Width, b.X + b.Width); int y1 = Math.Max(a.Y, b.Y); int y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); if (x2 >= x1 && y2 >= y1) { return new Rectangle(x1, y1, x2 - x1, y2 - y1); } return Empty; } /// <summary> /// Determines if this rectangle intersects with rect. /// </summary> [Pure] public bool IntersectsWith(Rectangle rect) => (rect.X < X + Width) && (X < rect.X + rect.Width) && (rect.Y < Y + Height) && (Y < rect.Y + rect.Height); /// <summary> /// <para> /// Creates a rectangle that represents the union between a and /// b. /// </para> /// </summary> [Pure] public static Rectangle Union(Rectangle a, Rectangle b) { int x1 = Math.Min(a.X, b.X); int x2 = Math.Max(a.X + a.Width, b.X + b.Width); int y1 = Math.Min(a.Y, b.Y); int y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new Rectangle(x1, y1, x2 - x1, y2 - y1); } /// <summary> /// <para> /// Adjusts the location of this rectangle by the specified amount. /// </para> /// </summary> public void Offset(Point pos) => Offset(pos.X, pos.Y); /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(int x, int y) { unchecked { X += x; Y += y; } } /// <summary> /// <para> /// Converts the attributes of this <see cref='System.Drawing.Rectangle'/> to a /// human readable string. /// </para> /// </summary> public override string ToString() => "{X=" + X.ToString() + ",Y=" + Y.ToString() + ",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}"; } }
// 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.Xml; using Microsoft.Build.Construction; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using Xunit; namespace Microsoft.Build.UnitTests.OM.Construction { /// <summary> /// Tests for the ProjectOnErrorElement class /// </summary> public class ProjectOnErrorElement_Tests { /// <summary> /// Read a target containing only OnError /// </summary> [Fact] public void ReadTargetOnlyContainingOnError() { ProjectOnErrorElement onError = GetOnError(); Assert.Equal("t", onError.ExecuteTargetsAttribute); Assert.Equal("c", onError.Condition); } /// <summary> /// Read a target with two onerrors, and some tasks /// </summary> [Fact] public void ReadTargetTwoOnErrors() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <t1/> <t2/> <OnError ExecuteTargets='1'/> <OnError ExecuteTargets='2'/> </Target> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children); var onErrors = Helpers.MakeList(target.OnErrors); ProjectOnErrorElement onError1 = onErrors[0]; ProjectOnErrorElement onError2 = onErrors[1]; Assert.Equal("1", onError1.ExecuteTargetsAttribute); Assert.Equal("2", onError2.ExecuteTargetsAttribute); } /// <summary> /// Read onerror with no executetargets attribute /// </summary> /// <remarks> /// This was accidentally allowed in 2.0/3.5 but it should be an error now. /// </remarks> [Fact] public void ReadMissingExecuteTargets() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <OnError/> </Target> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children); ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children); Assert.Equal(String.Empty, onError.ExecuteTargetsAttribute); } ); } /// <summary> /// Read onerror with empty executetargets attribute /// </summary> /// <remarks> /// This was accidentally allowed in 2.0/3.5 but it should be an error now. /// </remarks> [Fact] public void ReadEmptyExecuteTargets() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <OnError ExecuteTargets=''/> </Target> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children); ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children); Assert.Equal(String.Empty, onError.ExecuteTargetsAttribute); } ); } /// <summary> /// Read onerror with invalid attribute /// </summary> [Fact] public void ReadInvalidUnexpectedAttribute() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <OnError ExecuteTargets='t' XX='YY'/> </Target> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read onerror with invalid child element /// </summary> [Fact] public void ReadInvalidUnexpectedChild() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <OnError ExecuteTargets='t'> <X/> </OnError> </Target> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read onerror before task /// </summary> [Fact] public void ReadInvalidBeforeTask() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <OnError ExecuteTargets='t'/> <t/> </Target> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read onerror before task /// </summary> [Fact] public void ReadInvalidBeforePropertyGroup() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <OnError ExecuteTargets='t'/> <PropertyGroup/> </Target> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read onerror before task /// </summary> [Fact] public void ReadInvalidBeforeItemGroup() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <OnError ExecuteTargets='t'/> <ItemGroup/> </Target> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Set ExecuteTargets /// </summary> [Fact] public void SetExecuteTargetsValid() { ProjectOnErrorElement onError = GetOnError(); onError.ExecuteTargetsAttribute = "t2"; Assert.Equal("t2", onError.ExecuteTargetsAttribute); } /// <summary> /// Set ExecuteTargets to null /// </summary> [Fact] public void SetInvalidExecuteTargetsNull() { Assert.Throws<ArgumentNullException>(() => { ProjectOnErrorElement onError = GetOnError(); onError.ExecuteTargetsAttribute = null; } ); } /// <summary> /// Set ExecuteTargets to empty string /// </summary> [Fact] public void SetInvalidExecuteTargetsEmpty() { Assert.Throws<ArgumentException>(() => { ProjectOnErrorElement onError = GetOnError(); onError.ExecuteTargetsAttribute = String.Empty; } ); } /// <summary> /// Set on error condition /// </summary> [Fact] public void SetCondition() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); ProjectOnErrorElement onError = project.CreateOnErrorElement("et"); target.AppendChild(onError); Helpers.ClearDirtyFlag(project); onError.Condition = "c"; Assert.Equal("c", onError.Condition); Assert.True(project.HasUnsavedChanges); } /// <summary> /// Set on error executetargets value /// </summary> [Fact] public void SetExecuteTargets() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); ProjectOnErrorElement onError = project.CreateOnErrorElement("et"); target.AppendChild(onError); Helpers.ClearDirtyFlag(project); onError.ExecuteTargetsAttribute = "et2"; Assert.Equal("et2", onError.ExecuteTargetsAttribute); Assert.True(project.HasUnsavedChanges); } /// <summary> /// Get a basic ProjectOnErrorElement /// </summary> private static ProjectOnErrorElement GetOnError() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <OnError ExecuteTargets='t' Condition='c'/> </Target> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children); ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children); return onError; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal sealed class StringFunctions : ValueQuery { private Function.FunctionType _funcType; private IList<Query> _argList; public StringFunctions(Function.FunctionType funcType, IList<Query> argList) { Debug.Assert(argList != null, "Use 'new Query[]{}' instead."); _funcType = funcType; _argList = argList; } private StringFunctions(StringFunctions other) : base(other) { _funcType = other._funcType; Query[] tmp = new Query[other._argList.Count]; { for (int i = 0; i < tmp.Length; i++) { tmp[i] = Clone(other._argList[i]); } } _argList = tmp; } public override void SetXsltContext(XsltContext context) { for (int i = 0; i < _argList.Count; i++) { _argList[i].SetXsltContext(context); } } public override object Evaluate(XPathNodeIterator nodeIterator) { switch (_funcType) { case Function.FunctionType.FuncString: return toString(nodeIterator); case Function.FunctionType.FuncConcat: return Concat(nodeIterator); case Function.FunctionType.FuncStartsWith: return StartsWith(nodeIterator); case Function.FunctionType.FuncContains: return Contains(nodeIterator); case Function.FunctionType.FuncSubstringBefore: return SubstringBefore(nodeIterator); case Function.FunctionType.FuncSubstringAfter: return SubstringAfter(nodeIterator); case Function.FunctionType.FuncSubstring: return Substring(nodeIterator); case Function.FunctionType.FuncStringLength: return StringLength(nodeIterator); case Function.FunctionType.FuncNormalize: return Normalize(nodeIterator); case Function.FunctionType.FuncTranslate: return Translate(nodeIterator); } return string.Empty; } internal static string toString(double num) { return num.ToString("R", NumberFormatInfo.InvariantInfo); } internal static string toString(bool b) { return b ? "true" : "false"; } private string toString(XPathNodeIterator nodeIterator) { if (_argList.Count > 0) { object argVal = _argList[0].Evaluate(nodeIterator); switch (GetXPathType(argVal)) { case XPathResultType.NodeSet: XPathNavigator value = _argList[0].Advance(); return value != null ? value.Value : string.Empty; case XPathResultType.String: return (string)argVal; case XPathResultType.Boolean: return ((bool)argVal) ? "true" : "false"; case XPathResultType_Navigator: return ((XPathNavigator)argVal).Value; default: Debug.Assert(GetXPathType(argVal) == XPathResultType.Number); return toString((double)argVal); } } return nodeIterator.Current.Value; } public override XPathResultType StaticType { get { if (_funcType == Function.FunctionType.FuncStringLength) { return XPathResultType.Number; } if ( _funcType == Function.FunctionType.FuncStartsWith || _funcType == Function.FunctionType.FuncContains ) { return XPathResultType.Boolean; } return XPathResultType.String; } } private string Concat(XPathNodeIterator nodeIterator) { int count = 0; StringBuilder s = new StringBuilder(); while (count < _argList.Count) { s.Append(_argList[count++].Evaluate(nodeIterator).ToString()); } return s.ToString(); } private bool StartsWith(XPathNodeIterator nodeIterator) { string s1 = _argList[0].Evaluate(nodeIterator).ToString(); string s2 = _argList[1].Evaluate(nodeIterator).ToString(); return s1.Length >= s2.Length && string.CompareOrdinal(s1, 0, s2, 0, s2.Length) == 0; } private static readonly CompareInfo s_compareInfo = CultureInfo.InvariantCulture.CompareInfo; private bool Contains(XPathNodeIterator nodeIterator) { string s1 = _argList[0].Evaluate(nodeIterator).ToString(); string s2 = _argList[1].Evaluate(nodeIterator).ToString(); return s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal) >= 0; } private string SubstringBefore(XPathNodeIterator nodeIterator) { string s1 = _argList[0].Evaluate(nodeIterator).ToString(); string s2 = _argList[1].Evaluate(nodeIterator).ToString(); if (s2.Length == 0) { return s2; } int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal); return (idx < 1) ? string.Empty : s1.Substring(0, idx); } private string SubstringAfter(XPathNodeIterator nodeIterator) { string s1 = _argList[0].Evaluate(nodeIterator).ToString(); string s2 = _argList[1].Evaluate(nodeIterator).ToString(); if (s2.Length == 0) { return s1; } int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal); return (idx < 0) ? string.Empty : s1.Substring(idx + s2.Length); } private string Substring(XPathNodeIterator nodeIterator) { string str1 = _argList[0].Evaluate(nodeIterator).ToString(); double num = XmlConvertEx.XPathRound(XmlConvertEx.ToXPathDouble(_argList[1].Evaluate(nodeIterator))) - 1; if (Double.IsNaN(num) || str1.Length <= num) { return string.Empty; } if (_argList.Count == 3) { double num1 = XmlConvertEx.XPathRound(XmlConvertEx.ToXPathDouble(_argList[2].Evaluate(nodeIterator))); if (Double.IsNaN(num1)) { return string.Empty; } if (num < 0 || num1 < 0) { num1 = num + num1; // NOTE: condition is true for NaN if (!(num1 > 0)) { return string.Empty; } num = 0; } double maxlength = str1.Length - num; if (num1 > maxlength) { num1 = maxlength; } return str1.Substring((int)num, (int)num1); } if (num < 0) { num = 0; } return str1.Substring((int)num); } private Double StringLength(XPathNodeIterator nodeIterator) { if (_argList.Count > 0) { return _argList[0].Evaluate(nodeIterator).ToString().Length; } return nodeIterator.Current.Value.Length; } private string Normalize(XPathNodeIterator nodeIterator) { string value; if (_argList.Count > 0) { value = _argList[0].Evaluate(nodeIterator).ToString(); } else { value = nodeIterator.Current.Value; } int modifyPos = -1; char[] chars = value.ToCharArray(); bool firstSpace = false; // Start false to trim the beginning XmlCharType xmlCharType = XmlCharType.Instance; for (int comparePos = 0; comparePos < chars.Length; comparePos++) { if (!xmlCharType.IsWhiteSpace(chars[comparePos])) { firstSpace = true; modifyPos++; chars[modifyPos] = chars[comparePos]; } else if (firstSpace) { firstSpace = false; modifyPos++; chars[modifyPos] = ' '; } } // Trim end if (modifyPos > -1 && chars[modifyPos] == ' ') modifyPos--; return new string(chars, 0, modifyPos + 1); } private string Translate(XPathNodeIterator nodeIterator) { string value = _argList[0].Evaluate(nodeIterator).ToString(); string mapFrom = _argList[1].Evaluate(nodeIterator).ToString(); string mapTo = _argList[2].Evaluate(nodeIterator).ToString(); int modifyPos = -1; char[] chars = value.ToCharArray(); for (int comparePos = 0; comparePos < chars.Length; comparePos++) { int index = mapFrom.IndexOf(chars[comparePos]); if (index != -1) { if (index < mapTo.Length) { modifyPos++; chars[modifyPos] = mapTo[index]; } } else { modifyPos++; chars[modifyPos] = chars[comparePos]; } } return new string(chars, 0, modifyPos + 1); } public override XPathNodeIterator Clone() { return new StringFunctions(this); } public override void PrintQuery(XmlWriter w) { w.WriteStartElement(this.GetType().Name); w.WriteAttributeString("name", _funcType.ToString()); foreach (Query arg in _argList) { arg.PrintQuery(w); } w.WriteEndElement(); } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; namespace Microsoft.VisualStudio.Project { [CLSCompliant(false)] public class SolutionListenerForProjectReferenceUpdate : SolutionListener { #region ctor public SolutionListenerForProjectReferenceUpdate(IServiceProvider serviceProvider) : base(serviceProvider) { } #endregion #region overridden methods /// <summary> /// Delete this project from the references of projects of this type, if it is found. /// </summary> /// <param name="hierarchy"></param> /// <param name="removed"></param> /// <returns></returns> public override int OnBeforeCloseProject(IVsHierarchy hierarchy, int removed) { if(removed != 0) { List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(hierarchy); foreach(ProjectReferenceNode projectReference in projectReferences) { projectReference.Remove(false); // Set back the remove state on the project refererence. The reason why we are doing this is that the OnBeforeUnloadProject immedaitely calls // OnBeforeCloseProject, thus we would be deleting references when we should not. Unload should not remove references. projectReference.CanRemoveReference = true; } } return VSConstants.S_OK; } /// <summary> /// Needs to update the dangling reference on projects that contain this hierarchy as project reference. /// </summary> /// <param name="stubHierarchy"></param> /// <param name="realHierarchy"></param> /// <returns></returns> public override int OnAfterLoadProject(IVsHierarchy stubHierarchy, IVsHierarchy realHierarchy) { List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(realHierarchy); // Refersh the project reference node. That should trigger the drawing of the normal project reference icon. foreach(ProjectReferenceNode projectReference in projectReferences) { projectReference.CanRemoveReference = true; projectReference.OnInvalidateItems(projectReference.Parent); } return VSConstants.S_OK; } public override int OnAfterRenameProject(IVsHierarchy hierarchy) { if(hierarchy == null) { return VSConstants.E_INVALIDARG; } try { List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(hierarchy); // Collect data that is needed to initialize the new project reference node. string projectRef; ErrorHandler.ThrowOnFailure(this.Solution.GetProjrefOfProject(hierarchy, out projectRef)); object nameAsObject; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Name, out nameAsObject)); string projectName = (string)nameAsObject; string projectPath = String.Empty; IVsProject3 project = hierarchy as IVsProject3; if(project != null) { ErrorHandler.ThrowOnFailure(project.GetMkDocument(VSConstants.VSITEMID_ROOT, out projectPath)); projectPath = Path.GetDirectoryName(projectPath); } // Remove and re add the node. foreach(ProjectReferenceNode projectReference in projectReferences) { ProjectNode projectMgr = projectReference.ProjectMgr; IReferenceContainer refContainer = projectMgr.GetReferenceContainer(); projectReference.Remove(false); VSCOMPONENTSELECTORDATA selectorData = new VSCOMPONENTSELECTORDATA(); selectorData.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project; selectorData.bstrTitle = projectName; selectorData.bstrFile = projectPath; selectorData.bstrProjRef = projectRef; refContainer.AddReferenceFromSelectorData(selectorData); } } catch(COMException e) { return e.ErrorCode; } return VSConstants.S_OK; } public override int OnBeforeUnloadProject(IVsHierarchy realHierarchy, IVsHierarchy stubHierarchy) { List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(realHierarchy); // Refresh the project reference node. That should trigger the drawing of the dangling project reference icon. foreach(ProjectReferenceNode projectReference in projectReferences) { projectReference.IsNodeValid = true; projectReference.OnInvalidateItems(projectReference.Parent); projectReference.CanRemoveReference = false; projectReference.IsNodeValid = false; projectReference.ReferencedProjectObject = null; } return VSConstants.S_OK; } #endregion #region helper methods private List<ProjectReferenceNode> GetProjectReferencesContainingThisProject(IVsHierarchy inputHierarchy) { List<ProjectReferenceNode> projectReferences = new List<ProjectReferenceNode>(); if(this.Solution == null || inputHierarchy == null) { return projectReferences; } uint flags = (uint)(__VSENUMPROJFLAGS.EPF_ALLPROJECTS | __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION); Guid enumOnlyThisType = Guid.Empty; IEnumHierarchies enumHierarchies = null; ErrorHandler.ThrowOnFailure(this.Solution.GetProjectEnum(flags, ref enumOnlyThisType, out enumHierarchies)); Debug.Assert(enumHierarchies != null, "Could not get list of hierarchies in solution"); IVsHierarchy[] hierarchies = new IVsHierarchy[1]; uint fetched; int returnValue = VSConstants.S_OK; do { returnValue = enumHierarchies.Next(1, hierarchies, out fetched); Debug.Assert(fetched <= 1, "We asked one project to be fetched VSCore gave more than one. We cannot handle that"); if(returnValue == VSConstants.S_OK && fetched == 1) { IVsHierarchy hierarchy = hierarchies[0]; Debug.Assert(hierarchy != null, "Could not retrieve a hierarchy"); IReferenceContainerProvider provider = hierarchy as IReferenceContainerProvider; if(provider != null) { IReferenceContainer referenceContainer = provider.GetReferenceContainer(); Debug.Assert(referenceContainer != null, "Could not found the References virtual node"); ProjectReferenceNode projectReferenceNode = GetProjectReferenceOnNodeForHierarchy(referenceContainer.EnumReferences(), inputHierarchy); if(projectReferenceNode != null) { projectReferences.Add(projectReferenceNode); } } } } while(returnValue == VSConstants.S_OK && fetched == 1); return projectReferences; } private static ProjectReferenceNode GetProjectReferenceOnNodeForHierarchy(IList<ReferenceNode> references, IVsHierarchy inputHierarchy) { if(references == null) { return null; } Guid projectGuid; ErrorHandler.ThrowOnFailure(inputHierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out projectGuid)); string canonicalName; ErrorHandler.ThrowOnFailure(inputHierarchy.GetCanonicalName(VSConstants.VSITEMID_ROOT, out canonicalName)); foreach(ReferenceNode refNode in references) { ProjectReferenceNode projRefNode = refNode as ProjectReferenceNode; if(projRefNode != null) { if(projRefNode.ReferencedProjectGuid == projectGuid) { return projRefNode; } // Try with canonical names, if the project that is removed is an unloaded project than the above criteria will not pass. if(!String.IsNullOrEmpty(projRefNode.Url) && NativeMethods.IsSamePath(projRefNode.Url, canonicalName)) { return projRefNode; } } } return null; } #endregion } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.Tests { using System; using System.Collections.Generic; using Magnum.Extensions; using Magnum.TestFramework; using Messages; using NUnit.Framework; using TestConsumers; using TestFramework; using TextFixtures; [TestFixture] public class MessageContext_Specs : LoopbackLocalAndRemoteTestFixture { [Test] public void A_response_should_be_published_if_no_reply_address_is_specified() { var ping = new PingMessage(); var otherConsumer = new TestMessageConsumer<PongMessage>(); RemoteBus.SubscribeInstance(otherConsumer); LocalBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(ping.CorrelationId); LocalBus.SubscribeInstance(consumer); var pong = new FutureMessage<PongMessage>(); RemoteBus.SubscribeHandler<PingMessage>(message => { pong.Set(new PongMessage(message.CorrelationId)); RemoteBus.Context().Respond(pong.Message); }); RemoteBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); LocalBus.ShouldHaveRemoteSubscriptionFor<PingMessage>(); LocalBus.Publish(ping); pong.IsAvailable(8.Seconds()).ShouldBeTrue("No pong generated"); consumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds()); otherConsumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds()); } [Test] public void A_response_should_be_sent_directly_if_a_reply_address_is_specified() { var ping = new PingMessage(); var otherConsumer = new TestMessageConsumer<PongMessage>(); RemoteBus.SubscribeInstance(otherConsumer); var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(ping.CorrelationId); LocalBus.SubscribeInstance(consumer); var pong = new FutureMessage<PongMessage>(); RemoteBus.SubscribeHandler<PingMessage>(message => { pong.Set(new PongMessage(message.CorrelationId)); RemoteBus.Context().Respond(pong.Message); }); RemoteBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); LocalBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); LocalBus.ShouldHaveRemoteSubscriptionFor<PingMessage>(); LocalBus.Publish(ping, context => context.SendResponseTo(LocalBus)); Assert.IsTrue(pong.IsAvailable(8.Seconds()), "No pong generated"); consumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds()); otherConsumer.ShouldNotHaveReceivedMessage(pong.Message, 1.Seconds()); } [Test] public void The_destination_address_should_pass() { var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(LocalBus.Endpoint.Address.Uri, LocalBus.Context().DestinationAddress); received.Set(message); }); LocalBus.Publish(new PingMessage()); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_fault_address_should_pass() { var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(LocalBus.Endpoint.Address.Uri, LocalBus.Context().FaultAddress); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SendFaultTo(LocalBus)); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_response_address_should_pass() { var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(LocalBus.Endpoint.Address.Uri, LocalBus.Context().ResponseAddress); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SendResponseTo(LocalBus)); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_source_address_should_pass() { var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(LocalBus.Endpoint.Address.Uri, LocalBus.Context().SourceAddress); received.Set(message); }); LocalBus.Publish(new PingMessage()); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_request_id_should_pass() { Guid id = Guid.NewGuid(); var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(id.ToString(), LocalBus.Context().RequestId); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SetRequestId(id.ToString())); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_conversation_id_should_pass() { Guid id = Guid.NewGuid(); var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(id.ToString(), LocalBus.Context().ConversationId); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SetConversationId(id.ToString())); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_correlation_id_should_pass() { Guid id = Guid.NewGuid(); var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(id.ToString(), LocalBus.Context().CorrelationId); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SetCorrelationId(id.ToString())); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void A_random_header_should_pass() { Guid id = Guid.NewGuid(); var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(id.ToString(), LocalBus.Context().Headers["RequestId"]); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SetHeader("RequestId", id.ToString())); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } } [TestFixture] public class When_publishing_a_message_with_no_consumers : LoopbackLocalAndRemoteTestFixture { [Test] public void The_method_should_be_called_to_notify_the_caller() { var ping = new PingMessage(); bool noConsumers = false; LocalBus.Publish(ping, x => { x.IfNoSubscribers(() => { noConsumers = true; }); }); Assert.IsTrue(noConsumers, "There should have been no consumers"); } [Test] public void The_method_should_not_carry_over_the_subsequent_calls() { var ping = new PingMessage(); int hitCount = 0; LocalBus.Publish(ping, x => x.IfNoSubscribers(() => hitCount++)); LocalBus.Publish(ping); Assert.AreEqual(1, hitCount, "There should have been no consumers"); } } [TestFixture] public class When_publishing_a_message_with_an_each_consumer_action_specified : LoopbackLocalAndRemoteTestFixture { [Test] public void The_method_should_be_called_for_each_destination_endpoint() { LocalBus.SubscribeHandler<PingMessage>(x => { }); var ping = new PingMessage(); var consumers = new List<Uri>(); LocalBus.Publish(ping, x => { x.ForEachSubscriber(address => consumers.Add(address.Uri)); }); Assert.AreEqual(1, consumers.Count); Assert.AreEqual(LocalBus.Endpoint.Address.Uri, consumers[0]); } [Test] public void The_method_should_be_called_for_each_destination_endpoint_when_there_are_multiple() { RemoteBus.SubscribeHandler<PingMessage>(x => { }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(x => { }); var ping = new PingMessage(); var consumers = new List<Uri>(); LocalBus.Publish(ping, x => { x.ForEachSubscriber(address => consumers.Add(address.Uri)); }); Assert.AreEqual(2, consumers.Count); Assert.IsTrue(consumers.Contains(LocalBus.Endpoint.Address.Uri)); Assert.IsTrue(consumers.Contains(RemoteBus.Endpoint.Address.Uri)); } [Test] public void The_method_should_not_be_called_when_there_are_no_subscribers() { var ping = new PingMessage(); var consumers = new List<Uri>(); LocalBus.Publish(ping, x => { x.ForEachSubscriber(address => consumers.Add(address.Uri)); }); Assert.AreEqual(0, consumers.Count); } [Test] public void The_method_should_not_carry_over_to_the_next_call_context() { var ping = new PingMessage(); var consumers = new List<Uri>(); LocalBus.Publish(ping, x => { x.ForEachSubscriber(address => consumers.Add(address.Uri)); }); LocalBus.SubscribeHandler<PingMessage>(x => { }); LocalBus.Publish(ping); Assert.AreEqual(0, consumers.Count); } } }
//------------------------------------------------------------------------------- // <copyright file="ExtensionTest.cs" company="Appccelerate"> // Copyright (c) 2008-2015 // // 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> //------------------------------------------------------------------------------- namespace Appccelerate.StateMachine { using System; using Appccelerate.StateMachine.Machine; using Appccelerate.StateMachine.Machine.Contexts; using FakeItEasy; using FluentAssertions; using Xunit; /// <summary> /// Tests that the extensions can interact with the state machine. /// </summary> public class ExtensionTest { private readonly StateMachine<States, Events> testee; private readonly IExtension<States, Events> extension; private readonly OverrideExtension overrideExtension; /// <summary> /// Initializes a new instance of the <see cref="ExtensionTest"/> class. /// </summary> public ExtensionTest() { this.testee = new StateMachine<States, Events>(); this.extension = A.Fake<IExtension<States, Events>>(); this.overrideExtension = new OverrideExtension(); this.testee.AddExtension(this.extension); this.testee.AddExtension(this.overrideExtension); } /// <summary> /// When the state machine is initialized then the extensions get notified. /// </summary> [Fact] public void Initialize() { States initialState = States.A; this.testee.Initialize(initialState); A.CallTo(() => this.extension.InitializingStateMachine(this.testee, ref initialState)) .MustHaveHappened(); A.CallTo(() => this.extension.InitializedStateMachine(this.testee, initialState)) .MustHaveHappened(); } [Fact] public void EnterInitialState() { const States InitialState = States.A; this.testee.Initialize(InitialState); this.testee.EnterInitialState(); A.CallTo(() => this.extension.EnteringInitialState(this.testee, InitialState)) .MustHaveHappened(); A.CallTo(() => this.extension.EnteredInitialState( this.testee, InitialState, A<TransitionContext<States, Events>>.That.Matches(context => context.State == null))) .MustHaveHappened(); } /// <summary> /// An extension can override the state to which the state machine is initialized. /// </summary> [Fact] public void OverrideInitialState() { this.overrideExtension.OverriddenState = States.B; this.testee.Initialize(States.A); this.testee.EnterInitialState(); States? actualState = this.testee.CurrentStateId; actualState.Should().Be(States.B); } /// <summary> /// When an event is fired on the state machine then the extensions are notified. /// </summary> [Fact] public void Fire() { this.testee.In(States.A).On(Events.B).Goto(States.B); this.testee.Initialize(States.A); this.testee.EnterInitialState(); Events eventId = Events.B; var eventArgument = new object(); this.testee.Fire(eventId, eventArgument); A.CallTo(() => this.extension.FiringEvent(this.testee, ref eventId, ref eventArgument)) .MustHaveHappened(); A.CallTo(() => this.extension.FiredEvent( this.testee, A<ITransitionContext<States, Events>>.That.Matches( context => context.State.Id == States.A && context.EventId.Value == eventId && context.EventArgument == eventArgument))) .MustHaveHappened(); } /// <summary> /// An extension can override the event id and the event arguments. /// </summary> [Fact] public void OverrideFiredEvent() { this.testee.In(States.A) .On(Events.B).Goto(States.B) .On(Events.C).Goto(States.C); this.testee.Initialize(States.A); this.testee.EnterInitialState(); const Events NewEvent = Events.C; var newEventArgument = new object(); this.overrideExtension.OverriddenEvent = NewEvent; this.overrideExtension.OverriddenEventArgument = newEventArgument; this.testee.Fire(Events.B); A.CallTo(() => this.extension.FiredEvent( this.testee, A<ITransitionContext<States, Events>>.That.Matches( c => c.EventId.Value == NewEvent && c.EventArgument == newEventArgument))) .MustHaveHappened(); } [Fact] public void NotifiesAboutTransitions() { const States Source = States.A; const States Target = States.B; const Events Event = Events.B; this.testee.In(Source) .On(Event).Goto(Target); this.testee.Initialize(Source); this.testee.EnterInitialState(); this.testee.Fire(Event); A.CallTo(() => this.extension.ExecutingTransition( this.testee, A<ITransition<States, Events>>.That.Matches( t => t.Source.Id == Source && t.Target.Id == Target), A<ITransitionContext<States, Events>>.That.Matches( c => c.EventId.Value == Event && c.State.Id == Source))) .MustHaveHappened(); A.CallTo(() => this.extension.ExecutedTransition( this.testee, A<ITransition<States, Events>>.That.Matches( t => t.Source.Id == Source && t.Target.Id == Target), A<ITransitionContext<States, Events>>.That.Matches( c => c.EventId.Value == Event && c.State.Id == Source))) .MustHaveHappened(); } /// <summary> /// Exceptions thrown by guards are passed to extensions. /// </summary> [Fact] public void ExceptionThrowingGuard() { Exception exception = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A).On(Events.B).If(() => { throw exception; }).Execute(() => { }); this.testee.Initialize(States.A); this.testee.EnterInitialState(); this.testee.Fire(Events.B); A.CallTo(() => this.extension.HandlingGuardException( this.testee, Transition(States.A), Context(States.A, Events.B), ref exception)) .MustHaveHappened(); A.CallTo(() => this.extension.HandledGuardException( this.testee, Transition(States.A), Context(States.A, Events.B), exception)) .MustHaveHappened(); } /// <summary> /// An extension can override the exception thrown by a transition guard. /// </summary> [Fact] public void OverrideGuardException() { Exception exception = new Exception(); Exception overriddenException = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A).On(Events.B).If(() => { throw exception; }).Execute(() => { }); this.testee.Initialize(States.A); this.testee.EnterInitialState(); this.overrideExtension.OverriddenException = overriddenException; this.testee.Fire(Events.B); A.CallTo(() => this.extension.HandledGuardException( this.testee, A<ITransition<States, Events>>._, A<ITransitionContext<States, Events>>._, overriddenException)) .MustHaveHappened(); } /// <summary> /// Exceptions thrown in actions are passed to the extensions. /// </summary> [Fact] public void ExceptionThrowingAction() { Exception exception = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A).On(Events.B).Execute(() => { throw exception; }); this.testee.Initialize(States.A); this.testee.EnterInitialState(); this.testee.Fire(Events.B); A.CallTo(() => this.extension.HandlingTransitionException( this.testee, Transition(States.A), Context(States.A, Events.B), ref exception)) .MustHaveHappened(); A.CallTo(() => this.extension.HandledTransitionException( this.testee, Transition(States.A), Context(States.A, Events.B), exception)) .MustHaveHappened(); } /// <summary> /// An extension can override the exception thrown by an action. /// </summary> [Fact] public void OverrideActionException() { Exception exception = new Exception(); Exception overriddenException = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A).On(Events.B).Execute(() => { throw exception; }); this.testee.Initialize(States.A); this.testee.EnterInitialState(); this.overrideExtension.OverriddenException = overriddenException; this.testee.Fire(Events.B); A.CallTo(() => this.extension.HandledTransitionException( this.testee, A<ITransition<States, Events>>._, A<ITransitionContext<States, Events>>._, overriddenException)) .MustHaveHappened(); } /// <summary> /// Exceptions thrown by entry actions are passed to extensions. /// </summary> [Fact] public void EntryActionException() { Exception exception = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A).On(Events.B).Goto(States.B); this.testee.In(States.B).ExecuteOnEntry(() => { throw exception; }); this.testee.Initialize(States.A); this.testee.EnterInitialState(); this.testee.Fire(Events.B); A.CallTo(() => this.extension.HandlingEntryActionException( this.testee, State(States.B), Context(States.A, Events.B), ref exception)) .MustHaveHappened(); A.CallTo(() => this.extension.HandledEntryActionException( this.testee, State(States.B), Context(States.A, Events.B), exception)) .MustHaveHappened(); } /// <summary> /// An extension can override the exception thrown by an entry action. /// </summary> [Fact] public void OverrideEntryActionException() { Exception exception = new Exception(); Exception overriddenException = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A).On(Events.B).Goto(States.B); this.testee.In(States.B).ExecuteOnEntry(() => { throw exception; }); this.testee.Initialize(States.A); this.testee.EnterInitialState(); this.overrideExtension.OverriddenException = overriddenException; this.testee.Fire(Events.B); A.CallTo(() => this.extension.HandledEntryActionException( this.testee, A<IState<States, Events>>._, A<ITransitionContext<States, Events>>._, overriddenException)) .MustHaveHappened(); } /// <summary> /// Exceptions thrown by exit actions are passed to extensions. /// </summary> [Fact] public void ExitActionException() { Exception exception = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A) .ExecuteOnExit(() => { throw exception; }) .On(Events.B).Goto(States.B); this.testee.Initialize(States.A); this.testee.EnterInitialState(); this.testee.Fire(Events.B); A.CallTo(() => this.extension.HandlingExitActionException( this.testee, State(States.A), Context(States.A, Events.B), ref exception)) .MustHaveHappened(); A.CallTo(() => this.extension.HandledExitActionException( this.testee, State(States.A), Context(States.A, Events.B), exception)) .MustHaveHappened(); } /// <summary> /// Exceptions thrown by exit actions can be overridden by extensions. /// </summary> [Fact] public void OverrideExitActionException() { Exception exception = new Exception(); Exception overriddenException = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A) .ExecuteOnExit(() => { throw exception; }) .On(Events.B).Goto(States.B); this.testee.Initialize(States.A); this.testee.EnterInitialState(); this.overrideExtension.OverriddenException = overriddenException; this.testee.Fire(Events.B); A.CallTo(() => this.extension.HandledExitActionException( this.testee, A<IState<States, Events>>._, A<ITransitionContext<States, Events>>._, overriddenException)) .MustHaveHappened(); } /// <summary> /// Exceptions thrown by entry actions during initialization are passed to extensions. /// </summary> [Fact] public void EntryActionExceptionDuringInitialization() { Exception exception = new Exception(); this.testee.TransitionExceptionThrown += (s, e) => { }; this.testee.In(States.A).ExecuteOnEntry(() => { throw exception; }); this.testee.Initialize(States.A); this.testee.EnterInitialState(); A.CallTo(() => this.extension.HandlingEntryActionException( this.testee, State(States.A), A<TransitionContext<States, Events>>.That.Matches(context => context.State == null), ref exception)) .MustHaveHappened(); A.CallTo(() => this.extension.HandledEntryActionException( this.testee, State(States.A), A<TransitionContext<States, Events>>.That.Matches(context => context.State == null), exception)) .MustHaveHappened(); } private static IState<States, Events> State(States stateId) { return A<IState<States, Events>>.That.Matches(state => state.Id == stateId); } private static ITransition<States, Events> Transition(States sourceState) { return A<ITransition<States, Events>>.That.Matches(transition => transition.Source.Id == sourceState); } private static ITransitionContext<States, Events> Context(States sourceState, Events eventId) { return A<ITransitionContext<States, Events>>.That.Matches(context => context.EventId.Value == eventId && context.State.Id == sourceState); } private class OverrideExtension : Extensions.ExtensionBase<States, Events> { public States? OverriddenState { get; set; } public Events? OverriddenEvent { get; set; } public object OverriddenEventArgument { get; set; } public Exception OverriddenException { get; set; } public override void InitializingStateMachine(IStateMachineInformation<States, Events> stateMachine, ref States initialState) { if (this.OverriddenState.HasValue) { initialState = this.OverriddenState.Value; } } public override void FiringEvent(IStateMachineInformation<States, Events> stateMachine, ref Events eventId, ref object eventArgument) { if (this.OverriddenEvent.HasValue) { eventId = this.OverriddenEvent.Value; } if (this.OverriddenEventArgument != null) { eventArgument = this.OverriddenEventArgument; } } public override void HandlingGuardException(IStateMachineInformation<States, Events> stateMachine, ITransition<States, Events> transition, ITransitionContext<States, Events> transitionContext, ref Exception exception) { if (this.OverriddenException != null) { exception = this.OverriddenException; } } public override void HandlingTransitionException(IStateMachineInformation<States, Events> stateMachine, ITransition<States, Events> transition, ITransitionContext<States, Events> context, ref Exception exception) { if (this.OverriddenException != null) { exception = this.OverriddenException; } } public override void HandlingEntryActionException(IStateMachineInformation<States, Events> stateMachine, IState<States, Events> state, ITransitionContext<States, Events> context, ref Exception exception) { if (this.OverriddenException != null) { exception = this.OverriddenException; } } public override void HandlingExitActionException(IStateMachineInformation<States, Events> stateMachine, IState<States, Events> state, ITransitionContext<States, Events> context, ref Exception exception) { if (this.OverriddenException != null) { exception = this.OverriddenException; } } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Globalization; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected internal enum State { /// <summary> /// The Read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The Close method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private List<JsonPosition> _stack; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState { get { return _currentState; } } /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the reader is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the reader is closed; otherwise false. The default is true. /// </value> public bool CloseInput { get; set; } /// <summary> /// Gets or sets a value indicating whether multiple pieces of JSON content can /// be read from a continuous stream without erroring. /// </summary> /// <value> /// true to support reading multiple pieces of JSON content; otherwise false. The default is false. /// </value> public bool SupportMultipleContent { get; set; } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || #if !NET20 value > DateParseHandling.DateTimeOffset #else value > DateParseHandling.DateTime #endif ) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException(nameof(value)); } _floatParseHandling = value; } } /// <summary> /// Get or set how custom date formatted strings are parsed when reading JSON. /// </summary> public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", nameof(value)); } _maxDepth = value; } } /// <summary> /// Gets the type of the current JSON token. /// </summary> public virtual JsonToken TokenType { get { return _tokenType; } } /// <summary> /// Gets the text value of the current JSON token. /// </summary> public virtual object Value { get { return _value; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current JSON token. /// </summary> public virtual Type ValueType { get { return (_value != null) ? _value.GetType() : null; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = (_stack != null) ? _stack.Count : 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return depth; } else { return depth + 1; } } } /// <summary> /// Gets the path of the current JSON token. /// </summary> public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; return JsonPosition.BuildPath(_stack, current); } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); } else { if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition oldPosition; if (_stack != null && _stack.Count > 0) { oldPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { oldPosition = _currentPosition; _currentPosition = new JsonPosition(); } if (_maxDepth != null && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual int? ReadAsInt32() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is int)) { SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false); } return (int)Value; case JsonToken.String: string s = (string)Value; return ReadInt32String(s); } throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal int? ReadInt32String(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } int i; if (int.TryParse(s, NumberStyles.Integer, Culture, out i)) { SetToken(JsonToken.Integer, i, false); return i; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual string ReadAsString() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; } if (JsonTokenUtils.IsPrimitiveToken(t)) { if (Value != null) { string s; if (Value is IFormattable) { s = ((IFormattable)Value).ToString(null, Culture); } else if (Value is Uri) { s = ((Uri)Value).OriginalString; } else { s = Value.ToString(); } SetToken(JsonToken.String, s, false); return s; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Byte"/>[]. /// </summary> /// <returns>A <see cref="Byte"/>[] or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns> public virtual byte[] ReadAsBytes() { JsonToken t = GetContentToken(); if (t == JsonToken.None) { return null; } if (TokenType == JsonToken.StartObject) { ReadIntoWrappedTypeObject(); byte[] data = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, data, false); return data; } switch (t) { case JsonToken.String: { // attempt to convert possible base 64 or GUID string to bytes // GUID has to have format 00000000-0000-0000-0000-000000000000 string s = (string)Value; byte[] data; Guid g; if (s.Length == 0) { data = new byte[0]; } else if (ConvertUtils.TryConvertGuid(s, out g)) { data = g.ToByteArray(); } else { data = Convert.FromBase64String(s); } SetToken(JsonToken.Bytes, data, false); return data; } case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (ValueType == typeof(Guid)) { byte[] data = ((Guid)Value).ToByteArray(); SetToken(JsonToken.Bytes, data, false); return data; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal byte[] ReadArrayIntoByteArray() { List<byte> buffer = new List<byte>(); while (true) { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); break; case JsonToken.EndArray: byte[] d = buffer.ToArray(); SetToken(JsonToken.Bytes, d, false); return d; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual double? ReadAsDouble() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is double)) { SetToken(JsonToken.Float, Convert.ToDouble(Value, CultureInfo.InvariantCulture), false); } return (double) Value; case JsonToken.String: return ReadDoubleString((string) Value); } throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal double? ReadDoubleString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } double d; if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Boolean}"/>. /// </summary> /// <returns>A <see cref="Nullable{Boolean}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual bool? ReadAsBoolean() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: bool b; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (Value is BigInteger) { b = (BigInteger)Value != 0; } else #endif { b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); } SetToken(JsonToken.Boolean, b, false); return b; case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; } throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal bool? ReadBooleanString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } bool b; if (bool.TryParse(s, out b)) { SetToken(JsonToken.Boolean, b, false); return b; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual decimal? ReadAsDecimal() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is decimal)) { SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false); } return (decimal)Value; case JsonToken.String: return ReadDecimalString((string)Value); } throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal decimal? ReadDecimalString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } decimal d; if (decimal.TryParse(s, NumberStyles.Number, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTime}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: #if !NET20 if (Value is DateTimeOffset) { SetToken(JsonToken.Date, ((DateTimeOffset)Value).DateTime, false); } #endif return (DateTime)Value; case JsonToken.String: string s = (string)Value; return ReadDateTimeString(s); } throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal DateTime? ReadDateTimeString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } DateTime dt; if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime) { SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false); } return (DateTimeOffset)Value; case JsonToken.String: string s = (string)Value; return ReadDateTimeOffsetString(s); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } DateTimeOffset dt; if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } #endif internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.TypePropertyName) { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null, true); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, true); } internal void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: SetPostValueState(updateIndex); break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); } if (Peek() != JsonContainerType.None) { _currentState = State.PostValue; } else { SetFinished(); } } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JsonContainerType currentObject = Peek(); switch (currentObject) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } private void SetFinished() { if (SupportMultipleContent) { _currentState = State.Start; } else { _currentState = State.Finished; } } private JsonContainerType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonContainerType.Object; case JsonToken.EndArray: return JsonContainerType.Array; case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } /// <summary> /// Changes the <see cref="State"/> to Closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadAndMoveToContent() { return Read() && MoveToContent(); } internal bool MoveToContent() { JsonToken t = TokenType; while (t == JsonToken.None || t == JsonToken.Comment) { if (!Read()) { return false; } t = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken t; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } else { t = TokenType; } } while (t == JsonToken.Comment); return t; } } }
/// /// Copyright (c) 2004 Thong Nguyen ([email protected]) /// using System; using System.IO; using System.Drawing; using System.Threading; using System.Reflection; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Text.RegularExpressions; [assembly:AssemblyVersion("0.0.1")] namespace ThreadsDemo { /// <summary> /// Summary description for MainForm. /// </summary> public class MainForm : System.Windows.Forms.Form, DeveloperController { private System.ComponentModel.IContainer components; public virtual event EventHandler Start; private int m_NumberOfDevelopers; private int m_DefaultDeveloperWidth; private int m_DefaultDeveloperHeight; private System.Windows.Forms.Panel topPanel; private System.Windows.Forms.Panel mainPanel; private System.Windows.Forms.Label labelTitle; private System.Windows.Forms.Label labelDescription; public const double DegreesPerRadian = 360 / (2 * Math.PI); private double angleSpin = 0; private double angleSpinAdjust = 0.5; private System.Windows.Forms.Timer timer; private int m_CodingDelay = 1500, m_ThinkingDelay = 1500; private System.Windows.Forms.HScrollBar scrollSpinSpeed; Regex fileNameRegex = new Regex(@"^Developer[_](?<filename>(?<name>.*)\..*)$", RegexOptions.IgnoreCase); private void StartControllers() { if (Start != null) { Start(this, EventArgs.Empty); } } public MainForm() { const string filename = "DotGNU_Logo.png"; // // Required for Windows Form Designer support // InitializeComponent(); LoadOptions(); if (!CreateDevelopers()) { Environment.Exit(1); } // Display the form so that handles are created. Show(); BackColor = Color.White; try { // Load the DotGNU logo PictureBox picture = new PictureBox(); picture.Image = Image.FromFile(filename); mainPanel.Controls.Add(picture); picture.SendToBack(); picture.Anchor = AnchorStyles.None; picture.SizeMode = PictureBoxSizeMode.StretchImage; picture.Width = 250; picture.Height = (int)(picture.Width * ((double)picture.Image.Height / (double)picture.Image.Width)); picture.Left = (mainPanel.Width - picture.Width) / 2; picture.Top = (mainPanel.Height - picture.Height) / 2; } catch (FileNotFoundException) { #if CONFIG_SMALL_CONSOLE Console.WriteLine("Warning: Couldn't find {0}", filename); #else Console.Error.WriteLine("Warning: Couldn't find {0}", filename); #endif } // Layout the developers. mainPanel.Layout += new LayoutEventHandler(DeveloperViews_Layout); mainPanel.PerformLayout(); scrollSpinSpeed.Value = scrollSpinSpeed.Maximum / 2; UpdateSpin(); StartControllers(); } /// <summary> /// Load up the command line options. /// </summary> private void LoadOptions() { string[] args = Environment.GetCommandLineArgs(); for (int i = 1; i < args.Length; i++) { switch (args[i]) { case "-codingdelay": case "--codingdelay": i++; if (i >= args.Length) { #if CONFIG_SMALL_CONSOLE Console.Write("Missing value for coding delay."); #else Console.Error.Write("Missing value for coding delay."); #endif } m_CodingDelay = int.Parse(args[i]); break; case "-thinkingdelay": case "--thinkingdelay": i++; if (i >= args.Length) { #if CONFIG_SMALL_CONSOLE Console.Write("Missing value for coding delay."); #else Console.Error.Write("Missing value for coding delay."); #endif } m_ThinkingDelay = int.Parse(args[i]); break; case "-help": case "--help": ShowHelp(); Environment.Exit(0); break; default: Console.WriteLine("Unknown option {0}\n", args[i]); break; } } } /// <summary> /// Show help. /// </summary> private void ShowHelp() { AssemblyName name = GetType().Assembly.GetName(); Console.WriteLine("Coding Developers ({0}) {1}", GetType().Module.Name, name.Version); Console.WriteLine(); Console.WriteLine("This program is an implementation of the \"dining Developers\" problem and"); Console.WriteLine("is used to to test and demonstrate Portable.NET's Threading and UI libraries"); Console.WriteLine("as well as attach faces to names of some DotGNU developers."); Console.WriteLine(); Console.WriteLine("Usage:"); Console.WriteLine(); Console.WriteLine("--codingdelay [delay] Default amount of time a developer spends coding"); Console.WriteLine("--thinkingdelay [delay] Default amount of time a developer spends thinking"); Console.WriteLine("--help Display this help text"); Console.WriteLine(); Console.WriteLine("Coddev will pick up developer image files from the current directory. The"); Console.WriteLine("pictures must use the naming pattern: Developer_<name>.*"); Console.WriteLine(); } /// <summary> /// Callback for the timer that makes the developers spin in a circle. /// </summary> private void Timer_Tick(object sender, System.EventArgs e) { angleSpin = (angleSpin + angleSpinAdjust) % 360; mainPanel.PerformLayout(); } /// <summary> /// Callback for when the spin speed scrollbar changes.. /// </summary> private void ScrollSpinSpeed_ValueChanged(object sender, System.EventArgs e) { UpdateSpin(); } /// <summary> /// Update he spin speed and angle adjust based on the spin speed scrollbar value. /// </summary> private void UpdateSpin() { int value; int max, middle; max = scrollSpinSpeed.Maximum - scrollSpinSpeed.LargeChange; value = scrollSpinSpeed.Value ; if (value > max / 2) { value = (max / 2) - (value - (max / 2)); angleSpinAdjust = 0.75; } else { angleSpinAdjust = -0.75; } if (value <= 0) { value = 1; } value = (int)(Math.Log(value, 2) * 3); if (value == 0) { value = 1; } middle = max / 2; if (scrollSpinSpeed.Value < middle - scrollSpinSpeed.LargeChange || scrollSpinSpeed.Value > middle + scrollSpinSpeed.LargeChange) { timer.Interval = value; timer.Enabled = true; } else { timer.Enabled = false; } } /// <summary> /// Layout the developers in an ellipse formation. /// </summary> private void DeveloperViews_Layout(object sender, LayoutEventArgs e) { DeveloperView view; int x, y, centrex, centrey; double radiusx, radiusy, angle, angleDelta; Control panel = sender as Control; if (m_NumberOfDevelopers == 0) { return; } angle = 0; centrex = mainPanel.ClientRectangle.Width / 2; centrey = mainPanel.ClientRectangle.Height / 2; radiusx = centrex - m_DefaultDeveloperWidth / 2; radiusy = centrey - m_DefaultDeveloperHeight / 2; angle = -90 + angleSpin; angleDelta = 360 / m_NumberOfDevelopers; foreach (Control ctl in panel.Controls) { view = ctl as DeveloperView; if (view != null) { x = (int)(radiusx * Math.Cos(angle / DegreesPerRadian ) + centrex - (view.Width / 2)); y = (int)(radiusy * Math.Sin(angle / DegreesPerRadian) + centrey) - (view.Height / 2); view.Left = x; view.Top = y; angle += angleDelta; } } } /// <summary> /// Create the developers. /// </summary> private bool CreateDevelopers() { int x; FileInfo[] files; DeveloperView view; DeveloperFactory factory; Random random = new Random(); Developer first, prev, developer; DirectoryInfo dirInfo = new DirectoryInfo(Environment.CurrentDirectory); factory = DeveloperFactory.GetFactory(); prev = first = developer = null; files = dirInfo.GetFiles(); for (int i = 0; i < files.Length; i++) { FileInfo fileinfo; x = random.Next(i, files.Length - 1); fileinfo = files[i]; files[i] = files[x]; files[x] = fileinfo; } for (int i = 0; i < files.Length; i++) { Match match; string filename, name; name = files[i].Name; match = fileNameRegex.Match(name); if (match.Length == 0) { continue; } filename = match.Groups["filename"].Value; name = match.Groups["name"].Value; m_NumberOfDevelopers++; Console.WriteLine("Found " + files[i].Name); developer = factory.NewDeveloper(name, prev, null, this); developer.CodingDelay = m_CodingDelay; developer.ThinkingDelay = m_ThinkingDelay; if (prev != null) { prev.Right = developer; } if (m_NumberOfDevelopers == 1) { first = developer; } view = new DeveloperView(developer, files[i].FullName); mainPanel.Controls.Add(view); m_DefaultDeveloperWidth = view.Width; m_DefaultDeveloperHeight = view.Height; prev = developer; } if (m_NumberOfDevelopers < 1) { string message = "No developer pictures found."; #if CONFIG_SMALL_CONSOLE Console.WriteLine(message); #else Console.Error.WriteLine(message); #endif MessageBox.Show(message); Application.Exit(); return false; } first.Left = developer; developer.Right = first; return true; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region InitializeComponent private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.topPanel = new System.Windows.Forms.Panel(); this.scrollSpinSpeed = new System.Windows.Forms.HScrollBar(); this.labelDescription = new System.Windows.Forms.Label(); this.labelTitle = new System.Windows.Forms.Label(); this.mainPanel = new System.Windows.Forms.Panel(); this.timer = new System.Windows.Forms.Timer(this.components); this.topPanel.SuspendLayout(); this.SuspendLayout(); // // topPanel // this.topPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.topPanel.Controls.Add(this.scrollSpinSpeed); this.topPanel.Controls.Add(this.labelDescription); this.topPanel.Controls.Add(this.labelTitle); this.topPanel.Location = new System.Drawing.Point(8, 8); this.topPanel.Name = "topPanel"; this.topPanel.Size = new System.Drawing.Size(976, 112); this.topPanel.TabIndex = 0; // // scrollSpinSpeed // this.scrollSpinSpeed.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.scrollSpinSpeed.Location = new System.Drawing.Point(216, 72); this.scrollSpinSpeed.Maximum = 200; this.scrollSpinSpeed.Name = "scrollSpinSpeed"; this.scrollSpinSpeed.Size = new System.Drawing.Size(528, 24); this.scrollSpinSpeed.TabIndex = 2; this.scrollSpinSpeed.Value = 100; this.scrollSpinSpeed.ValueChanged += new System.EventHandler(this.ScrollSpinSpeed_ValueChanged); // // labelDescription // this.labelDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelDescription.Location = new System.Drawing.Point(8, 32); this.labelDescription.Name = "labelDescription"; this.labelDescription.Size = new System.Drawing.Size(960, 32); this.labelDescription.TabIndex = 1; this.labelDescription.Text = "System.Threading, System.Threading.Monitor and System.Windows.Forms demo (based on the Dini" + "ng Philosophers problem)"; this.labelDescription.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // labelTitle // this.labelTitle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelTitle.Font = new System.Drawing.Font("Arial", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelTitle.Location = new System.Drawing.Point(16, 8); this.labelTitle.Name = "labelTitle"; this.labelTitle.Size = new System.Drawing.Size(952, 24); this.labelTitle.TabIndex = 0; this.labelTitle.Text = "DotGNU \"Coding Developers\""; this.labelTitle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // mainPanel // this.mainPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.mainPanel.Location = new System.Drawing.Point(8, 128); this.mainPanel.Name = "mainPanel"; this.mainPanel.Size = new System.Drawing.Size(976, 648); this.mainPanel.TabIndex = 0; // // timer // this.timer.Interval = 10; this.timer.Tick += new System.EventHandler(this.Timer_Tick); // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(992, 792); this.Controls.Add(this.mainPanel); this.Controls.Add(this.topPanel); this.Name = "MainForm"; this.Text = "DotGNU \"Coding Developers\""; this.topPanel.ResumeLayout(false); this.ResumeLayout(false); } #endregion [STAThread] public static void Main() { Application.Run(new MainForm()); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: bgs/low/pb/client/notification_types.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Bgs.Protocol.Notification.V1 { /// <summary>Holder for reflection information generated from bgs/low/pb/client/notification_types.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class NotificationTypesReflection { #region Descriptor /// <summary>File descriptor for bgs/low/pb/client/notification_types.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static NotificationTypesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CipiZ3MvbG93L3BiL2NsaWVudC9ub3RpZmljYXRpb25fdHlwZXMucHJvdG8S", "HGJncy5wcm90b2NvbC5ub3RpZmljYXRpb24udjEaJWJncy9sb3cvcGIvY2xp", "ZW50L2FjY291bnRfdHlwZXMucHJvdG8aJ2Jncy9sb3cvcGIvY2xpZW50L2F0", "dHJpYnV0ZV90eXBlcy5wcm90bxokYmdzL2xvdy9wYi9jbGllbnQvZW50aXR5", "X3R5cGVzLnByb3RvGiFiZ3MvbG93L3BiL2NsaWVudC9ycGNfdHlwZXMucHJv", "dG8iSwoGVGFyZ2V0EjMKCGlkZW50aXR5GAEgASgLMiEuYmdzLnByb3RvY29s", "LmFjY291bnQudjEuSWRlbnRpdHkSDAoEdHlwZRgCIAEoCSKWAQoMU3Vic2Ny", "aXB0aW9uEjQKBnRhcmdldBgBIAMoCzIkLmJncy5wcm90b2NvbC5ub3RpZmlj", "YXRpb24udjEuVGFyZ2V0EjUKCnN1YnNjcmliZXIYAiABKAsyIS5iZ3MucHJv", "dG9jb2wuYWNjb3VudC52MS5JZGVudGl0eRIZChFkZWxpdmVyeV9yZXF1aXJl", "ZBgDIAEoCCKhAwoMTm90aWZpY2F0aW9uEikKCXNlbmRlcl9pZBgBIAEoCzIW", "LmJncy5wcm90b2NvbC5FbnRpdHlJZBIpCgl0YXJnZXRfaWQYAiABKAsyFi5i", "Z3MucHJvdG9jb2wuRW50aXR5SWQSDAoEdHlwZRgDIAEoCRIqCglhdHRyaWJ1", "dGUYBCADKAsyFy5iZ3MucHJvdG9jb2wuQXR0cmlidXRlEjEKEXNlbmRlcl9h", "Y2NvdW50X2lkGAUgASgLMhYuYmdzLnByb3RvY29sLkVudGl0eUlkEjEKEXRh", "cmdldF9hY2NvdW50X2lkGAYgASgLMhYuYmdzLnByb3RvY29sLkVudGl0eUlk", "EhkKEXNlbmRlcl9iYXR0bGVfdGFnGAcgASgJEhkKEXRhcmdldF9iYXR0bGVf", "dGFnGAggASgJEiUKBHBlZXIYCSABKAsyFy5iZ3MucHJvdG9jb2wuUHJvY2Vz", "c0lkEj4KE2ZvcndhcmRpbmdfaWRlbnRpdHkYCiABKAsyIS5iZ3MucHJvdG9j", "b2wuYWNjb3VudC52MS5JZGVudGl0eUICSAJiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Bgs.Protocol.Account.V1.AccountTypesReflection.Descriptor, global::Bgs.Protocol.AttributeTypesReflection.Descriptor, global::Bgs.Protocol.EntityTypesReflection.Descriptor, global::Bgs.Protocol.RpcTypesReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Notification.V1.Target), global::Bgs.Protocol.Notification.V1.Target.Parser, new[]{ "Identity", "Type" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Notification.V1.Subscription), global::Bgs.Protocol.Notification.V1.Subscription.Parser, new[]{ "Target", "Subscriber", "DeliveryRequired" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Notification.V1.Notification), global::Bgs.Protocol.Notification.V1.Notification.Parser, new[]{ "SenderId", "TargetId", "Type", "Attribute", "SenderAccountId", "TargetAccountId", "SenderBattleTag", "TargetBattleTag", "Peer", "ForwardingIdentity" }, null, null, null) })); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Target : pb::IMessage<Target> { private static readonly pb::MessageParser<Target> _parser = new pb::MessageParser<Target>(() => new Target()); public static pb::MessageParser<Target> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Bgs.Protocol.Notification.V1.NotificationTypesReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Target() { OnConstruction(); } partial void OnConstruction(); public Target(Target other) : this() { Identity = other.identity_ != null ? other.Identity.Clone() : null; type_ = other.type_; } public Target Clone() { return new Target(this); } /// <summary>Field number for the "identity" field.</summary> public const int IdentityFieldNumber = 1; private global::Bgs.Protocol.Account.V1.Identity identity_; public global::Bgs.Protocol.Account.V1.Identity Identity { get { return identity_; } set { identity_ = value; } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 2; private string type_ = ""; public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as Target); } public bool Equals(Target other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Identity, other.Identity)) return false; if (Type != other.Type) return false; return true; } public override int GetHashCode() { int hash = 1; if (identity_ != null) hash ^= Identity.GetHashCode(); if (Type.Length != 0) hash ^= Type.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (identity_ != null) { output.WriteRawTag(10); output.WriteMessage(Identity); } if (Type.Length != 0) { output.WriteRawTag(18); output.WriteString(Type); } } public int CalculateSize() { int size = 0; if (identity_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Identity); } if (Type.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } return size; } public void MergeFrom(Target other) { if (other == null) { return; } if (other.identity_ != null) { if (identity_ == null) { identity_ = new global::Bgs.Protocol.Account.V1.Identity(); } Identity.MergeFrom(other.Identity); } if (other.Type.Length != 0) { Type = other.Type; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (identity_ == null) { identity_ = new global::Bgs.Protocol.Account.V1.Identity(); } input.ReadMessage(identity_); break; } case 18: { Type = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Subscription : pb::IMessage<Subscription> { private static readonly pb::MessageParser<Subscription> _parser = new pb::MessageParser<Subscription>(() => new Subscription()); public static pb::MessageParser<Subscription> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Bgs.Protocol.Notification.V1.NotificationTypesReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Subscription() { OnConstruction(); } partial void OnConstruction(); public Subscription(Subscription other) : this() { target_ = other.target_.Clone(); Subscriber = other.subscriber_ != null ? other.Subscriber.Clone() : null; deliveryRequired_ = other.deliveryRequired_; } public Subscription Clone() { return new Subscription(this); } /// <summary>Field number for the "target" field.</summary> public const int TargetFieldNumber = 1; private static readonly pb::FieldCodec<global::Bgs.Protocol.Notification.V1.Target> _repeated_target_codec = pb::FieldCodec.ForMessage(10, global::Bgs.Protocol.Notification.V1.Target.Parser); private readonly pbc::RepeatedField<global::Bgs.Protocol.Notification.V1.Target> target_ = new pbc::RepeatedField<global::Bgs.Protocol.Notification.V1.Target>(); public pbc::RepeatedField<global::Bgs.Protocol.Notification.V1.Target> Target { get { return target_; } } /// <summary>Field number for the "subscriber" field.</summary> public const int SubscriberFieldNumber = 2; private global::Bgs.Protocol.Account.V1.Identity subscriber_; public global::Bgs.Protocol.Account.V1.Identity Subscriber { get { return subscriber_; } set { subscriber_ = value; } } /// <summary>Field number for the "delivery_required" field.</summary> public const int DeliveryRequiredFieldNumber = 3; private bool deliveryRequired_; public bool DeliveryRequired { get { return deliveryRequired_; } set { deliveryRequired_ = value; } } public override bool Equals(object other) { return Equals(other as Subscription); } public bool Equals(Subscription other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!target_.Equals(other.target_)) return false; if (!object.Equals(Subscriber, other.Subscriber)) return false; if (DeliveryRequired != other.DeliveryRequired) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= target_.GetHashCode(); if (subscriber_ != null) hash ^= Subscriber.GetHashCode(); if (DeliveryRequired != false) hash ^= DeliveryRequired.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { target_.WriteTo(output, _repeated_target_codec); if (subscriber_ != null) { output.WriteRawTag(18); output.WriteMessage(Subscriber); } if (DeliveryRequired != false) { output.WriteRawTag(24); output.WriteBool(DeliveryRequired); } } public int CalculateSize() { int size = 0; size += target_.CalculateSize(_repeated_target_codec); if (subscriber_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Subscriber); } if (DeliveryRequired != false) { size += 1 + 1; } return size; } public void MergeFrom(Subscription other) { if (other == null) { return; } target_.Add(other.target_); if (other.subscriber_ != null) { if (subscriber_ == null) { subscriber_ = new global::Bgs.Protocol.Account.V1.Identity(); } Subscriber.MergeFrom(other.Subscriber); } if (other.DeliveryRequired != false) { DeliveryRequired = other.DeliveryRequired; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { target_.AddEntriesFrom(input, _repeated_target_codec); break; } case 18: { if (subscriber_ == null) { subscriber_ = new global::Bgs.Protocol.Account.V1.Identity(); } input.ReadMessage(subscriber_); break; } case 24: { DeliveryRequired = input.ReadBool(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Notification : pb::IMessage<Notification> { private static readonly pb::MessageParser<Notification> _parser = new pb::MessageParser<Notification>(() => new Notification()); public static pb::MessageParser<Notification> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Bgs.Protocol.Notification.V1.NotificationTypesReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Notification() { OnConstruction(); } partial void OnConstruction(); public Notification(Notification other) : this() { SenderId = other.senderId_ != null ? other.SenderId.Clone() : null; TargetId = other.targetId_ != null ? other.TargetId.Clone() : null; type_ = other.type_; attribute_ = other.attribute_.Clone(); SenderAccountId = other.senderAccountId_ != null ? other.SenderAccountId.Clone() : null; TargetAccountId = other.targetAccountId_ != null ? other.TargetAccountId.Clone() : null; senderBattleTag_ = other.senderBattleTag_; targetBattleTag_ = other.targetBattleTag_; Peer = other.peer_ != null ? other.Peer.Clone() : null; ForwardingIdentity = other.forwardingIdentity_ != null ? other.ForwardingIdentity.Clone() : null; } public Notification Clone() { return new Notification(this); } /// <summary>Field number for the "sender_id" field.</summary> public const int SenderIdFieldNumber = 1; private global::Bgs.Protocol.EntityId senderId_; public global::Bgs.Protocol.EntityId SenderId { get { return senderId_; } set { senderId_ = value; } } /// <summary>Field number for the "target_id" field.</summary> public const int TargetIdFieldNumber = 2; private global::Bgs.Protocol.EntityId targetId_; public global::Bgs.Protocol.EntityId TargetId { get { return targetId_; } set { targetId_ = value; } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 3; private string type_ = ""; public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "attribute" field.</summary> public const int AttributeFieldNumber = 4; private static readonly pb::FieldCodec<global::Bgs.Protocol.Attribute> _repeated_attribute_codec = pb::FieldCodec.ForMessage(34, global::Bgs.Protocol.Attribute.Parser); private readonly pbc::RepeatedField<global::Bgs.Protocol.Attribute> attribute_ = new pbc::RepeatedField<global::Bgs.Protocol.Attribute>(); public pbc::RepeatedField<global::Bgs.Protocol.Attribute> Attribute { get { return attribute_; } } /// <summary>Field number for the "sender_account_id" field.</summary> public const int SenderAccountIdFieldNumber = 5; private global::Bgs.Protocol.EntityId senderAccountId_; public global::Bgs.Protocol.EntityId SenderAccountId { get { return senderAccountId_; } set { senderAccountId_ = value; } } /// <summary>Field number for the "target_account_id" field.</summary> public const int TargetAccountIdFieldNumber = 6; private global::Bgs.Protocol.EntityId targetAccountId_; public global::Bgs.Protocol.EntityId TargetAccountId { get { return targetAccountId_; } set { targetAccountId_ = value; } } /// <summary>Field number for the "sender_battle_tag" field.</summary> public const int SenderBattleTagFieldNumber = 7; private string senderBattleTag_ = ""; public string SenderBattleTag { get { return senderBattleTag_; } set { senderBattleTag_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "target_battle_tag" field.</summary> public const int TargetBattleTagFieldNumber = 8; private string targetBattleTag_ = ""; public string TargetBattleTag { get { return targetBattleTag_; } set { targetBattleTag_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "peer" field.</summary> public const int PeerFieldNumber = 9; private global::Bgs.Protocol.ProcessId peer_; public global::Bgs.Protocol.ProcessId Peer { get { return peer_; } set { peer_ = value; } } /// <summary>Field number for the "forwarding_identity" field.</summary> public const int ForwardingIdentityFieldNumber = 10; private global::Bgs.Protocol.Account.V1.Identity forwardingIdentity_; public global::Bgs.Protocol.Account.V1.Identity ForwardingIdentity { get { return forwardingIdentity_; } set { forwardingIdentity_ = value; } } public override bool Equals(object other) { return Equals(other as Notification); } public bool Equals(Notification other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(SenderId, other.SenderId)) return false; if (!object.Equals(TargetId, other.TargetId)) return false; if (Type != other.Type) return false; if(!attribute_.Equals(other.attribute_)) return false; if (!object.Equals(SenderAccountId, other.SenderAccountId)) return false; if (!object.Equals(TargetAccountId, other.TargetAccountId)) return false; if (SenderBattleTag != other.SenderBattleTag) return false; if (TargetBattleTag != other.TargetBattleTag) return false; if (!object.Equals(Peer, other.Peer)) return false; if (!object.Equals(ForwardingIdentity, other.ForwardingIdentity)) return false; return true; } public override int GetHashCode() { int hash = 1; if (senderId_ != null) hash ^= SenderId.GetHashCode(); hash ^= TargetId.GetHashCode(); hash ^= Type.GetHashCode(); hash ^= attribute_.GetHashCode(); if (senderAccountId_ != null) hash ^= SenderAccountId.GetHashCode(); if (targetAccountId_ != null) hash ^= TargetAccountId.GetHashCode(); if (SenderBattleTag.Length != 0) hash ^= SenderBattleTag.GetHashCode(); if (TargetBattleTag.Length != 0) hash ^= TargetBattleTag.GetHashCode(); if (peer_ != null) hash ^= Peer.GetHashCode(); if (forwardingIdentity_ != null) hash ^= ForwardingIdentity.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (senderId_ != null) { output.WriteRawTag(10); output.WriteMessage(SenderId); } { output.WriteRawTag(18); output.WriteMessage(TargetId); } { output.WriteRawTag(26); output.WriteString(Type); } attribute_.WriteTo(output, _repeated_attribute_codec); if (senderAccountId_ != null) { output.WriteRawTag(42); output.WriteMessage(SenderAccountId); } if (targetAccountId_ != null) { output.WriteRawTag(50); output.WriteMessage(TargetAccountId); } if (SenderBattleTag.Length != 0) { output.WriteRawTag(58); output.WriteString(SenderBattleTag); } if (TargetBattleTag.Length != 0) { output.WriteRawTag(66); output.WriteString(TargetBattleTag); } if (peer_ != null) { output.WriteRawTag(74); output.WriteMessage(Peer); } if (forwardingIdentity_ != null) { output.WriteRawTag(82); output.WriteMessage(ForwardingIdentity); } } public int CalculateSize() { int size = 0; if (senderId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SenderId); } { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TargetId); } { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } size += attribute_.CalculateSize(_repeated_attribute_codec); if (senderAccountId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SenderAccountId); } if (targetAccountId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TargetAccountId); } if (SenderBattleTag.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SenderBattleTag); } if (TargetBattleTag.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TargetBattleTag); } if (peer_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Peer); } if (forwardingIdentity_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ForwardingIdentity); } return size; } public void MergeFrom(Notification other) { if (other == null) { return; } if (other.senderId_ != null) { if (senderId_ == null) { senderId_ = new global::Bgs.Protocol.EntityId(); } SenderId.MergeFrom(other.SenderId); } if (other.targetId_ != null) { if (targetId_ == null) { targetId_ = new global::Bgs.Protocol.EntityId(); } TargetId.MergeFrom(other.TargetId); } if (other.Type.Length != 0) { Type = other.Type; } attribute_.Add(other.attribute_); if (other.senderAccountId_ != null) { if (senderAccountId_ == null) { senderAccountId_ = new global::Bgs.Protocol.EntityId(); } SenderAccountId.MergeFrom(other.SenderAccountId); } if (other.targetAccountId_ != null) { if (targetAccountId_ == null) { targetAccountId_ = new global::Bgs.Protocol.EntityId(); } TargetAccountId.MergeFrom(other.TargetAccountId); } if (other.SenderBattleTag.Length != 0) { SenderBattleTag = other.SenderBattleTag; } if (other.TargetBattleTag.Length != 0) { TargetBattleTag = other.TargetBattleTag; } if (other.peer_ != null) { if (peer_ == null) { peer_ = new global::Bgs.Protocol.ProcessId(); } Peer.MergeFrom(other.Peer); } if (other.forwardingIdentity_ != null) { if (forwardingIdentity_ == null) { forwardingIdentity_ = new global::Bgs.Protocol.Account.V1.Identity(); } ForwardingIdentity.MergeFrom(other.ForwardingIdentity); } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (senderId_ == null) { senderId_ = new global::Bgs.Protocol.EntityId(); } input.ReadMessage(senderId_); break; } case 18: { if (targetId_ == null) { targetId_ = new global::Bgs.Protocol.EntityId(); } input.ReadMessage(targetId_); break; } case 26: { Type = input.ReadString(); break; } case 34: { attribute_.AddEntriesFrom(input, _repeated_attribute_codec); break; } case 42: { if (senderAccountId_ == null) { senderAccountId_ = new global::Bgs.Protocol.EntityId(); } input.ReadMessage(senderAccountId_); break; } case 50: { if (targetAccountId_ == null) { targetAccountId_ = new global::Bgs.Protocol.EntityId(); } input.ReadMessage(targetAccountId_); break; } case 58: { SenderBattleTag = input.ReadString(); break; } case 66: { TargetBattleTag = input.ReadString(); break; } case 74: { if (peer_ == null) { peer_ = new global::Bgs.Protocol.ProcessId(); } input.ReadMessage(peer_); break; } case 82: { if (forwardingIdentity_ == null) { forwardingIdentity_ = new global::Bgs.Protocol.Account.V1.Identity(); } input.ReadMessage(forwardingIdentity_); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using ALinq.Mapping; using System.Globalization; using System.IO; using System.Text; using ALinq.SqlClient; namespace ALinq.SQLite { internal class SQLiteSqlBuilder { private SqlIdentifier SqlIdentifier; private SqlProvider sqlProvider; public SQLiteSqlBuilder(SqlProvider sqlProvider) { SqlIdentifier = sqlProvider.SqlIdentifier; this.sqlProvider = sqlProvider; } // Methods internal void BuildFieldDeclarations(MetaTable table, StringBuilder sb) { int num = 0; var memberNameToMappedName = new Dictionary<object, string>(); foreach (MetaType type in table.RowType.InheritanceTypes) { num += BuildFieldDeclarations(type, memberNameToMappedName, sb); } if (num == 0) { throw SqlClient.Error.CreateDatabaseFailedBecauseOfClassWithNoMembers(table.RowType.Type); } } private int BuildFieldDeclarations(MetaType type, IDictionary<object, string> memberNameToMappedName, StringBuilder sb) { int num = 0; foreach (MetaDataMember member in type.DataMembers) { string str; if ((!member.IsDeclaredBy(type) || member.IsAssociation) || !member.IsPersistent) { continue; } object key = InheritanceRules.DistinguishedMemberName(member.Member); if (memberNameToMappedName.TryGetValue(key, out str)) { if (!(str == member.MappedName)) { goto Label_0075; } continue; } memberNameToMappedName.Add(key, member.MappedName); Label_0075: if (sb.Length > 0) { sb.Append(", "); } sb.AppendLine(); sb.Append(string.Format(CultureInfo.InvariantCulture, " {0} ", new object[] { SqlIdentifier.QuoteCompoundIdentifier(member.MappedName) })); if (!string.IsNullOrEmpty(member.Expression)) { sb.Append("AS " + member.Expression); } else { sb.Append(GetDbType(member)); } num++; } return num; } private string BuildKey(IEnumerable<MetaDataMember> members) { var builder = new StringBuilder(); foreach (MetaDataMember member in members) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(SqlIdentifier.QuoteCompoundIdentifier(member.MappedName)); } return builder.ToString(); } private void BuildPrimaryKey(MetaTable table, StringBuilder sb) { foreach (MetaDataMember member in table.RowType.IdentityMembers) { if (sb.Length > 0) { sb.Append(", "); } sb.Append(SqlIdentifier.QuoteCompoundIdentifier(member.MappedName)); } } public string GetCreateDatabaseCommand(string catalog, string dataFilename, string logFilename) { var builder = new StringBuilder(); builder.AppendFormat("CREATE DATABASE {0}", SqlIdentifier.QuoteIdentifier(catalog)); if (dataFilename != null) { builder.AppendFormat(" ON PRIMARY (NAME='{0}', FILENAME='{1}')", Path.GetFileName(dataFilename), dataFilename); builder.AppendFormat(" LOG ON (NAME='{0}', FILENAME='{1}')", Path.GetFileName(logFilename), logFilename); } return builder.ToString(); } public IEnumerable<string> GetCreateForeignKeyCommands(MetaTable table) { foreach (var metaType in table.RowType.InheritanceTypes) { foreach (var command in GetCreateForeignKeyCommands(metaType)) { yield return command; } } } private IEnumerable<string> GetCreateForeignKeyCommands(MetaType metaType) { foreach (var member in metaType.DataMembers) { if (member.IsDeclaredBy(metaType) && member.IsAssociation) { MetaAssociation association = member.Association; if (association.IsForeignKey) { var stringBuilder = new StringBuilder(); var thisKey = BuildKey(association.ThisKey); var otherKey = BuildKey(association.OtherKey); var otherTable = association.OtherType.Table.TableName; var mappedName = member.MappedName; if (mappedName == member.Name) { mappedName = string.Format(CultureInfo.InvariantCulture, "FK_{0}_{1}", new object[] { metaType.Table.TableName, member.Name }); } var command = "ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3}({4})"; var otherMember = association.OtherMember; if (otherMember != null) { string deleteRule = association.DeleteRule; if (deleteRule != null) { command += Environment.NewLine + " ON DELETE " + deleteRule; } } yield return stringBuilder.AppendFormat(command, new object[] { SqlIdentifier.QuoteCompoundIdentifier(metaType.Table.TableName), SqlIdentifier.QuoteIdentifier(mappedName), SqlIdentifier.QuoteCompoundIdentifier(thisKey), SqlIdentifier.QuoteCompoundIdentifier(otherTable), SqlIdentifier.QuoteCompoundIdentifier(otherKey) }).ToString(); } } } } private string GetCreateTableCommand(MetaTable table) { var builder = new StringBuilder(); var sb = new StringBuilder(); BuildFieldDeclarations(table, sb); builder.AppendFormat("CREATE TABLE {0}", SqlIdentifier.QuoteCompoundIdentifier(table.TableName)); builder.Append("("); builder.Append(sb.ToString()); sb = new StringBuilder(); if (table.RowType.IdentityMembers.Count > 0) if (table.RowType.IdentityMembers.Count > 1 || table.RowType.IdentityMembers[0].IsDbGenerated == false) { BuildPrimaryKey(table, sb); if (sb.Length > 0) { string s = string.Format(CultureInfo.InvariantCulture, "PK_{0}", new object[] { table.TableName }); builder.Append(", "); builder.AppendLine(); builder.AppendFormat(" CONSTRAINT {0} PRIMARY KEY ({1})", SqlIdentifier.QuoteIdentifier(s), sb); } } builder.AppendLine(); builder.Append(" )"); return builder.ToString(); } internal IEnumerable<string> GetCreateTableCommands(MetaTable table) { yield return this.GetCreateTableCommand(table); } #region MyRegion //private static string GetDbType(MetaDataMember mm) //{ // string dbType = mm.DbType; // if (dbType != null) // { // return dbType; // } // var builder = new StringBuilder(); // Type type = mm.Type; // bool canBeNull = mm.CanBeNull; // if (type.IsValueType && IsNullable(type)) // { // type = type.GetGenericArguments()[0]; // } // #region MyRegion // // if (mm.IsVersion) // // { // // builder.Append("Timestamp"); // // } // // else if (mm.IsPrimaryKey && mm.IsDbGenerated) // // { // // switch (Type.GetTypeCode(type)) // // { // // case TypeCode.Object: // // if (type != typeof(Guid)) // // { // // throw Error.CouldNotDetermineDbGeneratedSqlType(type); // // } // // builder.Append("UniqueIdentifier"); // // goto Label_02AD; // // case TypeCode.DBNull: // // case TypeCode.Boolean: // // case TypeCode.Char: // // case TypeCode.Single: // // case TypeCode.Double: // // goto Label_02AD; // // case TypeCode.SByte: // // case TypeCode.Int16: // // builder.Append("SmallInt"); // // goto Label_02AD; // // case TypeCode.Byte: // // builder.Append("TinyInt"); // // return builder.ToString(); // // case TypeCode.UInt16: // // case TypeCode.Int32: // // builder.Append("Int"); // // goto Label_02AD; // // //builder.Append("ROWID"); // // //return builder.ToString(); // // break; // // case TypeCode.UInt32: // // case TypeCode.Int64: // // builder.Append("BigInt"); // // goto Label_02AD; // // case TypeCode.UInt64: // // case TypeCode.Decimal: // // builder.Append("Real"); // // goto Label_02AD; // // } // // } // // else // // { // // switch (Type.GetTypeCode(type)) // // { // // case TypeCode.Object: // // builder.Append("BINARY"); // // goto Label_02AD; // // case TypeCode.DBNull: // // goto Label_02AD; // // case TypeCode.Boolean: // // builder.Append("BIT"); // // goto Label_02AD; // // case TypeCode.Char: // // builder.Append("CHAR(1)"); // // goto Label_02AD; // // case TypeCode.SByte: // // case TypeCode.Int16: // // builder.Append("SmallInt"); // // goto Label_02AD; // // case TypeCode.Byte: // // builder.Append("TinyInt"); // // goto Label_02AD; // // case TypeCode.UInt16: // // case TypeCode.Int32: // // builder.Append("Int"); // // goto Label_02AD; // // case TypeCode.UInt32: // // case TypeCode.Int64: // // builder.Append("BigInt"); // // goto Label_02AD; // // case TypeCode.UInt64: // // builder.Append("Decimal(20)"); // // goto Label_02AD; // // case TypeCode.Single: // // builder.Append("Real"); // // goto Label_02AD; // // case TypeCode.Double: // // builder.Append("Float"); // // goto Label_02AD; // // case TypeCode.Decimal: // // builder.Append("Real"); // // goto Label_02AD; // // case TypeCode.DateTime: // // builder.Append("DateTime"); // // goto Label_02AD; // // case TypeCode.String: // // builder.Append("TEXT"); // // goto Label_02AD; // // } // // } // //Label_02AD: // #endregion // switch (Type.GetTypeCode(type)) // { // case TypeCode.Object: // builder.Append("BINARY"); // break; // case TypeCode.DBNull: // break; // case TypeCode.Boolean: // builder.Append("BIT"); // break; // case TypeCode.Char: // builder.Append("CHAR(1)"); // break; // case TypeCode.SByte: // case TypeCode.Int16: // builder.Append("SmallInt"); // break; // case TypeCode.Byte: // builder.Append("TinyInt"); // break; // case TypeCode.UInt16: // case TypeCode.Int32: // builder.Append("Integer"); // break; // case TypeCode.UInt32: // case TypeCode.Int64: // builder.Append("BigInt"); // break; // case TypeCode.UInt64: // builder.Append("Decimal(20)"); // break; // case TypeCode.Single: // builder.Append("Real"); // break; // case TypeCode.Double: // builder.Append("Float"); // break; // case TypeCode.Decimal: // builder.Append("Real"); // break; // case TypeCode.DateTime: // builder.Append("DateTime"); // break; // case TypeCode.String: // builder.Append("TEXT"); // break; // } // if (!canBeNull) // { // builder.Append(" NOT NULL"); // } // if (mm.IsPrimaryKey) // { // builder.Append(" PRIMARY KEY"); // if (mm.IsDbGenerated) // { // builder.Append(" AUTOINCREMENT"); // } // } // //if (mm.IsPrimaryKey && mm.IsDbGenerated) // //{ // // if (type == typeof(Guid)) // // { // // builder.Append(" DEFAULT NEWID()"); // // } // // else // // { // // builder.Append(" IDENTITY"); // // } // //} // return builder.ToString(); //} #endregion private string GetDbType(MetaDataMember mm) { string dbType = mm.DbType; if (string.IsNullOrEmpty(dbType)) { var sqlDataType = this.sqlProvider.TypeProvider.From(mm.Type); dbType = sqlDataType.ToQueryString(); } var builder = new StringBuilder(); builder.Append(dbType); bool canBeNull = mm.CanBeNull; if (!canBeNull) { builder.Append(" NOT NULL"); } if (mm.IsPrimaryKey && mm.IsDbGenerated) { builder.Append(" PRIMARY KEY AUTOINCREMENT"); } return builder.ToString(); } internal string GetDropDatabaseCommand(string catalog) { var builder = new StringBuilder(); builder.AppendFormat("DROP DATABASE {0}", SqlIdentifier.QuoteIdentifier(catalog)); return builder.ToString(); } internal static bool IsNullable(Type type) { return (type.IsGenericType && typeof(Nullable<>).IsAssignableFrom(type.GetGenericTypeDefinition())); } // Nested Types } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Net; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; /***************************************************** * * XMLRPCModule * * Module for accepting incoming communications from * external XMLRPC client and calling a remote data * procedure for a registered data channel/prim. * * * 1. On module load, open a listener port * 2. Attach an XMLRPC handler * 3. When a request is received: * 3.1 Parse into components: channel key, int, string * 3.2 Look up registered channel listeners * 3.3 Call the channel (prim) remote data method * 3.4 Capture the response (llRemoteDataReply) * 3.5 Return response to client caller * 3.6 If no response from llRemoteDataReply within * RemoteReplyScriptTimeout, generate script timeout fault * * Prims in script must: * 1. Open a remote data channel * 1.1 Generate a channel ID * 1.2 Register primid,channelid pair with module * 2. Implement the remote data procedure handler * * llOpenRemoteDataChannel * llRemoteDataReply * remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval) * llCloseRemoteDataChannel * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC { public class XMLRPCModule : IRegionModule, IXMLRPC { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_name = "XMLRPCModule"; // <channel id, RPCChannelInfo> private Dictionary<UUID, RPCChannelInfo> m_openChannels; private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses; private int m_remoteDataPort = 0; private Dictionary<UUID, RPCRequestInfo> m_rpcPending; private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses; private List<Scene> m_scenes = new List<Scene>(); private int RemoteReplyScriptTimeout = 9000; private int RemoteReplyScriptWait = 300; private object XMLRPCListLock = new object(); #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { // We need to create these early because the scripts might be calling // But since this gets called for every region, we need to make sure they // get called only one time (or we lose any open channels) if (null == m_openChannels) { m_openChannels = new Dictionary<UUID, RPCChannelInfo>(); m_rpcPending = new Dictionary<UUID, RPCRequestInfo>(); m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>(); m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>(); try { m_remoteDataPort = config.Configs["Network"].GetInt("remoteDataPort", m_remoteDataPort); } catch (Exception) { } } if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); scene.RegisterModuleInterface<IXMLRPC>(this); } } public void PostInitialise() { if (IsEnabled()) { // Start http server // Attach xmlrpc handlers m_log.Info("[REMOTE_DATA]: " + "Starting XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands."); BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort, null); // XmlRpc httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData); // New Style httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("llRemoteData"), XmlRpcRemoteData)); httpServer.Start(); } } public void Close() { } public string Name { get { return m_name; } } public bool IsSharedModule { get { return true; } } public int Port { get { return m_remoteDataPort; } } #endregion #region IXMLRPC Members public bool IsEnabled() { return (m_remoteDataPort > 0); } /********************************************** * OpenXMLRPCChannel * * Generate a UUID channel key and add it and * the prim id to dictionary <channelUUID, primUUID> * * A custom channel key can be proposed. * Otherwise, passing UUID.Zero will generate * and return a random channel * * First check if there is a channel assigned for * this itemID. If there is, then someone called * llOpenRemoteDataChannel twice. Just return the * original channel. Other option is to delete the * current channel and assign a new one. * * ********************************************/ public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID) { UUID newChannel = UUID.Zero; // This should no longer happen, but the check is reasonable anyway if (null == m_openChannels) { m_log.Warn("[RemoteDataReply] Attempt to open channel before initialization is complete"); return newChannel; } //Is a dupe? foreach (RPCChannelInfo ci in m_openChannels.Values) { if (ci.GetItemID().Equals(itemID)) { // return the original channel ID for this item newChannel = ci.GetChannelID(); break; } } if (newChannel == UUID.Zero) { newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID; RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel); lock (XMLRPCListLock) { m_openChannels.Add(newChannel, rpcChanInfo); } } return newChannel; } // Delete channels based on itemID // for when a script is deleted public void DeleteChannels(UUID itemID) { if (m_openChannels != null) { ArrayList tmp = new ArrayList(); lock (XMLRPCListLock) { foreach (RPCChannelInfo li in m_openChannels.Values) { if (li.GetItemID().Equals(itemID)) { tmp.Add(itemID); } } IEnumerator tmpEnumerator = tmp.GetEnumerator(); while (tmpEnumerator.MoveNext()) m_openChannels.Remove((UUID) tmpEnumerator.Current); } } } /********************************************** * Remote Data Reply * * Response to RPC message * *********************************************/ public void RemoteDataReply(string channel, string message_id, string sdata, int idata) { UUID message_key = new UUID(message_id); UUID channel_key = new UUID(channel); RPCRequestInfo rpcInfo = null; if (message_key == UUID.Zero) { foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values) if (oneRpcInfo.GetChannelKey() == channel_key) rpcInfo = oneRpcInfo; } else { m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo); } if (rpcInfo != null) { rpcInfo.SetStrRetval(sdata); rpcInfo.SetIntRetval(idata); rpcInfo.SetProcessed(true); m_rpcPendingResponses.Remove(message_key); } else { m_log.Warn("[RemoteDataReply]: Channel or message_id not found"); } } /********************************************** * CloseXMLRPCChannel * * Remove channel from dictionary * *********************************************/ public void CloseXMLRPCChannel(UUID channelKey) { if (m_openChannels.ContainsKey(channelKey)) m_openChannels.Remove(channelKey); } public bool hasRequests() { lock (XMLRPCListLock) { if (m_rpcPending != null) return (m_rpcPending.Count > 0); else return false; } } public IXmlRpcRequestInfo GetNextCompletedRequest() { if (m_rpcPending != null) { lock (XMLRPCListLock) { foreach (UUID luid in m_rpcPending.Keys) { RPCRequestInfo tmpReq; if (m_rpcPending.TryGetValue(luid, out tmpReq)) { if (!tmpReq.IsProcessed()) return tmpReq; } } } } return null; } public void RemoveCompletedRequest(UUID id) { lock (XMLRPCListLock) { RPCRequestInfo tmp; if (m_rpcPending.TryGetValue(id, out tmp)) { m_rpcPending.Remove(id); m_rpcPendingResponses.Add(id, tmp); } else { m_log.Error("UNABLE TO REMOVE COMPLETED REQUEST"); } } } public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata) { SendRemoteDataRequest req = new SendRemoteDataRequest( localID, itemID, channel, dest, idata, sdata ); m_pendingSRDResponses.Add(req.GetReqID(), req); req.Process(); return req.ReqID; } public IServiceRequest GetNextCompletedSRDRequest() { if (m_pendingSRDResponses != null) { lock (XMLRPCListLock) { foreach (UUID luid in m_pendingSRDResponses.Keys) { SendRemoteDataRequest tmpReq; if (m_pendingSRDResponses.TryGetValue(luid, out tmpReq)) { if (tmpReq.Finished) return tmpReq; } } } } return null; } public void RemoveCompletedSRDRequest(UUID id) { lock (XMLRPCListLock) { SendRemoteDataRequest tmpReq; if (m_pendingSRDResponses.TryGetValue(id, out tmpReq)) { m_pendingSRDResponses.Remove(id); } } } public void CancelSRDRequests(UUID itemID) { if (m_pendingSRDResponses != null) { lock (XMLRPCListLock) { foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values) { if (li.ItemID.Equals(itemID)) m_pendingSRDResponses.Remove(li.GetReqID()); } } } } #endregion public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable) request.Params[0]; bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") && requestData.Contains("StringValue")); if (GoodXML) { UUID channel = new UUID((string) requestData["Channel"]); RPCChannelInfo rpcChanInfo; if (m_openChannels.TryGetValue(channel, out rpcChanInfo)) { string intVal = Convert.ToInt32(requestData["IntValue"]).ToString(); string strVal = (string) requestData["StringValue"]; RPCRequestInfo rpcInfo; lock (XMLRPCListLock) { rpcInfo = new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal, intVal); m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo); } int timeoutCtr = 0; while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout)) { Thread.Sleep(RemoteReplyScriptWait); timeoutCtr += RemoteReplyScriptWait; } if (rpcInfo.IsProcessed()) { Hashtable param = new Hashtable(); param["StringValue"] = rpcInfo.GetStrRetval(); param["IntValue"] = rpcInfo.GetIntRetval(); ArrayList parameters = new ArrayList(); parameters.Add(param); response.Value = parameters; rpcInfo = null; } else { response.SetFault(-1, "Script timeout"); rpcInfo = null; } } else { response.SetFault(-1, "Invalid channel"); } } return response; } } public class RPCRequestInfo: IXmlRpcRequestInfo { private UUID m_ChannelKey; private string m_IntVal; private UUID m_ItemID; private uint m_localID; private UUID m_MessageID; private bool m_processed; private int m_respInt; private string m_respStr; private string m_StrVal; public RPCRequestInfo(uint localID, UUID itemID, UUID channelKey, string strVal, string intVal) { m_localID = localID; m_StrVal = strVal; m_IntVal = intVal; m_ItemID = itemID; m_ChannelKey = channelKey; m_MessageID = UUID.Random(); m_processed = false; m_respStr = String.Empty; m_respInt = 0; } public bool IsProcessed() { return m_processed; } public UUID GetChannelKey() { return m_ChannelKey; } public void SetProcessed(bool processed) { m_processed = processed; } public void SetStrRetval(string resp) { m_respStr = resp; } public string GetStrRetval() { return m_respStr; } public void SetIntRetval(int resp) { m_respInt = resp; } public int GetIntRetval() { return m_respInt; } public uint GetLocalID() { return m_localID; } public UUID GetItemID() { return m_ItemID; } public string GetStrVal() { return m_StrVal; } public int GetIntValue() { return int.Parse(m_IntVal); } public UUID GetMessageID() { return m_MessageID; } } public class RPCChannelInfo { private UUID m_ChannelKey; private UUID m_itemID; private uint m_localID; public RPCChannelInfo(uint localID, UUID itemID, UUID channelID) { m_ChannelKey = channelID; m_localID = localID; m_itemID = itemID; } public UUID GetItemID() { return m_itemID; } public UUID GetChannelID() { return m_ChannelKey; } public uint GetLocalID() { return m_localID; } } public class SendRemoteDataRequest: IServiceRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Channel; public string DestURL; private bool _finished; public bool Finished { get { return _finished; } set { _finished = value; } } private Thread httpThread; public int Idata; private UUID _itemID; public UUID ItemID { get { return _itemID; } set { _itemID = value; } } private uint _localID; public uint LocalID { get { return _localID; } set { _localID = value; } } private UUID _reqID; public UUID ReqID { get { return _reqID; } set { _reqID = value; } } public XmlRpcRequest Request; public int ResponseIdata; public string ResponseSdata; public string Sdata; public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata) { this.Channel = channel; DestURL = dest; this.Idata = idata; this.Sdata = sdata; ItemID = itemID; LocalID = localID; ReqID = UUID.Random(); } public void Process() { httpThread = new Thread(SendRequest); httpThread.Name = "HttpRequestThread"; httpThread.Priority = ThreadPriority.BelowNormal; httpThread.IsBackground = true; _finished = false; httpThread.Start(); ThreadTracker.Add(httpThread); } /* * TODO: More work on the response codes. Right now * returning 200 for success or 499 for exception */ public void SendRequest() { Hashtable param = new Hashtable(); // Check if channel is an UUID // if not, use as method name UUID parseUID; string mName = "llRemoteData"; if ((Channel != null) && (Channel != "")) if (!UUID.TryParse(Channel, out parseUID)) mName = Channel; else param["Channel"] = Channel; param["StringValue"] = Sdata; param["IntValue"] = Convert.ToString(Idata); ArrayList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest(mName, parameters); try { XmlRpcResponse resp = req.Send(DestURL, 30000); if (resp != null) { Hashtable respParms; if (resp.Value.GetType().Equals(typeof(Hashtable))) { respParms = (Hashtable) resp.Value; } else { ArrayList respData = (ArrayList) resp.Value; respParms = (Hashtable) respData[0]; } if (respParms != null) { if (respParms.Contains("StringValue")) { Sdata = (string) respParms["StringValue"]; } if (respParms.Contains("IntValue")) { Idata = Convert.ToInt32((string) respParms["IntValue"]); } if (respParms.Contains("faultString")) { Sdata = (string) respParms["faultString"]; } if (respParms.Contains("faultCode")) { Idata = Convert.ToInt32(respParms["faultCode"]); } } } } catch (Exception we) { Sdata = we.Message; m_log.Warn("[SendRemoteDataRequest]: Request failed"); m_log.Warn(we.StackTrace); } _finished = true; } public void Stop() { try { httpThread.Abort(); } catch (Exception) { } } public UUID GetReqID() { return ReqID; } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using BarcodeFormat = com.google.zxing.BarcodeFormat; using ReaderException = com.google.zxing.ReaderException; using Result = com.google.zxing.Result; using ResultPoint = com.google.zxing.ResultPoint; using BitArray = com.google.zxing.common.BitArray; namespace com.google.zxing.oned { /// <summary> <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source /// </author> public sealed class Code39Reader:OneDReader { internal const System.String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHABET '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly char[] ALPHABET = ALPHABET_STRING.ToCharArray(); /// <summary> These represent the encodings of characters, as patterns of wide and narrow bars. /// The 9 least-significant bits of each int correspond to the pattern of wide and narrow, /// with 1s representing "wide" and 0s representing narrow. /// </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'CHARACTER_ENCODINGS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] CHARACTER_ENCODINGS = new int[]{0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, 0x0A8, 0x0A2, 0x08A, 0x02A}; //UPGRADE_NOTE: Final was removed from the declaration of 'ASTERISK_ENCODING '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; //UPGRADE_NOTE: Final was removed from the declaration of 'usingCheckDigit '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private bool usingCheckDigit; //UPGRADE_NOTE: Final was removed from the declaration of 'extendedMode '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private bool extendedMode; /// <summary> Creates a reader that assumes all encoded data is data, and does not treat the final /// character as a check digit. It will not decoded "extended Code 39" sequences. /// </summary> public Code39Reader() { usingCheckDigit = false; extendedMode = false; } /// <summary> Creates a reader that can be configured to check the last character as a check digit. /// It will not decoded "extended Code 39" sequences. /// /// </summary> /// <param name="usingCheckDigit">if true, treat the last data character as a check digit, not /// data, and verify that the checksum passes. /// </param> public Code39Reader(bool usingCheckDigit) { this.usingCheckDigit = usingCheckDigit; this.extendedMode = false; } /// <summary> Creates a reader that can be configured to check the last character as a check digit, /// or optionally attempt to decode "extended Code 39" sequences that are used to encode /// the full ASCII character set. /// /// </summary> /// <param name="usingCheckDigit">if true, treat the last data character as a check digit, not /// data, and verify that the checksum passes. /// </param> /// <param name="extendedMode">if true, will attempt to decode extended Code 39 sequences in the /// text. /// </param> public Code39Reader(bool usingCheckDigit, bool extendedMode) { this.usingCheckDigit = usingCheckDigit; this.extendedMode = extendedMode; } public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { int[] start = findAsteriskPattern(row); int nextStart = start[1]; int end = row.Size; // Read off white space while (nextStart < end && !row.get_Renamed(nextStart)) { nextStart++; } System.Text.StringBuilder result = new System.Text.StringBuilder(20); int[] counters = new int[9]; char decodedChar; int lastStart; do { recordPattern(row, nextStart, counters); int pattern = toNarrowWidePattern(counters); if (pattern < 0) { throw ReaderException.Instance; } decodedChar = patternToChar(pattern); result.Append(decodedChar); lastStart = nextStart; for (int i = 0; i < counters.Length; i++) { nextStart += counters[i]; } // Read off white space while (nextStart < end && !row.get_Renamed(nextStart)) { nextStart++; } } while (decodedChar != '*'); result.Remove(result.Length - 1, 1); // remove asterisk // Look for whitespace after pattern: int lastPatternSize = 0; for (int i = 0; i < counters.Length; i++) { lastPatternSize += counters[i]; } int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; // If 50% of last pattern size, following last pattern, is not whitespace, fail // (but if it's whitespace to the very end of the image, that's OK) if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) { throw ReaderException.Instance; } if (usingCheckDigit) { int max = result.Length - 1; int total = 0; for (int i = 0; i < max; i++) { total += ALPHABET_STRING.IndexOf((System.Char) result[i]); } if (total % 43 != ALPHABET_STRING.IndexOf((System.Char) result[max])) { throw ReaderException.Instance; } result.Remove(max, 1); } System.String resultString = result.ToString(); if (extendedMode) { resultString = decodeExtended(resultString); } if (resultString.Length == 0) { // Almost surely a false positive throw ReaderException.Instance; } //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float left = (float) (start[1] + start[0]) / 2.0f; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float right = (float) (nextStart + lastStart) / 2.0f; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return new Result(resultString, null, new ResultPoint[]{new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_39); } private static int[] findAsteriskPattern(BitArray row) { int width = row.Size; int rowOffset = 0; while (rowOffset < width) { if (row.get_Renamed(rowOffset)) { break; } rowOffset++; } int counterPosition = 0; int[] counters = new int[9]; int patternStart = rowOffset; bool isWhite = false; int patternLength = counters.Length; for (int i = rowOffset; i < width; i++) { bool pixel = row.get_Renamed(i); if (pixel ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) { // Look for whitespace before start pattern, >= 50% of width of start pattern if (row.isRange(System.Math.Max(0, patternStart - (i - patternStart) / 2), patternStart, false)) { return new int[]{patternStart, i}; } } patternStart += counters[0] + counters[1]; for (int y = 2; y < patternLength; y++) { counters[y - 2] = counters[y]; } counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw ReaderException.Instance; } // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions // per image when using some of our blackbox images. private static int toNarrowWidePattern(int[] counters) { int numCounters = counters.Length; int maxNarrowCounter = 0; int wideCounters; do { int minCounter = System.Int32.MaxValue; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counter < minCounter && counter > maxNarrowCounter) { minCounter = counter; } } maxNarrowCounter = minCounter; wideCounters = 0; int totalWideCountersWidth = 0; int pattern = 0; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counters[i] > maxNarrowCounter) { pattern |= 1 << (numCounters - 1 - i); wideCounters++; totalWideCountersWidth += counter; } } if (wideCounters == 3) { // Found 3 wide counters, but are they close enough in width? // We can perform a cheap, conservative check to see if any individual // counter is more than 1.5 times the average: for (int i = 0; i < numCounters && wideCounters > 0; i++) { int counter = counters[i]; if (counters[i] > maxNarrowCounter) { wideCounters--; // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average if ((counter << 1) >= totalWideCountersWidth) { return - 1; } } } return pattern; } } while (wideCounters > 3); return - 1; } private static char patternToChar(int pattern) { for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { return ALPHABET[i]; } } throw ReaderException.Instance; } private static System.String decodeExtended(System.String encoded) { int length = encoded.Length; System.Text.StringBuilder decoded = new System.Text.StringBuilder(length); for (int i = 0; i < length; i++) { char c = encoded[i]; if (c == '+' || c == '$' || c == '%' || c == '/') { char next = encoded[i + 1]; char decodedChar = '\x0000'; switch (c) { case '+': // +A to +Z map to a to z if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next + 32); } else { throw ReaderException.Instance; } break; case '$': // $A to $Z map to control codes SH to SB if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next - 64); } else { throw ReaderException.Instance; } break; case '%': // %A to %E map to control codes ESC to US if (next >= 'A' && next <= 'E') { decodedChar = (char) (next - 38); } else if (next >= 'F' && next <= 'W') { decodedChar = (char) (next - 11); } else { throw ReaderException.Instance; } break; case '/': // /A to /O map to ! to , and /Z maps to : if (next >= 'A' && next <= 'O') { decodedChar = (char) (next - 32); } else if (next == 'Z') { decodedChar = ':'; } else { throw ReaderException.Instance; } break; } decoded.Append(decodedChar); // bump up i again since we read two characters i++; } else { decoded.Append(c); } } return decoded.ToString(); } } }
// 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 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// HttpServerFailure operations. /// </summary> public partial class HttpServerFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpServerFailure { /// <summary> /// Initializes a new instance of the HttpServerFailure class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public HttpServerFailure(AutoRestHttpInfrastructureTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestHttpInfrastructureTestService /// </summary> public AutoRestHttpInfrastructureTestService Client { get; private set; } /// <summary> /// Return 501 status code - should be represented in the client as an error /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Error>> Head501WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Head501", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/http/failure/server/501").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("HEAD"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(httpResponse.IsSuccessStatusCode)) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Error>(); result.Request = httpRequest; result.Response = httpResponse; string defaultResponseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Error>(defaultResponseContent, this.Client.DeserializationSettings); if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Return 501 status code - should be represented in the client as an error /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Error>> Get501WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Get501", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/http/failure/server/501").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(httpResponse.IsSuccessStatusCode)) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Error>(); result.Request = httpRequest; result.Response = httpResponse; string defaultResponseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Error>(defaultResponseContent, this.Client.DeserializationSettings); if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Return 505 status code - should be represented in the client as an error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Error>> Post505WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Post505", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/http/failure/server/505").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(httpResponse.IsSuccessStatusCode)) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Error>(); result.Request = httpRequest; result.Response = httpResponse; string defaultResponseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Error>(defaultResponseContent, this.Client.DeserializationSettings); if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Return 505 status code - should be represented in the client as an error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Error>> Delete505WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Delete505", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/http/failure/server/505").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("DELETE"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(httpResponse.IsSuccessStatusCode)) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Error>(); result.Request = httpRequest; result.Response = httpResponse; string defaultResponseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Error>(defaultResponseContent, this.Client.DeserializationSettings); if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Threading; using System.Threading.Tasks; using Infrastructure.Common; using ScenarioTests.Common; using Xunit; public static partial class ServiceContractTests { [WcfFact] [OuterLoop] public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Buffered() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Buffered; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStream(stream); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_StreamedRequest() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.StreamedRequest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var result = serviceProxy.GetStringFromStream(stream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_StreamedResponse() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.StreamedResponse; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ var returnStream = serviceProxy.GetStreamFromString(testString); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStream(stream); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_Async() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStreamAsync(stream).Result; var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_WithSingleThreadedSyncContext timed-out."); } [WcfFact] [OuterLoop] public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_Async_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_Async(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: BasicHttp_DefaultSettings_Echo_RoundTrips_String_Streamed_Async_WithSingleThreadedSyncContext timed-out."); } [WcfFact] [OuterLoop] public static void BasicHttp_Streamed_Async_Delayed_And_Aborted_Request_Throws_TimeoutException() { // This test is a regression test that verifies an issue discovered where exceeding the timeout // and aborting the channel before the client's Task completed led to incorrect error handling. BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; int sendTimeoutMs = 3000; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; binding.SendTimeout = TimeSpan.FromMilliseconds(sendTimeoutMs); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy = factory.CreateChannel(); // Create a read stream that will both timeout and then abort the proxy channel when the // async read is called. We also intercept the synchronous read because that path can also // be executed during an async read. stream = new TestMockStream() { CopyToAsyncFunc = (Stream destination, int bufferSize, CancellationToken ct) => { // Abort to force the internal HttpClientChannelAsyncRequest.Cleanup() // to clear its data structures before the client's Task completes. Task.Delay(sendTimeoutMs * 2).Wait(); ((ICommunicationObject)serviceProxy).Abort(); return null; }, ReadFunc = (byte[] buffer, int offset, int count) => { // Abort to force the internal HttpClientChannelAsyncRequest.Cleanup() // to clear its data structures before the client's Task completes. Task.Delay(sendTimeoutMs * 2).Wait(); ((ICommunicationObject)serviceProxy).Abort(); return -1; } }; // *** EXECUTE *** \\ Assert.Throws<TimeoutException>(() => { var unused = serviceProxy.EchoStreamAsync(stream).GetAwaiter().GetResult(); }); // *** VALIDATE *** \\ // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_Streamed_Async_Delayed_Request_Throws_TimeoutException() { BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; int sendTimeoutMs = 3000; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; binding.SendTimeout = TimeSpan.FromMilliseconds(sendTimeoutMs); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy = factory.CreateChannel(); // Create a read stream that deliberately times out during the async read during the request. // We also intercept the synchronous read because that path can also be executed during // an async read. stream = new TestMockStream() { CopyToAsyncFunc = (Stream destination, int bufferSize, CancellationToken ct) => { Task.Delay(sendTimeoutMs * 2).Wait(); return null; }, ReadFunc = (byte[] buffer, int offset, int count) => { Task.Delay(sendTimeoutMs * 2).Wait(); return -1; } }; // *** EXECUTE *** \\ Assert.Throws<TimeoutException>(() => { var unused = serviceProxy.EchoStreamAsync(stream).GetAwaiter().GetResult(); }); // *** VALIDATE *** \\ // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_Buffered_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.None); binding.TransferMode = TransferMode.Buffered; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStream(stream); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_StreamedRequest_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = binding = new NetTcpBinding(SecurityMode.None); binding.TransferMode = TransferMode.StreamedRequest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var result = serviceProxy.GetStringFromStream(stream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_StreamedResponse_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.None); binding.TransferMode = TransferMode.StreamedResponse; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ var returnStream = serviceProxy.GetStreamFromString(testString); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_Streamed_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.None); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStream(stream); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_Streamed_Async_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.None); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStreamAsync(stream).Result; var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_StreamedRequest_Async_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.None); binding.TransferMode = TransferMode.StreamedRequest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStreamAsync(stream).Result; var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_StreamedResponse_Async_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.None); binding.TransferMode = TransferMode.StreamedResponse; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Streamed_NoSecurity_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStreamAsync(stream).Result; var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_Streamed_RoundTrips_String_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => ServiceContractTests.NetTcp_NoSecurity_Streamed_RoundTrips_String(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: NetTcp_NoSecurity_String_Streamed_RoundTrips_WithSingleThreadedSyncContext timed-out."); } [WcfFact] [OuterLoop] public static void NetTcp_NoSecurity_Streamed_Async_RoundTrips_String_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => ServiceContractTests.NetTcp_NoSecurity_Streamed_Async_RoundTrips_String(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: NetTcp_NoSecurity_Streamed_Async_RoundTrips_String_WithSingleThreadedSyncContext timed-out."); } [WcfFact] [OuterLoop] public static void ServiceContract_Call_Operation_With_MessageParameterAttribute() { // This test verifies the scenario where MessageParameter attribute is used in the contract ChannelFactory<IWcfServiceGenerated> factory = null; IWcfServiceGenerated serviceProxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); // Note the service interface used. It was manually generated with svcutil. factory = new ChannelFactory<IWcfServiceGenerated>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string echoString = "you"; string result = serviceProxy.EchoMessageParameter(echoString); // *** VALIDATE *** \\ Assert.True(string.Equals(result, "Hello " + echoString), String.Format("Expected response from Service: {0} Actual was: {1}", "Hello " + echoString, result)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_Abort_ChannelFactory_Operations_Active() { // Test creates 2 channels from a single channel factory and // aborts the channel factory while both channels are executing // operations. This verifies the operations are cancelled and // the channel factory is in the correct state. BasicHttpBinding binding = null; TimeSpan delayOperation = TimeSpan.FromSeconds(3); ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy1 = null; IWcfService serviceProxy2 = null; string expectedEcho1 = "first"; string expectedEcho2 = "second"; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.CloseTimeout = ScenarioTestHelpers.TestTimeout; binding.SendTimeout = ScenarioTestHelpers.TestTimeout; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy1 = factory.CreateChannel(); serviceProxy2 = factory.CreateChannel(); // *** EXECUTE *** \\ Task<string> t1 = serviceProxy1.EchoWithTimeoutAsync("first", delayOperation); Task<string> t2 = serviceProxy2.EchoWithTimeoutAsync("second", delayOperation); factory.Abort(); // *** VALIDATE *** \\ Assert.True(factory.State == CommunicationState.Closed, String.Format("Expected factory state 'Closed', actual was '{0}'", factory.State)); Exception exception1 = null; Exception exception2 = null; string actualEcho1 = null; string actualEcho2 = null; // Verification is slightly more complex for the close with active operations because // we don't know which might have completed first and whether the channel factory // was able to close and dispose either channel before it completed. So we just // ensure the Tasks complete with an exception or a successful return and have // been closed by the factory. try { actualEcho1 = t1.GetAwaiter().GetResult(); } catch (Exception e) { exception1 = e; } try { actualEcho2 = t2.GetAwaiter().GetResult(); } catch (Exception e) { exception2 = e; } Assert.True(exception1 != null || actualEcho1 != null, "First operation should have thrown Exception or returned an echo"); Assert.True(exception2 != null || actualEcho2 != null, "Second operation should have thrown Exception or returned an echo"); Assert.True(actualEcho1 == null || String.Equals(expectedEcho1, actualEcho1), String.Format("First operation returned '{0}' but expected '{1}'.", expectedEcho1, actualEcho1)); Assert.True(actualEcho2 == null || String.Equals(expectedEcho2, actualEcho2), String.Format("Second operation returned '{0}' but expected '{1}'.", expectedEcho2, actualEcho2)); Assert.True(((ICommunicationObject)serviceProxy1).State == CommunicationState.Closed, String.Format("Expected channel 1 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy1).State)); Assert.True(((ICommunicationObject)serviceProxy2).State == CommunicationState.Closed, String.Format("Expected channel 2 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy2).State)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy1).Abort(); ((ICommunicationObject)serviceProxy2).Abort(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy1, (ICommunicationObject)serviceProxy2, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_Close_ChannelFactory_Operations_Active() { // Test creates 2 channels from a single channel factory and // closes the channel factory while both channels are executing // operations. This verifies the operations are cancelled and // the channel factory is in the correct state. BasicHttpBinding binding = null; TimeSpan delayOperation = TimeSpan.FromSeconds(3); ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy1 = null; IWcfService serviceProxy2 = null; string expectedEcho1 = "first"; string expectedEcho2 = "second"; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.CloseTimeout = ScenarioTestHelpers.TestTimeout; binding.SendTimeout = ScenarioTestHelpers.TestTimeout; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy1 = factory.CreateChannel(); serviceProxy2 = factory.CreateChannel(); // *** EXECUTE *** \\ Task<string> t1 = serviceProxy1.EchoWithTimeoutAsync(expectedEcho1, delayOperation); Task<string> t2 = serviceProxy2.EchoWithTimeoutAsync(expectedEcho2, delayOperation); factory.Close(); // *** VALIDATE *** \\ Assert.True(factory.State == CommunicationState.Closed, String.Format("Expected factory state 'Closed', actual was '{0}'", factory.State)); Exception exception1 = null; Exception exception2 = null; string actualEcho1 = null; string actualEcho2 = null; // Verification is slightly more complex for the close with active operations because // we don't know which might have completed first and whether the channel factory // was able to close and dispose either channel before it completed. So we just // ensure the Tasks complete with an exception or a successful return and have // been closed by the factory. try { actualEcho1 = t1.GetAwaiter().GetResult(); } catch (Exception e) { exception1 = e; } try { actualEcho2 = t2.GetAwaiter().GetResult(); } catch (Exception e) { exception2 = e; } Assert.True(exception1 != null || actualEcho1 != null, "First operation should have thrown Exception or returned an echo"); Assert.True(exception2 != null || actualEcho2!= null, "Second operation should have thrown Exception or returned an echo"); Assert.True(actualEcho1 == null || String.Equals(expectedEcho1, actualEcho1), String.Format("First operation returned '{0}' but expected '{1}'.", expectedEcho1, actualEcho1)); Assert.True(actualEcho2 == null || String.Equals(expectedEcho2, actualEcho2), String.Format("Second operation returned '{0}' but expected '{1}'.", expectedEcho2, actualEcho2)); Assert.True(((ICommunicationObject)serviceProxy1).State == CommunicationState.Closed, String.Format("Expected channel 1 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy1).State)); Assert.True(((ICommunicationObject)serviceProxy2).State == CommunicationState.Closed, String.Format("Expected channel 2 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy2).State)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy1).Abort(); ((ICommunicationObject)serviceProxy2).Abort(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy1, (ICommunicationObject)serviceProxy2, factory); } } [WcfFact] [OuterLoop] public static void BasicHttp_Async_Close_ChannelFactory_Operations_Active() { // Test creates 2 channels from a single channel factory and // asynchronously closes the channel factory while both channels are // executing operations. This verifies the operations are cancelled and // the channel factory is in the correct state. BasicHttpBinding binding = null; TimeSpan delayOperation = TimeSpan.FromSeconds(3); ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy1 = null; IWcfService serviceProxy2 = null; string expectedEcho1 = "first"; string expectedEcho2 = "second"; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.CloseTimeout = ScenarioTestHelpers.TestTimeout; binding.SendTimeout = ScenarioTestHelpers.TestTimeout; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text)); serviceProxy1 = factory.CreateChannel(); serviceProxy2 = factory.CreateChannel(); // *** EXECUTE *** \\ Task<string> t1 = serviceProxy1.EchoWithTimeoutAsync(expectedEcho1, delayOperation); Task<string> t2 = serviceProxy2.EchoWithTimeoutAsync(expectedEcho2, delayOperation); Task factoryTask = Task.Factory.FromAsync(factory.BeginClose, factory.EndClose, TaskCreationOptions.None); // *** VALIDATE *** \\ factoryTask.GetAwaiter().GetResult(); Assert.True(factory.State == CommunicationState.Closed, String.Format("Expected factory state 'Closed', actual was '{0}'", factory.State)); Exception exception1 = null; Exception exception2 = null; string actualEcho1 = null; string actualEcho2 = null; // Verification is slightly more complex for the close with active operations because // we don't know which might have completed first and whether the channel factory // was able to close and dispose either channel before it completed. So we just // ensure the Tasks complete with an exception or a successful return and have // been closed by the factory. try { actualEcho1 = t1.GetAwaiter().GetResult(); } catch (Exception e) { exception1 = e; } try { actualEcho2 = t2.GetAwaiter().GetResult(); } catch (Exception e) { exception2 = e; } Assert.True(exception1 != null || actualEcho1 != null, "First operation should have thrown Exception or returned an echo"); Assert.True(exception2 != null || actualEcho2 != null, "Second operation should have thrown Exception or returned an echo"); Assert.True(actualEcho1 == null || String.Equals(expectedEcho1, actualEcho1), String.Format("First operation returned '{0}' but expected '{1}'.", expectedEcho1, actualEcho1)); Assert.True(actualEcho2 == null || String.Equals(expectedEcho2, actualEcho2), String.Format("Second operation returned '{0}' but expected '{1}'.", expectedEcho2, actualEcho2)); Assert.True(((ICommunicationObject)serviceProxy1).State == CommunicationState.Closed, String.Format("Expected channel 1 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy1).State)); Assert.True(((ICommunicationObject)serviceProxy2).State == CommunicationState.Closed, String.Format("Expected channel 2 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy2).State)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy1).Abort(); ((ICommunicationObject)serviceProxy2).Abort(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy1, (ICommunicationObject)serviceProxy2, factory); } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" #if !MONO using System; using System.Drawing; using System.Runtime.InteropServices; namespace TheArtOfDev.HtmlRenderer.WinForms.Utilities { /// <summary> /// Utility for Win32 API. /// </summary> internal static class Win32Utils { public const int WsBorder = 0x00800000; public const int WsExClientEdge = 0x200; /// <summary> /// Const for BitBlt copy raster-operation code. /// </summary> public const int BitBltCopy = 0x00CC0020; /// <summary> /// Const for BitBlt paint raster-operation code. /// </summary> public const int BitBltPaint = 0x00EE0086; public const int WmSetCursor = 0x20; public const int IdcHand = 32649; public const int TextAlignDefault = 0; public const int TextAlignRtl = 256; public const int TextAlignBaseline = 24; public const int TextAlignBaselineRtl = 256 + 24; [DllImport("user32.dll")] public static extern int SetCursor(int hCursor); [DllImport("user32.dll")] public static extern int LoadCursor(int hInstance, int lpCursorName); /// <summary> /// Create a compatible memory HDC from the given HDC.<br/> /// The memory HDC can be rendered into without effecting the original HDC.<br/> /// The returned memory HDC and <paramref name="dib"/> must be released using <see cref="ReleaseMemoryHdc"/>. /// </summary> /// <param name="hdc">the HDC to create memory HDC from</param> /// <param name="width">the width of the memory HDC to create</param> /// <param name="height">the height of the memory HDC to create</param> /// <param name="dib">returns used bitmap memory section that must be released when done with memory HDC</param> /// <returns>memory HDC</returns> public static IntPtr CreateMemoryHdc(IntPtr hdc, int width, int height, out IntPtr dib) { // Create a memory DC so we can work off-screen IntPtr memoryHdc = CreateCompatibleDC(hdc); SetBkMode(memoryHdc, 1); // Create a device-independent bitmap and select it into our DC var info = new BitMapInfo(); info.biSize = Marshal.SizeOf(info); info.biWidth = width; info.biHeight = -height; info.biPlanes = 1; info.biBitCount = 32; info.biCompression = 0; // BI_RGB IntPtr ppvBits; dib = CreateDIBSection(hdc, ref info, 0, out ppvBits, IntPtr.Zero, 0); SelectObject(memoryHdc, dib); return memoryHdc; } /// <summary> /// Release the given memory HDC and dib section created from <see cref="CreateMemoryHdc"/>. /// </summary> /// <param name="memoryHdc">Memory HDC to release</param> /// <param name="dib">bitmap section to release</param> public static void ReleaseMemoryHdc(IntPtr memoryHdc, IntPtr dib) { DeleteObject(dib); DeleteDC(memoryHdc); } [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr WindowFromDC(IntPtr hdc); /// <summary> /// Retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen. /// </summary> /// <remarks> /// In conformance with conventions for the RECT structure, the bottom-right coordinates of the returned rectangle are exclusive. In other words, /// the pixel at (right, bottom) lies immediately outside the rectangle. /// </remarks> /// <param name="hWnd">A handle to the window.</param> /// <param name="lpRect">A pointer to a RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window.</param> /// <returns>If the function succeeds, the return value is nonzero.</returns> [DllImport("User32", SetLastError = true)] public static extern int GetWindowRect(IntPtr hWnd, out Rectangle lpRect); /// <summary> /// Retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen. /// </summary> /// <remarks> /// In conformance with conventions for the RECT structure, the bottom-right coordinates of the returned rectangle are exclusive. In other words, /// the pixel at (right, bottom) lies immediately outside the rectangle. /// </remarks> /// <param name="handle">A handle to the window.</param> /// <returns>RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window.</returns> public static Rectangle GetWindowRectangle(IntPtr handle) { Rectangle rect; GetWindowRect(handle, out rect); return new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); } [DllImport("User32.dll")] public static extern bool MoveWindow(IntPtr handle, int x, int y, int width, int height, bool redraw); [DllImport("gdi32.dll")] public static extern int SetTextAlign(IntPtr hdc, uint fMode); [DllImport("gdi32.dll")] public static extern int SetBkMode(IntPtr hdc, int mode); [DllImport("gdi32.dll")] public static extern int SelectObject(IntPtr hdc, IntPtr hgdiObj); [DllImport("gdi32.dll")] public static extern int SetTextColor(IntPtr hdc, int color); [DllImport("gdi32.dll", CharSet = CharSet.Auto)] public static extern bool GetTextMetrics(IntPtr hdc, out TextMetric lptm); [DllImport("gdi32.dll", EntryPoint = "GetTextExtentPoint32W")] public static extern int GetTextExtentPoint32(IntPtr hdc, [MarshalAs(UnmanagedType.LPWStr)] string str, int len, ref Size size); [DllImport("gdi32.dll", EntryPoint = "GetTextExtentExPointW")] public static extern bool GetTextExtentExPoint(IntPtr hDc, [MarshalAs(UnmanagedType.LPWStr)] string str, int nLength, int nMaxExtent, int[] lpnFit, int[] alpDx, ref Size size); [DllImport("gdi32.dll", EntryPoint = "TextOutW")] public static extern bool TextOut(IntPtr hdc, int x, int y, [MarshalAs(UnmanagedType.LPWStr)] string str, int len); [DllImport("gdi32.dll")] public static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); [DllImport("gdi32.dll")] public static extern int GetClipBox(IntPtr hdc, out Rectangle lprc); [DllImport("gdi32.dll")] public static extern int SelectClipRgn(IntPtr hdc, IntPtr hrgn); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop); [DllImport("gdi32.dll", EntryPoint = "GdiAlphaBlend")] public static extern bool AlphaBlend(IntPtr hdcDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, IntPtr hdcSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, BlendFunction blendFunction); [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] public static extern bool DeleteDC(IntPtr hdc); [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref BitMapInfo pbmi, uint iUsage, out IntPtr ppvBits, IntPtr hSection, uint dwOffset); } [StructLayout(LayoutKind.Sequential)] internal struct BlendFunction { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; public BlendFunction(byte alpha) { BlendOp = 0; BlendFlags = 0; AlphaFormat = 0; SourceConstantAlpha = alpha; } } [StructLayout(LayoutKind.Sequential)] internal struct BitMapInfo { public int biSize; public int biWidth; public int biHeight; public short biPlanes; public short biBitCount; public int biCompression; public int biSizeImage; public int biXPelsPerMeter; public int biYPelsPerMeter; public int biClrUsed; public int biClrImportant; public byte bmiColors_rgbBlue; public byte bmiColors_rgbGreen; public byte bmiColors_rgbRed; public byte bmiColors_rgbReserved; } [StructLayout(LayoutKind.Sequential)] internal struct TextMetric { public int tmHeight; public int tmAscent; public int tmDescent; public int tmInternalLeading; public int tmExternalLeading; public int tmAveCharWidth; public int tmMaxCharWidth; public int tmWeight; public int tmOverhang; public int tmDigitizedAspectX; public int tmDigitizedAspectY; public char tmFirstChar; public char tmLastChar; public char tmDefaultChar; public char tmBreakChar; public byte tmItalic; public byte tmUnderlined; public byte tmStruckOut; public byte tmPitchAndFamily; public byte tmCharSet; } } #endif
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using BusinessObjects.Common; namespace BusinessObjects.MDSubjects { [Serializable] public partial class cMDSubjects_Enums_Bank: CoreBusinessClass<cMDSubjects_Enums_Bank> { #region Business Methods public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.String > nameProperty = RegisterProperty<System.String>(p => p.Name, string.Empty, ""); [System.ComponentModel.DataAnnotations.StringLength(100, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String Name { get { return GetProperty(nameProperty); } set { SetProperty(nameProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<bool> inactiveProperty = RegisterProperty<bool>(p => p.Inactive, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public bool Inactive { get { return GetProperty(inactiveProperty); } set { SetProperty(inactiveProperty, value); } } private static readonly PropertyInfo< System.Int32? > numberProperty = RegisterProperty<System.Int32?>(p => p.Number, string.Empty); public System.Int32? Number { get { return GetProperty(numberProperty); } set { SetProperty(numberProperty, value); } } protected static readonly PropertyInfo<System.Int32?> companyUsingServiceIdProperty = RegisterProperty<System.Int32?>(p => p.CompanyUsingServiceId, string.Empty); public System.Int32? CompanyUsingServiceId { get { return GetProperty(companyUsingServiceIdProperty); } set { SetProperty(companyUsingServiceIdProperty, value); } } private static readonly PropertyInfo<System.Int32?> HomeAddress_PlaceIdProperty = RegisterProperty<System.Int32?>(p => p.HomeAddress_PlaceId, string.Empty); public System.Int32? HomeAddress_PlaceId { get { return GetProperty(HomeAddress_PlaceIdProperty); } set { SetProperty(HomeAddress_PlaceIdProperty, value); } } protected static readonly PropertyInfo<System.Int32?> HomeAddress_CountryNumberProperty = RegisterProperty<System.Int32?>(p => p.HomeAddress_CountryNumber, string.Empty); public System.Int32? HomeAddress_CountryNumber { get { return GetProperty(HomeAddress_CountryNumberProperty); } set { SetProperty(HomeAddress_CountryNumberProperty, value); } } private static readonly PropertyInfo<System.String> HomeAddressProperty = RegisterProperty<System.String>(p => p.HomeAddress, string.Empty, ""); [System.ComponentModel.DataAnnotations.StringLength(100, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] public System.String HomeAddress { get { return GetProperty(HomeAddressProperty); } set { SetProperty(HomeAddressProperty, (value ?? "").Trim()); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; #endregion #region Factory Methods public static cMDSubjects_Enums_Bank NewMDSubjects_Enums_Bank() { return DataPortal.Create<cMDSubjects_Enums_Bank>(); } public static cMDSubjects_Enums_Bank GetMDSubjects_Enums_Bank(int uniqueId) { return DataPortal.Fetch<cMDSubjects_Enums_Bank>(new SingleCriteria<cMDSubjects_Enums_Bank, int>(uniqueId)); } internal static cMDSubjects_Enums_Bank GetMDSubjects_Enums_Bank(MDSubjects_Enums_Bank data) { return DataPortal.Fetch<cMDSubjects_Enums_Bank>(data); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cMDSubjects_Enums_Bank, int> criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = ctx.ObjectContext.MDSubjects_Enums_Bank.First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<int?>(numberProperty, data.Number); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LoadProperty<int?>(HomeAddress_PlaceIdProperty, data.HomeAddress_PlaceId); LoadProperty<string>(HomeAddressProperty, data.HomeAddress); LoadProperty<int?>(HomeAddress_CountryNumberProperty, data.HomeAddress_CountryNumber); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } } private void DataPortal_Fetch(MDSubjects_Enums_Bank data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<int?>(numberProperty, data.Number); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LoadProperty<int?>(HomeAddress_PlaceIdProperty, data.HomeAddress_PlaceId); LoadProperty<string>(HomeAddressProperty, data.HomeAddress); LoadProperty<int?>(HomeAddress_CountryNumberProperty, data.HomeAddress_CountryNumber); LastChanged = data.LastChanged; BusinessRules.CheckRules(); MarkAsChild(); } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Enums_Bank(); data.Name = ReadProperty<string>(nameProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.Number = (ReadProperty<int?>(numberProperty) ?? 0); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); data.HomeAddress_PlaceId = ReadProperty<int?>(HomeAddress_PlaceIdProperty); data.HomeAddress = ReadProperty<string>(HomeAddressProperty); data.HomeAddress_CountryNumber = ReadProperty<int?>(HomeAddress_CountryNumberProperty); ctx.ObjectContext.AddToMDSubjects_Enums_Bank(data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); ctx.ObjectContext.SaveChanges(); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Enums_Bank(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.Name = ReadProperty<string>(nameProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.Number = (ReadProperty<int?>(numberProperty) ?? 0); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); data.HomeAddress_PlaceId = ReadProperty<int?>(HomeAddress_PlaceIdProperty); data.HomeAddress = ReadProperty<string>(HomeAddressProperty); data.HomeAddress_CountryNumber = ReadProperty<int?>(HomeAddress_CountryNumberProperty); ctx.ObjectContext.SaveChanges(); } } #endregion } public partial class cMDSubjects_Enums_Bank_List : BusinessListBase<cMDSubjects_Enums_Bank_List, cMDSubjects_Enums_Bank> { public static cMDSubjects_Enums_Bank_List GetcMDSubjects_Enums_Bank_List() { return DataPortal.Fetch<cMDSubjects_Enums_Bank_List>(); } public static cMDSubjects_Enums_Bank_List GetcMDSubjects_Enums_Bank_List(int companyId, int includeInactiveId) { return DataPortal.Fetch<cMDSubjects_Enums_Bank_List>(new ActiveEnums_Criteria(companyId, includeInactiveId)); } private void DataPortal_Fetch() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var result = ctx.ObjectContext.MDSubjects_Enums_Bank; foreach (var data in result) { var obj = cMDSubjects_Enums_Bank.GetMDSubjects_Enums_Bank(data); this.Add(obj); } } } private void DataPortal_Fetch(ActiveEnums_Criteria criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var result = ctx.ObjectContext.MDSubjects_Enums_Bank.Where(p => (p.CompanyUsingServiceId == criteria.CompanyId || (p.CompanyUsingServiceId ?? 0) == 0) && (p.Inactive == false || p.Id == criteria.IncludeInactiveId)); foreach (var data in result) { var obj = cMDSubjects_Enums_Bank.GetMDSubjects_Enums_Bank(data); this.Add(obj); } } } } }
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2017 Baldur Karlsson * Copyright (c) 2014 Crytek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ using System; using System.Linq; using System.Runtime.InteropServices; using System.Reflection; using System.Collections.Generic; namespace renderdoc { // corresponds to rdctype::array on the C side [StructLayout(LayoutKind.Sequential)] public struct templated_array { public IntPtr elems; public Int32 count; }; public enum CustomUnmanagedType { TemplatedArray = 0, UTF8TemplatedString, FixedArray, Union, Skip, CustomClass, CustomClassPointer, } public enum CustomFixedType { None = 0, Float, UInt32, Int32, UInt16, Double, } // custom attribute that we can apply to structures we want to serialise public sealed class CustomMarshalAsAttribute : Attribute { public CustomMarshalAsAttribute(CustomUnmanagedType unmanagedType) { m_UnmanagedType = unmanagedType; } public CustomUnmanagedType CustomType { get { return m_UnmanagedType; } } public int FixedLength { get { return m_FixedLen; } set { m_FixedLen = value; } } public CustomFixedType FixedType { get { return m_FixedType; } set { m_FixedType = value; } } private CustomUnmanagedType m_UnmanagedType; private int m_FixedLen; private CustomFixedType m_FixedType = CustomFixedType.None; } // custom marshalling code to handle converting complex data types with our given formatting // over to .NET managed copies. public static class CustomMarshal { [DllImport("kernel32.dll", EntryPoint = "RtlFillMemory", SetLastError = false)] private static extern void FillMemory(IntPtr destination, int length, byte fill); [DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] private static extern void RENDERDOC_FreeArrayMem(IntPtr mem); // utility functions usable by wrappers around actual functions calling into the C++ core public static IntPtr Alloc(Type T) { IntPtr mem = Marshal.AllocHGlobal(CustomMarshal.SizeOf(T)); FillMemory(mem, CustomMarshal.SizeOf(T), 0); return mem; } public static IntPtr Alloc(Type T, int arraylen) { IntPtr mem = Marshal.AllocHGlobal(CustomMarshal.SizeOf(T)*arraylen); FillMemory(mem, CustomMarshal.SizeOf(T) * arraylen, 0); return mem; } public static IntPtr MakeUTF8String(string s) { int len = System.Text.Encoding.UTF8.GetByteCount(s); IntPtr mem = Marshal.AllocHGlobal(len + 1); byte[] bytes = new byte[len + 1]; bytes[len] = 0; // add NULL terminator System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); Marshal.Copy(bytes, 0, mem, len+1); return mem; } public static void Free(IntPtr mem) { Marshal.FreeHGlobal(mem); } // note that AlignOf and AddFieldSize and others are called rarely as the results // are cached lower down // match C/C++ alignment rules private static int AlignOf(FieldInfo field) { var cma = GetCustomAttr(field); if (cma != null && (cma.CustomType == CustomUnmanagedType.UTF8TemplatedString || cma.CustomType == CustomUnmanagedType.TemplatedArray || cma.CustomType == CustomUnmanagedType.CustomClassPointer) ) return IntPtr.Size; if (cma != null && cma.CustomType == CustomUnmanagedType.Skip) return 1; if (field.FieldType.IsPrimitive || (field.FieldType.IsArray && field.FieldType.GetElementType().IsPrimitive)) return Marshal.SizeOf(NonArrayType(field.FieldType)); // Get instance fields of the structure type. FieldInfo[] fieldInfo = NonArrayType(field.FieldType).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); int align = 1; foreach (FieldInfo f in fieldInfo) align = Math.Max(align, AlignOf(f)); return align; } private static Type NonArrayType(Type t) { return t.IsArray ? t.GetElementType() : t; } private static Dictionary<Type, CustomMarshalAsAttribute[]> m_CustomAttrCache = new Dictionary<Type, CustomMarshalAsAttribute[]>(); private static CustomMarshalAsAttribute GetCustomAttr(Type t, FieldInfo[] fields, int fieldIdx) { lock (m_CustomAttrCache) { if (!m_CustomAttrCache.ContainsKey(t)) { var arr = new CustomMarshalAsAttribute[fields.Length]; for (int i = 0; i < fields.Length; i++) arr[i] = GetCustomAttr(fields[i]); m_CustomAttrCache.Add(t, arr); } return m_CustomAttrCache[t][fieldIdx]; } } private static CustomMarshalAsAttribute GetCustomAttr(FieldInfo field) { if (CustomAttributeDefined(field)) { object[] attributes = field.GetCustomAttributes(false); foreach (object attribute in attributes) { if (attribute is CustomMarshalAsAttribute) { return (attribute as CustomMarshalAsAttribute); } } } return null; } // add a field's size to the size parameter, respecting alignment private static void AddFieldSize(FieldInfo field, ref long size) { int a = AlignOf(field); int alignment = (int)size % a; if (alignment != 0) size += a - alignment; var cma = GetCustomAttr(field); if (cma != null) { switch (cma.CustomType) { case CustomUnmanagedType.CustomClass: size += SizeOf(field.FieldType); break; case CustomUnmanagedType.CustomClassPointer: size += IntPtr.Size; break; case CustomUnmanagedType.Union: { FieldInfo[] fieldInfo = field.FieldType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); long unionsize = 0; foreach (FieldInfo unionfield in fieldInfo) { long maxsize = 0; AddFieldSize(unionfield, ref maxsize); unionsize = Math.Max(unionsize, maxsize); } size += unionsize; break; } case CustomUnmanagedType.TemplatedArray: case CustomUnmanagedType.UTF8TemplatedString: size += Marshal.SizeOf(typeof(templated_array)); break; case CustomUnmanagedType.FixedArray: size += cma.FixedLength * SizeOf(NonArrayType(field.FieldType)); break; case CustomUnmanagedType.Skip: break; default: throw new NotImplementedException("Unexpected attribute"); } } else { size += SizeOf(field.FieldType); } alignment = (int)size % a; if (alignment != 0) size += a - alignment; } // cache for sizes of types, since this will get called a lot private static Dictionary<Type, int> m_SizeCache = new Dictionary<Type, int>(); // return the size of the C++ equivalent of this type (so that we can allocate enough) // space to pass a pointer for example. private static int SizeOf(Type structureType) { if (structureType.IsPrimitive || (structureType.IsArray && structureType.GetElementType().IsPrimitive)) return Marshal.SizeOf(structureType); lock (m_SizeCache) { if (m_SizeCache.ContainsKey(structureType)) return m_SizeCache[structureType]; // Get instance fields of the structure type. FieldInfo[] fieldInfo = structureType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); long size = 0; int a = 1; foreach (FieldInfo field in fieldInfo) { AddFieldSize(field, ref size); a = Math.Max(a, AlignOf(field)); } int alignment = (int)size % a; if (alignment != 0) size += a - alignment; m_SizeCache.Add(structureType, (int)size); return (int)size; } } // caching the offset to the nth field from a base pointer to the type private static Dictionary<Type, Int64[]> m_OffsetCache = new Dictionary<Type, Int64[]>(); // caching how much to align up a pointer by to the first field (above offsets take care after that) private static Dictionary<Type, int> m_OffsetAlignCache = new Dictionary<Type, int>(); // offset a pointer to the idx'th field of a type private static IntPtr OffsetPtr(Type structureType, FieldInfo[] fieldInfo, int idx, IntPtr ptr) { if (fieldInfo.Length == 0) return ptr; lock (m_OffsetCache) { if (!m_OffsetAlignCache.ContainsKey(structureType)) { Int64[] cacheOffsets = new Int64[fieldInfo.Length]; int initialAlign = AlignOf(fieldInfo[0]); Int64 p = 0; for (int i = 0; i < fieldInfo.Length; i++) { FieldInfo field = fieldInfo[i]; int a = AlignOf(field); int alignment = (int)p % a; if (alignment != 0) p += a - alignment; cacheOffsets[i] = p; AddFieldSize(field, ref p); } m_OffsetAlignCache.Add(structureType, initialAlign); m_OffsetCache.Add(structureType, cacheOffsets); } { var p = ptr.ToInt64(); int a = m_OffsetAlignCache[structureType]; int alignment = (int)p % a; if (alignment != 0) p += a - alignment; p += m_OffsetCache[structureType][idx]; return new IntPtr(p); } } } private static bool CustomAttributeDefined(FieldInfo field) { return field.IsDefined(typeof(CustomMarshalAsAttribute), false); } // this function takes a pointer to a templated array (ie. a pointer to a list of Types, and a length) // and returns an array of that object type, and cleans up the memory if specified. public static object GetTemplatedArray(IntPtr sourcePtr, Type structureType, bool freeMem) { templated_array arr = (templated_array)Marshal.PtrToStructure(sourcePtr, typeof(templated_array)); if (structureType == typeof(byte)) { byte[] val = new byte[arr.count]; if(val.Length > 0) Marshal.Copy(arr.elems, val, 0, val.Length); if (freeMem) RENDERDOC_FreeArrayMem(arr.elems); return val; } else { Array val = Array.CreateInstance(structureType, arr.count); int sizeInBytes = SizeOf(structureType); for (int i = 0; i < val.Length; i++) { IntPtr p = new IntPtr((arr.elems.ToInt64() + i * sizeInBytes)); val.SetValue(PtrToStructure(p, structureType, freeMem), i); } if (freeMem) RENDERDOC_FreeArrayMem(arr.elems); return val; } } public static string PtrToStringUTF8(IntPtr elems, int count) { byte[] buffer = new byte[count]; if (count > 0) Marshal.Copy(elems, buffer, 0, buffer.Length); return System.Text.Encoding.UTF8.GetString(buffer); } public static string PtrToStringUTF8(IntPtr elems) { int len = 0; while (Marshal.ReadByte(elems, len) != 0) ++len; return PtrToStringUTF8(elems, len); } // specific versions of the above GetTemplatedArray for convenience. public static string TemplatedArrayToString(IntPtr sourcePtr, bool freeMem) { templated_array arr = (templated_array)Marshal.PtrToStructure(sourcePtr, typeof(templated_array)); string val = PtrToStringUTF8(arr.elems, arr.count); if (freeMem) RENDERDOC_FreeArrayMem(arr.elems); return val; } public static string[] TemplatedArrayToStringArray(IntPtr sourcePtr, bool freeMem) { templated_array arr = (templated_array)Marshal.PtrToStructure(sourcePtr, typeof(templated_array)); int arrSize = SizeOf(typeof(templated_array)); string[] ret = new string[arr.count]; for (int i = 0; i < arr.count; i++) { IntPtr ptr = new IntPtr((arr.elems.ToInt64() + i * arrSize)); ret[i] = TemplatedArrayToString(ptr, freeMem); } if (freeMem) RENDERDOC_FreeArrayMem(arr.elems); return ret; } public static object PtrToStructure(IntPtr sourcePtr, Type structureType, bool freeMem) { return PtrToStructure(sourcePtr, structureType, freeMem, false); } // take a pointer to a C++ structure of a given type, and convert it into the managed equivalent, // while handling alignment etc and freeing memory returned if it should be caller-freed private static object PtrToStructure(IntPtr sourcePtr, Type structureType, bool freeMem, bool isUnion) { if (sourcePtr == IntPtr.Zero) return null; // Get instance fields of the structure type. FieldInfo[] fields = structureType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance) .OrderBy(field => field.MetadataToken).ToArray(); object ret = Activator.CreateInstance(structureType); try { for (int fieldIdx = 0; fieldIdx < fields.Length; fieldIdx++) { FieldInfo field = fields[fieldIdx]; IntPtr fieldPtr = isUnion ? sourcePtr : OffsetPtr(structureType, fields, fieldIdx, sourcePtr); // no custom attribute, so just use the regular Marshal code var cma = GetCustomAttr(structureType, fields, fieldIdx); if (cma == null) { if (field.FieldType.IsEnum) field.SetValue(ret, (VarType)Marshal.ReadInt32(fieldPtr)); else field.SetValue(ret, Marshal.PtrToStructure(fieldPtr, field.FieldType)); } else { switch (cma.CustomType) { case CustomUnmanagedType.CustomClass: field.SetValue(ret, PtrToStructure(fieldPtr, field.FieldType, freeMem)); break; case CustomUnmanagedType.CustomClassPointer: IntPtr ptr = Marshal.ReadIntPtr(fieldPtr); if (ptr == IntPtr.Zero) field.SetValue(ret, null); else field.SetValue(ret, PtrToStructure(ptr, field.FieldType, freeMem)); break; case CustomUnmanagedType.Union: field.SetValue(ret, PtrToStructure(fieldPtr, field.FieldType, freeMem, true)); break; case CustomUnmanagedType.Skip: break; case CustomUnmanagedType.FixedArray: { if(cma.FixedType == CustomFixedType.Float) { float[] val = new float[cma.FixedLength]; Marshal.Copy(fieldPtr, val, 0, cma.FixedLength); field.SetValue(ret, val); } else if (cma.FixedType == CustomFixedType.UInt16) { Int16[] val = new Int16[cma.FixedLength]; Marshal.Copy(fieldPtr, val, 0, cma.FixedLength); UInt16[] realval = new UInt16[cma.FixedLength]; for (int i = 0; i < val.Length; i++) realval[i] = unchecked((UInt16)val[i]); field.SetValue(ret, val); } else if (cma.FixedType == CustomFixedType.Int32) { Int32[] val = new Int32[cma.FixedLength]; Marshal.Copy(fieldPtr, val, 0, cma.FixedLength); field.SetValue(ret, val); } else if (cma.FixedType == CustomFixedType.Double) { double[] val = new double[cma.FixedLength]; Marshal.Copy(fieldPtr, val, 0, cma.FixedLength); field.SetValue(ret, val); } else if (cma.FixedType == CustomFixedType.UInt32) { Int32[] val = new Int32[cma.FixedLength]; Marshal.Copy(fieldPtr, val, 0, cma.FixedLength); UInt32[] realval = new UInt32[cma.FixedLength]; for (int i = 0; i < val.Length; i++) realval[i] = unchecked((UInt32)val[i]); field.SetValue(ret, realval); } else { var arrayType = NonArrayType(field.FieldType); int sizeInBytes = SizeOf(arrayType); Array val = Array.CreateInstance(arrayType, cma.FixedLength); for (int i = 0; i < val.Length; i++) { IntPtr p = new IntPtr((fieldPtr.ToInt64() + i * sizeInBytes)); val.SetValue(PtrToStructure(p, arrayType, freeMem), i); } field.SetValue(ret, val); } break; } case CustomUnmanagedType.UTF8TemplatedString: case CustomUnmanagedType.TemplatedArray: { // templated_array must be pointer-aligned long alignment = fieldPtr.ToInt64() % IntPtr.Size; if (alignment != 0) { fieldPtr = new IntPtr(fieldPtr.ToInt64() + IntPtr.Size - alignment); } templated_array arr = (templated_array)Marshal.PtrToStructure(fieldPtr, typeof(templated_array)); if (field.FieldType == typeof(string)) { if (arr.elems == IntPtr.Zero) field.SetValue(ret, ""); else field.SetValue(ret, PtrToStringUTF8(arr.elems, arr.count)); } else { var arrayType = NonArrayType(field.FieldType); int sizeInBytes = SizeOf(arrayType); if (field.FieldType.IsArray && arrayType == typeof(byte)) { byte[] val = new byte[arr.count]; if(val.Length > 0) Marshal.Copy(arr.elems, val, 0, val.Length); field.SetValue(ret, val); } else if (field.FieldType.IsArray) { Array val = Array.CreateInstance(arrayType, arr.count); for (int i = 0; i < val.Length; i++) { IntPtr p = new IntPtr((arr.elems.ToInt64() + i * sizeInBytes)); val.SetValue(PtrToStructure(p, arrayType, freeMem), i); } field.SetValue(ret, val); } else { throw new NotImplementedException("non-array element marked to marshal as TemplatedArray"); } } if(freeMem) RENDERDOC_FreeArrayMem(arr.elems); break; } default: throw new NotImplementedException("Unexpected attribute"); } } } MethodInfo postMarshal = structureType.GetMethod("PostMarshal", BindingFlags.NonPublic | BindingFlags.Instance); if (postMarshal != null) postMarshal.Invoke(ret, new object[] { }); } catch (Exception ex) { System.Diagnostics.Debug.Fail(ex.Message); } return ret; } } }
#if UNITY_EDITOR using UnityEngine; using System.Collections.Generic; using UnityEditor; using System; using System.IO; public class InspectorPlusWindow : EditorWindow { public bool editing; public InspectorPlusManager manager; List<string> names; InspectorPlusTracker editComp; Vector2 scrollPosition; Vector2 openScrollPosition; string searchFilter = ""; string AssetPath { get { return Path.GetDirectoryName(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this))); } } void OnEnable() { manager = (InspectorPlusManager) AssetDatabase.LoadAssetAtPath(AssetPath + "/InspectorPlus.asset", typeof(InspectorPlusManager)); if (manager != null) { return; } manager = (InspectorPlusManager) CreateInstance(typeof(InspectorPlusManager)); AssetDatabase.CreateAsset(manager, AssetPath + "/InspectorPlus.asset"); } void OnDisable() { manager.Save(); } [MenuItem("Window/Inspector++")] static void ShowWindow() { GetWindow(typeof(InspectorPlusWindow)); } void CreateNew(string name, string path, Type t) { if (manager.GetTracker(name) != null) { return; } manager.AddInspector(name, path); } void OnSelectionChange() { Repaint(); } public void OnGUI() { if (!editing) { DrawOpen(); } else { DrawEditor(); } } bool CanHaveEditor(MonoScript m) { if (m.GetClass() == null) { return false; } if (m.GetClass().IsSubclassOf(typeof(MonoBehaviour))) { return true; } if (m.GetClass().IsSubclassOf(typeof(ScriptableObject))) { if (!m.GetClass().IsSubclassOf(typeof(Editor)) && !m.GetClass().IsSubclassOf(typeof(EditorWindow))) { return true; } } return false; } void DrawOpenNameList(List<string> names) { foreach (string n in names) { EditorGUILayout.BeginHorizontal(); GUILayout.Label(n, GUILayout.Width(200.0f)); GUILayout.Space(100.0f); if (GUILayout.Button("Edit", GUILayout.Width(180.0f))) { editing = true; manager.editName = n; } if (GUILayout.Button("Save to file", GUILayout.Width(100.0f))) { var filer = new InspectorPlusFiler(); filer.WriteToFile(n, manager.GetTracker(n), "InspectorPlusOutput/Editor"); AssetDatabase.Refresh(); EditorUtility.DisplayDialog("Inspector save to file", @" Your inspector has been saved to " + n + @"InspectorPlus.cs. Feel free to distribute this file!", "Ok"); } if (GUILayout.Button("Delete", GUILayout.Width(100.0f))) { manager.DeleteInspector(n); AssetDatabase.Refresh(); Repaint(); } EditorGUILayout.EndHorizontal(); } } void DrawOpen() { //gets only existing editors. GUILayout.BeginHorizontal(GUILayout.Width(Screen.width)); GUILayout.FlexibleSpace(); //left sidebar GUILayout.BeginVertical(); GUILayout.Space(50.0f); GUILayout.BeginVertical("Box", GUILayout.Width(700.0f)); GUILayout.BeginHorizontal(); searchFilter = GUILayout.TextField(searchFilter, "SearchTextField", GUILayout.Width(670.0f)); if (GUILayout.Button("", "SearchCancelButton", GUILayout.Width(20.0f))) { searchFilter = ""; } GUILayout.EndHorizontal(); GUILayout.BeginVertical(GUILayout.Width(700.0f)); openScrollPosition = GUILayout.BeginScrollView(openScrollPosition, false, false, GUIStyle.none, GUI.skin.GetStyle("verticalScrollbar"), GUILayout.Width(700.0f)); //draw existing editors DrawOpenNameList(manager.GetNames(searchFilter)); GUILayout.Space(20.0f); GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.EndVertical(); GUILayout.Space(40.0f); GUILayout.BeginHorizontal(GUILayout.Width(700.0f)); GUILayout.FlexibleSpace(); GUILayout.BeginVertical("Button", GUILayout.Width(180.0f)); UnityEngine.Object[] objs = Selection.GetFiltered(typeof(MonoScript), SelectionMode.Assets); var selected = new List<MonoScript>(); foreach (UnityEngine.Object o in objs) { var m = (MonoScript) o; if (m != null && CanHaveEditor(m)) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label(m.GetClass().Name); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); selected.Add(m); } } if (selected.Count == 0) { GUILayout.Label("Select scripts from the project view that need Inspector++'s magic!"); GUI.enabled = false; } if (GUILayout.Button("Create")) { foreach (MonoScript m in selected) { CreateNew(m.GetClass().Name, Application.dataPath + AssetDatabase.GetAssetPath(m).Replace("Assets", ""), m.GetClass()); } AssetDatabase.Refresh(); } GUI.enabled = true; GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); //right sidebar GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } void DrawEditor() { editComp = manager.GetTracker(manager.editName); scrollPosition = GUILayout.BeginScrollView(scrollPosition); editComp.DrawGUI(); GUILayout.EndScrollView(); GUILayout.Space(10.0f); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Back")) { editing = false; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(10.0f); GUILayout.FlexibleSpace(); } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Text; using System.Globalization; namespace System { // The class designed as to keep minimal the working set of Uri class. // The idea is to stay with static helper methods and strings internal static class IPv6AddressHelper { // fields private const int NumberOfLabels = 8; // Lower case hex, no leading zeros private const string CanonicalNumberFormat = "{0:x}"; private const string EmbeddedIPv4Format = ":{0:d}.{1:d}.{2:d}.{3:d}"; private const char Separator = ':'; // methods internal static string ParseCanonicalName(string str, int start, ref bool isLoopback, ref string scopeId) { unsafe { ushort* numbers = stackalloc ushort[NumberOfLabels]; // optimized zeroing of 8 shorts = 2 longs ((long*)numbers)[0] = 0L; ((long*)numbers)[1] = 0L; isLoopback = Parse(str, numbers, start, ref scopeId); return '[' + CreateCanonicalName(numbers) + ']'; } } internal unsafe static string CreateCanonicalName(ushort* numbers) { // RFC 5952 Sections 4 & 5 - Compressed, lower case, with possible embedded IPv4 addresses. // Start to finish, inclusive. <-1, -1> for no compression KeyValuePair<int, int> range = FindCompressionRange(numbers); bool ipv4Embedded = ShouldHaveIpv4Embedded(numbers); StringBuilder builder = new StringBuilder(); for (int i = 0; i < NumberOfLabels; i++) { if (ipv4Embedded && i == (NumberOfLabels - 2)) { // Write the remaining digits as an IPv4 address builder.AppendFormat(CultureInfo.InvariantCulture, EmbeddedIPv4Format, numbers[i] >> 8, numbers[i] & 0xFF, numbers[i + 1] >> 8, numbers[i + 1] & 0xFF); break; } // Compression; 1::1, ::1, 1:: if (range.Key == i) { // Start compression, add : builder.Append(Separator); } if (range.Key <= i && range.Value == (NumberOfLabels - 1)) { // Remainder compressed; 1:: builder.Append(Separator); break; } if (range.Key <= i && i <= range.Value) { continue; // Compressed } if (i != 0) { builder.Append(Separator); } builder.AppendFormat(CultureInfo.InvariantCulture, CanonicalNumberFormat, numbers[i]); } return builder.ToString(); } // RFC 5952 Section 4.2.3 // Longest consecutive sequence of zero segments, minimum 2. // On equal, first sequence wins. // <-1, -1> for no compression. private unsafe static KeyValuePair<int, int> FindCompressionRange(ushort* numbers) { int longestSequenceLength = 0; int longestSequenceStart = -1; int currentSequenceLength = 0; for (int i = 0; i < NumberOfLabels; i++) { if (numbers[i] == 0) { // In a sequence currentSequenceLength++; if (currentSequenceLength > longestSequenceLength) { longestSequenceLength = currentSequenceLength; longestSequenceStart = i - currentSequenceLength + 1; } } else { currentSequenceLength = 0; } } if (longestSequenceLength >= 2) { return new KeyValuePair<int, int>(longestSequenceStart, longestSequenceStart + longestSequenceLength - 1); } return new KeyValuePair<int, int>(-1, -1); // No compression } // Returns true if the IPv6 address should be formated with an embedded IPv4 address: // ::192.168.1.1 private unsafe static bool ShouldHaveIpv4Embedded(ushort* numbers) { // 0:0 : 0:0 : x:x : x.x.x.x if (numbers[0] == 0 && numbers[1] == 0 && numbers[2] == 0 && numbers[3] == 0 && numbers[6] != 0) { // RFC 5952 Section 5 - 0:0 : 0:0 : 0:[0 | FFFF] : x.x.x.x if (numbers[4] == 0 && (numbers[5] == 0 || numbers[5] == 0xFFFF)) { return true; } // SIIT - 0:0 : 0:0 : FFFF:0 : x.x.x.x else if (numbers[4] == 0xFFFF && numbers[5] == 0) { return true; } } // ISATAP if (numbers[4] == 0 && numbers[5] == 0x5EFE) { return true; } return false; } // // InternalIsValid // // Determine whether a name is a valid IPv6 address. Rules are: // // * 8 groups of 16-bit hex numbers, separated by ':' // * a *single* run of zeros can be compressed using the symbol '::' // * an optional string of a ScopeID delimited by '%' // * an optional (last) 1 or 2 character prefix length field delimited by '/' // * the last 32 bits in an address can be represented as an IPv4 address // // Inputs: // <argument> name // Domain name field of a URI to check for pattern match with // IPv6 address // validateStrictAddress: if set to true, it expects strict ipv6 address. Otherwise it expects // part of the string in ipv6 format. // // Outputs: // Nothing // // Assumes: // the correct name is terminated by ']' character // // Returns: // true if <name> has IPv6 format/ipv6 address based on validateStrictAddress, else false // // Throws: // Nothing // // Remarks: MUST NOT be used unless all input indexes are verified and trusted. // start must be next to '[' position, or error is reported unsafe private static bool InternalIsValid(char* name, int start, ref int end, bool validateStrictAddress) { int sequenceCount = 0; int sequenceLength = 0; bool haveCompressor = false; bool haveIPv4Address = false; bool havePrefix = false; bool expectingNumber = true; int lastSequence = 1; int i; for (i = start; i < end; ++i) { if (havePrefix ? (name[i] >= '0' && name[i] <= '9') : UriHelper.IsHexDigit(name[i])) { ++sequenceLength; expectingNumber = false; } else { if (sequenceLength > 4) { return false; } if (sequenceLength != 0) { ++sequenceCount; lastSequence = i - sequenceLength; } switch (name[i]) { case '%': while (true) { //accept anything in scopeID if (++i == end) { // no closing ']', fail return false; } if (name[i] == ']') { goto case ']'; } else if (name[i] == '/') { goto case '/'; } } case ']': start = i; i = end; //this will make i = end+1 continue; case ':': if ((i > 0) && (name[i - 1] == ':')) { if (haveCompressor) { // // can only have one per IPv6 address // return false; } haveCompressor = true; expectingNumber = false; } else { expectingNumber = true; } break; case '/': if (validateStrictAddress) { return false; } if ((sequenceCount == 0) || havePrefix) { return false; } havePrefix = true; expectingNumber = true; break; case '.': if (haveIPv4Address) { return false; } i = end; if (!IPv4AddressHelper.IsValid(name, lastSequence, ref i, true, false, false)) { return false; } // ipv4 address takes 2 slots in ipv6 address, one was just counted meeting the '.' ++sequenceCount; haveIPv4Address = true; --i; // it will be incremented back on the next loop break; default: return false; } sequenceLength = 0; } } // // if the last token was a prefix, check number of digits // if (havePrefix && ((sequenceLength < 1) || (sequenceLength > 2))) { return false; } // // these sequence counts are -1 because it is implied in end-of-sequence // int expectedSequenceCount = 8 + (havePrefix ? 1 : 0); if (!expectingNumber && (sequenceLength <= 4) && (haveCompressor ? (sequenceCount < expectedSequenceCount) : (sequenceCount == expectedSequenceCount))) { if (i == end + 1) { // ']' was found end = start + 1; return true; } return false; } return false; } // // IsValid // // Determine whether a name is a valid IPv6 address. Rules are: // // * 8 groups of 16-bit hex numbers, separated by ':' // * a *single* run of zeros can be compressed using the symbol '::' // * an optional string of a ScopeID delimited by '%' // * an optional (last) 1 or 2 character prefix length field delimited by '/' // * the last 32 bits in an address can be represented as an IPv4 address // // Inputs: // <argument> name // Domain name field of a URI to check for pattern match with // IPv6 address // // Outputs: // Nothing // // Assumes: // the correct name is terminated by ']' character // // Returns: // true if <name> has IPv6 format, else false // // Throws: // Nothing // // Remarks: MUST NOT be used unless all input indexes are verified and trusted. // start must be next to '[' position, or error is reported internal unsafe static bool IsValid(char* name, int start, ref int end) { return InternalIsValid(name, start, ref end, false); } // // IsValidStrict // // Determine whether a name is a valid IPv6 address. Rules are: // // * 8 groups of 16-bit hex numbers, separated by ':' // * a *single* run of zeros can be compressed using the symbol '::' // * an optional string of a ScopeID delimited by '%' // * the last 32 bits in an address can be represented as an IPv4 address // // Difference between IsValid() and IsValidStrict() is that IsValid() expects part of the string to // be ipv6 address where as IsValidStrict() expects strict ipv6 address. // // Inputs: // <argument> name // IPv6 address in string format // // Outputs: // Nothing // // Assumes: // the correct name is terminated by ']' character // // Returns: // true if <name> is IPv6 address, else false // // Throws: // Nothing // // Remarks: MUST NOT be used unless all input indexes are verified and trusted. // start must be next to '[' position, or error is reported internal unsafe static bool IsValidStrict(char* name, int start, ref int end) { return InternalIsValid(name, start, ref end, true); } // // Parse // // Convert this IPv6 address into a sequence of 8 16-bit numbers // // Inputs: // <member> Name // The validated IPv6 address // // Outputs: // <member> numbers // Array filled in with the numbers in the IPv6 groups // // <member> PrefixLength // Set to the number after the prefix separator (/) if found // // Assumes: // <Name> has been validated and contains only hex digits in groups of // 16-bit numbers, the characters ':' and '/', and a possible IPv4 // address // // Returns: // true if this is a loopback, false otherwise. There is no failure indication as the sting must be a valid one. // // Throws: // Nothing // unsafe internal static bool Parse(string address, ushort* numbers, int start, ref string scopeId) { int number = 0; int index = 0; int compressorIndex = -1; bool numberIsValid = true; //This used to be a class instance member but have not been used so far int PrefixLength = 0; if (address[start] == '[') { ++start; } for (int i = start; i < address.Length && address[i] != ']';) { switch (address[i]) { case '%': if (numberIsValid) { numbers[index++] = (ushort)number; numberIsValid = false; } start = i; for (++i; address[i] != ']' && address[i] != '/'; ++i) { ; } scopeId = address.Substring(start, i - start); // ignore prefix if any for (; address[i] != ']'; ++i) { ; } break; case ':': numbers[index++] = (ushort)number; number = 0; ++i; if (address[i] == ':') { compressorIndex = index; ++i; } else if ((compressorIndex < 0) && (index < 6)) { // // no point checking for IPv4 address if we don't // have a compressor or we haven't seen 6 16-bit // numbers yet // break; } // // check to see if the upcoming number is really an IPv4 // address. If it is, convert it to 2 ushort numbers // for (int j = i; (address[j] != ']') && (address[j] != ':') && (address[j] != '%') && (address[j] != '/') && (j < i + 4); ++j) { if (address[j] == '.') { // // we have an IPv4 address. Find the end of it: // we know that since we have a valid IPv6 // address, the only things that will terminate // the IPv4 address are the prefix delimiter '/' // or the end-of-string (which we conveniently // delimited with ']') // while ((address[j] != ']') && (address[j] != '/') && (address[j] != '%')) { ++j; } number = IPv4AddressHelper.ParseHostNumber(address, i, j); numbers[index++] = (ushort)(number >> 16); numbers[index++] = (ushort)number; i = j; // // set this to avoid adding another number to // the array if there's a prefix // number = 0; numberIsValid = false; break; } } break; case '/': if (numberIsValid) { numbers[index++] = (ushort)number; numberIsValid = false; } // // since we have a valid IPv6 address string, the prefix // length is the last token in the string // for (++i; address[i] != ']'; ++i) { PrefixLength = PrefixLength * 10 + (address[i] - '0'); } break; default: number = number * 16 + UriHelper.FromHex(address[i++]); break; } } // // add number to the array if its not the prefix length or part of // an IPv4 address that's already been handled // if (numberIsValid) { numbers[index++] = (ushort)number; } // // if we had a compressor sequence ("::") then we need to expand the // numbers array // if (compressorIndex > 0) { int toIndex = NumberOfLabels - 1; int fromIndex = index - 1; for (int i = index - compressorIndex; i > 0; --i) { numbers[toIndex--] = numbers[fromIndex]; numbers[fromIndex--] = 0; } } // // is the address loopback? Loopback is defined as one of: // // 0:0:0:0:0:0:0:1 // 0:0:0:0:0:0:127.0.0.1 == 0:0:0:0:0:0:7F00:0001 // 0:0:0:0:0:FFFF:127.0.0.1 == 0:0:0:0:0:FFFF:7F00:0001 // return ((numbers[0] == 0) && (numbers[1] == 0) && (numbers[2] == 0) && (numbers[3] == 0) && (numbers[4] == 0)) && (((numbers[5] == 0) && (numbers[6] == 0) && (numbers[7] == 1)) || (((numbers[6] == 0x7F00) && (numbers[7] == 0x0001)) && ((numbers[5] == 0) || (numbers[5] == 0xFFFF)))); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WngCodingTask.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); } } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using WebsitePanel.Server.Utils; using Microsoft.Win32; namespace WebsitePanel.Providers.Mail { public class AbilityMailServer : HostingServiceProviderBase, IMailServer { #region IMailServer Members public bool AccountExists(string mailboxName) { Tree users = AMSHelper.GetUsersConfig(); AmsMailbox accnt = new AmsMailbox(mailboxName); return accnt.Load(users); } public void AddDomainAlias(string domainName, string aliasName) { Tree domains = AMSHelper.GetDomainsConfig(); AmsDomain alias = new AmsDomain(aliasName); if (!alias.Load(domains)) { alias.DomainConfig["enabled"] = "1"; alias.DomainConfig["domain"] = aliasName; alias.DomainConfig["mode"] = "1"; // alias mode alias.DomainConfig["useconvertdomain"] = "1"; alias.DomainConfig["convertdomain"] = domainName; if (!alias.Save(domains)) { Log.WriteInfo("Couldn't save domains configuration."); throw new Exception("Couldn't add domain alias."); } } else { Log.WriteInfo("Alias already exists."); throw new Exception("Alias already exists."); } } public void CreateAccount(MailAccount mailbox) { Tree users = AMSHelper.GetUsersConfig(); AmsMailbox accnt = new AmsMailbox(mailbox.Name); if (accnt.Load(users)) throw new Exception("Mailbox is already registered."); accnt.Read(mailbox); if (!accnt.Save(users)) throw new Exception("Couldn't create a mailbox."); } public void CreateDomain(MailDomain domain) { Tree domains = AMSHelper.GetDomainsConfig(); AmsDomain amsDomain = new AmsDomain(domain.Name); if (amsDomain.Load(domains)) throw new Exception("Domain is already registered."); amsDomain.Read(domain); if (!amsDomain.Save(domains)) throw new Exception("Couldn't create a domain."); } public void CreateGroup(MailGroup group) { Tree users = AMSHelper.GetUsersConfig(); AmsMailbox amsGroup = new AmsMailbox(group.Name); if (amsGroup.Load(users)) throw new Exception("Mail group is already exists."); amsGroup.Read(group); if (!amsGroup.Save(users)) throw new Exception("Couldn't create a mail group."); } public void CreateList(MailList maillist) { Tree config = AMSHelper.GetMailListsConfig(); AmsMailList amsList = new AmsMailList(maillist.Name); if (amsList.Load(config)) throw new Exception("Mail list is already exists."); amsList.Read(maillist); if (!amsList.Save(config)) throw new Exception("Couldn't create a mail list."); } public void DeleteAccount(string mailboxName) { Tree config = AMSHelper.GetUsersConfig(); AmsMailbox amsMailbox = new AmsMailbox(mailboxName); if (amsMailbox.Load(config)) { if (!amsMailbox.Delete(config)) throw new Exception("Couldn't delete a specified account."); } else throw new Exception("Couldn't load account settings."); } public bool MailAliasExists(string mailAliasName) { throw new System.NotImplementedException(); } public MailAlias[] GetMailAliases(string domainName) { throw new System.NotImplementedException(); } public MailAlias GetMailAlias(string mailAliasName) { throw new System.NotImplementedException(); } public void CreateMailAlias(MailAlias mailAlias) { throw new System.NotImplementedException(); } public void UpdateMailAlias(MailAlias mailAlias) { throw new System.NotImplementedException(); } public void DeleteMailAlias(string mailAliasName) { throw new System.NotImplementedException(); } public void DeleteDomain(string domainName) { Tree config = AMSHelper.GetDomainsConfig(); AmsDomain amsDomain = new AmsDomain(domainName); if (amsDomain.Load(config)) { if (!amsDomain.Delete(config)) throw new Exception("Couldn't delete specified domain."); } else throw new Exception("Couldn't find specified domain."); } public void DeleteDomainAlias(string domainName, string aliasName) { Tree config = AMSHelper.GetDomainsConfig(); AmsDomain amsAlias = new AmsDomain(aliasName); if (amsAlias.Load(config)) { string amsDomain = amsAlias.DomainConfig["convertdomain"]; if (string.Compare(amsDomain, domainName, true) == 0) { if (!amsAlias.DeleteAlias(config)) throw new Exception("Couldn't delete alias."); } } else { throw new Exception("Couldn't find specified alias."); } } public void DeleteGroup(string groupName) { Tree config = AMSHelper.GetUsersConfig(); AmsMailbox amsGroup = new AmsMailbox(groupName); if (amsGroup.Load(config)) { if (!amsGroup.Delete(config)) throw new Exception("Couldn't delete specified mail group."); } else { throw new Exception("Couldn't find specified mail group."); } } public void DeleteList(string maillistName) { Tree config = AMSHelper.GetMailListsConfig(); AmsMailList amsList = new AmsMailList(maillistName); if (amsList.Load(config)) { if (!amsList.Delete(config)) throw new Exception("Couldn't delete a mail list."); } else { throw new Exception("Couldn't find specified mail list."); } } public bool DomainAliasExists(string domainName, string aliasName) { Tree config = AMSHelper.GetDomainsConfig(); AmsDomain amsAlias = new AmsDomain(aliasName); if (amsAlias.Load(config)) if (string.Compare(amsAlias.DomainConfig["convertdomain"], domainName, true) == 0) return true; return false; } public bool DomainExists(string domainName) { Tree config = AMSHelper.GetDomainsConfig(); AmsDomain amsDomain = new AmsDomain(domainName); return amsDomain.Load(config); } public MailAccount GetAccount(string mailboxName) { Tree config = AMSHelper.GetUsersConfig(); AmsMailbox amsMailbox = new AmsMailbox(mailboxName); if (amsMailbox.Load(config)) { amsMailbox.LoadAccountConfig(); return amsMailbox.ToMailAccount(); } return null; } public MailAccount[] GetAccounts(string domainName) { Tree config = AMSHelper.GetUsersConfig(); List<MailAccount> accounts = new List<MailAccount>(); AmsMailbox[] mbList = AmsMailbox.GetMailboxes(config, domainName); foreach (AmsMailbox mb in mbList) accounts.Add(mb.ToMailAccount()); return accounts.ToArray(); } public MailDomain GetDomain(string domainName) { Tree config = AMSHelper.GetDomainsConfig(); AmsDomain amsDomain = new AmsDomain(domainName); if (amsDomain.Load(config)) return amsDomain.ToMailDomain(); return null; } public virtual string[] GetDomains() { Tree config = AMSHelper.GetDomainsConfig(); return AmsDomain.GetDomains(config); } public string[] GetDomainAliases(string domainName) { Tree config = AMSHelper.GetDomainsConfig(); return AmsDomain.GetDomainAliases(config, domainName); } public MailGroup GetGroup(string groupName) { Tree config = AMSHelper.GetUsersConfig(); AmsMailbox amsGroup = new AmsMailbox(groupName); if (amsGroup.Load(config)) { amsGroup.LoadAccountConfig(); return amsGroup.ToMailGroup(); } return null; } public MailGroup[] GetGroups(string domainName) { List<MailGroup> groups = new List<MailGroup>(); Tree config = AMSHelper.GetUsersConfig(); AmsMailbox[] amsGroups = AmsMailbox.GetMailGroups(config, domainName); foreach (AmsMailbox amsGroup in amsGroups) groups.Add(amsGroup.ToMailGroup()); return groups.ToArray(); } public MailList GetList(string maillistName) { Tree config = AMSHelper.GetMailListsConfig(); AmsMailList amsList = new AmsMailList(maillistName); if (amsList.Load(config)) { amsList.LoadListConfig(); return amsList.ToMailList(); } return null; } public MailList[] GetLists(string domainName) { List<MailList> lists = new List<MailList>(); Tree config = AMSHelper.GetMailListsConfig(); AmsMailList[] amsLists = AmsMailList.GetMailLists(config, domainName); foreach (AmsMailList amsList in amsLists) lists.Add(amsList.ToMailList()); return lists.ToArray(); } public bool GroupExists(string groupName) { Tree config = AMSHelper.GetUsersConfig(); AmsMailbox amsGroup = new AmsMailbox(groupName); if (amsGroup.Load(config)) { amsGroup.LoadAccountConfig(); return amsGroup.IsMailGroup(); } return false; } public bool ListExists(string maillistName) { Tree config = AMSHelper.GetMailListsConfig(); AmsMailList amsList = new AmsMailList(maillistName); return amsList.Load(config); } public void UpdateAccount(MailAccount mailbox) { Tree config = AMSHelper.GetUsersConfig(); AmsMailbox amsMailbox = new AmsMailbox(mailbox.Name); if (amsMailbox.Load(config)) { amsMailbox.LoadAccountConfig(); amsMailbox.Read(mailbox); if (!amsMailbox.Save(config)) throw new Exception("Couldn't update specified mailbox."); } else { throw new Exception("Couldn't find specified mailbox."); } } public void UpdateDomain(MailDomain domain) { Tree config = AMSHelper.GetDomainsConfig(); AmsDomain amsDomain = new AmsDomain(domain.Name); if (amsDomain.Load(config)) { amsDomain.Read(domain); if (!amsDomain.Save(config)) throw new Exception("Couldn't update specified domain."); } else { throw new Exception("Couldn't find specified domain."); } } public void UpdateGroup(MailGroup group) { Tree config = AMSHelper.GetUsersConfig(); AmsMailbox amsGroup = new AmsMailbox(group.Name); if (amsGroup.Load(config)) { amsGroup.LoadAccountConfig(); amsGroup.Read(group); if (!amsGroup.Save(config)) throw new Exception("Couldn't update specified mail group."); } else { throw new Exception("Couldn't find specified mail group."); } } public void UpdateList(MailList maillist) { Tree config = AMSHelper.GetMailListsConfig(); AmsMailList amsList = new AmsMailList(maillist.Name); if (amsList.Load(config)) { amsList.LoadListConfig(); amsList.Read(maillist); if (!amsList.Save(config)) throw new Exception("Couldn't update specified mail list."); } else { throw new Exception("Couldn't find specified mail list."); } } #endregion #region HostingServiceProviderBase members public override void DeleteServiceItems(ServiceProviderItem[] items) { foreach (ServiceProviderItem item in items) { if (item is MailDomain) { try { // delete mail domain DeleteDomain(item.Name); } catch (Exception ex) { Log.WriteError(String.Format("Error deleting '{0}' mail domain", item.Name), ex); } } } } public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled) { foreach (ServiceProviderItem item in items) { if (item is MailDomain) { try { MailDomain domain = GetDomain(item.Name); domain.Enabled = enabled; // update mail domain UpdateDomain(domain); } catch (Exception ex) { Log.WriteError(String.Format("Error switching '{0}' mail domain", item.Name), ex); } } } } #endregion public override bool IsInstalled() { string name = null; string versionNumber = null; RegistryKey HKLM = Registry.LocalMachine; RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Ability Mail Server 2_is1"); if (key != null) { name = (string) key.GetValue("DisplayName"); string[] parts = name.Split(new char[] {' '}); versionNumber = parts[3]; } else { key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Ability Mail Server 2_is1"); if (key != null) { name = (string)key.GetValue("DisplayName"); string[] parts = name.Split(new char[] { ' ' }); versionNumber = parts[3]; } else { return false; } } string[] split = versionNumber.Split(new char[] {'.'}); return split[0].Equals("2"); } } }
using System; using System.Xml; using System.Data; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; using MyMeta; namespace MyGeneration { /// <summary> /// Summary description for DbTargetMappings. /// </summary> public class DbTargetMappings : DockContent, IMyGenContent { private IMyGenerationMDI mdi; GridLayoutHelper gridLayoutHelper; private System.ComponentModel.IContainer components; private System.Windows.Forms.ComboBox cboxDbTarget; private System.Windows.Forms.DataGrid XmlEditor; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ToolBar toolBar1; private System.Windows.Forms.ToolBarButton toolBarButton_Save; private System.Windows.Forms.ToolBarButton toolBarButton_New; private System.Windows.Forms.ToolBarButton toolBarButton1; private System.Windows.Forms.ToolBarButton toolBarButton_Delete; private System.Windows.Forms.DataGridTextBoxColumn col_From; private System.Windows.Forms.DataGridTextBoxColumn col_To; private System.Windows.Forms.DataGridTableStyle MyXmlStyle; public DbTargetMappings(IMyGenerationMDI mdi) { InitializeComponent(); this.mdi = mdi; this.ShowHint = DockState.DockRight; } protected override string GetPersistString() { return this.GetType().FullName; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DbTargetMappings)); this.XmlEditor = new System.Windows.Forms.DataGrid(); this.MyXmlStyle = new System.Windows.Forms.DataGridTableStyle(); this.col_From = new System.Windows.Forms.DataGridTextBoxColumn(); this.col_To = new System.Windows.Forms.DataGridTextBoxColumn(); this.cboxDbTarget = new System.Windows.Forms.ComboBox(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.toolBar1 = new System.Windows.Forms.ToolBar(); this.toolBarButton_Save = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_New = new System.Windows.Forms.ToolBarButton(); this.toolBarButton1 = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_Delete = new System.Windows.Forms.ToolBarButton(); ((System.ComponentModel.ISupportInitialize)(this.XmlEditor)).BeginInit(); this.SuspendLayout(); // // XmlEditor // this.XmlEditor.AlternatingBackColor = System.Drawing.Color.Moccasin; this.XmlEditor.BackColor = System.Drawing.Color.LightGray; this.XmlEditor.BackgroundColor = System.Drawing.Color.LightGray; this.XmlEditor.CaptionVisible = false; this.XmlEditor.DataMember = ""; this.XmlEditor.Dock = System.Windows.Forms.DockStyle.Fill; this.XmlEditor.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.XmlEditor.GridLineColor = System.Drawing.Color.BurlyWood; this.XmlEditor.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.XmlEditor.Location = new System.Drawing.Point(2, 49); this.XmlEditor.Name = "XmlEditor"; this.XmlEditor.Size = new System.Drawing.Size(476, 951); this.XmlEditor.TabIndex = 7; this.XmlEditor.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.MyXmlStyle}); // // MyXmlStyle // this.MyXmlStyle.AlternatingBackColor = System.Drawing.Color.LightGray; this.MyXmlStyle.BackColor = System.Drawing.Color.LightSteelBlue; this.MyXmlStyle.DataGrid = this.XmlEditor; this.MyXmlStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] { this.col_From, this.col_To}); this.MyXmlStyle.GridLineColor = System.Drawing.Color.DarkGray; this.MyXmlStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.MyXmlStyle.MappingName = "DbTarget"; // // col_From // this.col_From.Format = ""; this.col_From.FormatInfo = null; this.col_From.HeaderText = "From"; this.col_From.MappingName = "From"; this.col_From.NullText = ""; this.col_From.Width = 75; // // col_To // this.col_To.Format = ""; this.col_To.FormatInfo = null; this.col_To.HeaderText = "To"; this.col_To.MappingName = "To"; this.col_To.NullText = ""; this.col_To.Width = 75; // // cboxDbTarget // this.cboxDbTarget.Dock = System.Windows.Forms.DockStyle.Top; this.cboxDbTarget.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboxDbTarget.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cboxDbTarget.Location = new System.Drawing.Point(2, 2); this.cboxDbTarget.Name = "cboxDbTarget"; this.cboxDbTarget.Size = new System.Drawing.Size(476, 21); this.cboxDbTarget.TabIndex = 12; this.cboxDbTarget.SelectionChangeCommitted += new System.EventHandler(this.cboxLanguage_SelectionChangeCommitted); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Magenta; this.imageList1.Images.SetKeyName(0, ""); this.imageList1.Images.SetKeyName(1, ""); this.imageList1.Images.SetKeyName(2, ""); // // toolBar1 // this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.toolBarButton_Save, this.toolBarButton_New, this.toolBarButton1, this.toolBarButton_Delete}); this.toolBar1.Divider = false; this.toolBar1.DropDownArrows = true; this.toolBar1.ImageList = this.imageList1; this.toolBar1.Location = new System.Drawing.Point(2, 23); this.toolBar1.Name = "toolBar1"; this.toolBar1.ShowToolTips = true; this.toolBar1.Size = new System.Drawing.Size(476, 26); this.toolBar1.TabIndex = 14; this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick); // // toolBarButton_Save // this.toolBarButton_Save.ImageIndex = 0; this.toolBarButton_Save.Name = "toolBarButton_Save"; this.toolBarButton_Save.Tag = "save"; this.toolBarButton_Save.ToolTipText = "Save DbTarget Mappings"; // // toolBarButton_New // this.toolBarButton_New.ImageIndex = 2; this.toolBarButton_New.Name = "toolBarButton_New"; this.toolBarButton_New.Tag = "new"; this.toolBarButton_New.ToolTipText = "Create New DbTarget Mapping"; // // toolBarButton1 // this.toolBarButton1.Name = "toolBarButton1"; this.toolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator; // // toolBarButton_Delete // this.toolBarButton_Delete.ImageIndex = 1; this.toolBarButton_Delete.Name = "toolBarButton_Delete"; this.toolBarButton_Delete.Tag = "delete"; this.toolBarButton_Delete.ToolTipText = "Delete DbTarget Mappings"; // // DbTargetMappings // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(480, 1002); this.Controls.Add(this.XmlEditor); this.Controls.Add(this.toolBar1); this.Controls.Add(this.cboxDbTarget); this.HideOnClose = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "DbTargetMappings"; this.Padding = new System.Windows.Forms.Padding(2); this.TabText = "DbTarget Mappings"; this.Text = "DbTarget Mappings"; this.Load += new System.EventHandler(this.DbTargetMappings_Load); ((System.ComponentModel.ISupportInitialize)(this.XmlEditor)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public void DefaultSettingsChanged(DefaultSettings settings) { PromptForSave(false); this.dbDriver = settings.DbDriver; PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); } public bool CanClose(bool allowPrevent) { return PromptForSave(allowPrevent); } private bool PromptForSave(bool allowPrevent) { bool canClose = true; if(this.isDirty) { DialogResult result; if(allowPrevent) { result = MessageBox.Show("The DbTarget Mappings have been Modified, Do you wish to save them?", "DbTarget Mappings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); } else { result = MessageBox.Show("The DbTarget Mappings have been Modified, Do you wish to save them?", "DbTarget Mappings", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } switch(result) { case DialogResult.Yes: { DefaultSettings settings = DefaultSettings.Instance; xml.Save(settings.DbTargetMappingFile); MarkAsDirty(false); } break; case DialogResult.Cancel: canClose = false; break; } } return canClose; } private void MarkAsDirty(bool isDirty) { this.isDirty = isDirty; this.toolBarButton_Save.Visible = isDirty; } public void Show(DockPanel dockManager) { DefaultSettings settings = DefaultSettings.Instance; if (!System.IO.File.Exists(settings.DbTargetMappingFile)) { MessageBox.Show(this, "Database Target Mapping File does not exist at: " + settings.DbTargetMappingFile + "\r\nPlease fix this in DefaultSettings."); } else { base.Show(dockManager); } } private void DbTargetMappings_Load(object sender, System.EventArgs e) { this.col_From.TextBox.BorderStyle = BorderStyle.None; this.col_To.TextBox.BorderStyle = BorderStyle.None; this.col_From.TextBox.Move += new System.EventHandler(this.ColorTextBox); this.col_To.TextBox.Move += new System.EventHandler(this.ColorTextBox); DefaultSettings settings = DefaultSettings.Instance; this.dbDriver = settings.DbDriver; this.xml.Load(settings.DbTargetMappingFile); PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); gridLayoutHelper = new GridLayoutHelper(XmlEditor, MyXmlStyle, new decimal[] { 0.50M, 0.50M }, new int[] { 100, 100 }); } private void cboxLanguage_SelectionChangeCommitted(object sender, System.EventArgs e) { DefaultSettings settings = DefaultSettings.Instance; PopulateGrid(this.dbDriver); } private void PopulateComboBox(DefaultSettings settings) { this.cboxDbTarget.Items.Clear(); // Populate the ComboBox dbRoot myMeta = new dbRoot(); myMeta.DbTargetMappingFileName = settings.DbTargetMappingFile; myMeta.DbTarget = settings.DbTarget; string[] targets = myMeta.GetDbTargetMappings(settings.DbDriver); if(null != targets) { for(int i = 0; i < targets.Length; i++) { this.cboxDbTarget.Items.Add(targets[i]); } this.cboxDbTarget.SelectedItem = myMeta.DbTarget; if(this.cboxDbTarget.SelectedIndex == -1) { // The default doesn't exist, set it to the first in the list this.cboxDbTarget.SelectedIndex = 0; } } } private void PopulateGrid(string dbDriver) { string target; if(this.cboxDbTarget.SelectedItem != null) { XmlEditor.Enabled = true; target = this.cboxDbTarget.SelectedItem as String; } else { XmlEditor.Enabled = false; target = ""; } this.Text = "DbTarget Mappings for " + dbDriver; langNode = this.xml.SelectSingleNode(@"//DbTargets/DbTarget[@From='" + dbDriver + "' and @To='" + target + "']"); DataSet ds = new DataSet(); DataTable dt = new DataTable("this"); dt.Columns.Add("this", Type.GetType("System.Object")); ds.Tables.Add(dt); dt.Rows.Add(new object[] { this }); dt = new DataTable("DbTarget"); DataColumn from = dt.Columns.Add("From", Type.GetType("System.String")); from.AllowDBNull = false; DataColumn to = dt.Columns.Add("To", Type.GetType("System.String")); to.AllowDBNull = false; ds.Tables.Add(dt); UniqueConstraint pk = new UniqueConstraint(from, false); dt.Constraints.Add(pk); ds.EnforceConstraints = true; if(null != langNode) { foreach(XmlNode mappingpNode in langNode.ChildNodes) { XmlAttributeCollection attrs = mappingpNode.Attributes; string sFrom = attrs["From"].Value; string sTo = attrs["To"].Value; dt.Rows.Add( new object[] { sFrom, sTo } ); } dt.AcceptChanges(); } XmlEditor.DataSource = dt; dt.RowChanged += new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(GridRowDeleted); } private static void GridRowChanged(object sender, DataRowChangeEventArgs e) { DbTargetMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as DbTargetMappings; This.MarkAsDirty(true); This.GridRowChangedEvent(sender, e); } private static void GridRowDeleting(object sender, DataRowChangeEventArgs e) { DbTargetMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as DbTargetMappings; This.MarkAsDirty(true); This.GridRowDeletingEvent(sender, e); } private static void GridRowDeleted(object sender, DataRowChangeEventArgs e) { DbTargetMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as DbTargetMappings; This.MarkAsDirty(true); This.GridRowDeletedEvent(sender, e); } private void GridRowChangedEvent(object sender, DataRowChangeEventArgs e) { try { string sFrom = e.Row["From"] as string; string sTo = e.Row["To"] as string; string xPath; XmlNode typeNode; switch(e.Row.RowState) { case DataRowState.Added: { typeNode = langNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Type", null); langNode.AppendChild(typeNode); XmlAttribute attr; attr = langNode.OwnerDocument.CreateAttribute("From"); attr.Value = sFrom; typeNode.Attributes.Append(attr); attr = langNode.OwnerDocument.CreateAttribute("To"); attr.Value = sTo; typeNode.Attributes.Append(attr); } break; case DataRowState.Modified: { xPath = @"./Type[@From='" + sFrom + "']"; typeNode = langNode.SelectSingleNode(xPath); typeNode.Attributes["To"].Value = sTo; } break; } } catch{} } private void GridRowDeletingEvent(object sender, DataRowChangeEventArgs e) { string xPath = @"./Type[@From='" + e.Row["From"] + "' and @To='" + e.Row["To"] + "']"; XmlNode node = langNode.SelectSingleNode(xPath); if(node != null) { node.ParentNode.RemoveChild(node); } } private void GridRowDeletedEvent(object sender, DataRowChangeEventArgs e) { DataTable dt = e.Row.Table; dt.RowChanged -= new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting -= new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted -= new DataRowChangeEventHandler(GridRowDeleted); dt.AcceptChanges(); dt.RowChanged += new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(GridRowDeleted); } private void ColorTextBox(object sender, System.EventArgs e) { TextBox txtBox = (TextBox)sender; // Bail if we're in la la land Size size = txtBox.Size; if(size.Width == 0 && size.Height == 0) { return; } int row = this.XmlEditor.CurrentCell.RowNumber; int col = this.XmlEditor.CurrentCell.ColumnNumber; if(isEven(row)) txtBox.BackColor = Color.LightSteelBlue; else txtBox.BackColor = Color.LightGray; if(col == 0) { if(txtBox.Text == string.Empty) txtBox.ReadOnly = false; else txtBox.ReadOnly = true; } } private bool isEven(int x) { return (x & 1) == 0; } private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { DefaultSettings settings = DefaultSettings.Instance; switch(e.Button.Tag as string) { case "save": xml.Save(settings.DbTargetMappingFile); MarkAsDirty(false); break; case "new": { int count = this.cboxDbTarget.Items.Count; string[] dbTargets = new string[count]; for(int i = 0; i < this.cboxDbTarget.Items.Count; i++) { dbTargets[i] = this.cboxDbTarget.Items[i] as string; } AddDbTargetMappingDialog dialog = new AddDbTargetMappingDialog(dbTargets, this.dbDriver); if(dialog.ShowDialog() == DialogResult.OK) { if(dialog.BasedUpon != string.Empty) { string xPath = @"//DbTargets/DbTarget[@From='" + this.dbDriver + "' and @To='" + dialog.BasedUpon + "']"; XmlNode node = xml.SelectSingleNode(xPath); XmlNode newNode = node.CloneNode(true); newNode.Attributes["To"].Value = dialog.NewDbTarget; node.ParentNode.AppendChild(newNode); } else { XmlNode parentNode = xml.SelectSingleNode(@"//DbTargets"); XmlAttribute attr; // Language Node langNode = xml.CreateNode(XmlNodeType.Element, "DbTarget", null); parentNode.AppendChild(langNode); attr = xml.CreateAttribute("From"); attr.Value = settings.DbDriver; langNode.Attributes.Append(attr); attr = xml.CreateAttribute("To"); attr.Value = dialog.NewDbTarget; langNode.Attributes.Append(attr); } this.cboxDbTarget.Items.Add(dialog.NewDbTarget); this.cboxDbTarget.SelectedItem = dialog.NewDbTarget; PopulateGrid(this.dbDriver); MarkAsDirty(true); } } break; case "delete": if(this.cboxDbTarget.SelectedItem != null) { string target = this.cboxDbTarget.SelectedItem as String; DialogResult result = MessageBox.Show("Delete '" + target + "' Mappings. Are you sure?", "Delete DbTarget Mappings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if(result == DialogResult.Yes) { string xPath = @"//DbTargets/DbTarget[@From='" + this.dbDriver + "' and @To='" + target + "']"; XmlNode node = xml.SelectSingleNode(xPath); node.ParentNode.RemoveChild(node); this.cboxDbTarget.Items.Remove(target); if(this.cboxDbTarget.Items.Count > 0) { this.cboxDbTarget.SelectedItem = this.cboxDbTarget.SelectedIndex = 0; } PopulateGrid(this.dbDriver); MarkAsDirty(true); } } break; } } private XmlDocument xml = new XmlDocument(); private XmlNode langNode = null; private string dbDriver = ""; private bool isDirty = false; #region IMyGenContent Members public ToolStrip ToolStrip { get { throw new Exception("The method or operation is not implemented."); } } public void ProcessAlert(IMyGenContent sender, string command, params object[] args) { throw new Exception("The method or operation is not implemented."); } public DockContent DockContent { get { return this; } } #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 osu.Framework.Graphics.Primitives; using osuTK; namespace osu.Framework.Utils { /// <summary> /// Helper methods to approximate a path by interpolating a sequence of control points. /// </summary> public static class PathApproximator { private const float bezier_tolerance = 0.25f; /// <summary> /// The amount of pieces to calculate for each control point quadruplet. /// </summary> private const int catmull_detail = 50; private const float circular_arc_tolerance = 0.1f; /// <summary> /// Creates a piecewise-linear approximation of a bezier curve, by adaptively repeatedly subdividing /// the control points until their approximation error vanishes below a given threshold. /// </summary> /// <param name="controlPoints">The control points.</param> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateBezier(ReadOnlySpan<Vector2> controlPoints) { return ApproximateBSpline(controlPoints); } /// <summary> /// Creates a piecewise-linear approximation of a clamped uniform B-spline with polynomial order p, /// by dividing it into a series of bezier control points at its knots, then adaptively repeatedly /// subdividing those until their approximation error vanishes below a given threshold. /// Retains previous bezier approximation functionality when p is 0 or too large to create knots. /// Algorithm unsuitable for large values of p with many knots. /// </summary> /// <param name="controlPoints">The control points.</param> /// <param name="p">The polynomial order.</param> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateBSpline(ReadOnlySpan<Vector2> controlPoints, int p = 0) { List<Vector2> output = new List<Vector2>(); int n = controlPoints.Length - 1; if (n < 0) return output; Stack<Vector2[]> toFlatten = new Stack<Vector2[]>(); Stack<Vector2[]> freeBuffers = new Stack<Vector2[]>(); var points = controlPoints.ToArray(); if (p > 0 && p < n) { // Subdivide B-spline into bezier control points at knots. for (int i = 0; i < n - p; i++) { var subBezier = new Vector2[p + 1]; subBezier[0] = points[i]; // Destructively insert the knot p-1 times via Boehm's algorithm. for (int j = 0; j < p - 1; j++) { subBezier[j + 1] = points[i + 1]; for (int k = 1; k < p - j; k++) { int l = Math.Min(k, n - p - i); points[i + k] = (l * points[i + k] + points[i + k + 1]) / (l + 1); } } subBezier[p] = points[i + 1]; toFlatten.Push(subBezier); } toFlatten.Push(points[(n - p)..]); // Reverse the stack so elements can be accessed in order. toFlatten = new Stack<Vector2[]>(toFlatten); } else { // B-spline subdivision unnecessary, degenerate to single bezier. p = n; toFlatten.Push(points); } // "toFlatten" contains all the curves which are not yet approximated well enough. // We use a stack to emulate recursion without the risk of running into a stack overflow. // (More specifically, we iteratively and adaptively refine our curve with a // <a href="https://en.wikipedia.org/wiki/Depth-first_search">Depth-first search</a> // over the tree resulting from the subdivisions we make.) var subdivisionBuffer1 = new Vector2[p + 1]; var subdivisionBuffer2 = new Vector2[p * 2 + 1]; Vector2[] leftChild = subdivisionBuffer2; while (toFlatten.Count > 0) { Vector2[] parent = toFlatten.Pop(); if (bezierIsFlatEnough(parent)) { // If the control points we currently operate on are sufficiently "flat", we use // an extension to De Casteljau's algorithm to obtain a piecewise-linear approximation // of the bezier curve represented by our control points, consisting of the same amount // of points as there are control points. bezierApproximate(parent, output, subdivisionBuffer1, subdivisionBuffer2, p + 1); freeBuffers.Push(parent); continue; } // If we do not yet have a sufficiently "flat" (in other words, detailed) approximation we keep // subdividing the curve we are currently operating on. Vector2[] rightChild = freeBuffers.Count > 0 ? freeBuffers.Pop() : new Vector2[p + 1]; bezierSubdivide(parent, leftChild, rightChild, subdivisionBuffer1, p + 1); // We re-use the buffer of the parent for one of the children, so that we save one allocation per iteration. for (int i = 0; i < p + 1; ++i) parent[i] = leftChild[i]; toFlatten.Push(rightChild); toFlatten.Push(parent); } output.Add(controlPoints[n]); return output; } /// <summary> /// Creates a piecewise-linear approximation of a Catmull-Rom spline. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateCatmull(ReadOnlySpan<Vector2> controlPoints) { var result = new List<Vector2>((controlPoints.Length - 1) * catmull_detail * 2); for (int i = 0; i < controlPoints.Length - 1; i++) { var v1 = i > 0 ? controlPoints[i - 1] : controlPoints[i]; var v2 = controlPoints[i]; var v3 = i < controlPoints.Length - 1 ? controlPoints[i + 1] : v2 + v2 - v1; var v4 = i < controlPoints.Length - 2 ? controlPoints[i + 2] : v3 + v3 - v2; for (int c = 0; c < catmull_detail; c++) { result.Add(catmullFindPoint(ref v1, ref v2, ref v3, ref v4, (float)c / catmull_detail)); result.Add(catmullFindPoint(ref v1, ref v2, ref v3, ref v4, (float)(c + 1) / catmull_detail)); } } return result; } /// <summary> /// Creates a piecewise-linear approximation of a circular arc curve. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateCircularArc(ReadOnlySpan<Vector2> controlPoints) { CircularArcProperties pr = circularArcProperties(controlPoints); if (!pr.IsValid) return ApproximateBezier(controlPoints); // We select the amount of points for the approximation by requiring the discrete curvature // to be smaller than the provided tolerance. The exact angle required to meet the tolerance // is: 2 * Math.Acos(1 - TOLERANCE / r) // The special case is required for extremely short sliders where the radius is smaller than // the tolerance. This is a pathological rather than a realistic case. int amountPoints = 2 * pr.Radius <= circular_arc_tolerance ? 2 : Math.Max(2, (int)Math.Ceiling(pr.ThetaRange / (2 * Math.Acos(1 - circular_arc_tolerance / pr.Radius)))); List<Vector2> output = new List<Vector2>(amountPoints); for (int i = 0; i < amountPoints; ++i) { double fract = (double)i / (amountPoints - 1); double theta = pr.ThetaStart + pr.Direction * fract * pr.ThetaRange; Vector2 o = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * pr.Radius; output.Add(pr.Centre + o); } return output; } /// <summary> /// Computes the bounding box of a circular arc. /// </summary> /// <param name="controlPoints">Three distinct points on the arc.</param> /// <returns>The rectangle inscribing the circular arc.</returns> public static RectangleF CircularArcBoundingBox(ReadOnlySpan<Vector2> controlPoints) { CircularArcProperties pr = circularArcProperties(controlPoints); if (!pr.IsValid) return RectangleF.Empty; // We find the bounding box using the end-points, as well as // each 90 degree angle inside the range of the arc List<Vector2> points = new List<Vector2> { controlPoints[0], controlPoints[2] }; const double right_angle = Math.PI / 2; double step = right_angle * pr.Direction; double quotient = pr.ThetaStart / right_angle; // choose an initial right angle, closest to ThetaStart, going in the direction of the arc. // thanks to this, when looping over quadrant points to check if they lie on the arc, we only need to check against ThetaEnd. double closestRightAngle = right_angle * (pr.Direction > 0 ? Math.Ceiling(quotient) : Math.Floor(quotient)); // at most, four quadrant points must be considered. for (int i = 0; i < 4; ++i) { double angle = closestRightAngle + step * i; // check whether angle has exceeded ThetaEnd. // multiplying by Direction eliminates branching caused by the fact that step can be either positive or negative. if (Precision.DefinitelyBigger((angle - pr.ThetaEnd) * pr.Direction, 0)) break; Vector2 o = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)) * pr.Radius; points.Add(pr.Centre + o); } float minX = points.Min(p => p.X); float minY = points.Min(p => p.Y); float maxX = points.Max(p => p.X); float maxY = points.Max(p => p.Y); return new RectangleF(minX, minY, maxX - minX, maxY - minY); } /// <summary> /// Creates a piecewise-linear approximation of a linear curve. /// Basically, returns the input. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateLinear(ReadOnlySpan<Vector2> controlPoints) { var result = new List<Vector2>(controlPoints.Length); foreach (var c in controlPoints) result.Add(c); return result; } /// <summary> /// Creates a piecewise-linear approximation of a lagrange polynomial. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateLagrangePolynomial(ReadOnlySpan<Vector2> controlPoints) { // TODO: add some smarter logic here, chebyshev nodes? const int num_steps = 51; var result = new List<Vector2>(num_steps); double[] weights = Interpolation.BarycentricWeights(controlPoints); float minX = controlPoints[0].X; float maxX = controlPoints[0].X; for (int i = 1; i < controlPoints.Length; i++) { minX = Math.Min(minX, controlPoints[i].X); maxX = Math.Max(maxX, controlPoints[i].X); } float dx = maxX - minX; for (int i = 0; i < num_steps; i++) { float x = minX + dx / (num_steps - 1) * i; float y = (float)Interpolation.BarycentricLagrange(controlPoints, weights, x); result.Add(new Vector2(x, y)); } return result; } private readonly struct CircularArcProperties { public readonly bool IsValid; public readonly double ThetaStart; public readonly double ThetaRange; public readonly double Direction; public readonly float Radius; public readonly Vector2 Centre; public double ThetaEnd => ThetaStart + ThetaRange * Direction; public CircularArcProperties(double thetaStart, double thetaRange, double direction, float radius, Vector2 centre) { IsValid = true; ThetaStart = thetaStart; ThetaRange = thetaRange; Direction = direction; Radius = radius; Centre = centre; } } /// <summary> /// Computes various properties that can be used to approximate the circular arc. /// </summary> /// <param name="controlPoints">Three distinct points on the arc.</param> private static CircularArcProperties circularArcProperties(ReadOnlySpan<Vector2> controlPoints) { Vector2 a = controlPoints[0]; Vector2 b = controlPoints[1]; Vector2 c = controlPoints[2]; // If we have a degenerate triangle where a side-length is almost zero, then give up and fallback to a more numerically stable method. if (Precision.AlmostEquals(0, (b.Y - a.Y) * (c.X - a.X) - (b.X - a.X) * (c.Y - a.Y))) return default; // Implicitly sets `IsValid` to false // See: https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2 float d = 2 * (a.X * (b - c).Y + b.X * (c - a).Y + c.X * (a - b).Y); float aSq = a.LengthSquared; float bSq = b.LengthSquared; float cSq = c.LengthSquared; Vector2 centre = new Vector2( aSq * (b - c).Y + bSq * (c - a).Y + cSq * (a - b).Y, aSq * (c - b).X + bSq * (a - c).X + cSq * (b - a).X) / d; Vector2 dA = a - centre; Vector2 dC = c - centre; float r = dA.Length; double thetaStart = Math.Atan2(dA.Y, dA.X); double thetaEnd = Math.Atan2(dC.Y, dC.X); while (thetaEnd < thetaStart) thetaEnd += 2 * Math.PI; double dir = 1; double thetaRange = thetaEnd - thetaStart; // Decide in which direction to draw the circle, depending on which side of // AC B lies. Vector2 orthoAtoC = c - a; orthoAtoC = new Vector2(orthoAtoC.Y, -orthoAtoC.X); if (Vector2.Dot(orthoAtoC, b - a) < 0) { dir = -dir; thetaRange = 2 * Math.PI - thetaRange; } return new CircularArcProperties(thetaStart, thetaRange, dir, r, centre); } /// <summary> /// Make sure the 2nd order derivative (approximated using finite elements) is within tolerable bounds. /// NOTE: The 2nd order derivative of a 2d curve represents its curvature, so intuitively this function /// checks (as the name suggests) whether our approximation is _locally_ "flat". More curvy parts /// need to have a denser approximation to be more "flat". /// </summary> /// <param name="controlPoints">The control points to check for flatness.</param> /// <returns>Whether the control points are flat enough.</returns> private static bool bezierIsFlatEnough(Vector2[] controlPoints) { for (int i = 1; i < controlPoints.Length - 1; i++) { if ((controlPoints[i - 1] - 2 * controlPoints[i] + controlPoints[i + 1]).LengthSquared > bezier_tolerance * bezier_tolerance * 4) return false; } return true; } /// <summary> /// Subdivides n control points representing a bezier curve into 2 sets of n control points, each /// describing a bezier curve equivalent to a half of the original curve. Effectively this splits /// the original curve into 2 curves which result in the original curve when pieced back together. /// </summary> /// <param name="controlPoints">The control points to split.</param> /// <param name="l">Output: The control points corresponding to the left half of the curve.</param> /// <param name="r">Output: The control points corresponding to the right half of the curve.</param> /// <param name="subdivisionBuffer">The first buffer containing the current subdivision state.</param> /// <param name="count">The number of control points in the original list.</param> private static void bezierSubdivide(Vector2[] controlPoints, Vector2[] l, Vector2[] r, Vector2[] subdivisionBuffer, int count) { Vector2[] midpoints = subdivisionBuffer; for (int i = 0; i < count; ++i) midpoints[i] = controlPoints[i]; for (int i = 0; i < count; i++) { l[i] = midpoints[0]; r[count - i - 1] = midpoints[count - i - 1]; for (int j = 0; j < count - i - 1; j++) midpoints[j] = (midpoints[j] + midpoints[j + 1]) / 2; } } /// <summary> /// This uses <a href="https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm">De Casteljau's algorithm</a> to obtain an optimal /// piecewise-linear approximation of the bezier curve with the same amount of points as there are control points. /// </summary> /// <param name="controlPoints">The control points describing the bezier curve to be approximated.</param> /// <param name="output">The points representing the resulting piecewise-linear approximation.</param> /// <param name="count">The number of control points in the original list.</param> /// <param name="subdivisionBuffer1">The first buffer containing the current subdivision state.</param> /// <param name="subdivisionBuffer2">The second buffer containing the current subdivision state.</param> private static void bezierApproximate(Vector2[] controlPoints, List<Vector2> output, Vector2[] subdivisionBuffer1, Vector2[] subdivisionBuffer2, int count) { Vector2[] l = subdivisionBuffer2; Vector2[] r = subdivisionBuffer1; bezierSubdivide(controlPoints, l, r, subdivisionBuffer1, count); for (int i = 0; i < count - 1; ++i) l[count + i] = r[i + 1]; output.Add(controlPoints[0]); for (int i = 1; i < count - 1; ++i) { int index = 2 * i; Vector2 p = 0.25f * (l[index - 1] + 2 * l[index] + l[index + 1]); output.Add(p); } } /// <summary> /// Finds a point on the spline at the position of a parameter. /// </summary> /// <param name="vec1">The first vector.</param> /// <param name="vec2">The second vector.</param> /// <param name="vec3">The third vector.</param> /// <param name="vec4">The fourth vector.</param> /// <param name="t">The parameter at which to find the point on the spline, in the range [0, 1].</param> /// <returns>The point on the spline at <paramref name="t"/>.</returns> private static Vector2 catmullFindPoint(ref Vector2 vec1, ref Vector2 vec2, ref Vector2 vec3, ref Vector2 vec4, float t) { float t2 = t * t; float t3 = t * t2; Vector2 result; result.X = 0.5f * (2f * vec2.X + (-vec1.X + vec3.X) * t + (2f * vec1.X - 5f * vec2.X + 4f * vec3.X - vec4.X) * t2 + (-vec1.X + 3f * vec2.X - 3f * vec3.X + vec4.X) * t3); result.Y = 0.5f * (2f * vec2.Y + (-vec1.Y + vec3.Y) * t + (2f * vec1.Y - 5f * vec2.Y + 4f * vec3.Y - vec4.Y) * t2 + (-vec1.Y + 3f * vec2.Y - 3f * vec3.Y + vec4.Y) * t3); return result; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// .Net client wrapper for the REST API for Azure ApiManagement Service /// </summary> public static partial class TenantAccessInformationOperationsExtensions { /// <summary> /// Get tenant settings. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ITenantAccessInformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// Get Tenant Access Information operation response details. /// </returns> public static AccessInformationGetResponse Get(this ITenantAccessInformationOperations operations, string resourceGroupName, string serviceName) { return Task.Factory.StartNew((object s) => { return ((ITenantAccessInformationOperations)s).GetAsync(resourceGroupName, serviceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get tenant settings. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ITenantAccessInformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// Get Tenant Access Information operation response details. /// </returns> public static Task<AccessInformationGetResponse> GetAsync(this ITenantAccessInformationOperations operations, string resourceGroupName, string serviceName) { return operations.GetAsync(resourceGroupName, serviceName, CancellationToken.None); } /// <summary> /// Regenerate primary access key. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ITenantAccessInformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse RegeneratePrimaryKey(this ITenantAccessInformationOperations operations, string resourceGroupName, string serviceName) { return Task.Factory.StartNew((object s) => { return ((ITenantAccessInformationOperations)s).RegeneratePrimaryKeyAsync(resourceGroupName, serviceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerate primary access key. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ITenantAccessInformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> RegeneratePrimaryKeyAsync(this ITenantAccessInformationOperations operations, string resourceGroupName, string serviceName) { return operations.RegeneratePrimaryKeyAsync(resourceGroupName, serviceName, CancellationToken.None); } /// <summary> /// Regenerate secondary access key. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ITenantAccessInformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse RegenerateSecondaryKey(this ITenantAccessInformationOperations operations, string resourceGroupName, string serviceName) { return Task.Factory.StartNew((object s) => { return ((ITenantAccessInformationOperations)s).RegenerateSecondaryKeyAsync(resourceGroupName, serviceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerate secondary access key. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ITenantAccessInformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> RegenerateSecondaryKeyAsync(this ITenantAccessInformationOperations operations, string resourceGroupName, string serviceName) { return operations.RegenerateSecondaryKeyAsync(resourceGroupName, serviceName, CancellationToken.None); } /// <summary> /// Update tenant settings. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ITenantAccessInformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Update(this ITenantAccessInformationOperations operations, string resourceGroupName, string serviceName, AccessInformationUpdateParameters parameters, string etag) { return Task.Factory.StartNew((object s) => { return ((ITenantAccessInformationOperations)s).UpdateAsync(resourceGroupName, serviceName, parameters, etag); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update tenant settings. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ITenantAccessInformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='parameters'> /// Required. Parameters. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> UpdateAsync(this ITenantAccessInformationOperations operations, string resourceGroupName, string serviceName, AccessInformationUpdateParameters parameters, string etag) { return operations.UpdateAsync(resourceGroupName, serviceName, parameters, etag, CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Web; using System.Web.Script.Serialization; using System.Web.UI; using System.Web.UI.WebControls; #region [ Resources ] [assembly: System.Web.UI.WebResource("Tabs.Tabs.js", "application/x-javascript")] [assembly: System.Web.UI.WebResource("Tabs.Tabs.debug.js", "application/x-javascript")] [assembly: WebResource("Tabs.Tabs_resource.css", "text/css", PerformSubstitution = true)] [assembly: WebResource("Tabs.tab-line.gif", "image/gif")] // horizontal top (default) images [assembly: WebResource("Tabs.tab.gif", "image/gif")] [assembly: WebResource("Tabs.tab-left.gif", "image/gif")] [assembly: WebResource("Tabs.tab-right.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover-left.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover-right.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active-left.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active-right.gif", "image/gif")] // horizontal bottom images [assembly: WebResource("Tabs.tab-bottom.gif", "image/gif")] [assembly: WebResource("Tabs.tab-bottom-left.gif", "image/gif")] [assembly: WebResource("Tabs.tab-bottom-right.gif", "image/gif")] [assembly: WebResource("Tabs.tab-bottom-hover.gif", "image/gif")] [assembly: WebResource("Tabs.tab-bottom-hover-left.gif", "image/gif")] [assembly: WebResource("Tabs.tab-bottom-hover-right.gif", "image/gif")] [assembly: WebResource("Tabs.tab-bottom-active.gif", "image/gif")] [assembly: WebResource("Tabs.tab-bottom-active-left.gif", "image/gif")] [assembly: WebResource("Tabs.tab-bottom-active-right.gif", "image/gif")] // vertical left images [assembly: WebResource("Tabs.tab-verticalleft.gif", "image/gif")] [assembly: WebResource("Tabs.tab-left-verticalleft.gif", "image/gif")] [assembly: WebResource("Tabs.tab-right-verticalleft.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover-verticalleft.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover-left-verticalleft.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover-right-verticalleft.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active-verticalleft.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active-left-verticalleft.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active-right-verticalleft.gif", "image/gif")] // vertical right images [assembly: WebResource("Tabs.tab-verticalright.gif", "image/gif")] [assembly: WebResource("Tabs.tab-left-verticalright.gif", "image/gif")] [assembly: WebResource("Tabs.tab-right-verticalright.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover-verticalright.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover-left-verticalright.gif", "image/gif")] [assembly: WebResource("Tabs.tab-hover-right-verticalright.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active-verticalright.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active-left-verticalright.gif", "image/gif")] [assembly: WebResource("Tabs.tab-active-right-verticalright.gif", "image/gif")] #endregion namespace AjaxControlToolkit { /// <summary> /// TabContainer contains functionality to provide container for various TabPanels /// </summary> [Designer("AjaxControlToolkit.TabContainerDesigner, AjaxControlToolkit")] [ParseChildren(typeof(TabPanel))] [RequiredScript(typeof(CommonToolkitScripts))] [ClientCssResource("Tabs.Tabs_resource.css")] [ClientScriptResource("Sys.Extended.UI.TabContainer", "Tabs.Tabs.js")] [System.Drawing.ToolboxBitmap(typeof(TabContainer), "Tabs.Tabs.ico")] public class TabContainer : ScriptControlBase, IPostBackEventHandler { #region [ Static Fields ] private static readonly object EventActiveTabChanged = new object(); #endregion #region [ Fields ] private int _activeTabIndex = -1; private int _cachedActiveTabIndex = -1; private bool _initialized; private bool _autoPostBack; private TabStripPlacement _tabStripPlacement; private bool _useVerticalStripPlacement; private Unit _verticalStripWidth = new Unit(120, UnitType.Pixel); private bool _onDemand; #endregion #region [ Constructors ] /// <summary> /// Initializes a new TabContainer /// </summary> public TabContainer() : base(true, HtmlTextWriterTag.Div) { } #endregion #region [ Events ] /// <summary> /// Attach/remove method to the ActiveTabChanged Event Handler /// </summary> [Category("Behavior")] public event EventHandler ActiveTabChanged { add { Events.AddHandler(EventActiveTabChanged, value); } remove { Events.RemoveHandler(EventActiveTabChanged, value); } } #endregion #region [ Properties ] /// <summary> /// Gets index of Active Tab at client side /// </summary> [DefaultValue(-1)] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("activeTabIndex")] public int ActiveTabIndexForClient { get { int counter = ActiveTabIndex; for (int i = 0; i <= ActiveTabIndex && i < Tabs.Count; i++) { if (!Tabs[i].Visible) counter--; } if (counter < 0) counter = 0; return counter; } } /// <summary> /// Checks if script is rendering. /// </summary> /// <returns>True if script is rendering otherwise false</returns> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeActiveTabIndexForClient() { return IsRenderingScript; } /// <summary> /// Index of active tab. /// </summary> [DefaultValue(-1)] [Category("Behavior")] public virtual int ActiveTabIndex { get { if (_cachedActiveTabIndex > -1) { return _cachedActiveTabIndex; } if (Tabs.Count == 0) { return -1; } return _activeTabIndex; } set { if (value < -1) throw new ArgumentOutOfRangeException("value"); if (Tabs.Count == 0 && !_initialized) { _cachedActiveTabIndex = value; } else { if (ActiveTabIndex != value) { if (ActiveTabIndex != -1 && ActiveTabIndex < Tabs.Count) { Tabs[ActiveTabIndex].Active = false; } if (value >= Tabs.Count) { _activeTabIndex = Tabs.Count - 1; _cachedActiveTabIndex = value; } else { _activeTabIndex = value; _cachedActiveTabIndex = -1; } if (ActiveTabIndex != -1 && ActiveTabIndex < Tabs.Count) { Tabs[ActiveTabIndex].Active = true; } } } } } /// <summary> /// Index of last active tab /// </summary> private int LastActiveTabIndex { get { return (int)(ViewState["LastActiveTabIndex"] ?? -1); } set { ViewState["LastActiveTabIndex"] = value; } } /// <summary> /// Keeps collection of tabPanels those will be contained by the TabContainer. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TabPanelCollection Tabs { get { return (TabPanelCollection)Controls; } } /// <summary> /// Provides object of current active tab panel. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TabPanel ActiveTab { get { int i = ActiveTabIndex; if (i < 0 || i >= Tabs.Count) { return null; } EnsureActiveTab(); return Tabs[i]; } set { int i = Tabs.IndexOf(value); if (i < 0) { throw new ArgumentOutOfRangeException("value"); } ActiveTabIndex = i; } } /// <summary> /// Determine whether to raise ActiveTabChanged from the client side. /// </summary> [DefaultValue(false)] [Category("Behavior")] public bool AutoPostBack { get { return _autoPostBack; } set { _autoPostBack = value; } } /// <summary> /// Height of the Tab Container. /// </summary> [DefaultValue(typeof(Unit), "")] [Category("Appearance")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Justification = "Assembly is not localized")] public override Unit Height { get { return base.Height; } set { //if (!value.IsEmpty && value.Type != UnitType.Pixel) //{ // throw new ArgumentOutOfRangeException("value", "Height must be set in pixels only, or Empty."); //} base.Height = value; } } /// <summary> /// Width of Tab Container. /// </summary> [DefaultValue(typeof(Unit), "")] [Category("Appearance")] public override Unit Width { get { return base.Width; } set { base.Width = value; } } /// <summary> /// To customize theme of TabContainer. /// </summary> [DefaultValue("ajax__tab_xp")] [Category("Appearance")] public override string CssClass { get { return base.CssClass; } set { base.CssClass = value; } } /// <summary> /// Determine whether to display scrollbars or not when contents are overflowing. /// </summary> [DefaultValue(ScrollBars.None)] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("scrollBars")] public ScrollBars ScrollBars { get { return (ScrollBars)(ViewState["ScrollBars"] ?? ScrollBars.None); } set { ViewState["ScrollBars"] = value; } } /// <summary> /// Where the tabs should be displayed (Top, TopRight, Bottom, BottomRight). /// </summary> [DefaultValue(TabStripPlacement.Top)] [Category("Appearance")] public TabStripPlacement TabStripPlacement { get { return _tabStripPlacement; } set { _tabStripPlacement = value; } } /// <summary> /// Attaches Client function to handle OnClientActiveTabChanged event handler. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("activeTabChanged")] public string OnClientActiveTabChanged { get { return (string)(ViewState["OnClientActiveTabChanged"] ?? string.Empty); } set { ViewState["OnClientActiveTabChanged"] = value; } } /// <summary> /// To enable AutoPostBack, we need to call an ASP.NET script method with the UniqueId /// on the client side. To do this, we just use this property as the one to serialize and /// alias it's name. /// </summary> [ExtenderControlProperty] [ClientPropertyName("autoPostBackId")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", MessageId = "Member", Justification = "Following ASP.NET naming conventions...")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value", Justification = "Required for serialization")] public new string UniqueID { get { return base.UniqueID; } set { // need to add a setter for serialization to work properly. } } // has to be public so reflection can get at it... // this method determines if the UniqueID property will // be code generated. [EditorBrowsable(EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", MessageId = "Member", Justification = "Following ASP.NET naming conventions...")] public bool ShouldSerializeUniqueID() { return IsRenderingScript && AutoPostBack; } /// <summary> /// Change tab header placement verticaly /// </summary> [Description("Change tab header placement vertically when value set to true")] [DefaultValue(false)] [Category("Appearance")] public bool UseVerticalStripPlacement { get { return _useVerticalStripPlacement; } set { _useVerticalStripPlacement = value; } } /// <summary> /// Set width of tab strips when UseVerticalStripPlacement is set to true /// </summary> [Description("Set width of tab strips when UseVerticalStripPlacement is set to true. Size must be in pixel")] [DefaultValue(typeof(Unit), "120px")] [Category("Appearance")] public Unit VerticalStripWidth { get { return _verticalStripWidth; } set { if (!value.IsEmpty && value.Type != UnitType.Pixel) { throw new ArgumentOutOfRangeException("value", "VerticalStripWidth must be set in pixels only, or Empty."); } _verticalStripWidth = value; } } /// <summary> /// Load tab content when it's activated /// </summary> [DefaultValue(false)] [Category("Behavior")] public bool OnDemand { get { return _onDemand; } set { _onDemand = value; } } #endregion #region [ Methods ] /// <summary> /// Fires when pages initializes. /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { base.OnInit(e); Page.RegisterRequiresControlState(this); _initialized = true; if (_cachedActiveTabIndex > -1) { ActiveTabIndex = _cachedActiveTabIndex; if (ActiveTabIndex < Tabs.Count) { Tabs[ActiveTabIndex].Active = true; } } else if (Tabs.Count > 0) { ActiveTabIndex = 0; } } /// <summary> /// Fires when Active tab changes. /// </summary> /// <param name="e"></param> protected virtual void OnActiveTabChanged(EventArgs e) { EventHandler eh = Events[EventActiveTabChanged] as EventHandler; if (eh != null) { eh(this, e); } } /// <summary> /// AddParseSubObject checks if object is not null and type of TabPanel. /// </summary> /// <param name="obj">Object to add in the container</param> protected override void AddParsedSubObject(object obj) { TabPanel objTabPanel = obj as TabPanel; if (null != objTabPanel) { Controls.Add(objTabPanel); } else if (!(obj is LiteralControl)) { throw new HttpException(string.Format(CultureInfo.CurrentCulture, "TabContainer cannot have children of type '{0}'.", obj.GetType())); } } /// <summary> /// Sets TabContainer as owner of control and Addes the control into the base /// at specified index. /// </summary> /// <param name="control">Object of type TabPanel</param> /// <param name="index">Index where to add the control</param> protected override void AddedControl(Control control, int index) { ((TabPanel)control).SetOwner(this); base.AddedControl(control, index); } /// <summary> /// Removed the TabPanel control from the base. /// </summary> /// <param name="control">Object of type TabPanel</param> protected override void RemovedControl(Control control) { TabPanel controlTabPanel = control as TabPanel; if (control != null && controlTabPanel.Active && ActiveTabIndex < Tabs.Count) { EnsureActiveTab(); } controlTabPanel.SetOwner(null); base.RemovedControl(control); } /// <summary> /// provides collection of TabPanels. /// </summary> /// <returns>ControlCollection</returns> protected override ControlCollection CreateControlCollection() { return new TabPanelCollection(this); } /// <summary> /// Creates the theme/style of TabContainer. /// </summary> /// <returns>object of TabContainerStyle type</returns> protected override Style CreateControlStyle() { TabContainerStyle style = new TabContainerStyle(ViewState); style.CssClass = "ajax__tab_xp"; return style; } /// <summary> /// Returns server side index of current Active Tab. /// </summary> /// <param name="clientActiveTabIndex">Index of current active tab at client side.</param> /// <returns>Index of server side active tab.</returns> private int GetServerActiveTabIndex(int clientActiveTabIndex) { int counter = -1; int result = clientActiveTabIndex; for (int i = 0; i < Tabs.Count; i++) { if (Tabs[i].Visible) counter++; if (counter == clientActiveTabIndex) { result = i; break; } } return result; } /// <summary> /// Loads the client state. /// </summary> /// <param name="clientState">string containing client state values.</param> protected override void LoadClientState(string clientState) { Dictionary<string, object> state = (Dictionary<string, object>)new JavaScriptSerializer().DeserializeObject(clientState); if (state != null) { ActiveTabIndex = (int)state["ActiveTabIndex"]; ActiveTabIndex = GetServerActiveTabIndex(ActiveTabIndex); object[] tabEnabledState = (object[])state["TabEnabledState"]; object[] tabWasLoadedOnceState = (object[])state["TabWasLoadedOnceState"]; for (int i = 0; i < tabEnabledState.Length; i++) { int j = GetServerActiveTabIndex(i); if (j < Tabs.Count) { Tabs[j].Enabled = (bool)tabEnabledState[i]; Tabs[j].WasLoadedOnce = (bool)tabWasLoadedOnceState[i]; } } } } /// <summary> /// Saves the client states values. /// </summary> /// <returns>string containing client state values.</returns> protected override string SaveClientState() { Dictionary<string, object> state = new Dictionary<string, object>(); state["ActiveTabIndex"] = ActiveTabIndex; List<object> tabEnabledState = new List<object>(); List<object> tabWasLoadedOnceState = new List<object>(); foreach (TabPanel tab in Tabs) { tabEnabledState.Add(tab.Enabled); tabWasLoadedOnceState.Add(tab.WasLoadedOnce); } state["TabEnabledState"] = tabEnabledState; state["TabWasLoadedOnceState"] = tabWasLoadedOnceState; return new JavaScriptSerializer().Serialize(state); } /// <summary> /// Loads the savedState of TabContainer. /// </summary> /// <param name="savedState">savedState</param> protected override void LoadControlState(object savedState) { Pair p = (Pair)savedState; if (p != null) { base.LoadControlState(p.First); ActiveTabIndex = (int)p.Second; } else { base.LoadControlState(null); } } /// <summary> /// Saves the controlState to load next postback. /// </summary> /// <returns>object containing savedstate</returns> protected override object SaveControlState() { // Saving last active tab index this.LastActiveTabIndex = this.ActiveTabIndex; Pair p = new Pair(); p.First = base.SaveControlState(); p.Second = ActiveTabIndex; if (p.First == null && p.Second == null) { return null; } else { return p; } } /// <summary> /// Customize functionality to Add attributes at the time of rendering. /// </summary> /// <param name="writer">HtmlTextWriter object</param> protected override void AddAttributesToRender(HtmlTextWriter writer) { Style.Remove(HtmlTextWriterStyle.Visibility); if (!ControlStyleCreated) writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_xp"); if (_useVerticalStripPlacement) writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); if (!Height.IsEmpty && Height.Type == UnitType.Percentage) writer.AddStyleAttribute(HtmlTextWriterStyle.Height, Height.ToString()); base.AddAttributesToRender(writer); writer.AddStyleAttribute(HtmlTextWriterStyle.Visibility, "hidden"); } /// <summary> /// Renders contents to the client. /// </summary> /// <param name="writer">HtmlTextWriter object</param> protected override void RenderContents(HtmlTextWriter writer) { //base.Render(writer); Page.VerifyRenderingInServerForm(this); if (_tabStripPlacement == TabStripPlacement.Top || _tabStripPlacement == TabStripPlacement.TopRight || (_tabStripPlacement == TabStripPlacement.Bottom && _useVerticalStripPlacement) || (_tabStripPlacement == TabStripPlacement.BottomRight && _useVerticalStripPlacement) ) RenderHeader(writer); if (!Height.IsEmpty) writer.AddStyleAttribute(HtmlTextWriterStyle.Height, Height.ToString()); else writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%"); writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_body"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_body" + GetSuffixTabStripPlacementCss()); writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); writer.RenderBeginTag(HtmlTextWriterTag.Div); RenderChildren(writer); writer.RenderEndTag(); if ((_tabStripPlacement == TabStripPlacement.Bottom && !_useVerticalStripPlacement) || _tabStripPlacement == TabStripPlacement.BottomRight && !_useVerticalStripPlacement) RenderHeader(writer); } /// <summary> /// Render header part of the TabContainer. /// </summary> /// <param name="writer">HtmlTextWriter object</param> protected virtual void RenderHeader(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_header"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_header" + GetSuffixTabStripPlacementCss()); if (_tabStripPlacement == TabStripPlacement.BottomRight || _tabStripPlacement == TabStripPlacement.TopRight) writer.AddStyleAttribute(HtmlTextWriterStyle.Direction, "rtl"); if (_useVerticalStripPlacement) { writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); if (_tabStripPlacement == TabStripPlacement.Bottom || _tabStripPlacement == TabStripPlacement.Top) { writer.AddAttribute(HtmlTextWriterAttribute.Style, "float:left"); } else { writer.AddAttribute(HtmlTextWriterAttribute.Style, "float:right"); } writer.AddStyleAttribute(HtmlTextWriterStyle.Width, _verticalStripWidth.ToString()); } writer.RenderBeginTag(HtmlTextWriterTag.Div); if (_tabStripPlacement == TabStripPlacement.Bottom || _tabStripPlacement == TabStripPlacement.BottomRight) RenderSpannerForVerticalTabs(writer); if (!_useVerticalStripPlacement && (_tabStripPlacement == TabStripPlacement.BottomRight || _tabStripPlacement == TabStripPlacement.TopRight)) { // reverse tab order placement var tabs = Tabs.Count; for (int i = tabs - 1; i >= 0; i--) { var panel = Tabs[i]; if (panel.Visible) { panel.RenderHeader(writer); } } } else { foreach (TabPanel panel in Tabs) { if (panel.Visible) { panel.RenderHeader(writer); } } } if (_tabStripPlacement == TabStripPlacement.Top || _tabStripPlacement == TabStripPlacement.TopRight) RenderSpannerForVerticalTabs(writer); writer.RenderEndTag(); } private void RenderSpannerForVerticalTabs(HtmlTextWriter writer) { if (_useVerticalStripPlacement) { writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_headerSpannerHeight"); writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.RenderEndTag(); } } private string GetSuffixTabStripPlacementCss() { var tabStripPlacementCss = ""; if (_useVerticalStripPlacement) { tabStripPlacementCss += "_vertical"; switch (_tabStripPlacement) { case TabStripPlacement.Top: case TabStripPlacement.Bottom: tabStripPlacementCss += "left"; break; case TabStripPlacement.TopRight: case TabStripPlacement.BottomRight: tabStripPlacementCss += "right"; break; } } else { switch (_tabStripPlacement) { case TabStripPlacement.Bottom: case TabStripPlacement.BottomRight: tabStripPlacementCss = "_bottom"; break; } } return tabStripPlacementCss; } /// <summary> /// Loads PostBackData /// </summary> /// <param name="postDataKey">Post Data Key</param> /// <param name="postCollection">Collection of Postback data</param> /// <returns>flag whether data loaded</returns> protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { int tabIndex = ActiveTabIndex; bool result = base.LoadPostData(postDataKey, postCollection); if (ActiveTabIndex == 0 || tabIndex != ActiveTabIndex) { return true; } return result; } /// <summary> /// Raises event for data changed at postback. /// </summary> protected override void RaisePostDataChangedEvent() { // If the tab index changed if (this.LastActiveTabIndex != this.ActiveTabIndex) { // Saving last active tab index this.LastActiveTabIndex = this.ActiveTabIndex; // The event fires only when the new active tab exists and has OnDemandMode = Always or // when OnDemandMode = Once and tab wasn't loaded yet TabPanel activeTab = this.ActiveTab; if (activeTab != null && (activeTab.OnDemandMode == OnDemandMode.Always || activeTab.OnDemandMode == OnDemandMode.Once && !activeTab.WasLoadedOnce)) OnActiveTabChanged(EventArgs.Empty); } } private void EnsureActiveTab() { if (_activeTabIndex < 0 || _activeTabIndex >= Tabs.Count) { _activeTabIndex = 0; } for (int i = 0; i < Tabs.Count; i++) { if (i == ActiveTabIndex) { Tabs[i].Active = true; } else { Tabs[i].Active = false; } } } /// <summary> /// Reset the loaded status of tab panels with once demand mode /// </summary> public void ResetLoadedOnceTabs() { foreach (TabPanel tab in this.Tabs) { if (tab.OnDemandMode == OnDemandMode.Once && tab.WasLoadedOnce) tab.WasLoadedOnce = false; } } #endregion #region [ TabContainerStyle ] private sealed class TabContainerStyle : Style { /// <summary> /// Constructor for TabContainerStyle /// </summary> /// <param name="state"></param> public TabContainerStyle(StateBag state) : base(state) { } /// <summary> /// Fills Style attribute to the base. /// </summary> /// <param name="attributes"></param> /// <param name="urlResolver"></param> protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) { base.FillStyleAttributes(attributes, urlResolver); attributes.Remove(HtmlTextWriterStyle.Height); // commented below line to fix the issue #25821 //attributes.Remove(HtmlTextWriterStyle.BackgroundColor); attributes.Remove(HtmlTextWriterStyle.BackgroundImage); } } #endregion #region IPostBackEventHandler Members [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Called by ASP.NET infrastructure")] void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { if (eventArgument.StartsWith("activeTabChanged", StringComparison.Ordinal)) { // change the active tab. // int parseIndex = eventArgument.IndexOf(":", StringComparison.Ordinal); Debug.Assert(parseIndex != -1, "Expected new active tab index!"); if (parseIndex != -1 && Int32.TryParse(eventArgument.Substring(parseIndex + 1), out parseIndex)) { parseIndex = GetServerActiveTabIndex(parseIndex); if (parseIndex != ActiveTabIndex) { ActiveTabIndex = parseIndex; OnActiveTabChanged(EventArgs.Empty); } } } } #endregion protected override void DescribeComponent(ScriptComponentDescriptor descriptor) { base.DescribeComponent(descriptor); descriptor.AddProperty("tabStripPlacement", this.TabStripPlacement); descriptor.AddProperty("useVerticalStripPlacement", this.UseVerticalStripPlacement); descriptor.AddProperty("onDemand", this.OnDemand); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; #if SILVERLIGHT #endif using System.Threading; using ServiceStack.Common.Support; namespace ServiceStack.Text { /// <summary> /// Utils to load types /// </summary> public static class AssemblyUtils { private const string FileUri = "file:///"; private const string DllExt = "dll"; private const string ExeExt = "dll"; private const char UriSeperator = '/'; private static Dictionary<string, Type> TypeCache = new Dictionary<string, Type>(); #if !XBOX /// <summary> /// Find the type from the name supplied /// </summary> /// <param name="typeName">[typeName] or [typeName, assemblyName]</param> /// <returns></returns> public static Type FindType(string typeName) { Type type = null; if (TypeCache.TryGetValue(typeName, out type)) return type; #if !SILVERLIGHT type = Type.GetType(typeName); #endif if (type == null) { var typeDef = new AssemblyTypeDefinition(typeName); type = !string.IsNullOrEmpty(typeDef.AssemblyName) ? FindType(typeDef.TypeName, typeDef.AssemblyName) : FindTypeFromLoadedAssemblies(typeDef.TypeName); } Dictionary<string, Type> snapshot, newCache; do { snapshot = TypeCache; newCache = new Dictionary<string, Type>(TypeCache); newCache[typeName] = type; } while (!ReferenceEquals( Interlocked.CompareExchange(ref TypeCache, newCache, snapshot), snapshot)); return type; } #endif #if !XBOX /// <summary> /// The top-most interface of the given type, if any. /// </summary> public static Type MainInterface<T>() { var t = typeof(T); #if NETFX_CORE if (t.GetTypeInfo().BaseType == typeof(object)) { // on Windows, this can be just "t.GetInterfaces()" but Mono doesn't return in order. var interfaceType = t.GetTypeInfo().ImplementedInterfaces.FirstOrDefault(i => !t.GetTypeInfo().ImplementedInterfaces.Any(i2 => i2.GetTypeInfo().ImplementedInterfaces.Contains(i))); if (interfaceType != null) return interfaceType; } #else if (t.BaseType == typeof(object)) { // on Windows, this can be just "t.GetInterfaces()" but Mono doesn't return in order. var interfaceType = t.GetInterfaces().FirstOrDefault(i => !t.GetInterfaces().Any(i2 => i2.GetInterfaces().Contains(i))); if (interfaceType != null) return interfaceType; } #endif return t; // not safe to use interface, as it might be a superclass's one. } /// <summary> /// Find type if it exists /// </summary> /// <param name="typeName"></param> /// <param name="assemblyName"></param> /// <returns>The type if it exists</returns> public static Type FindType(string typeName, string assemblyName) { var type = FindTypeFromLoadedAssemblies(typeName); if (type != null) { return type; } #if !NETFX_CORE var binPath = GetAssemblyBinPath(Assembly.GetExecutingAssembly()); Assembly assembly = null; var assemblyDllPath = binPath + String.Format("{0}.{1}", assemblyName, DllExt); if (File.Exists(assemblyDllPath)) { assembly = LoadAssembly(assemblyDllPath); } var assemblyExePath = binPath + String.Format("{0}.{1}", assemblyName, ExeExt); if (File.Exists(assemblyExePath)) { assembly = LoadAssembly(assemblyExePath); } return assembly != null ? assembly.GetType(typeName) : null; #else return null; #endif } #endif #if NETFX_CORE private sealed class AppDomain { public static AppDomain CurrentDomain { get; private set; } public static Assembly[] cacheObj = null; static AppDomain() { CurrentDomain = new AppDomain(); } public Assembly[] GetAssemblies() { return cacheObj ?? GetAssemblyListAsync().Result.ToArray(); } private async System.Threading.Tasks.Task<IEnumerable<Assembly>> GetAssemblyListAsync() { var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; List<Assembly> assemblies = new List<Assembly>(); foreach (Windows.Storage.StorageFile file in await folder.GetFilesAsync()) { if (file.FileType == ".dll" || file.FileType == ".exe") { try { var filename = file.Name.Substring(0, file.Name.Length - file.FileType.Length); AssemblyName name = new AssemblyName() { Name = filename }; Assembly asm = Assembly.Load(name); assemblies.Add(asm); } catch (Exception) { // Invalid WinRT assembly! } } } cacheObj = assemblies.ToArray(); return cacheObj; } } #endif #if !XBOX public static Type FindTypeFromLoadedAssemblies(string typeName) { #if SILVERLIGHT4 var assemblies = ((dynamic) AppDomain.CurrentDomain).GetAssemblies() as Assembly[]; #else var assemblies = AppDomain.CurrentDomain.GetAssemblies(); #endif foreach (var assembly in assemblies) { var type = assembly.GetType(typeName); if (type != null) { return type; } } return null; } #endif #if !SILVERLIGHT private static Assembly LoadAssembly(string assemblyPath) { return Assembly.LoadFrom(assemblyPath); } #elif NETFX_CORE private static Assembly LoadAssembly(string assemblyPath) { return Assembly.Load(new AssemblyName(assemblyPath)); } #elif WINDOWS_PHONE private static Assembly LoadAssembly(string assemblyPath) { return Assembly.LoadFrom(assemblyPath); } #else private static Assembly LoadAssembly(string assemblyPath) { var sri = System.Windows.Application.GetResourceStream(new Uri(assemblyPath, UriKind.Relative)); var myPart = new System.Windows.AssemblyPart(); var assembly = myPart.Load(sri.Stream); return assembly; } #endif #if !XBOX public static string GetAssemblyBinPath(Assembly assembly) { #if WINDOWS_PHONE var codeBase = assembly.GetName().CodeBase; #elif NETFX_CORE var codeBase = assembly.GetName().FullName; #else var codeBase = assembly.CodeBase; #endif var binPathPos = codeBase.LastIndexOf(UriSeperator); var assemblyPath = codeBase.Substring(0, binPathPos + 1); if (assemblyPath.StartsWith(FileUri, StringComparison.OrdinalIgnoreCase)) { assemblyPath = assemblyPath.Remove(0, FileUri.Length); } return assemblyPath; } #endif #if !SILVERLIGHT static readonly Regex versionRegEx = new Regex(", Version=[^\\]]+", RegexOptions.Compiled); #else static readonly Regex versionRegEx = new Regex(", Version=[^\\]]+"); #endif public static string ToTypeString(this Type type) { return versionRegEx.Replace(type.AssemblyQualifiedName, ""); } public static string WriteType(Type type) { return type.ToTypeString(); } } }
/**************************************************************************** * Class Name : ErrorWarnInfoProvider.cs * Author : Kenneth J. Koteles * Created : 10/04/2007 2:14 PM * C# Version : .NET 2.0 * Description : This code is designed to create a new provider object to * work specifically with CSLA BusinessBase objects. In * addition to providing the red error icon for items in the * BrokenRulesCollection with Csla.Rules.RuleSeverity.Error, * this object also provides a yellow warning icon for items * with Csla.Rules.RuleSeverity.Warning and a blue * information icon for items with * Csla.Rules.RuleSeverity.Information. Since warnings * and information type items do not need to be fixed / * corrected prior to the object being saved, the tooltip * displayed when hovering over the respective icon contains * all the control's associated (by severity) broken rules. * Revised : 11/20/2007 8:32 AM * Change : Warning and information icons were not being updated for * dependant properties (controls without the focus) when * changes were being made to a related property (control with * the focus). Added a list of controls to be recursed * through each time a change was made to any control. This * obviously could result in performance issues; however, * there is no consistent way to question the BusinessObject * in order to get a list of dependant properties based on a * property name. It can be exposed to the UI (using * ValidationRules.GetRuleDescriptions()); however, it is up * to each developer to implement their own public method on * on the Business Object to do so. To make this generic for * all CSLA Business Objects, I cannot assume the developer * always exposes the dependant properties (nor do I know what * they'll call the method); therefore, this is the best I can * do right now. * Revised : 11/23/2007 9:02 AM * Change : Added new property ProcessDependantProperties to allow for * controlling when all controls are recursed through (for * dependant properties or not). Default value is 'false'. * This allows the developer to ba able to choose whether or * not to use the control in this manner (which could have * performance implications). * Revised : 10/05/2009, Jonny Bekkum * Change: Added initialization of controls list (controls attached to BindingSource) * and will update errors on all controls. Optimized retrieval of error, warn, info * messages and setting these on the controls. ****************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Text; using System.Windows.Forms; namespace CslaContrib.Windows { [DesignerCategory("")] [ToolboxItem(true), ToolboxBitmap(typeof(ErrorWarnInfoProvider), "Cascade.ico")] public class ErrorWarnInfoProvider : ErrorProvider, IExtenderProvider, ISupportInitialize { #region internal variables private readonly System.ComponentModel.IContainer components = null; private readonly System.Windows.Forms.ErrorProvider _errorProviderInfo; private readonly System.Windows.Forms.ErrorProvider _errorProviderWarn; private readonly List<Control> _controls = new List<Control>(); private static readonly Icon DefaultIconInformation; private static readonly Icon DefaultIconWarning; private int _offsetInformation = 32; private int _offsetWarning = 16; private bool _showInformation = true; private bool _showWarning = true; private bool _showMostSevereOnly = true; private readonly Dictionary<string, string> _errorList = new Dictionary<string, string>(); private readonly Dictionary<string, string> _warningList = new Dictionary<string, string>(); private readonly Dictionary<string, string> _infoList = new Dictionary<string, string>(); private bool _isInitializing = false; #endregion #region Constructors static ErrorWarnInfoProvider() { DefaultIconInformation = CslaContrib.Windows.Properties.Resources.InformationIco16; DefaultIconWarning = CslaContrib.Windows.Properties.Resources.WarningIco16; } public ErrorWarnInfoProvider() { this.components = new System.ComponentModel.Container(); this._errorProviderInfo = new System.Windows.Forms.ErrorProvider(this.components); this._errorProviderWarn = new System.Windows.Forms.ErrorProvider(this.components); BlinkRate = 0; _errorProviderInfo.BlinkRate = 0; _errorProviderInfo.Icon = DefaultIconInformation; _errorProviderWarn.BlinkRate = 0; _errorProviderWarn.Icon = DefaultIconWarning; } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="container">The container of the control.</param> public ErrorWarnInfoProvider(IContainer container) : this() { container.Add(this); } protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #endregion #region IExtenderProvider Members /// <summary> /// Gets a value indicating whether the extender control /// can extend the specified control. /// </summary> /// <param name="extendee">The control to be extended.</param> /// <remarks> /// Any control implementing either a ReadOnly property or /// Enabled property can be extended. /// </remarks> bool IExtenderProvider.CanExtend(object extendee) { //if (extendee is ErrorProvider) //{ // return true; //} if ((extendee is Control && !(extendee is Form))) { return !(extendee is ToolBar); } else { return false; } } #endregion #region Public properties /// <summary> /// Gets or sets the blink rate information. /// </summary> /// <value>The blink rate information.</value> [Category("Behavior")] [DefaultValue(0)] [Description("The rate in milliseconds at which the error icon blinks.")] public new int BlinkRate { get { return base.BlinkRate; } set { if (value < 0) { throw new ArgumentOutOfRangeException("BlinkRate", value, "Blink rate must be zero or more"); } base.BlinkRate = value; if (value == 0) { BlinkStyle = ErrorBlinkStyle.NeverBlink; } } } [Category("Behavior")] [DefaultValue(0)] [Description("The rate in milliseconds at which the information icon blinks.")] public int BlinkRateInformation { get { return _errorProviderInfo.BlinkRate; } set { if (value < 0) throw new ArgumentOutOfRangeException("BlinkRateInformation", value, "Blink rate must be zero or more"); _errorProviderInfo.BlinkRate = value; if (value == 0) _errorProviderInfo.BlinkStyle = ErrorBlinkStyle.NeverBlink; } } [Category("Behavior")] [DefaultValue(0)] [Description("The rate in milliseconds at which the warning icon blinks.")] public int BlinkRateWarning { get { return _errorProviderWarn.BlinkRate; } set { if (value < 0) throw new ArgumentOutOfRangeException("BlinkRateWarning", value, "Blink rate must be zero or more"); _errorProviderWarn.BlinkRate = value; if (value == 0) _errorProviderWarn.BlinkStyle = ErrorBlinkStyle.NeverBlink; } } [Category("Behavior")] [DefaultValue(ErrorBlinkStyle.NeverBlink)] [Description("Controls whether the error icon blinks when an error is set.")] public new ErrorBlinkStyle BlinkStyle { get { return base.BlinkStyle; } set { base.BlinkStyle = value; } } [Category("Behavior")] [DefaultValue(ErrorBlinkStyle.NeverBlink)] [Description("Controls whether the information icon blinks when information is set.")] public ErrorBlinkStyle BlinkStyleInformation { get { return _errorProviderInfo.BlinkStyle; } set { _errorProviderWarn.BlinkStyle = value; } } [Category("Behavior")] [DefaultValue(ErrorBlinkStyle.NeverBlink)] [Description("Controls whether the warning icon blinks when a warning is set.")] public ErrorBlinkStyle BlinkStyleWarning { get { return _errorProviderWarn.BlinkStyle; } set { _errorProviderWarn.BlinkStyle = value; } } /// <summary> /// Gets or sets the data source that the <see cref="T:System.Windows.Forms.ErrorProvider"></see> monitors. /// </summary> /// <value></value> /// <returns>A data source based on the <see cref="T:System.Collections.IList"></see> interface to be monitored for errors. Typically, this is a <see cref="T:System.Data.DataSet"></see> to be monitored for errors.</returns> /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> [DefaultValue((string)null)] public new object DataSource { get { return base.DataSource; } set { if (base.DataSource != value) { var bs1 = base.DataSource as BindingSource; if (bs1 != null) { bs1.CurrentItemChanged -= DataSource_CurrentItemChanged; } } base.DataSource = value; var bs = value as BindingSource; if (bs != null) { bs.CurrentItemChanged += DataSource_CurrentItemChanged; } } } private void UpdateBindingsAndProcessAllControls() { if (ContainerControl != null) { InitializeAllControls(ContainerControl.Controls); } ProcessAllControls(); } /// <summary> /// Gets or sets the icon information. /// </summary> /// <value>The icon information.</value> [Category("Behavior")] [Description("The icon used to indicate information.")] public Icon IconInformation { get { return _errorProviderInfo.Icon; } set { if (value == null) value = DefaultIconInformation; _errorProviderInfo.Icon = value; } } /// <summary> /// Gets or sets the icon warning. /// </summary> /// <value>The icon warning.</value> [Category("Behavior")] [Description("The icon used to indicate a warning.")] public Icon IconWarning { get { return _errorProviderWarn.Icon; } set { if (value == null) value = DefaultIconWarning; _errorProviderWarn.Icon = value; } } /// <summary> /// Gets or sets the offset information. /// </summary> /// <value>The offset information.</value> [Category("Behavior")] [DefaultValue(32), Description("The number of pixels the information icon will be offset from the error icon.")] public int OffsetInformation { get { return _offsetInformation; } set { _offsetInformation = value; } } /// <summary> /// Gets or sets the offset warning. /// </summary> /// <value>The offset warning.</value> [Category("Behavior")] [DefaultValue(16), Description("The number of pixels the warning icon will be offset from the error icon.")] public int OffsetWarning { get { return _offsetWarning; } set { _offsetWarning = value; } } /// <summary> /// Gets or sets a value indicating whether broken rules with severity Infomation should be visible. /// </summary> /// <value><c>true</c> if Infomation is visible; otherwise, <c>false</c>.</value> [Category("Behavior")] [DefaultValue(true), Description("Determines if the information icon should be displayed when information exists.")] public bool ShowInformation { get { return _showInformation; } set { _showInformation = value; } } /// <summary> /// Gets or sets a value indicating whether broken rules with severity Warning should be visible. /// </summary> /// <value><c>true</c> if Warning is visible; otherwise, <c>false</c>.</value> [Category("Behavior")] [DefaultValue(true), Description("Determines if the warning icon should be displayed when warnings exist.")] public bool ShowWarning { get { return _showWarning; } set { _showWarning = value; } } /// <summary> /// Gets or sets a value indicating whether show only most severe broken rules message. /// </summary> /// <value><c>true</c> if show only most severe; otherwise, <c>false</c>.</value> [Category("Behavior")] [DefaultValue(true), Description("Determines if the broken rules are show by severity - if true only most severe level is shown.")] public bool ShowOnlyMostSevere { get { return _showMostSevereOnly; } set { if (_showMostSevereOnly != value) { _showMostSevereOnly = value; //Refresh controls ProcessAllControls(); } } } #endregion #region Methods /// <summary> /// Clears all errors associated with this component. /// </summary> /// <PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> public new void Clear() { base.Clear(); _errorProviderInfo.Clear(); _errorProviderWarn.Clear(); } /// <summary> /// Gets the information. /// </summary> /// <param name="control">The control.</param> /// <returns></returns> public string GetInformation(Control control) { return _errorProviderInfo.GetError(control); } /// <summary> /// Gets the warning. /// </summary> /// <param name="control">The control.</param> /// <returns></returns> public string GetWarning(Control control) { return _errorProviderWarn.GetError(control); } private void InitializeAllControls(Control.ControlCollection controls) { // clear internal _controls.Clear(); // run recursive initialize of controls Initialize(controls); } private void Initialize(Control.ControlCollection controls) { //We don't provide an extended property, so if the control is // not a Label then 'hook' the validating event here! foreach (Control control in controls) { if (control is Label) continue; // Initialize bindings foreach (Binding binding in control.DataBindings) { // get the Binding if appropriate if (binding.DataSource == DataSource) { _controls.Add(control); } } // Initialize any subcontrols if (control.Controls.Count > 0) { Initialize(control.Controls); } } } void DataSource_CurrentItemChanged(object sender, EventArgs e) { Debug.Print("ErrorWarnInfo: CurrentItemChanged, {0}", DateTime.Now.Ticks); ProcessAllControls(); } private void ProcessAllControls() { if (_isInitializing) return; // get error/warn/info list from bussiness object GetWarnInfoList(); // process controls in window ProcessControls(); } private void GetWarnInfoList() { _infoList.Clear(); _warningList.Clear(); _errorList.Clear(); BindingSource bs = (BindingSource)DataSource; if (bs == null) return; if (bs.Position == -1) return; // we can only deal with CSLA BusinessBase objects if (bs.Current is Csla.Core.BusinessBase) { // get the BusinessBase object Csla.Core.BusinessBase bb = bs.Current as Csla.Core.BusinessBase; if (bb != null) { foreach (Csla.Rules.BrokenRule br in bb.BrokenRulesCollection) { // we do not want to import result of object level broken rules if (br.Property == null) continue; switch (br.Severity) { case Csla.Rules.RuleSeverity.Error: if (_errorList.ContainsKey(br.Property)) { _errorList[br.Property] = String.Concat(_errorList[br.Property], Environment.NewLine, br.Description); } else { _errorList.Add(br.Property, br.Description); } break; case Csla.Rules.RuleSeverity.Warning: if (_warningList.ContainsKey(br.Property)) { _warningList[br.Property] = String.Concat(_warningList[br.Property], Environment.NewLine, br.Description); } else { _warningList.Add(br.Property, br.Description); } break; default: // consider it an Info if (_infoList.ContainsKey(br.Property)) { _infoList[br.Property] = String.Concat(_infoList[br.Property], Environment.NewLine, br.Description); } else { _infoList.Add(br.Property, br.Description); } break; } } } } } private void ProcessControls() { foreach (Control control in _controls) { ProcessControl(control); } } /// <summary> /// Processes the control. /// </summary> /// <param name="control">The control.</param> private void ProcessControl(Control control) { if (control == null) throw new ArgumentNullException("control"); bool hasWarning = false; bool hasInfo = false; var sbError = new StringBuilder(); var sbWarn = new StringBuilder(); var sbInfo = new StringBuilder(); foreach (Binding binding in control.DataBindings) { // get the Binding if appropriate if (binding.DataSource == DataSource) { string propertyName = binding.BindingMemberInfo.BindingField; if (_errorList.ContainsKey(propertyName)) sbError.AppendLine(_errorList[propertyName]); if (_warningList.ContainsKey(propertyName)) sbWarn.AppendLine(_warningList[propertyName]); if (_infoList.ContainsKey(propertyName)) sbInfo.AppendLine(propertyName); } } bool bError = sbError.Length > 0; bool bWarn = sbWarn.Length > 0; bool bInfo = sbInfo.Length > 0; // set flags to indicat if Warning or Info is highest severity; else false if (_showMostSevereOnly) { bInfo = bInfo && !bWarn && !bError; bWarn = bWarn && !bError; } int offsetInformation = _offsetInformation; int offsetWarning = _offsetWarning; // Set / fix offsets // by default the setting are correct for Error (0), Warning and Info if (!bError) { if (bWarn) { // warning and possibly info, no error offsetInformation = _offsetInformation - _offsetWarning; offsetWarning = 0; } else { // Info only offsetInformation = 0; } } else if (!bWarn) { offsetInformation = _offsetInformation - _offsetWarning; } // should warning be visible if (_showWarning && bWarn) { _errorProviderWarn.SetError(control, sbWarn.ToString()); _errorProviderWarn.SetIconPadding(control, base.GetIconPadding(control) + offsetWarning); _errorProviderWarn.SetIconAlignment(control, base.GetIconAlignment(control)); hasWarning = true; } // should info be shown if (_showInformation && bInfo) { _errorProviderInfo.SetError(control, sbInfo.ToString()); _errorProviderInfo.SetIconPadding(control, base.GetIconPadding(control) + offsetInformation); _errorProviderInfo.SetIconAlignment(control, base.GetIconAlignment(control)); hasInfo = true; } if (!hasWarning) _errorProviderWarn.SetError((Control)control, string.Empty); if (!hasInfo) _errorProviderInfo.SetError((Control)control, string.Empty); } private void ResetBlinkStyleInformation() { BlinkStyleInformation = ErrorBlinkStyle.BlinkIfDifferentError; } private void ResetBlinkStyleWarning() { BlinkStyleWarning = ErrorBlinkStyle.BlinkIfDifferentError; } private void ResetIconInformation() { IconInformation = DefaultIconInformation; } private void ResetIconWarning() { IconWarning = DefaultIconWarning; } /// <summary> /// Sets the information. /// </summary> /// <param name="control">The control.</param> /// <param name="value">The value.</param> public void SetInformation(Control control, string value) { _errorProviderInfo.SetError(control, value); } /// <summary> /// Sets the warning. /// </summary> /// <param name="control">The control.</param> /// <param name="value">The value.</param> public void SetWarning(Control control, string value) { _errorProviderWarn.SetError(control, value); } private bool ShouldSerializeIconInformation() { return (IconInformation != DefaultIconInformation); } private bool ShouldSerializeIconWarning() { return (IconWarning != DefaultIconWarning); } private bool ShouldSerializeBlinkStyleInformation() { return (BlinkStyleInformation != ErrorBlinkStyle.BlinkIfDifferentError); } private bool ShouldSerializeBlinkStyleWarning() { return (BlinkStyleWarning != ErrorBlinkStyle.BlinkIfDifferentError); } /// <summary> /// Provides a method to update the bindings of the <see cref="P:System.Windows.Forms.ErrorProvider.DataSource"></see>, <see cref="P:System.Windows.Forms.ErrorProvider.DataMember"></see>, and the error text. /// </summary> /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> public new void UpdateBinding() { base.UpdateBinding(); _errorProviderInfo.UpdateBinding(); _errorProviderWarn.UpdateBinding(); } #endregion #region ISupportInitialize Members void ISupportInitialize.BeginInit() { _isInitializing = true; } void ISupportInitialize.EndInit() { _isInitializing = false; if (this.ContainerControl != null) { InitializeAllControls(this.ContainerControl.Controls); } } #endregion } }
/* * PROPRIETARY INFORMATION. This software is proprietary to * Side Effects Software Inc., and is not to be reproduced, * transmitted, or disclosed in any way without written permission. * * Produced by: * Side Effects Software Inc * 123 Front Street West, Suite 1401 * Toronto, Ontario * Canada M5J 2M2 * 416-504-9876 * * COMMENTS: * */ // Master control for enabling runtime. #if ( UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX || ( UNITY_METRO && UNITY_EDITOR ) ) #define HAPI_ENABLE_RUNTIME #endif using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Reflection; [ CustomEditor( typeof( HoudiniAsset ) ) ] public class HoudiniAssetGUI : Editor { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Public public virtual void OnEnable() { myAsset = target as HoudiniAsset; myUndoInfo = myAsset.prAssetUndoInfo; myParmChanges = true; myUnbuiltChanges = false; myFocusChanged = true; myHelpScrollPosition = new Vector2( 0.0f, 0.0f ); HoudiniHost.myRepaintDelegate += this.refresh; HoudiniHost.myDeselectionDelegate += this.deselect; HoudiniHost.mySelectionTarget = myAsset.gameObject; } public virtual void OnDisable() { HoudiniHost.myRepaintDelegate -= this.refresh; HoudiniHost.myDeselectionDelegate -= this.deselect; HoudiniHost.mySelectionTarget = null; } public virtual void refresh() { Repaint(); SceneView.lastActiveSceneView.Repaint(); } public virtual void deselect() { if ( HoudiniHost.mySelectionTarget == myAsset.gameObject ) HoudiniHost.mySelectionTarget = null; } public override void OnInspectorGUI() { bool gui_enable = GUI.enabled; // We can only build or do anything if we can link to our libraries. #if !( HAPI_ENABLE_RUNTIME ) HoudiniGUI.help( HoudiniConstants.HAPI_UNSUPPORTED_PLATFORM_MSG, MessageType.Info ); GUI.enabled = false; #else if ( !HoudiniHost.isInstallationOk() ) { HoudiniGUI.help( HoudiniHost.getMissingEngineInstallHelpString(), MessageType.Info ); GUI.enabled = false; } #endif // !( HAPI_ENABLE_RUNTIME ) try { myDelayBuild = false; myParmChanges = false; /////////////////////////////////////////////////////////////////////// // Draw License/Logo Thingy #if ( HAPI_ENABLE_RUNTIME ) drawLicenseLogo(); #endif /////////////////////////////////////////////////////////////////////// // Draw Game Object Controls if ( HoudiniHost.isAssetValid( myAsset.prAssetId, myAsset.prAssetValidationId ) && ( myAsset.prTransformInputCount > 0 || myAsset.prGeoInputCount > 0 ) && myAsset.prAssetSubType != HAPI_AssetSubType.HAPI_ASSETSUBTYPE_CURVE ) { myAsset.prShowInputControls = HoudiniGUI.foldout( "Inputs", myAsset.prShowInputControls, true ); if ( myAsset.prShowInputControls ) { if ( myAsset.prHAPIAssetType == HAPI_AssetType.HAPI_ASSETTYPE_OBJ ) for ( int ii = 0; ii < myAsset.prTransformInputCount; ++ii ) myParmChanges |= setTransformInput( ii ); if ( myAsset.prUpStreamGeoObjects == null || myAsset.prUpStreamGeoAssets == null || myAsset.prUpStreamGeoObjects.Count <= 0 || myAsset.prUpStreamGeoAssets.Count <= 0 ) return; for ( int input_index = 0; input_index < myAsset.prGeoInputCount; ++input_index ) { bool join_last = false; bool no_label_toggle_last = true; HoudiniGUIParm geo_input = new HoudiniGUIParm( "geo_input_" + input_index, myAsset.prGeoInputNames[ input_index ] ); Object obj = (Object) myAsset.prUpStreamGeoObjects[ input_index ]; myParmChanges |= HoudiniGUI.objectField( ref geo_input, ref obj, typeof( GameObject ), ref join_last, ref no_label_toggle_last ); if ( myParmChanges || !myAsset.isGeoInputValid( input_index ) ) { if ( !obj ) { myAsset.removeGeoInput( input_index ); myAsset.buildClientSide(); } else { GameObject new_obj = (GameObject) obj; myAsset.prUpStreamGeoObjects[ input_index ] = new_obj; // Select the asset component (if it exists). HoudiniAsset asset = new_obj.GetComponent< HoudiniAsset >(); // If we're selecting a specific object to input than try and // get the object id. Note that by getting the HAPI_ObjectControl // component we also cover the geo and part controls because // they all inherit from HAPI_ObjectControl. The user can therefore // drag any gameObject under the asset into another asset's // input and have it all work. int object_index = 0; HoudiniObjectControl obj_control = new_obj.GetComponent< HoudiniObjectControl >(); if ( obj_control ) { object_index = obj_control.prObjectId; asset = obj_control.prAsset; } if ( asset == null ) { myAsset.addGeoAsGeoInput( new_obj, input_index ); myAsset.buildClientSide(); } else if ( myAsset.prUpStreamGeoAssets[ input_index ] != asset ) { if ( myAsset == asset ) Debug.LogError( "Can't connect an asset to itself!" ); else { myAsset.addAssetAsGeoInput( asset, object_index, input_index ); myAsset.buildClientSide(); } } } } } // for } // if } // if // Draw Cook Log Pane myAsset.prShowCookLog = HoudiniGUI.foldout( "Asset Cook Log", myAsset.prShowCookLog, true ); if ( myAsset.prShowCookLog ) drawCookLog(); } catch ( HoudiniError e ) { Debug.LogError( e.ToString() ); } GUI.enabled = gui_enable; } public virtual void OnSceneGUI() { } protected bool setTransformInput( int index ) { if ( myAsset.prUpStreamTransformObjects == null || myAsset.prUpStreamTransformObjects.Count <= 0 ) return false; bool join_last = false; bool no_label_toggle_last = true; HoudiniGUIParm trans_input = new HoudiniGUIParm( "trans_input_" + index, myAsset.prTransInputNames[ index ] ); Object obj = (Object) myAsset.prUpStreamTransformObjects[ index ]; bool changed = HoudiniGUI.objectField( ref trans_input, ref obj, typeof( GameObject ), ref join_last, ref no_label_toggle_last ); if ( changed ) { if ( !obj ) { myAsset.prUpStreamTransformObjects[ index ] = null; myAsset.removeTransformInput( index ); } else { GameObject game_obj = (GameObject) obj; myAsset.prUpStreamTransformObjects[ index ] = game_obj; HoudiniAsset input_asset = game_obj.GetComponent< HoudiniAsset >(); if ( input_asset ) myAsset.addAssetAsTransformInput( input_asset, index ); else myAsset.removeTransformInput( index ); myAsset.buildClientSide(); } } return changed; } protected void drawLicenseLogo() { if ( HoudiniHost.getCurrentLicense() != HAPI_License.HAPI_LICENSE_HOUDINI_ENGINE_INDIE ) return; HoudiniGUI.separator(); int skin = EditorPrefs.GetInt( "UserSkin" ); bool is_light_skin = skin == 0; #if false if ( myDarkSkinLogo == null && is_dark_skin ) myDarkSkinLogo = Resources.Load< Texture2D >( "hEngine_white_color" ); if ( myLightSkinLogo == null && is_light_skin ) myLightSkinLogo = Resources.Load< Texture2D >( "hEngine_black_color" ); Texture2D logo = ( is_light_skin ? myLightSkinLogo : myDarkSkinLogo ); float pane_width = (float) Screen.width - 60; float ratio = Mathf.Min( 0.2f, pane_width / logo.width ); GUIStyle image_style = new GUIStyle( GUI.skin.label ); image_style.normal.background = logo; image_style.imagePosition = ImagePosition.ImageAbove; EditorGUILayout.LabelField( "", image_style, GUILayout.Height( logo.height * ratio ), GUILayout.Width( logo.width * ratio ) ); #endif GUIStyle label_style = new GUIStyle( GUI.skin.label ); label_style.fontStyle = FontStyle.Bold; label_style.normal.textColor = is_light_skin ? Color.red : Color.yellow; EditorGUILayout.LabelField( "Houdini Engine Indie - For Limited Commercial Use Only", label_style ); HoudiniGUI.separator(); } protected void drawHelpBox( string text ) { float width = (float) Screen.width - 60; myHelpScrollPosition = EditorGUILayout.BeginScrollView( myHelpScrollPosition, GUILayout.Height( 200 ) ); GUIStyle sel_label = new GUIStyle( GUI.skin.label ); sel_label.stretchWidth = true; sel_label.wordWrap = true; float height = sel_label.CalcHeight( new GUIContent( text ), width ); EditorGUILayout.SelectableLabel( text, sel_label, GUILayout.Width( width ), GUILayout.Height( height ) ); EditorGUILayout.EndScrollView(); } protected void drawCookLog() { if ( HoudiniGUI.button( "get_cook_log", "Get Cook Log" ) ) { myAsset.buildClientSide(); myLastCookLog = HoudiniHost.getStatusString( HAPI_StatusType.HAPI_STATUS_COOK_RESULT, HAPI_StatusVerbosity.HAPI_STATUSVERBOSITY_MESSAGES ); } float width = (float) Screen.width - 60; myCookLogScrollPosition = EditorGUILayout.BeginScrollView( myCookLogScrollPosition, GUILayout.Height( 200 ) ); GUIStyle sel_label = new GUIStyle( GUI.skin.label ); sel_label.stretchWidth = true; sel_label.wordWrap = true; float height = sel_label.CalcHeight( new GUIContent( myLastCookLog ), width ); EditorGUILayout.SelectableLabel( myLastCookLog, sel_label, GUILayout.Width( width ), GUILayout.Height( height ) ); EditorGUILayout.EndScrollView(); } protected delegate void valueChangedFunc(); protected void createToggleForProperty( string name, string label, string property_name, ref bool undo_info_value, valueChangedFunc func ) { createToggleForProperty( name, label, property_name, ref undo_info_value, func, false ); } protected void createToggleForProperty( string name, string label, string property_name, ref bool undo_info_value, valueChangedFunc func, bool global_overwrite ) { createToggleForProperty( name, label, property_name, ref undo_info_value, func, global_overwrite, false, "" ); } protected void createToggleForProperty( string name, string label, string property_name, ref bool undo_info_value, valueChangedFunc func, bool global_overwrite, bool local_overwrite, string local_overwrite_message ) { bool gui_enabled = GUI.enabled; try { PropertyInfo property = typeof( HoudiniAsset ).GetProperty( property_name ); if ( property == null ) throw new HoudiniErrorInvalidArgument( property_name + " is not a valid property of HAPI_Asset!" ); if ( property.PropertyType != typeof( bool ) ) throw new HoudiniErrorInvalidArgument( property_name + " is not a boolean!" ); GUI.enabled = !global_overwrite && !local_overwrite && GUI.enabled; if ( global_overwrite ) label += " (overwritted by global setting)"; else if ( local_overwrite ) label += local_overwrite_message; bool value = ( bool ) property.GetValue( myAsset, null ); bool changed = HoudiniGUI.toggle( name, label, false, ref value, myUndoInfo, ref undo_info_value ); if ( changed ) { property.SetValue( myAsset, value, null ); if ( func != null ) func(); } } catch ( System.Exception error ) { Debug.LogError( "Failed to create toggle for: " + label + "\n" + error.ToString() + "\nSource: " + error.Source ); } GUI.enabled = gui_enabled; } protected HoudiniAsset myAsset; protected bool myDelayBuild; protected bool myParmChanges; protected bool myUnbuiltChanges; protected bool myFocusChanged; protected Vector2 myCookLogScrollPosition = new Vector2( 0.0f, 0.0f ); protected string myLastCookLog = ""; protected Vector2 myHelpScrollPosition = new Vector2( 0.0f, 0.0f ); protected HoudiniAssetUndoInfo myUndoInfo; protected HoudiniAsset myParentPrefabAsset; private const int myInputFormatDropdownWidth = 62; #if false private static Texture2D myLightSkinLogo = null; private static Texture2D myDarkSkinLogo = null; #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Linq.Expressions.Compiler { internal static class ILGen { internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase) { Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo); var ctor = methodBase as ConstructorInfo; if ((object)ctor != null) { il.Emit(opcode, ctor); } else { il.Emit(opcode, (MethodInfo)methodBase); } } #region Instruction helpers internal static void EmitLoadArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); switch (index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (index <= byte.MaxValue) { il.Emit(OpCodes.Ldarg_S, (byte)index); } else { il.Emit(OpCodes.Ldarg, index); } break; } } internal static void EmitLoadArgAddress(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= byte.MaxValue) { il.Emit(OpCodes.Ldarga_S, (byte)index); } else { il.Emit(OpCodes.Ldarga, index); } } internal static void EmitStoreArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= byte.MaxValue) { il.Emit(OpCodes.Starg_S, (byte)index); } else { il.Emit(OpCodes.Starg, index); } } /// <summary> /// Emits a Ldind* instruction for the appropriate type /// </summary> internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) { Debug.Assert(type != null); switch (type.GetTypeCode()) { case TypeCode.Byte: il.Emit(OpCodes.Ldind_I1); break; case TypeCode.Boolean: case TypeCode.SByte: il.Emit(OpCodes.Ldind_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Ldind_I2); break; case TypeCode.Char: case TypeCode.UInt16: il.Emit(OpCodes.Ldind_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Ldind_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldind_U4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldind_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldind_R4); break; case TypeCode.Double: il.Emit(OpCodes.Ldind_R8); break; default: if (type.IsValueType) { il.Emit(OpCodes.Ldobj, type); } else { il.Emit(OpCodes.Ldind_Ref); } break; } } /// <summary> /// Emits a Stind* instruction for the appropriate type. /// </summary> internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) { Debug.Assert(type != null); switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.Byte: case TypeCode.SByte: il.Emit(OpCodes.Stind_I1); break; case TypeCode.Char: case TypeCode.Int16: case TypeCode.UInt16: il.Emit(OpCodes.Stind_I2); break; case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Stind_I4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Stind_I8); break; case TypeCode.Single: il.Emit(OpCodes.Stind_R4); break; case TypeCode.Double: il.Emit(OpCodes.Stind_R8); break; default: if (type.IsValueType) { il.Emit(OpCodes.Stobj, type); } else { il.Emit(OpCodes.Stind_Ref); } break; } } // Emits the Ldelem* instruction for the appropriate type internal static void EmitLoadElement(this ILGenerator il, Type type) { Debug.Assert(type != null); if (!type.IsValueType) { il.Emit(OpCodes.Ldelem_Ref); } else { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: il.Emit(OpCodes.Ldelem_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Ldelem_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Ldelem_I2); break; case TypeCode.Char: case TypeCode.UInt16: il.Emit(OpCodes.Ldelem_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Ldelem_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldelem_U4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Ldelem_R8); break; default: il.Emit(OpCodes.Ldelem, type); break; } } } /// <summary> /// Emits a Stelem* instruction for the appropriate type. /// </summary> internal static void EmitStoreElement(this ILGenerator il, Type type) { Debug.Assert(type != null); switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: il.Emit(OpCodes.Stelem_I1); break; case TypeCode.Char: case TypeCode.Int16: case TypeCode.UInt16: il.Emit(OpCodes.Stelem_I2); break; case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Stelem_I4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Stelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Stelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Stelem_R8); break; default: if (type.IsValueType) { il.Emit(OpCodes.Stelem, type); } else { il.Emit(OpCodes.Stelem_Ref); } break; } } internal static void EmitType(this ILGenerator il, Type type) { Debug.Assert(type != null); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); } #endregion #region Fields, properties and methods internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi) { Debug.Assert(fi != null); il.Emit(fi.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda, fi); } internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi) { Debug.Assert(fi != null); il.Emit(fi.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, fi); } internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi) { Debug.Assert(fi != null); il.Emit(fi.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fi); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, ConstructorInfo ci) { Debug.Assert(ci != null); Debug.Assert(!ci.DeclaringType.ContainsGenericParameters); il.Emit(OpCodes.Newobj, ci); } #endregion #region Constants internal static void EmitNull(this ILGenerator il) { il.Emit(OpCodes.Ldnull); } internal static void EmitString(this ILGenerator il, string value) { Debug.Assert(value != null); il.Emit(OpCodes.Ldstr, value); } internal static void EmitPrimitive(this ILGenerator il, bool value) { il.Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); } internal static void EmitPrimitive(this ILGenerator il, int value) { OpCode c; switch (value) { case -1: c = OpCodes.Ldc_I4_M1; break; case 0: c = OpCodes.Ldc_I4_0; break; case 1: c = OpCodes.Ldc_I4_1; break; case 2: c = OpCodes.Ldc_I4_2; break; case 3: c = OpCodes.Ldc_I4_3; break; case 4: c = OpCodes.Ldc_I4_4; break; case 5: c = OpCodes.Ldc_I4_5; break; case 6: c = OpCodes.Ldc_I4_6; break; case 7: c = OpCodes.Ldc_I4_7; break; case 8: c = OpCodes.Ldc_I4_8; break; default: if (value >= sbyte.MinValue && value <= sbyte.MaxValue) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } return; } il.Emit(c); } private static void EmitPrimitive(this ILGenerator il, uint value) { il.EmitPrimitive(unchecked((int)value)); } private static void EmitPrimitive(this ILGenerator il, long value) { if (int.MinValue <= value & value <= uint.MaxValue) { il.EmitPrimitive(unchecked((int)value)); // While often not of consequence depending on what follows, there are cases where this // casting matters. Values [0, int.MaxValue] can use either safely, but negative values // must use conv.i8 and those (int.MaxValue, uint.MaxValue] must use conv.u8, or else // the higher bits will be wrong. il.Emit(value > 0 ? OpCodes.Conv_U8 : OpCodes.Conv_I8); } else { il.Emit(OpCodes.Ldc_I8, value); } } private static void EmitPrimitive(this ILGenerator il, ulong value) { il.EmitPrimitive(unchecked((long)value)); } private static void EmitPrimitive(this ILGenerator il, double value) { il.Emit(OpCodes.Ldc_R8, value); } private static void EmitPrimitive(this ILGenerator il, float value) { il.Emit(OpCodes.Ldc_R4, value); } // matches TryEmitConstant internal static bool CanEmitConstant(object value, Type type) { if (value == null || CanEmitILConstant(type)) { return true; } Type t = value as Type; if (t != null) { return ShouldLdtoken(t); } MethodBase mb = value as MethodBase; return mb != null && ShouldLdtoken(mb); } // matches TryEmitILConstant private static bool CanEmitILConstant(Type type) { switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Char: case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.String: return true; } return false; } // // Note: we support emitting more things as IL constants than // Linq does internal static bool TryEmitConstant(this ILGenerator il, object value, Type type, ILocalCache locals) { if (value == null) { // Smarter than the Linq implementation which uses the initobj // pattern for all value types (works, but requires a local and // more IL) il.EmitDefault(type, locals); return true; } // Handle the easy cases if (il.TryEmitILConstant(value, type)) { return true; } // Check for a few more types that we support emitting as constants Type t = value as Type; if (t != null) { if (ShouldLdtoken(t)) { il.EmitType(t); if (type != typeof(Type)) { il.Emit(OpCodes.Castclass, type); } return true; } return false; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { il.Emit(OpCodes.Ldtoken, mb); Type dt = mb.DeclaringType; if (dt != null && dt.IsGenericType) { il.Emit(OpCodes.Ldtoken, dt); il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle); } else { il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle); } if (type != typeof(MethodBase)) { il.Emit(OpCodes.Castclass, type); } return true; } return false; } private static bool ShouldLdtoken(Type t) { // If CompileToMethod is re-enabled, t is TypeBuilder should also return // true when not compiling to a DynamicMethod return t.IsGenericParameter || t.IsVisible; } internal static bool ShouldLdtoken(MethodBase mb) { // Can't ldtoken on a DynamicMethod if (mb is DynamicMethod) { return false; } Type dt = mb.DeclaringType; return dt == null || ShouldLdtoken(dt); } private static bool TryEmitILConstant(this ILGenerator il, object value, Type type) { Debug.Assert(value != null); if (type.IsNullableType()) { Type nonNullType = type.GetNonNullableType(); if (TryEmitILConstant(il, value, nonNullType)) { il.Emit(OpCodes.Newobj, type.GetConstructor(new[] { nonNullType })); return true; } return false; } switch (type.GetTypeCode()) { case TypeCode.Boolean: il.EmitPrimitive((bool)value); return true; case TypeCode.SByte: il.EmitPrimitive((sbyte)value); return true; case TypeCode.Int16: il.EmitPrimitive((short)value); return true; case TypeCode.Int32: il.EmitPrimitive((int)value); return true; case TypeCode.Int64: il.EmitPrimitive((long)value); return true; case TypeCode.Single: il.EmitPrimitive((float)value); return true; case TypeCode.Double: il.EmitPrimitive((double)value); return true; case TypeCode.Char: il.EmitPrimitive((char)value); return true; case TypeCode.Byte: il.EmitPrimitive((byte)value); return true; case TypeCode.UInt16: il.EmitPrimitive((ushort)value); return true; case TypeCode.UInt32: il.EmitPrimitive((uint)value); return true; case TypeCode.UInt64: il.EmitPrimitive((ulong)value); return true; case TypeCode.Decimal: il.EmitDecimal((decimal)value); return true; case TypeCode.String: il.EmitString((string)value); return true; default: return false; } } #endregion #region Linq Conversions internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { if (TypeUtils.AreEquivalent(typeFrom, typeTo)) { return; } Debug.Assert(typeFrom != typeof(void) && typeTo != typeof(void)); bool isTypeFromNullable = typeFrom.IsNullableType(); bool isTypeToNullable = typeTo.IsNullableType(); Type nnExprType = typeFrom.GetNonNullableType(); Type nnType = typeTo.GetNonNullableType(); if (typeFrom.IsInterface || // interface cast typeTo.IsInterface || typeFrom == typeof(object) || // boxing cast typeTo == typeof(object) || typeFrom == typeof(System.Enum) || typeFrom == typeof(System.ValueType) || TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo)) { il.EmitCastToType(typeFrom, typeTo); } else if (isTypeFromNullable || isTypeToNullable) { il.EmitNullableConversion(typeFrom, typeTo, isChecked, locals); } else if (!(typeFrom.IsConvertible() && typeTo.IsConvertible()) // primitive runtime conversion && (nnExprType.IsAssignableFrom(nnType) || // down cast nnType.IsAssignableFrom(nnExprType))) // up cast { il.EmitCastToType(typeFrom, typeTo); } else if (typeFrom.IsArray && typeTo.IsArray) { // See DevDiv Bugs #94657. il.EmitCastToType(typeFrom, typeTo); } else { il.EmitNumericConversion(typeFrom, typeTo, isChecked); } } private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo) { if (typeFrom.IsValueType) { Debug.Assert(!typeTo.IsValueType); il.Emit(OpCodes.Box, typeFrom); if (typeTo != typeof(object)) { il.Emit(OpCodes.Castclass, typeTo); } } else { il.Emit(typeTo.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, typeTo); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { TypeCode tc = typeTo.GetTypeCode(); TypeCode tf = typeFrom.GetTypeCode(); if (tc == tf) { // Between enums of same underlying type, or between such an enum and the underlying type itself. // Includes bool-backed enums, which is the only valid conversion to or from bool. // Just leave the value on the stack, and treat it as the wanted type. return; } bool isFromUnsigned = tf.IsUnsigned(); OpCode convCode; switch (tc) { case TypeCode.Single: if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); convCode = OpCodes.Conv_R4; break; case TypeCode.Double: if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); convCode = OpCodes.Conv_R8; break; case TypeCode.Decimal: // NB: TypeUtils.IsImplicitNumericConversion makes the promise that implicit conversions // from various integral types and char to decimal are possible. Coalesce allows the // conversion lambda to be omitted in these cases, so we have to handle this case in // here as well, by using the op_Implicit operator implementation on System.Decimal // because there are no opcodes for System.Decimal. Debug.Assert(typeFrom != typeTo); MethodInfo method; switch (tf) { case TypeCode.Byte: method = Decimal_op_Implicit_Byte; break; case TypeCode.SByte: method = Decimal_op_Implicit_SByte; break; case TypeCode.Int16: method = Decimal_op_Implicit_Int16; break; case TypeCode.UInt16: method = Decimal_op_Implicit_UInt16; break; case TypeCode.Int32: method = Decimal_op_Implicit_Int32; break; case TypeCode.UInt32: method = Decimal_op_Implicit_UInt32; break; case TypeCode.Int64: method = Decimal_op_Implicit_Int64; break; case TypeCode.UInt64: method = Decimal_op_Implicit_UInt64; break; case TypeCode.Char: method = Decimal_op_Implicit_Char; break; default: throw ContractUtils.Unreachable; } il.Emit(OpCodes.Call, method); return; case TypeCode.SByte: if (isChecked) { convCode = isFromUnsigned ? OpCodes.Conv_Ovf_I1_Un : OpCodes.Conv_Ovf_I1; } else { if (tf == TypeCode.Byte) { return; } convCode = OpCodes.Conv_I1; } break; case TypeCode.Byte: if (isChecked) { convCode = isFromUnsigned ? OpCodes.Conv_Ovf_U1_Un : OpCodes.Conv_Ovf_U1; } else { if (tf == TypeCode.SByte) { return; } convCode = OpCodes.Conv_U1; } break; case TypeCode.Int16: switch (tf) { case TypeCode.SByte: case TypeCode.Byte: return; case TypeCode.Char: case TypeCode.UInt16: if (!isChecked) { return; } break; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_I2_Un : OpCodes.Conv_Ovf_I2) : OpCodes.Conv_I2; break; case TypeCode.Char: case TypeCode.UInt16: switch (tf) { case TypeCode.Byte: case TypeCode.Char: case TypeCode.UInt16: return; case TypeCode.SByte: case TypeCode.Int16: if (!isChecked) { return; } break; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_U2_Un : OpCodes.Conv_Ovf_U2) : OpCodes.Conv_U2; break; case TypeCode.Int32: switch (tf) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.UInt16: return; case TypeCode.UInt32: if (!isChecked) { return; } break; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4) : OpCodes.Conv_I4; break; case TypeCode.UInt32: switch (tf) { case TypeCode.Byte: case TypeCode.Char: case TypeCode.UInt16: return; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: if (!isChecked) { return; } break; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_U4_Un : OpCodes.Conv_Ovf_U4) : OpCodes.Conv_U4; break; case TypeCode.Int64: if (!isChecked && tf == TypeCode.UInt64) { return; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_I8_Un : OpCodes.Conv_Ovf_I8) : (isFromUnsigned ? OpCodes.Conv_U8 : OpCodes.Conv_I8); break; case TypeCode.UInt64: if (!isChecked && tf == TypeCode.Int64) { return; } convCode = isChecked ? (isFromUnsigned || tf.IsFloatingPoint() ? OpCodes.Conv_Ovf_U8_Un : OpCodes.Conv_Ovf_U8) : (isFromUnsigned || tf.IsFloatingPoint() ? OpCodes.Conv_U8 : OpCodes.Conv_I8); break; default: throw ContractUtils.Unreachable; } il.Emit(convCode); } private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { Debug.Assert(typeFrom.IsNullableType()); Debug.Assert(typeTo.IsNullableType()); Label labIfNull; Label labEnd; LocalBuilder locFrom = locals.GetLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); LocalBuilder locTo = locals.GetLocal(typeTo); // test for null il.Emit(OpCodes.Ldloca, locFrom); il.EmitHasValue(typeFrom); labIfNull = il.DefineLabel(); il.Emit(OpCodes.Brfalse_S, labIfNull); il.Emit(OpCodes.Ldloca, locFrom); locals.FreeLocal(locFrom); il.EmitGetValueOrDefault(typeFrom); Type nnTypeFrom = typeFrom.GetNonNullableType(); Type nnTypeTo = typeTo.GetNonNullableType(); il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked, locals); // construct result type ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); labEnd = il.DefineLabel(); il.Emit(OpCodes.Br_S, labEnd); // if null then create a default one il.MarkLabel(labIfNull); il.Emit(OpCodes.Ldloca, locTo); il.Emit(OpCodes.Initobj, typeTo); il.MarkLabel(labEnd); il.Emit(OpCodes.Ldloc, locTo); locals.FreeLocal(locTo); } private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { Debug.Assert(!typeFrom.IsNullableType()); Debug.Assert(typeTo.IsNullableType()); LocalBuilder locTo = locals.GetLocal(typeTo); Type nnTypeTo = typeTo.GetNonNullableType(); il.EmitConvertToType(typeFrom, nnTypeTo, isChecked, locals); ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); il.Emit(OpCodes.Ldloc, locTo); locals.FreeLocal(locTo); } private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { Debug.Assert(typeFrom.IsNullableType()); Debug.Assert(!typeTo.IsNullableType()); if (typeTo.IsValueType) il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked, locals); else il.EmitNullableToReferenceConversion(typeFrom); } private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { Debug.Assert(typeFrom.IsNullableType()); Debug.Assert(!typeTo.IsNullableType()); Debug.Assert(typeTo.IsValueType); LocalBuilder locFrom = locals.GetLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); il.Emit(OpCodes.Ldloca, locFrom); locals.FreeLocal(locFrom); il.EmitGetValue(typeFrom); Type nnTypeFrom = typeFrom.GetNonNullableType(); il.EmitConvertToType(nnTypeFrom, typeTo, isChecked, locals); } private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom) { Debug.Assert(typeFrom.IsNullableType()); // We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that // we get the nullable semantics. il.Emit(OpCodes.Box, typeFrom); } private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { bool isTypeFromNullable = typeFrom.IsNullableType(); bool isTypeToNullable = typeTo.IsNullableType(); Debug.Assert(isTypeFromNullable || isTypeToNullable); if (isTypeFromNullable && isTypeToNullable) il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked, locals); else if (isTypeFromNullable) il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked, locals); else il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked, locals); } internal static void EmitHasValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", System.Type.EmptyTypes); Debug.Assert(nullableType.IsValueType); il.Emit(OpCodes.Call, mi); } #endregion #region Arrays #if FEATURE_COMPILE_TO_METHODBUILDER /// <summary> /// Emits an array of constant values provided in the given array. /// The array is strongly typed. /// </summary> internal static void EmitArray<T>(this ILGenerator il, T[] items, ILocalCache locals) { Debug.Assert(items != null); il.EmitPrimitive(items.Length); il.Emit(OpCodes.Newarr, typeof(T)); for (int i = 0; i < items.Length; i++) { il.Emit(OpCodes.Dup); il.EmitPrimitive(i); il.TryEmitConstant(items[i], typeof(T), locals); il.EmitStoreElement(typeof(T)); } } #endif /// <summary> /// Emits an array of values of count size. /// </summary> internal static void EmitArray(this ILGenerator il, Type elementType, int count) { Debug.Assert(elementType != null); Debug.Assert(count >= 0); il.EmitPrimitive(count); il.Emit(OpCodes.Newarr, elementType); } /// <summary> /// Emits an array construction code. /// The code assumes that bounds for all dimensions /// are already emitted. /// </summary> internal static void EmitArray(this ILGenerator il, Type arrayType) { Debug.Assert(arrayType != null); Debug.Assert(arrayType.IsArray); if (arrayType.IsSZArray) { il.Emit(OpCodes.Newarr, arrayType.GetElementType()); } else { Type[] types = new Type[arrayType.GetArrayRank()]; for (int i = 0; i < types.Length; i++) { types[i] = typeof(int); } ConstructorInfo ci = arrayType.GetConstructor(types); Debug.Assert(ci != null); il.EmitNew(ci); } } #endregion #region Support for emitting constants private static void EmitDecimal(this ILGenerator il, decimal value) { int[] bits = decimal.GetBits(value); int scale = (bits[3] & int.MaxValue) >> 16; if (scale == 0) { if (int.MinValue <= value) { if (value <= int.MaxValue) { int intValue = decimal.ToInt32(value); switch (intValue) { case -1: il.Emit(OpCodes.Ldsfld, Decimal_MinusOne); return; case 0: il.EmitDefault(typeof(decimal), locals: null); // locals won't be used. return; case 1: il.Emit(OpCodes.Ldsfld, Decimal_One); return; default: il.EmitPrimitive(intValue); il.EmitNew(Decimal_Ctor_Int32); return; } } if (value <= uint.MaxValue) { il.EmitPrimitive(decimal.ToUInt32(value)); il.EmitNew(Decimal_Ctor_UInt32); return; } } if (long.MinValue <= value) { if (value <= long.MaxValue) { il.EmitPrimitive(decimal.ToInt64(value)); il.EmitNew(Decimal_Ctor_Int64); return; } if (value <= ulong.MaxValue) { il.EmitPrimitive(decimal.ToUInt64(value)); il.EmitNew(Decimal_Ctor_UInt64); return; } if (value == decimal.MaxValue) { il.Emit(OpCodes.Ldsfld, Decimal_MaxValue); return; } } else if (value == decimal.MinValue) { il.Emit(OpCodes.Ldsfld, Decimal_MinValue); return; } } il.EmitPrimitive(bits[0]); il.EmitPrimitive(bits[1]); il.EmitPrimitive(bits[2]); il.EmitPrimitive((bits[3] & 0x80000000) != 0); il.EmitPrimitive(unchecked((byte)scale)); il.EmitNew(Decimal_Ctor_Int32_Int32_Int32_Bool_Byte); } /// <summary> /// Emits default(T) /// Semantics match C# compiler behavior /// </summary> internal static void EmitDefault(this ILGenerator il, Type type, ILocalCache locals) { switch (type.GetTypeCode()) { case TypeCode.DateTime: il.Emit(OpCodes.Ldsfld, DateTime_MinValue); break; case TypeCode.Object: if (type.IsValueType) { // Type.GetTypeCode on an enum returns the underlying // integer TypeCode, so we won't get here. Debug.Assert(!type.IsEnum); // This is the IL for default(T) if T is a generic type // parameter, so it should work for any type. It's also // the standard pattern for structs. LocalBuilder lb = locals.GetLocal(type); il.Emit(OpCodes.Ldloca, lb); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Ldloc, lb); locals.FreeLocal(lb); break; } goto case TypeCode.Empty; case TypeCode.Empty: case TypeCode.String: case TypeCode.DBNull: il.Emit(OpCodes.Ldnull); break; case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Ldc_I4_0); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Conv_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldc_R4, default(float)); break; case TypeCode.Double: il.Emit(OpCodes.Ldc_R8, default(double)); break; case TypeCode.Decimal: il.Emit(OpCodes.Ldsfld, Decimal_Zero); break; default: throw ContractUtils.Unreachable; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol.Models { using Microsoft.Azure; using Microsoft.Azure.Batch; using Microsoft.Azure.Batch.Protocol; using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// Resource usage statistics for a job schedule. /// </summary> public partial class JobScheduleStatistics { /// <summary> /// Initializes a new instance of the JobScheduleStatistics class. /// </summary> public JobScheduleStatistics() { CustomInit(); } /// <summary> /// Initializes a new instance of the JobScheduleStatistics class. /// </summary> /// <param name="url">The URL of the statistics.</param> /// <param name="startTime">The start time of the time range covered by /// the statistics.</param> /// <param name="lastUpdateTime">The time at which the statistics were /// last updated. All statistics are limited to the range between /// startTime and lastUpdateTime.</param> /// <param name="userCPUTime">The total user mode CPU time (summed /// across all cores and all compute nodes) consumed by all tasks in /// all jobs created under the schedule.</param> /// <param name="kernelCPUTime">The total kernel mode CPU time (summed /// across all cores and all compute nodes) consumed by all tasks in /// all jobs created under the schedule.</param> /// <param name="wallClockTime">The total wall clock time of all the /// tasks in all the jobs created under the schedule.</param> /// <param name="readIOps">The total number of disk read operations /// made by all tasks in all jobs created under the schedule.</param> /// <param name="writeIOps">The total number of disk write operations /// made by all tasks in all jobs created under the schedule.</param> /// <param name="readIOGiB">The total gibibytes read from disk by all /// tasks in all jobs created under the schedule.</param> /// <param name="writeIOGiB">The total gibibytes written to disk by all /// tasks in all jobs created under the schedule.</param> /// <param name="numSucceededTasks">The total number of tasks /// successfully completed during the given time range in jobs created /// under the schedule. A task completes successfully if it returns /// exit code 0.</param> /// <param name="numFailedTasks">The total number of tasks that failed /// during the given time range in jobs created under the schedule. A /// task fails if it exhausts its maximum retry count without returning /// exit code 0.</param> /// <param name="numTaskRetries">The total number of retries during the /// given time range on all tasks in all jobs created under the /// schedule.</param> /// <param name="waitTime">The total wait time of all tasks in all jobs /// created under the schedule. The wait time for a task is defined as /// the elapsed time between the creation of the task and the start of /// task execution. (If the task is retried due to failures, the wait /// time is the time to the most recent task execution.)</param> public JobScheduleStatistics(string url, System.DateTime startTime, System.DateTime lastUpdateTime, System.TimeSpan userCPUTime, System.TimeSpan kernelCPUTime, System.TimeSpan wallClockTime, long readIOps, long writeIOps, double readIOGiB, double writeIOGiB, long numSucceededTasks, long numFailedTasks, long numTaskRetries, System.TimeSpan waitTime) { Url = url; StartTime = startTime; LastUpdateTime = lastUpdateTime; UserCPUTime = userCPUTime; KernelCPUTime = kernelCPUTime; WallClockTime = wallClockTime; ReadIOps = readIOps; WriteIOps = writeIOps; ReadIOGiB = readIOGiB; WriteIOGiB = writeIOGiB; NumSucceededTasks = numSucceededTasks; NumFailedTasks = numFailedTasks; NumTaskRetries = numTaskRetries; WaitTime = waitTime; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the URL of the statistics. /// </summary> [JsonProperty(PropertyName = "url")] public string Url { get; set; } /// <summary> /// Gets or sets the start time of the time range covered by the /// statistics. /// </summary> [JsonProperty(PropertyName = "startTime")] public System.DateTime StartTime { get; set; } /// <summary> /// Gets or sets the time at which the statistics were last updated. /// All statistics are limited to the range between startTime and /// lastUpdateTime. /// </summary> [JsonProperty(PropertyName = "lastUpdateTime")] public System.DateTime LastUpdateTime { get; set; } /// <summary> /// Gets or sets the total user mode CPU time (summed across all cores /// and all compute nodes) consumed by all tasks in all jobs created /// under the schedule. /// </summary> [JsonProperty(PropertyName = "userCPUTime")] public System.TimeSpan UserCPUTime { get; set; } /// <summary> /// Gets or sets the total kernel mode CPU time (summed across all /// cores and all compute nodes) consumed by all tasks in all jobs /// created under the schedule. /// </summary> [JsonProperty(PropertyName = "kernelCPUTime")] public System.TimeSpan KernelCPUTime { get; set; } /// <summary> /// Gets or sets the total wall clock time of all the tasks in all the /// jobs created under the schedule. /// </summary> /// <remarks> /// The wall clock time is the elapsed time from when the task started /// running on a compute node to when it finished (or to the last time /// the statistics were updated, if the task had not finished by then). /// If a task was retried, this includes the wall clock time of all the /// task retries. /// </remarks> [JsonProperty(PropertyName = "wallClockTime")] public System.TimeSpan WallClockTime { get; set; } /// <summary> /// Gets or sets the total number of disk read operations made by all /// tasks in all jobs created under the schedule. /// </summary> [JsonProperty(PropertyName = "readIOps")] public long ReadIOps { get; set; } /// <summary> /// Gets or sets the total number of disk write operations made by all /// tasks in all jobs created under the schedule. /// </summary> [JsonProperty(PropertyName = "writeIOps")] public long WriteIOps { get; set; } /// <summary> /// Gets or sets the total gibibytes read from disk by all tasks in all /// jobs created under the schedule. /// </summary> [JsonProperty(PropertyName = "readIOGiB")] public double ReadIOGiB { get; set; } /// <summary> /// Gets or sets the total gibibytes written to disk by all tasks in /// all jobs created under the schedule. /// </summary> [JsonProperty(PropertyName = "writeIOGiB")] public double WriteIOGiB { get; set; } /// <summary> /// Gets or sets the total number of tasks successfully completed /// during the given time range in jobs created under the schedule. A /// task completes successfully if it returns exit code 0. /// </summary> [JsonProperty(PropertyName = "numSucceededTasks")] public long NumSucceededTasks { get; set; } /// <summary> /// Gets or sets the total number of tasks that failed during the given /// time range in jobs created under the schedule. A task fails if it /// exhausts its maximum retry count without returning exit code 0. /// </summary> [JsonProperty(PropertyName = "numFailedTasks")] public long NumFailedTasks { get; set; } /// <summary> /// Gets or sets the total number of retries during the given time /// range on all tasks in all jobs created under the schedule. /// </summary> [JsonProperty(PropertyName = "numTaskRetries")] public long NumTaskRetries { get; set; } /// <summary> /// Gets or sets the total wait time of all tasks in all jobs created /// under the schedule. The wait time for a task is defined as the /// elapsed time between the creation of the task and the start of task /// execution. (If the task is retried due to failures, the wait time /// is the time to the most recent task execution.) /// </summary> /// <remarks> /// This value is only reported in the account lifetime statistics; it /// is not included in the job statistics. /// </remarks> [JsonProperty(PropertyName = "waitTime")] public System.TimeSpan WaitTime { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Url == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Url"); } } } }
/* * Exchange Web Services Managed API * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Net; using System.Text; using System.Xml; /// <summary> /// Represents an abstract service request. /// </summary> internal abstract class ServiceRequestBase { #region Private Constants /// <summary> /// The two contants below are used to set the AnchorMailbox and ExplicitLogonUser values /// in the request header. /// </summary> /// <remarks> /// Note: Setting this values will route the request directly to the backend hosting the /// AnchorMailbox. These headers should be used primarily for UnifiedGroup scenario where /// a request needs to be routed directly to the group mailbox versus the user mailbox. /// </remarks> private const string AnchorMailboxHeaderName = "X-AnchorMailbox"; private const string ExplicitLogonUserHeaderName = "X-OWA-ExplicitLogonUser"; private static readonly string[] RequestIdResponseHeaders = new[] { "RequestId", "request-id", }; private const string XMLSchemaNamespace = "http://www.w3.org/2001/XMLSchema"; private const string XMLSchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; private const string ClientStatisticsRequestHeader = "X-ClientStatistics"; #endregion /// <summary> /// Gets or sets the anchor mailbox associated with the request /// </summary> /// <remarks> /// Setting this value will add special headers to the request which in turn /// will route the request directly to the mailbox server against which the request /// is to be executed. /// </remarks> internal string AnchorMailbox { get; set; } /// <summary> /// Maintains the collection of client side statistics for requests already completed /// </summary> private static List<string> clientStatisticsCache = new List<string>(); private ExchangeService service; /// <summary> /// Gets the response stream (may be wrapped with GZip/Deflate stream to decompress content) /// </summary> /// <param name="response">HttpWebResponse.</param> /// <returns>ResponseStream</returns> protected static Stream GetResponseStream(IEwsHttpWebResponse response) { string contentEncoding = response.ContentEncoding; Stream responseStream = response.GetResponseStream(); return WrapStream(responseStream, response.ContentEncoding); } /// <summary> /// Gets the response stream (may be wrapped with GZip/Deflate stream to decompress content) /// </summary> /// <param name="response">HttpWebResponse.</param> /// <param name="readTimeout">read timeout in milliseconds</param> /// <returns>ResponseStream</returns> protected static Stream GetResponseStream(IEwsHttpWebResponse response, int readTimeout) { Stream responseStream = response.GetResponseStream(); responseStream.ReadTimeout = readTimeout; return WrapStream(responseStream, response.ContentEncoding); } private static Stream WrapStream(Stream responseStream, string contentEncoding) { if (contentEncoding.ToLowerInvariant().Contains("gzip")) { return new GZipStream(responseStream, CompressionMode.Decompress); } else if (contentEncoding.ToLowerInvariant().Contains("deflate")) { return new DeflateStream(responseStream, CompressionMode.Decompress); } else { return responseStream; } } #region Methods for subclasses to override /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name,</returns> internal abstract string GetXmlElementName(); /// <summary> /// Gets the name of the response XML element. /// </summary> /// <returns>XML element name,</returns> internal abstract string GetResponseXmlElementName(); /// <summary> /// Gets the minimum server version required to process this request. /// </summary> /// <returns>Exchange server version.</returns> internal abstract ExchangeVersion GetMinimumRequiredServerVersion(); /// <summary> /// Writes XML elements. /// </summary> /// <param name="writer">The writer.</param> internal abstract void WriteElementsToXml(EwsServiceXmlWriter writer); /// <summary> /// Parses the response. /// </summary> /// <param name="reader">The reader.</param> /// <returns>Response object.</returns> internal virtual object ParseResponse(EwsServiceXmlReader reader) { throw new NotImplementedException("you must override either this or the 2-parameter version"); } /// <summary> /// Parses the response. /// </summary> /// <param name="reader">The reader.</param> /// <param name="responseHeaders">Response headers</param> /// <returns>Response object.</returns> /// <remarks>If this is overriden instead of the 1-parameter version, you can read response headers</remarks> internal virtual object ParseResponse(EwsServiceXmlReader reader, WebHeaderCollection responseHeaders) { return this.ParseResponse(reader); } /// <summary> /// Gets a value indicating whether the TimeZoneContext SOAP header should be eimitted. /// </summary> /// <value><c>true</c> if the time zone should be emitted; otherwise, <c>false</c>.</value> internal virtual bool EmitTimeZoneHeader { get { return false; } } #endregion /// <summary> /// Validate request. /// </summary> internal virtual void Validate() { this.Service.Validate(); } /// <summary> /// Writes XML body. /// </summary> /// <param name="writer">The writer.</param> internal void WriteBodyToXml(EwsServiceXmlWriter writer) { writer.WriteStartElement(XmlNamespace.Messages, this.GetXmlElementName()); this.WriteAttributesToXml(writer); this.WriteElementsToXml(writer); writer.WriteEndElement(); // m:this.GetXmlElementName() } /// <summary> /// Writes XML attributes. /// </summary> /// <remarks> /// Subclass will override if it has XML attributes. /// </remarks> /// <param name="writer">The writer.</param> internal virtual void WriteAttributesToXml(EwsServiceXmlWriter writer) { } /// <summary> /// Allows the subclasses to add their own header information /// </summary> /// <param name="webHeaderCollection">The HTTP request headers</param> internal virtual void AddHeaders(WebHeaderCollection webHeaderCollection) { if (!string.IsNullOrEmpty(this.AnchorMailbox)) { webHeaderCollection.Set(AnchorMailboxHeaderName, this.AnchorMailbox); webHeaderCollection.Set(ExplicitLogonUserHeaderName, this.AnchorMailbox); } } /// <summary> /// Initializes a new instance of the <see cref="ServiceRequestBase"/> class. /// </summary> /// <param name="service">The service.</param> internal ServiceRequestBase(ExchangeService service) { if (service == null) { throw new ArgumentNullException("service"); } this.service = service; this.ThrowIfNotSupportedByRequestedServerVersion(); } /// <summary> /// Gets the service. /// </summary> /// <value>The service.</value> internal ExchangeService Service { get { return this.service; } } /// <summary> /// Throw exception if request is not supported in requested server version. /// </summary> /// <exception cref="ServiceVersionException">Raised if request requires a later version of Exchange.</exception> internal void ThrowIfNotSupportedByRequestedServerVersion() { if (this.Service.RequestedServerVersion < this.GetMinimumRequiredServerVersion()) { throw new ServiceVersionException( string.Format( Strings.RequestIncompatibleWithRequestVersion, this.GetXmlElementName(), this.GetMinimumRequiredServerVersion())); } } #region HttpWebRequest-based implementation /// <summary> /// Writes XML. /// </summary> /// <param name="writer">The writer.</param> internal void WriteToXml(EwsServiceXmlWriter writer) { writer.WriteStartElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName); writer.WriteAttributeValue("xmlns", EwsUtilities.EwsXmlSchemaInstanceNamespacePrefix, EwsUtilities.EwsXmlSchemaInstanceNamespace); writer.WriteAttributeValue("xmlns", EwsUtilities.EwsMessagesNamespacePrefix, EwsUtilities.EwsMessagesNamespace); writer.WriteAttributeValue("xmlns", EwsUtilities.EwsTypesNamespacePrefix, EwsUtilities.EwsTypesNamespace); if (writer.RequireWSSecurityUtilityNamespace) { writer.WriteAttributeValue("xmlns", EwsUtilities.WSSecurityUtilityNamespacePrefix, EwsUtilities.WSSecurityUtilityNamespace); } writer.WriteStartElement(XmlNamespace.Soap, XmlElementNames.SOAPHeaderElementName); if (this.Service.Credentials != null) { this.Service.Credentials.EmitExtraSoapHeaderNamespaceAliases(writer.InternalWriter); } // Emit the RequestServerVersion header if (!this.Service.SuppressXmlVersionHeader) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.RequestServerVersion); writer.WriteAttributeValue(XmlAttributeNames.Version, this.GetRequestedServiceVersionString()); writer.WriteEndElement(); // RequestServerVersion } // Against Exchange 2007 SP1, we always emit the simplified time zone header. It adds very little to // the request, so bandwidth consumption is not an issue. Against Exchange 2010 and above, we emit // the full time zone header but only when the request actually needs it. // // The exception to this is if we are in Exchange2007 Compat Mode, in which case we should never emit // the header. (Note: Exchange2007 Compat Mode is enabled for testability purposes only.) // if ((this.Service.RequestedServerVersion == ExchangeVersion.Exchange2007_SP1 || this.EmitTimeZoneHeader) && (!this.Service.Exchange2007CompatibilityMode)) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.TimeZoneContext); this.Service.TimeZoneDefinition.WriteToXml(writer); writer.WriteEndElement(); // TimeZoneContext writer.IsTimeZoneHeaderEmitted = true; } // Emit the MailboxCulture header if (this.Service.PreferredCulture != null) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.MailboxCulture, this.Service.PreferredCulture.Name); } // Emit the DateTimePrecision header if (this.Service.DateTimePrecision != DateTimePrecision.Default) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DateTimePrecision, this.Service.DateTimePrecision.ToString()); } // Emit the ExchangeImpersonation header if (this.Service.ImpersonatedUserId != null) { this.Service.ImpersonatedUserId.WriteToXml(writer); } else if (this.Service.PrivilegedUserId != null) { this.Service.PrivilegedUserId.WriteToXml(writer, this.Service.RequestedServerVersion); } else if (this.Service.ManagementRoles != null) { this.Service.ManagementRoles.WriteToXml(writer); } if (this.Service.Credentials != null) { this.Service.Credentials.SerializeExtraSoapHeaders(writer.InternalWriter, this.GetXmlElementName()); } this.Service.DoOnSerializeCustomSoapHeaders(writer.InternalWriter); writer.WriteEndElement(); // soap:Header writer.WriteStartElement(XmlNamespace.Soap, XmlElementNames.SOAPBodyElementName); this.WriteBodyToXml(writer); writer.WriteEndElement(); // soap:Body writer.WriteEndElement(); // soap:Envelope } /// <summary> /// Gets string representation of requested server version. /// </summary> /// <remarks> /// In order to support E12 RTM servers, ExchangeService has another flag indicating that /// we should use "Exchange2007" as the server version string rather than Exchange2007_SP1. /// </remarks> /// <returns>String representation of requested server version.</returns> private string GetRequestedServiceVersionString() { if (this.Service.Exchange2007CompatibilityMode && this.Service.RequestedServerVersion == ExchangeVersion.Exchange2007_SP1) { return "Exchange2007"; } else { return this.Service.RequestedServerVersion.ToString(); } } /// <summary> /// Emits the request. /// </summary> /// <param name="request">The request.</param> private void EmitRequest(IEwsHttpWebRequest request) { using (Stream requestStream = this.GetWebRequestStream(request)) { using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, requestStream)) { this.WriteToXml(writer); } } } /// <summary> /// Traces the and emits the request. /// </summary> /// <param name="request">The request.</param> /// <param name="needSignature"></param> /// <param name="needTrace"></param> private void TraceAndEmitRequest(IEwsHttpWebRequest request, bool needSignature, bool needTrace) { using (MemoryStream memoryStream = new MemoryStream()) { using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, memoryStream)) { writer.RequireWSSecurityUtilityNamespace = needSignature; this.WriteToXml(writer); } if (needSignature) { this.service.Credentials.Sign(memoryStream); } if (needTrace) { this.TraceXmlRequest(memoryStream); } using (Stream serviceRequestStream = this.GetWebRequestStream(request)) { EwsUtilities.CopyStream(memoryStream, serviceRequestStream); } } } /// <summary> /// Get the request stream /// </summary> /// <param name="request">The request</param> /// <returns>The Request stream</returns> private Stream GetWebRequestStream(IEwsHttpWebRequest request) { // In the async case, although we can use async callback to make the entire worflow completely async, // there is little perf gain with this approach because of EWS's message nature. // The overall latency of BeginGetRequestStream() is same as GetRequestStream() in this case. // The overhead to implement a two-step async operation includes wait handle synchronization, exception handling and wrapping. // Therefore, we only leverage BeginGetResponse() and EndGetReponse() to provide the async functionality. // Reference: http://www.wintellect.com/CS/blogs/jeffreyr/archive/2009/02/08/httpwebrequest-its-request-stream-and-sending-data-in-chunks.aspx return request.EndGetRequestStream(request.BeginGetRequestStream(null, null)); } /// <summary> /// Reads the response. /// </summary> /// <param name="ewsXmlReader">The XML reader.</param> /// <param name="responseHeaders">HTTP response headers</param> /// <returns>Service response.</returns> protected object ReadResponse(EwsServiceXmlReader ewsXmlReader, WebHeaderCollection responseHeaders) { object serviceResponse; this.ReadPreamble(ewsXmlReader); ewsXmlReader.ReadStartElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName); this.ReadSoapHeader(ewsXmlReader); ewsXmlReader.ReadStartElement(XmlNamespace.Soap, XmlElementNames.SOAPBodyElementName); ewsXmlReader.ReadStartElement(XmlNamespace.Messages, this.GetResponseXmlElementName()); if (responseHeaders != null) { serviceResponse = this.ParseResponse(ewsXmlReader, responseHeaders); } else { serviceResponse = this.ParseResponse(ewsXmlReader); } ewsXmlReader.ReadEndElementIfNecessary(XmlNamespace.Messages, this.GetResponseXmlElementName()); ewsXmlReader.ReadEndElement(XmlNamespace.Soap, XmlElementNames.SOAPBodyElementName); ewsXmlReader.ReadEndElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName); return serviceResponse; } /// <summary> /// Reads any preamble data not part of the core response. /// </summary> /// <param name="ewsXmlReader">The EwsServiceXmlReader.</param> protected virtual void ReadPreamble(EwsServiceXmlReader ewsXmlReader) { this.ReadXmlDeclaration(ewsXmlReader); } /// <summary> /// Read SOAP header and extract server version /// </summary> /// <param name="reader">EwsServiceXmlReader</param> private void ReadSoapHeader(EwsServiceXmlReader reader) { reader.ReadStartElement(XmlNamespace.Soap, XmlElementNames.SOAPHeaderElementName); do { reader.Read(); // Is this the ServerVersionInfo? if (reader.IsStartElement(XmlNamespace.Types, XmlElementNames.ServerVersionInfo)) { this.Service.ServerInfo = ExchangeServerInfo.Parse(reader); } // Ignore anything else inside the SOAP header } while (!reader.IsEndElement(XmlNamespace.Soap, XmlElementNames.SOAPHeaderElementName)); } /// <summary> /// Reads the SOAP fault. /// </summary> /// <param name="reader">The reader.</param> /// <returns>SOAP fault details.</returns> protected SoapFaultDetails ReadSoapFault(EwsServiceXmlReader reader) { SoapFaultDetails soapFaultDetails = null; try { this.ReadXmlDeclaration(reader); reader.Read(); if (!reader.IsStartElement() || (reader.LocalName != XmlElementNames.SOAPEnvelopeElementName)) { return soapFaultDetails; } // EWS can sometimes return SOAP faults using the SOAP 1.2 namespace. Get the // namespace URI from the envelope element and use it for the rest of the parsing. // If it's not 1.1 or 1.2, we can't continue. XmlNamespace soapNamespace = EwsUtilities.GetNamespaceFromUri(reader.NamespaceUri); if (soapNamespace == XmlNamespace.NotSpecified) { return soapFaultDetails; } reader.Read(); // EWS doesn't always return a SOAP header. If this response contains a header element, // read the server version information contained in the header. if (reader.IsStartElement(soapNamespace, XmlElementNames.SOAPHeaderElementName)) { do { reader.Read(); if (reader.IsStartElement(XmlNamespace.Types, XmlElementNames.ServerVersionInfo)) { this.Service.ServerInfo = ExchangeServerInfo.Parse(reader); } } while (!reader.IsEndElement(soapNamespace, XmlElementNames.SOAPHeaderElementName)); // Queue up the next read reader.Read(); } // Parse the fault element contained within the SOAP body. if (reader.IsStartElement(soapNamespace, XmlElementNames.SOAPBodyElementName)) { do { reader.Read(); // Parse Fault element if (reader.IsStartElement(soapNamespace, XmlElementNames.SOAPFaultElementName)) { soapFaultDetails = SoapFaultDetails.Parse(reader, soapNamespace); } } while (!reader.IsEndElement(soapNamespace, XmlElementNames.SOAPBodyElementName)); } reader.ReadEndElement(soapNamespace, XmlElementNames.SOAPEnvelopeElementName); } catch (XmlException) { // If response doesn't contain a valid SOAP fault, just ignore exception and // return null for SOAP fault details. } return soapFaultDetails; } /// <summary> /// Validates request parameters, and emits the request to the server. /// </summary> /// <param name="request">The request.</param> /// <returns>The response returned by the server.</returns> protected IEwsHttpWebResponse ValidateAndEmitRequest(out IEwsHttpWebRequest request) { this.Validate(); request = this.BuildEwsHttpWebRequest(); if (this.service.SendClientLatencies) { string clientStatisticsToAdd = null; lock (clientStatisticsCache) { if (clientStatisticsCache.Count > 0) { clientStatisticsToAdd = clientStatisticsCache[0]; clientStatisticsCache.RemoveAt(0); } } if (!string.IsNullOrEmpty(clientStatisticsToAdd)) { if (request.Headers[ClientStatisticsRequestHeader] != null) { request.Headers[ClientStatisticsRequestHeader] = request.Headers[ClientStatisticsRequestHeader] + clientStatisticsToAdd; } else { request.Headers.Add( ClientStatisticsRequestHeader, clientStatisticsToAdd); } } } DateTime startTime = DateTime.UtcNow; IEwsHttpWebResponse response = null; try { response = this.GetEwsHttpWebResponse(request); } finally { if (this.service.SendClientLatencies) { int clientSideLatency = (int)(DateTime.UtcNow - startTime).TotalMilliseconds; string requestId = string.Empty; string soapAction = this.GetType().Name.Replace("Request", string.Empty); if (response != null && response.Headers != null) { foreach (string requestIdHeader in ServiceRequestBase.RequestIdResponseHeaders) { string requestIdValue = response.Headers.Get(requestIdHeader); if (!string.IsNullOrEmpty(requestIdValue)) { requestId = requestIdValue; break; } } } StringBuilder sb = new StringBuilder(); sb.Append("MessageId="); sb.Append(requestId); sb.Append(",ResponseTime="); sb.Append(clientSideLatency); sb.Append(",SoapAction="); sb.Append(soapAction); sb.Append(";"); lock (clientStatisticsCache) { clientStatisticsCache.Add(sb.ToString()); } } } return response; } /// <summary> /// Builds the IEwsHttpWebRequest object for current service request with exception handling. /// </summary> /// <returns>An IEwsHttpWebRequest instance</returns> protected IEwsHttpWebRequest BuildEwsHttpWebRequest() { try { IEwsHttpWebRequest request = this.Service.PrepareHttpWebRequest(this.GetXmlElementName()); this.Service.TraceHttpRequestHeaders(TraceFlags.EwsRequestHttpHeaders, request); bool needSignature = this.Service.Credentials != null && this.Service.Credentials.NeedSignature; bool needTrace = this.Service.IsTraceEnabledFor(TraceFlags.EwsRequest); // The request might need to add additional headers this.AddHeaders(request.Headers); // If tracing is enabled, we generate the request in-memory so that we // can pass it along to the ITraceListener. Then we copy the stream to // the request stream. if (needSignature || needTrace) { this.TraceAndEmitRequest(request, needSignature, needTrace); } else { this.EmitRequest(request); } return request; } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { this.ProcessWebException(ex); } // Wrap exception if the above code block didn't throw throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex); } catch (IOException e) { // Wrap exception. throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e); } } /// <summary> /// Gets the IEwsHttpWebRequest object from the specified IEwsHttpWebRequest object with exception handling /// </summary> /// <param name="request">The specified IEwsHttpWebRequest</param> /// <returns>An IEwsHttpWebResponse instance</returns> protected IEwsHttpWebResponse GetEwsHttpWebResponse(IEwsHttpWebRequest request) { try { return request.GetResponse(); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { this.ProcessWebException(ex); } // Wrap exception if the above code block didn't throw throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex); } catch (IOException e) { // Wrap exception. throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e); } } /// <summary> /// Ends getting the specified async IEwsHttpWebRequest object from the specified IEwsHttpWebRequest object with exception handling. /// </summary> /// <param name="request">The specified IEwsHttpWebRequest</param> /// <param name="asyncResult">An IAsyncResult that references the asynchronous request.</param> /// <returns>An IEwsHttpWebResponse instance</returns> protected IEwsHttpWebResponse EndGetEwsHttpWebResponse(IEwsHttpWebRequest request, IAsyncResult asyncResult) { try { // Note that this call may throw ArgumentException if the HttpWebRequest instance is not the original one, // and we just let it out return request.EndGetResponse(asyncResult); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { this.ProcessWebException(ex); } // Wrap exception if the above code block didn't throw throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex); } catch (IOException e) { // Wrap exception. throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e); } } /// <summary> /// Processes the web exception. /// </summary> /// <param name="webException">The web exception.</param> private void ProcessWebException(WebException webException) { if (webException.Response != null) { IEwsHttpWebResponse httpWebResponse = this.Service.HttpWebRequestFactory.CreateExceptionResponse(webException); SoapFaultDetails soapFaultDetails = null; if (httpWebResponse.StatusCode == HttpStatusCode.InternalServerError) { this.Service.ProcessHttpResponseHeaders(TraceFlags.EwsResponseHttpHeaders, httpWebResponse); // If tracing is enabled, we read the entire response into a MemoryStream so that we // can pass it along to the ITraceListener. Then we parse the response from the // MemoryStream. if (this.Service.IsTraceEnabledFor(TraceFlags.EwsResponse)) { using (MemoryStream memoryStream = new MemoryStream()) { using (Stream serviceResponseStream = ServiceRequestBase.GetResponseStream(httpWebResponse)) { // Copy response to in-memory stream and reset position to start. EwsUtilities.CopyStream(serviceResponseStream, memoryStream); memoryStream.Position = 0; } this.TraceResponseXml(httpWebResponse, memoryStream); EwsServiceXmlReader reader = new EwsServiceXmlReader(memoryStream, this.Service); soapFaultDetails = this.ReadSoapFault(reader); } } else { using (Stream stream = ServiceRequestBase.GetResponseStream(httpWebResponse)) { EwsServiceXmlReader reader = new EwsServiceXmlReader(stream, this.Service); soapFaultDetails = this.ReadSoapFault(reader); } } if (soapFaultDetails != null) { switch (soapFaultDetails.ResponseCode) { case ServiceError.ErrorInvalidServerVersion: throw new ServiceVersionException(Strings.ServerVersionNotSupported); case ServiceError.ErrorSchemaValidation: // If we're talking to an E12 server (8.00.xxxx.xxx), a schema validation error is the same as a version mismatch error. // (Which only will happen if we send a request that's not valid for E12). if ((this.Service.ServerInfo != null) && (this.Service.ServerInfo.MajorVersion == 8) && (this.Service.ServerInfo.MinorVersion == 0)) { throw new ServiceVersionException(Strings.ServerVersionNotSupported); } break; case ServiceError.ErrorIncorrectSchemaVersion: // This shouldn't happen. It indicates that a request wasn't valid for the version that was specified. EwsUtilities.Assert( false, "ServiceRequestBase.ProcessWebException", "Exchange server supports requested version but request was invalid for that version"); break; case ServiceError.ErrorServerBusy: throw new ServerBusyException(new ServiceResponse(soapFaultDetails)); default: // Other error codes will be reported as remote error break; } // General fall-through case: throw a ServiceResponseException throw new ServiceResponseException(new ServiceResponse(soapFaultDetails)); } } else { this.Service.ProcessHttpErrorResponse(httpWebResponse, webException); } } } /// <summary> /// Traces an XML request. This should only be used for synchronous requests, or synchronous situations /// (such as a WebException on an asynchrounous request). /// </summary> /// <param name="memoryStream">The request content in a MemoryStream.</param> protected void TraceXmlRequest(MemoryStream memoryStream) { this.Service.TraceXml(TraceFlags.EwsRequest, memoryStream); } /// <summary> /// Traces the response. This should only be used for synchronous requests, or synchronous situations /// (such as a WebException on an asynchrounous request). /// </summary> /// <param name="response">The response.</param> /// <param name="memoryStream">The response content in a MemoryStream.</param> protected void TraceResponseXml(IEwsHttpWebResponse response, MemoryStream memoryStream) { if (!string.IsNullOrEmpty(response.ContentType) && (response.ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) || response.ContentType.StartsWith("application/soap", StringComparison.OrdinalIgnoreCase))) { this.Service.TraceXml(TraceFlags.EwsResponse, memoryStream); } else { this.Service.TraceMessage(TraceFlags.EwsResponse, "Non-textual response"); } } /// <summary> /// Try to read the XML declaration. If it's not there, the server didn't return XML. /// </summary> /// <param name="reader">The reader.</param> private void ReadXmlDeclaration(EwsServiceXmlReader reader) { try { reader.Read(XmlNodeType.XmlDeclaration); } catch (XmlException ex) { throw new ServiceRequestException(Strings.ServiceResponseDoesNotContainXml, ex); } catch (ServiceXmlDeserializationException ex) { throw new ServiceRequestException(Strings.ServiceResponseDoesNotContainXml, ex); } } #endregion } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> //----------------------------------------------------------------------- #endregion using System; using System.Runtime.WootzJs; using WootzJs.Testing; namespace WootzJs.Compiler.Tests { public class NumberTests : TestFixture { [Test] public void ToHex() { var number = 20; AssertEquals(number.ToString("X4"), "0014"); } [Test] public void IntTryParse() { var s = "1"; int i; AssertTrue(int.TryParse(s, out i)); AssertEquals(i, 1); } [Test] public void IntTryParseFalse() { var s = "a"; int i; AssertTrue(!int.TryParse(s, out i)); } [Test] public void TruncFloatViaCast() { var f = 1.234f; var i = (int)f; AssertEquals(i, 1); } [Test] public void ToLocaleString() { var s = 1.234.As<JsNumber>().toLocaleString(); AssertEquals(s, "1.234"); } [Test] public void FormatException() { try { int.Parse("a"); AssertTrue(false); } catch (FormatException e) { AssertTrue(true); } } [Test] public void CastIntToByte() { var castIntToByteI = 2342342342; var b = (byte)castIntToByteI; AssertEquals(b, 198); } [Test] public void Byte() { byte a = (byte)50; byte b = 230; AssertEquals(a + b, 280); } [Test] public void RightShiftAssign() { int a = 3; a >>= 1; AssertEquals(a, 1); } [Test] public void LeftShiftAssign() { int a = 3; a <<= 1; AssertEquals(a, 6); } [Test] public void BitwiseOrAssign() { int a = 1; a |= 4; AssertEquals(a, 5); } [Test] public void BitwiseAndAssign() { int a = 78; a &= 2; AssertEquals(a, 2); } [Test] public void ExclusiveOrAssign() { int a = 77; a ^= 55; AssertEquals(a, 122); } [Test] public void DefaultByteReturnsValue() { AssertEquals(DefaultByte(), 255); } public byte DefaultByte(byte test = 255) // fails { return test; } [Test] public void DefaultSByteReturnsValue() { AssertEquals(DefaultSByte(), -127); } public sbyte DefaultSByte(sbyte test = -127) // fails { return test; } [Test] public void DefaultShortReturnsValue() { AssertEquals(DefaultShort(), 432); } public short DefaultShort(short test = 432) // fails { return test; } [Test] public void DefaultUShortReturnsValue() { AssertEquals(DefaultUShort(), 23456); } public ushort DefaultUShort(ushort test = 23456) // fails { return test; } [Test] public void IntegerToString() { var i = 5; AssertEquals(i.ToString("0"), "5"); } [Test] public void DecimalToString() { var n = 1.2345; AssertEquals(n.ToString("0"), "1"); } /* [Test] public void AssignmentOperators() { int a = 3; int b = 0; a >>= b; a <<= b; a |= b; a &= b; a ^= b; } */ } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using hw.DebugFormatter; using hw.Helper; using JetBrains.Annotations; // ReSharper disable ConvertMethodToExpressionBody // ReSharper disable MergeConditionalExpression namespace hw.Forms { /// <summary> /// Used to persist location of window of parent /// </summary> public sealed class PositionConfig : IDisposable { Form _target; bool _loadPositionCalled; readonly Func<string> _getFileName; /// <summary> /// Ctor /// </summary> /// <param name="getFileName"> /// function to obtain filename of configuration file. /// <para>It will be called each time the name is required. </para> /// <para>Default: Target.Name</para> /// </param> public PositionConfig(Func<string> getFileName = null) { _getFileName = getFileName ?? (() => _target == null ? null : _target.Name); } /// <summary> /// Form that will be controlled by this instance /// </summary> public Form Target { [UsedImplicitly] get { return _target; } set { Disconnect(); _target = value; Connect(); } } /// <summary> /// Name that will be used as filename /// </summary> public string FileName { get { return _getFileName(); } } void IDisposable.Dispose() { Disconnect(); } void Disconnect() { if(_target == null) return; _target.SuspendLayout(); _loadPositionCalled = false; _target.Load -= OnLoad; _target.LocationChanged -= OnLocationChanged; _target.SizeChanged -= OnLocationChanged; _target.ResumeLayout(); _target = null; } void Connect() { if(_target == null) return; _target.SuspendLayout(); _loadPositionCalled = false; _target.Load += OnLoad; _target.LocationChanged += OnLocationChanged; _target.SizeChanged += OnLocationChanged; _target.ResumeLayout(); } void OnLocationChanged(object target, EventArgs e) { if(target != _target) return; SavePosition(); } void OnLoad(object target, EventArgs e) { if(target != _target) return; LoadPosition(); } Rectangle? Position { get { return Convert (0, null, s => (Rectangle?) new RectangleConverter().ConvertFromString(s)); } set { Save(value, WindowState); } } string[] ParameterStrings { get { if(_target == null) return null; var content = FileHandle.String; return content == null ? null : content.Split('\n'); } } File FileHandle { get { var fileName = FileName; return fileName == null ? null : fileName.FileHandle(); } } void Save(Rectangle? position, FormWindowState state) { var fileHandle = FileHandle; Tracer.Assert(fileHandle != null); fileHandle.String = "{0}\n{1}" .ReplaceArgs ( position == null ? "" : new RectangleConverter().ConvertToString(position.Value), state ); } FormWindowState WindowState { get { return Convert(1, FormWindowState.Normal, s => s.Parse<FormWindowState>()); } set { Save(Position, value); } } T Convert<T>(int position, T defaultValue, Func<string, T> converter) { return ParameterStrings == null || ParameterStrings.Length <= position ? defaultValue : converter(ParameterStrings[position]); } void LoadPosition() { var fileHandle = FileHandle; Tracer.Assert(fileHandle != null); if(fileHandle.String != null) { var position = Position; Tracer.Assert(position != null); _target.SuspendLayout(); _target.StartPosition = FormStartPosition.Manual; _target.Bounds = EnsureVisible(position.Value); _target.WindowState = WindowState; _target.ResumeLayout(true); } _loadPositionCalled = true; } void SavePosition() { if(!_loadPositionCalled) return; if(_target.WindowState == FormWindowState.Normal) Position = _target.Bounds; WindowState = _target.WindowState; } static Rectangle EnsureVisible(Rectangle value) { var allScreens = Screen.AllScreens; if(allScreens.Any(s => s.Bounds.IntersectsWith(value))) return value; var closestScreen = Screen.FromRectangle(value); var result = value; var leftDistance = value.Left - closestScreen.Bounds.Right; var rightDistance = value.Right - closestScreen.Bounds.Left; if(leftDistance > 0 && rightDistance > 0) result.X += leftDistance < rightDistance ? -(leftDistance + 10) : rightDistance + 10; var topDistance = value.Top - closestScreen.Bounds.Bottom; var bottomDistance = value.Bottom - closestScreen.Bounds.Top; if(topDistance > 0 && bottomDistance > 0) result.Y += topDistance < bottomDistance ? -(topDistance + 10) : bottomDistance + 10; Tracer.Assert(closestScreen.Bounds.IntersectsWith(result)); return result; } } }
// // Copyright 2012 Hakan Kjellerstrand // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.IO; using System.Text.RegularExpressions; using Google.OrTools.ConstraintSolver; public class StableMarriage { /** * * Solves some stable marriage problems. * See http://www.hakank.org/or-tools/stable_marriage.py * */ private static void Solve(int[][][] ranks, String problem_name) { Solver solver = new Solver("StableMarriage"); // // data // int n = ranks[0].Length; Console.WriteLine("\n#####################"); Console.WriteLine("Problem: " + problem_name); int[][] rankWomen = ranks[0]; int[][] rankMen = ranks[1]; // // Decision variables // IntVar[] wife = solver.MakeIntVarArray(n, 0, n - 1, "wife"); IntVar[] husband = solver.MakeIntVarArray(n, 0, n - 1, "husband"); // // Constraints // // (The comments below are the Comet code) // // forall(m in Men) // cp.post(husband[wife[m]] == m); for(int m = 0; m < n; m++) { solver.Add(husband.Element(wife[m]) == m); } // forall(w in Women) // cp.post(wife[husband[w]] == w); for(int w = 0; w < n; w++) { solver.Add(wife.Element(husband[w]) == w); } // forall(m in Men, o in Women) // cp.post(rankMen[m,o] < rankMen[m, wife[m]] => // rankWomen[o,husband[o]] < rankWomen[o,m]); for(int m = 0; m < n; m++) { for(int o = 0; o < n; o++) { IntVar b1 = rankMen[m].Element(wife[m]) > rankMen[m][o]; IntVar b2 = rankWomen[o].Element(husband[o]) < rankWomen[o][m]; solver.Add(b1 <= b2); } } // forall(w in Women, o in Men) // cp.post(rankWomen[w,o] < rankWomen[w,husband[w]] => // rankMen[o,wife[o]] < rankMen[o,w]); for(int w = 0; w < n; w++) { for(int o = 0; o < n; o++) { IntVar b1 = rankWomen[w].Element(husband[w]) > rankWomen[w][o]; IntVar b2 = rankMen[o].Element(wife[o]) < rankMen[o][w]; solver.Add(b1 <= b2); } } // // Search // DecisionBuilder db = solver.MakePhase(wife, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("wife : "); for(int i = 0; i < n; i++) { Console.Write(wife[i].Value() + " "); } Console.Write("\nhusband: "); for(int i = 0; i < n; i++) { Console.Write(husband[i].Value() + " "); } Console.WriteLine("\n"); } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); Console.WriteLine("WallTime: {0}ms", solver.WallTime()); Console.WriteLine("Failures: {0}", solver.Failures()); Console.WriteLine("Branches: {0} ", solver.Branches()); solver.EndSearch(); } public static void Main(String[] args) { // // From Pascal Van Hentenryck's OPL book // int[][][] van_hentenryck = { // rankWomen new int[][] { new int[] {1, 2, 4, 3, 5}, new int[] {3, 5, 1, 2, 4}, new int[] {5, 4, 2, 1, 3}, new int[] {1, 3, 5, 4, 2}, new int[] {4, 2, 3, 5, 1}}, // rankMen new int[][] { new int[] {5, 1, 2, 4, 3}, new int[] {4, 1, 3, 2, 5}, new int[] {5, 3, 2, 4, 1}, new int[] {1, 5, 4, 3, 2}, new int[] {4, 3, 2, 1, 5}} }; // // Data from MathWorld // http://mathworld.wolfram.com/StableMarriageProblem.html // int[][][] mathworld = { // rankWomen new int[][] { new int[] {3, 1, 5, 2, 8, 7, 6, 9, 4}, new int[] {9, 4, 8, 1, 7, 6, 3, 2, 5}, new int[] {3, 1, 8, 9, 5, 4, 2, 6, 7}, new int[] {8, 7, 5, 3, 2, 6, 4, 9, 1}, new int[] {6, 9, 2, 5, 1, 4, 7, 3, 8}, new int[] {2, 4, 5, 1, 6, 8, 3, 9, 7}, new int[] {9, 3, 8, 2, 7, 5, 4, 6, 1}, new int[] {6, 3, 2, 1, 8, 4, 5, 9, 7}, new int[] {8, 2, 6, 4, 9, 1, 3, 7, 5}}, // rankMen new int[][] { new int[] {7, 3, 8, 9, 6, 4, 2, 1, 5}, new int[] {5, 4, 8, 3, 1, 2, 6, 7, 9}, new int[] {4, 8, 3, 9, 7, 5, 6, 1, 2}, new int[] {9, 7, 4, 2, 5, 8, 3, 1, 6}, new int[] {2, 6, 4, 9, 8, 7, 5, 1, 3}, new int[] {2, 7, 8, 6, 5, 3, 4, 1, 9}, new int[] {1, 6, 2, 3, 8, 5, 4, 9, 7}, new int[] {5, 6, 9, 1, 2, 8, 4, 3, 7}, new int[] {6, 1, 4, 7, 5, 8, 3, 9, 2}} }; // // Data from // http://www.csee.wvu.edu/~ksmani/courses/fa01/random/lecnotes/lecture5.pdf // int[][][] problem3 = { // rankWomen new int[][] { new int[] {1,2,3,4}, new int[] {4,3,2,1}, new int[] {1,2,3,4}, new int[] {3,4,1,2}}, // rankMen new int[][] { new int[] {1,2,3,4}, new int[] {2,1,3,4}, new int[] {1,4,3,2}, new int[] {4,3,1,2}} }; // // Data from // http://www.comp.rgu.ac.uk/staff/ha/ZCSP/additional_problems/stable_marriage/stable_marriage.pdf // page 4 // int[][][] problem4 = { // rankWomen new int[][] { new int[] {1,5,4,6,2,3}, new int[] {4,1,5,2,6,3}, new int[] {6,4,2,1,5,3}, new int[] {1,5,2,4,3,6}, new int[] {4,2,1,5,6,3}, new int[] {2,6,3,5,1,4}}, // rankMen new int[][] { new int[] {1,4,2,5,6,3}, new int[] {3,4,6,1,5,2}, new int[] {1,6,4,2,3,5}, new int[] {6,5,3,4,2,1}, new int[] {3,1,2,4,5,6}, new int[] {2,3,1,6,5,4}}}; Solve(van_hentenryck, "Van Hentenryck"); Solve(mathworld, "MathWorld"); Solve(problem3, "Problem 3"); Solve(problem4, "Problem 4"); } }
//------------------------------------------------------------------------------ // <copyright file="TransferJob.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement { using System; using System.Globalization; using System.Runtime.Serialization; using System.Threading; /// <summary> /// Represents transfer of a single file/blob. /// </summary> #if BINARY_SERIALIZATION [Serializable] #else [DataContract] [KnownType(typeof(AzureBlobDirectoryLocation))] [KnownType(typeof(AzureBlobLocation))] [KnownType(typeof(AzureFileDirectoryLocation))] [KnownType(typeof(AzureFileLocation))] [KnownType(typeof(DirectoryLocation))] [KnownType(typeof(FileLocation))] // StreamLocation intentionally omitted because it is not serializable [KnownType(typeof(UriLocation))] #endif // BINARY_SERIALIZATION internal class TransferJob #if BINARY_SERIALIZATION : ISerializable #endif // BINARY_SERIALIZATION { private const string SourceName = "Source"; private const string DestName = "Dest"; private const string CheckedOverwriteName = "CheckedOverwrite"; private const string OverwriteName = "Overwrite"; private const string CopyIdName = "CopyId"; private const string CheckpointName = "Checkpoint"; private const string StatusName = "Status"; /// <summary> /// Initializes a new instance of the <see cref="TransferJob"/> class. /// </summary> /// <param name="transfer">Transfer object.</param> public TransferJob(Transfer transfer) { this.Transfer = transfer; this.CheckPoint = new SingleObjectCheckpoint(); } #if BINARY_SERIALIZATION /// <summary> /// Initializes a new instance of the <see cref="TransferJob"/> class. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected TransferJob(SerializationInfo info, StreamingContext context) { if (info.GetBoolean(CheckedOverwriteName)) { this.Overwrite = info.GetBoolean(OverwriteName); } else { this.Overwrite = null; } this.CopyId = info.GetString(CopyIdName); this.CheckPoint = (SingleObjectCheckpoint)info.GetValue(CheckpointName, typeof(SingleObjectCheckpoint)); this.Status = (TransferJobStatus)info.GetValue(StatusName, typeof(TransferJobStatus)); } #endif // BINARY_SERIALIZATION /// <summary> /// Initializes a new instance of the <see cref="TransferJob"/> class. /// </summary> private TransferJob(TransferJob other) { this.Overwrite = other.Overwrite; this.CopyId = other.CopyId; this.CheckPoint = other.CheckPoint.Copy(); this.Status = other.Status; } public ReaderWriterLockSlim ProgressUpdateLock { get; set; } /// <summary> /// Gets source location for this transfer job. /// </summary> public TransferLocation Source { get { return this.Transfer.Source; } } /// <summary> /// Gets destination location for this transfer job. /// </summary> public TransferLocation Destination { get { return this.Transfer.Destination; } } /// <summary> /// Gets or sets the overwrite flag. /// </summary> #if !BINARY_SERIALIZATION [DataMember] #endif public bool? Overwrite { get; set; } /// <summary> /// Gets ID for the asynchronous copy operation. /// </summary> /// <value>ID for the asynchronous copy operation.</value> #if !BINARY_SERIALIZATION [DataMember] #endif public string CopyId { get; set; } #if !BINARY_SERIALIZATION [DataMember] #endif public TransferJobStatus Status { get; set; } #if !BINARY_SERIALIZATION [DataMember] #endif public SingleObjectCheckpoint CheckPoint { get; set; } /// <summary> /// Gets or sets the parent transfer of this transfer job /// </summary> public Transfer Transfer { get; set; } #if BINARY_SERIALIZATION /// <summary> /// Serializes the object. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue(CheckedOverwriteName, this.Overwrite.HasValue); if (this.Overwrite.HasValue) { info.AddValue(OverwriteName, this.Overwrite.Value); } info.AddValue(CopyIdName, this.CopyId, typeof(string)); info.AddValue(CheckpointName, this.CheckPoint, typeof(SingleObjectCheckpoint)); info.AddValue(StatusName, this.Status, typeof(TransferJobStatus)); } #endif // BINARY_SERIALIZATION /// <summary> /// Gets a copy of this transfer job. /// </summary> /// <returns>A copy of current transfer job</returns> public TransferJob Copy() { return new TransferJob(this); } } }
/** * Project: emergetk: stateful web framework for the masses * File name: .cs * Description: * * @author Ben Joldersma, All-In-One Creations, Ltd. http://all-in-one-creations.net, Copyright (C) 2006. * * @see The GNU Public License (GPL) */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using EmergeTk.Model; namespace EmergeTk.Widgets.Html { /// <summary> /// Summary description for LabeledTextBox. /// </summary> public class LabeledWidget<T> : HtmlElement, IDataBindable, IWidgetDecorator where T : Widget, new() { HtmlElement label; Label error; Literal labelText; T widget; IDataBindable db; bool added = false; public override void Add(Widget c) { if (!(c is Label)) { if (added) { RemoveChild(widget); } widget = c as T; db = widget as IDataBindable; added = true; } base.Add(c); } public HtmlElement Label { get { setupLabel(); return label; } } private void setupLabel() { if( label == null ) { label = RootContext.CreateWidget<HtmlElement>(); Insert(label, 0); labelText = RootContext.CreateWidget<Literal>(label); } } public string LabelText { get { setupLabel(); return labelText.Html; } set { setupLabel(); labelText.Html = value; RaisePropertyChangedNotification("LabelText"); } } public T Widget { get { if (widget == null) { widget = RootContext.CreateWidget<T>(); Label.SetClientElementAttribute("for", "'" + widget.ClientId + "'" ); Add(widget); added = true; } return widget; } set { Add(value); Label.SetClientElementAttribute("for", "'" + widget.ClientId + "'" ); RaisePropertyChangedNotification("Widget"); } } public override void Initialize() { TagName = "div"; Label.Id = "_label"; Label.TagName = "label"; if (!added) { widget = RootContext.CreateWidget<T>(); Add(widget); Label.SetClientElementAttribute("for", "'" + widget.ClientId + "'" ); added = true; } } public void SetError( string text ) { if( text == null && error != null ) { error.Remove(); } else if( text != null && error != null ) { error.Text = text; } else if( text != null && error == null ) { error = RootContext.CreateWidget<Label>(); error.ClassName = "error"; error.Text = text; error.Inline = true; this.Add(error); } } public override bool SetAttribute(string Name, string Value) { switch( Name ) { case "Label": labelText.Html = Value; //Label.Text = Value; break; case "Id": this.Id = Value; break; case "Model": break; case "Visible": this.Visible = bool.Parse(Value); break; default: return Widget.SetAttribute( Name, Value ); } return true; } public override object this[string k] { get { try { return base[k]; } catch { if( db != null ) return db[k]; } return null; } set { base[k] = value; } } override public object Value { get { if( db != null ) return db.Value; else return null; } set { if( db != null ) db.Value = value.ToString(); } } override public string DefaultProperty { get { if( db != null ) return db.DefaultProperty; else return "Value"; } } #region IWidgetDecorator Members Widget IWidgetDecorator.Widget { get { return widget; } set { if (value is T) widget = value as T; RaisePropertyChangedNotification("Widget"); } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.HDInsight.Job; using Microsoft.Azure.Management.HDInsight.Job.Models; namespace Microsoft.Azure.Management.HDInsight.Job { /// <summary> /// The HDInsight job client manages jobs against HDInsight clusters. /// </summary> public static partial class JobOperationsExtensions { /// <summary> /// Gets job details from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Required. The id of the job. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static JobGetResponse GetJob(this IJobOperations operations, string jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetJobAsync(jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets job details from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Required. The id of the job. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static Task<JobGetResponse> GetJobAsync(this IJobOperations operations, string jobId) { return operations.GetJobAsync(jobId, CancellationToken.None); } /// <summary> /// Initiates cancel on given running job in the specified HDInsight /// cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Required. The id of the job. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static JobGetResponse KillJob(this IJobOperations operations, string jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).KillJobAsync(jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Initiates cancel on given running job in the specified HDInsight /// cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Required. The id of the job. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static Task<JobGetResponse> KillJobAsync(this IJobOperations operations, string jobId) { return operations.KillJobAsync(jobId, CancellationToken.None); } /// <summary> /// Gets the list of jobs from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <returns> /// The List Job operation response. /// </returns> public static JobListResponse ListJobs(this IJobOperations operations) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ListJobsAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of jobs from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <returns> /// The List Job operation response. /// </returns> public static Task<JobListResponse> ListJobsAsync(this IJobOperations operations) { return operations.ListJobsAsync(CancellationToken.None); } /// <summary> /// Gets numOfJobs after jobId from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Optional. jobId from where to list jobs. /// </param> /// <param name='numOfJobs'> /// Required. Number of jobs to fetch. Use -1 to get all. /// </param> /// <returns> /// The List Job operation response. /// </returns> public static JobListResponse ListJobsAfterJobId(this IJobOperations operations, string jobId, int numOfJobs) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ListJobsAfterJobIdAsync(jobId, numOfJobs); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets numOfJobs after jobId from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Optional. jobId from where to list jobs. /// </param> /// <param name='numOfJobs'> /// Required. Number of jobs to fetch. Use -1 to get all. /// </param> /// <returns> /// The List Job operation response. /// </returns> public static Task<JobListResponse> ListJobsAfterJobIdAsync(this IJobOperations operations, string jobId, int numOfJobs) { return operations.ListJobsAfterJobIdAsync(jobId, numOfJobs, CancellationToken.None); } /// <summary> /// Submits a Hive job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Hive job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitHiveJob(this IJobOperations operations, JobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitHiveJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits a Hive job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Hive job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitHiveJobAsync(this IJobOperations operations, JobSubmissionParameters parameters) { return operations.SubmitHiveJobAsync(parameters, CancellationToken.None); } /// <summary> /// Submits a MapReduce job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. MapReduce job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitMapReduceJob(this IJobOperations operations, JobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitMapReduceJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits a MapReduce job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. MapReduce job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitMapReduceJobAsync(this IJobOperations operations, JobSubmissionParameters parameters) { return operations.SubmitMapReduceJobAsync(parameters, CancellationToken.None); } /// <summary> /// Submits a MapReduce streaming job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. MapReduce job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitMapReduceStreamingJob(this IJobOperations operations, JobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitMapReduceStreamingJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits a MapReduce streaming job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. MapReduce job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitMapReduceStreamingJobAsync(this IJobOperations operations, JobSubmissionParameters parameters) { return operations.SubmitMapReduceStreamingJobAsync(parameters, CancellationToken.None); } /// <summary> /// Submits a Pig job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Pig job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitPigJob(this IJobOperations operations, JobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitPigJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits a Pig job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Pig job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitPigJobAsync(this IJobOperations operations, JobSubmissionParameters parameters) { return operations.SubmitPigJobAsync(parameters, CancellationToken.None); } /// <summary> /// Submits a Sqoop job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Sqoop job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitSqoopJob(this IJobOperations operations, JobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitSqoopJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits a Sqoop job to an HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Sqoop job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitSqoopJobAsync(this IJobOperations operations, JobSubmissionParameters parameters) { return operations.SubmitSqoopJobAsync(parameters, CancellationToken.None); } } }
//#define USE_SharpZipLib #if !UNITY_WEBPLAYER //#define USE_FileIO #endif /* * * * * * A simple JSON Parser / builder * ------------------------------ * * It mainly has been written as a simple JSON parser. It can build a JSON string * from the node-tree, or generate a node tree from any valid JSON string. * * If you want to use compression when saving to file / stream / B64 you have to include * SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and * define "USE_SharpZipLib" at the top of the file * * Written by Bunny83 * 2012-06-09 * * Features / attributes: * - provides strongly typed node classes and lists / dictionaries * - provides easy access to class members / array items / data values * - the parser ignores data types. Each value is a string. * - only double quotes (") are used for quoting strings. * - values and names are not restricted to quoted strings. They simply add up and are trimmed. * - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData) * - provides "casting" properties to easily convert to / from those types: * int / float / double / bool * - provides a common interface for each node so no explicit casting is required. * - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined * * * 2012-12-17 UpdatePosition: * - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree * Now you can simple reference any item that doesn'transform exist yet and it will return a JSONLazyCreator * The class determines the required type by it's further use, creates the type and removes itself. * - Added binary serialization / deserialization. * - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) * The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top * - The serializer uses different types when it comes to store the values. Since my data values * are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string. * It's not the most efficient way but for a moderate amount of data it should work on all platforms. * * * * * */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace AltProg.CleanEmptyDir //namespace SimpleJSON { public enum JSONBinaryTag { Array = 1, Class = 2, Value = 3, IntValue = 4, DoubleValue = 5, BoolValue = 6, FloatValue = 7, } public class JSONNode { #region common interface public virtual void Add(string aKey, JSONNode aItem){ } public virtual JSONNode this[int aIndex] { get { return null; } set { } } public virtual JSONNode this[string aKey] { get { return null; } set { } } public virtual string Value { get { return ""; } set { } } public virtual int Count { get { return 0; } } public virtual void Add(JSONNode aItem) { Add("", aItem); } public virtual JSONNode Remove(string aKey) { return null; } public virtual JSONNode Remove(int aIndex) { return null; } public virtual JSONNode Remove(JSONNode aNode) { return aNode; } public virtual IEnumerable<JSONNode> Childs { get { yield break;} } public IEnumerable<JSONNode> DeepChilds { get { foreach (var C in Childs) foreach (var D in C.DeepChilds) yield return D; } } public override string ToString() { return "JSONNode"; } public virtual string ToString(string aPrefix) { return "JSONNode"; } #endregion common interface #region typecasting properties public virtual int AsInt { get { int v = 0; if (int.TryParse(Value,out v)) return v; return 0; } set { Value = value.ToString(); } } public virtual float AsFloat { get { float v = 0.0f; if (float.TryParse(Value,out v)) return v; return 0.0f; } set { Value = value.ToString(); } } public virtual double AsDouble { get { double v = 0.0; if (double.TryParse(Value,out v)) return v; return 0.0; } set { Value = value.ToString(); } } public virtual bool AsBool { get { bool v = false; if (bool.TryParse(Value,out v)) return v; return !string.IsNullOrEmpty(Value); } set { Value = (value)?"true":"false"; } } public virtual JSONArray AsArray { get { return this as JSONArray; } } public virtual JSONClass AsObject { get { return this as JSONClass; } } #endregion typecasting properties #region operators public static implicit operator JSONNode(string s) { return new JSONData(s); } public static implicit operator string(JSONNode d) { return (d == null)?null:d.Value; } public static bool operator ==(JSONNode a, object b) { if (b == null && a is JSONLazyCreator) return true; return System.Object.ReferenceEquals(a,b); } public static bool operator !=(JSONNode a, object b) { return !(a == b); } public override bool Equals (object obj) { return System.Object.ReferenceEquals(this, obj); } public override int GetHashCode () { return base.GetHashCode(); } #endregion operators internal static string Escape(string aText) { string result = ""; foreach(char c in aText) { switch(c) { case '\\' : result += "\\\\"; break; case '\"' : result += "\\\""; break; case '\n' : result += "\\n" ; break; case '\r' : result += "\\r" ; break; case '\t' : result += "\\t" ; break; case '\b' : result += "\\b" ; break; case '\f' : result += "\\f" ; break; default : result += c ; break; } } return result; } public static JSONNode Parse(string aJSON) { Stack<JSONNode> stack = new Stack<JSONNode>(); JSONNode ctx = null; int i = 0; string Token = ""; string TokenName = ""; bool QuoteMode = false; while (i < aJSON.Length) { switch (aJSON[i]) { case '{': if (QuoteMode) { Token += aJSON[i]; break; } stack.Push(new JSONClass()); if (ctx != null) { TokenName = TokenName.Trim(); if (ctx is JSONArray) ctx.Add(stack.Peek()); else if (TokenName != "") ctx.Add(TokenName,stack.Peek()); } TokenName = ""; Token = ""; ctx = stack.Peek(); break; case '[': if (QuoteMode) { Token += aJSON[i]; break; } stack.Push(new JSONArray()); if (ctx != null) { TokenName = TokenName.Trim(); if (ctx is JSONArray) ctx.Add(stack.Peek()); else if (TokenName != "") ctx.Add(TokenName,stack.Peek()); } TokenName = ""; Token = ""; ctx = stack.Peek(); break; case '}': case ']': if (QuoteMode) { Token += aJSON[i]; break; } if (stack.Count == 0) throw new Exception("JSON Parse: Too many closing brackets"); stack.Pop(); if (Token != "") { TokenName = TokenName.Trim(); if (ctx is JSONArray) ctx.Add(Token); else if (TokenName != "") ctx.Add(TokenName,Token); } TokenName = ""; Token = ""; if (stack.Count>0) ctx = stack.Peek(); break; case ':': if (QuoteMode) { Token += aJSON[i]; break; } TokenName = Token; Token = ""; break; case '"': QuoteMode ^= true; break; case ',': if (QuoteMode) { Token += aJSON[i]; break; } if (Token != "") { if (ctx is JSONArray) ctx.Add(Token); else if (TokenName != "") ctx.Add(TokenName, Token); } TokenName = ""; Token = ""; break; case '\r': case '\n': break; case ' ': case '\t': if (QuoteMode) Token += aJSON[i]; break; case '\\': ++i; if (QuoteMode) { char C = aJSON[i]; switch (C) { case 't' : Token += '\t'; break; case 'r' : Token += '\r'; break; case 'n' : Token += '\n'; break; case 'b' : Token += '\b'; break; case 'f' : Token += '\f'; break; case 'u': { string s = aJSON.Substring(i+1,4); Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier); i += 4; break; } default : Token += C; break; } } break; default: Token += aJSON[i]; break; } ++i; } if (QuoteMode) { throw new Exception("JSON Parse: Quotation marks seems to be messed up."); } return ctx; } public virtual void Serialize(System.IO.BinaryWriter aWriter) {} public void SaveToStream(System.IO.Stream aData) { var W = new System.IO.BinaryWriter(aData); Serialize(W); } #if USE_SharpZipLib public void SaveToCompressedStream(System.IO.Stream aData) { using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData)) { gzipOut.IsStreamOwner = false; SaveToStream(gzipOut); gzipOut.Close(); } } public void SaveToCompressedFile(string aFileName) { #if USE_FileIO System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName); using(var F = System.IO.File.OpenWrite(aFileName)) { SaveToCompressedStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public string SaveToCompressedBase64() { using (var stream = new System.IO.MemoryStream()) { SaveToCompressedStream(stream); stream.Position = 0; return System.Convert.ToBase64String(stream.ToArray()); } } #else public void SaveToCompressedStream(System.IO.Stream aData) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public void SaveToCompressedFile(string aFileName) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public string SaveToCompressedBase64() { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } #endif public void SaveToFile(string aFileName) { #if USE_FileIO System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName); using(var F = System.IO.File.OpenWrite(aFileName)) { SaveToStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public string SaveToBase64() { using (var stream = new System.IO.MemoryStream()) { SaveToStream(stream); stream.Position = 0; return System.Convert.ToBase64String(stream.ToArray()); } } public static JSONNode Deserialize(System.IO.BinaryReader aReader) { JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte(); switch(type) { case JSONBinaryTag.Array: { int count = aReader.ReadInt32(); JSONArray tmp = new JSONArray(); for(int i = 0; i < count; i++) tmp.Add(Deserialize(aReader)); return tmp; } case JSONBinaryTag.Class: { int count = aReader.ReadInt32(); JSONClass tmp = new JSONClass(); for(int i = 0; i < count; i++) { string key = aReader.ReadString(); var val = Deserialize(aReader); tmp.Add(key, val); } return tmp; } case JSONBinaryTag.Value: { return new JSONData(aReader.ReadString()); } case JSONBinaryTag.IntValue: { return new JSONData(aReader.ReadInt32()); } case JSONBinaryTag.DoubleValue: { return new JSONData(aReader.ReadDouble()); } case JSONBinaryTag.BoolValue: { return new JSONData(aReader.ReadBoolean()); } case JSONBinaryTag.FloatValue: { return new JSONData(aReader.ReadSingle()); } default: { throw new Exception("Error deserializing JSON. Unknown tag: " + type); } } } #if USE_SharpZipLib public static JSONNode LoadFromCompressedStream(System.IO.Stream aData) { var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData); return LoadFromStream(zin); } public static JSONNode LoadFromCompressedFile(string aFileName) { #if USE_FileIO using(var F = System.IO.File.OpenRead(aFileName)) { return LoadFromCompressedStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public static JSONNode LoadFromCompressedBase64(string aBase64) { var tmp = System.Convert.FromBase64String(aBase64); var stream = new System.IO.MemoryStream(tmp); stream.Position = 0; return LoadFromCompressedStream(stream); } #else public static JSONNode LoadFromCompressedFile(string aFileName) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public static JSONNode LoadFromCompressedStream(System.IO.Stream aData) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public static JSONNode LoadFromCompressedBase64(string aBase64) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } #endif public static JSONNode LoadFromStream(System.IO.Stream aData) { using(var R = new System.IO.BinaryReader(aData)) { return Deserialize(R); } } public static JSONNode LoadFromFile(string aFileName) { #if USE_FileIO using(var F = System.IO.File.OpenRead(aFileName)) { return LoadFromStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public static JSONNode LoadFromBase64(string aBase64) { var tmp = System.Convert.FromBase64String(aBase64); var stream = new System.IO.MemoryStream(tmp); stream.Position = 0; return LoadFromStream(stream); } } // End of JSONNode public class JSONArray : JSONNode, IEnumerable { private List<JSONNode> m_List = new List<JSONNode>(); public override JSONNode this[int aIndex] { get { if (aIndex<0 || aIndex >= m_List.Count) return new JSONLazyCreator(this); return m_List[aIndex]; } set { if (aIndex<0 || aIndex >= m_List.Count) m_List.Add(value); else m_List[aIndex] = value; } } public override JSONNode this[string aKey] { get{ return new JSONLazyCreator(this);} set{ m_List.Add(value); } } public override int Count { get { return m_List.Count; } } public override void Add(string aKey, JSONNode aItem) { m_List.Add(aItem); } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_List.Count) return null; JSONNode tmp = m_List[aIndex]; m_List.RemoveAt(aIndex); return tmp; } public override JSONNode Remove(JSONNode aNode) { m_List.Remove(aNode); return aNode; } public override IEnumerable<JSONNode> Childs { get { foreach(JSONNode N in m_List) yield return N; } } public IEnumerator GetEnumerator() { foreach(JSONNode N in m_List) yield return N; } public override string ToString() { string result = "[ "; foreach (JSONNode N in m_List) { if (result.Length > 2) result += ", "; result += N.ToString(); } result += " ]"; return result; } public override string ToString(string aPrefix) { string result = "[ "; foreach (JSONNode N in m_List) { if (result.Length > 3) result += ", "; result += "\n" + aPrefix + " "; result += N.ToString(aPrefix+" "); } result += "\n" + aPrefix + "]"; return result; } public override void Serialize (System.IO.BinaryWriter aWriter) { aWriter.Write((byte)JSONBinaryTag.Array); aWriter.Write(m_List.Count); for(int i = 0; i < m_List.Count; i++) { m_List[i].Serialize(aWriter); } } } // End of JSONArray public class JSONClass : JSONNode, IEnumerable { private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>(); public override JSONNode this[string aKey] { get { if (m_Dict.ContainsKey(aKey)) return m_Dict[aKey]; else return new JSONLazyCreator(this, aKey); } set { if (m_Dict.ContainsKey(aKey)) m_Dict[aKey] = value; else m_Dict.Add(aKey,value); } } public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_Dict.Count) return null; return m_Dict.ElementAt(aIndex).Value; } set { if (aIndex < 0 || aIndex >= m_Dict.Count) return; string key = m_Dict.ElementAt(aIndex).Key; m_Dict[key] = value; } } public override int Count { get { return m_Dict.Count; } } public override void Add(string aKey, JSONNode aItem) { if (!string.IsNullOrEmpty(aKey)) { if (m_Dict.ContainsKey(aKey)) m_Dict[aKey] = aItem; else m_Dict.Add(aKey, aItem); } else m_Dict.Add(Guid.NewGuid().ToString(), aItem); } public override JSONNode Remove(string aKey) { if (!m_Dict.ContainsKey(aKey)) return null; JSONNode tmp = m_Dict[aKey]; m_Dict.Remove(aKey); return tmp; } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_Dict.Count) return null; var item = m_Dict.ElementAt(aIndex); m_Dict.Remove(item.Key); return item.Value; } public override JSONNode Remove(JSONNode aNode) { try { var item = m_Dict.Where(k => k.Value == aNode).First(); m_Dict.Remove(item.Key); return aNode; } catch { return null; } } public override IEnumerable<JSONNode> Childs { get { foreach(KeyValuePair<string,JSONNode> N in m_Dict) yield return N.Value; } } public IEnumerator GetEnumerator() { foreach(KeyValuePair<string, JSONNode> N in m_Dict) yield return N; } public override string ToString() { string result = "{"; foreach (KeyValuePair<string, JSONNode> N in m_Dict) { if (result.Length > 2) result += ", "; result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString(); } result += "}"; return result; } public override string ToString(string aPrefix) { string result = "{ "; foreach (KeyValuePair<string, JSONNode> N in m_Dict) { if (result.Length > 3) result += ", "; result += "\n" + aPrefix + " "; result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" "); } result += "\n" + aPrefix + "}"; return result; } public override void Serialize (System.IO.BinaryWriter aWriter) { aWriter.Write((byte)JSONBinaryTag.Class); aWriter.Write(m_Dict.Count); foreach(string K in m_Dict.Keys) { aWriter.Write(K); m_Dict[K].Serialize(aWriter); } } } // End of JSONClass public class JSONData : JSONNode { private string m_Data; public override string Value { get { return m_Data; } set { m_Data = value; } } public JSONData(string aData) { m_Data = aData; } public JSONData(float aData) { AsFloat = aData; } public JSONData(double aData) { AsDouble = aData; } public JSONData(bool aData) { AsBool = aData; } public JSONData(int aData) { AsInt = aData; } public override string ToString() { return "\"" + Escape(m_Data) + "\""; } public override string ToString(string aPrefix) { return "\"" + Escape(m_Data) + "\""; } public override void Serialize (System.IO.BinaryWriter aWriter) { var tmp = new JSONData(""); tmp.AsInt = AsInt; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.IntValue); aWriter.Write(AsInt); return; } tmp.AsFloat = AsFloat; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.FloatValue); aWriter.Write(AsFloat); return; } tmp.AsDouble = AsDouble; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.DoubleValue); aWriter.Write(AsDouble); return; } tmp.AsBool = AsBool; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.BoolValue); aWriter.Write(AsBool); return; } aWriter.Write((byte)JSONBinaryTag.Value); aWriter.Write(m_Data); } } // End of JSONData internal class JSONLazyCreator : JSONNode { private JSONNode m_Node = null; private string m_Key = null; public JSONLazyCreator(JSONNode aNode) { m_Node = aNode; m_Key = null; } public JSONLazyCreator(JSONNode aNode, string aKey) { m_Node = aNode; m_Key = aKey; } private void Set(JSONNode aVal) { if (m_Key == null) { m_Node.Add(aVal); } else { m_Node.Add(m_Key, aVal); } m_Node = null; // Be GC friendly. } public override JSONNode this[int aIndex] { get { return new JSONLazyCreator(this); } set { var tmp = new JSONArray(); tmp.Add(value); Set(tmp); } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this, aKey); } set { var tmp = new JSONClass(); tmp.Add(aKey, value); Set(tmp); } } public override void Add (JSONNode aItem) { var tmp = new JSONArray(); tmp.Add(aItem); Set(tmp); } public override void Add (string aKey, JSONNode aItem) { var tmp = new JSONClass(); tmp.Add(aKey, aItem); Set(tmp); } public static bool operator ==(JSONLazyCreator a, object b) { if (b == null) return true; return System.Object.ReferenceEquals(a,b); } public static bool operator !=(JSONLazyCreator a, object b) { return !(a == b); } public override bool Equals (object obj) { if (obj == null) return true; return System.Object.ReferenceEquals(this, obj); } public override int GetHashCode () { return base.GetHashCode(); } public override string ToString() { return ""; } public override string ToString(string aPrefix) { return ""; } public override int AsInt { get { JSONData tmp = new JSONData(0); Set(tmp); return 0; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override float AsFloat { get { JSONData tmp = new JSONData(0.0f); Set(tmp); return 0.0f; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override double AsDouble { get { JSONData tmp = new JSONData(0.0); Set(tmp); return 0.0; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override bool AsBool { get { JSONData tmp = new JSONData(false); Set(tmp); return false; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override JSONArray AsArray { get { JSONArray tmp = new JSONArray(); Set(tmp); return tmp; } } public override JSONClass AsObject { get { JSONClass tmp = new JSONClass(); Set(tmp); return tmp; } } } // End of JSONLazyCreator public static class JSON { public static JSONNode Parse(string aJSON) { return JSONNode.Parse(aJSON); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Net; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Statistics; using OpenSim.Data; namespace OpenSim.Framework.Communications.Services { public abstract class LoginService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_welcomeMessage = "Welcome to InWorldz"; protected string m_MapServerURI = String.Empty; protected string m_ProfileServerURI = String.Empty; protected int m_minLoginLevel = 0; protected UserProfileManager m_userManager = null; /// <summary> /// Used during login to send the skeleton of the OpenSim Library to the client. /// </summary> protected LibraryRootFolder m_libraryRootFolder; protected uint m_defaultHomeX; protected uint m_defaultHomeY; private const string BAD_VIEWERS_FILE = "badviewers.txt"; private List<string> _badViewerStrings = new List<string>(); // For new users' first-time logins private const string DEFAULT_LOGINS_FILE = "defaultlogins.txt"; private List<string> _DefaultLoginsList = new List<string>(); // For returning users' where the preferred region is down private const string DEFAULT_REGIONS_FILE = "defaultregions.txt"; private List<string> _DefaultRegionsList = new List<string>(); /// <summary> /// LoadStringListFromFile /// </summary> /// <param name="theList"></param> /// <param name="fn"></param> /// <param name="desc"></param> private void LoadStringListFromFile(List<string> theList, string fn, string desc) { if (File.Exists(fn)) { using (System.IO.StreamReader file = new System.IO.StreamReader(fn)) { string line; while ((line = file.ReadLine()) != null) { line = line.Trim(); if (!String.IsNullOrEmpty(line) && !line.StartsWith(";") && !line.StartsWith("//")) { theList.Add(line); m_log.InfoFormat("[LOGINSERVICE] Added {0} {1}", desc, line); } } } } } /// <summary> /// Constructor /// </summary> /// <param name="userManager"></param> /// <param name="libraryRootFolder"></param> /// <param name="welcomeMess"></param> public LoginService(UserProfileManager userManager, LibraryRootFolder libraryRootFolder, string welcomeMess, string mapServerURI, string profileServerURI) { m_userManager = userManager; m_libraryRootFolder = libraryRootFolder; if (!String.IsNullOrEmpty(welcomeMess)) m_welcomeMessage = welcomeMess; if (!String.IsNullOrEmpty(mapServerURI)) m_MapServerURI = mapServerURI; if (!String.IsNullOrEmpty(profileServerURI)) m_ProfileServerURI = profileServerURI; // For new users' first-time logins LoadDefaultLoginsFromFile(DEFAULT_LOGINS_FILE); // For returning users' where the preferred region is down LoadDefaultRegionsFromFile(DEFAULT_REGIONS_FILE); LoadStringListFromFile(_badViewerStrings, BAD_VIEWERS_FILE, "blacklisted viewer"); } /// <summary> /// If the user is already logged in, try to notify the region that the user they've got is dead. /// </summary> /// <param name="theUser"></param> public virtual void LogOffUser(UserProfileData theUser, string message) { } public void DumpRegionsList(List<string> theList, string desc) { m_log.Info(desc + ":"); foreach (string location in theList) m_log.Info(" " + location); } public List<string> LoadRegionsFromFile(string fileName, string desc) { List<string> newList = new List<string>(); LoadStringListFromFile(newList, fileName, desc); if (newList.Count < 1) m_log.ErrorFormat("{0}: No locations found.", fileName); else m_log.InfoFormat("{0} updated with {1} locations.", desc, newList.Count); return newList; } // For new users' first-time logins public void LoadDefaultLoginsFromFile(string fileName) { if (String.IsNullOrEmpty(fileName)) DumpRegionsList(_DefaultLoginsList, "Default login locations for new users"); else _DefaultLoginsList = LoadRegionsFromFile(fileName, "Default login locations for new users"); } // For returning users' where the preferred region is down public void LoadDefaultRegionsFromFile(string fileName) { if (String.IsNullOrEmpty(fileName)) DumpRegionsList(_DefaultRegionsList, "Default region locations"); else _DefaultRegionsList = LoadRegionsFromFile(fileName, "Default region locations"); } private const string BANS_FILE = "bans.txt"; private List<string> bannedIPs = new List<string>(); private DateTime bannedIPsLoadedAt = DateTime.MinValue; private void LoadBannedIPs() { if (File.Exists(BANS_FILE)) { DateTime changedAt = File.GetLastWriteTime(BANS_FILE); lock (bannedIPs) // don't reload it in parallel, block login if reloading { if ( changedAt > bannedIPsLoadedAt) { bannedIPsLoadedAt = DateTime.Now; bannedIPs.Clear(); string[] lines = File.ReadAllLines("bans.txt"); foreach (string line in lines) { bannedIPs.Add(line.Trim()); } } } } } // Assumes IPstr is trimmed. private bool IsBannedIP(string IPstr) { LoadBannedIPs(); // refresh, if changed lock (bannedIPs) { foreach (string ban in bannedIPs) { if (IPstr.StartsWith(ban)) return true; } } return false; } private HashSet<string> _loginsProcessing = new HashSet<string>(); /// <summary> /// Called when we receive the client's initial XMLRPC login_to_simulator request message /// </summary> /// <param name="request">The XMLRPC request</param> /// <returns>The response to send</returns> public virtual XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient) { string loginUsername = null; try { LoginResponse logResponse = new LoginResponse(); IPAddress IPaddr = remoteClient.Address; string IPstr = IPaddr.ToString(); if (this.IsBannedIP(IPstr)) { m_log.WarnFormat("[LOGIN]: Denying login, IP {0} is BANNED.", IPstr); return logResponse.CreateIPBannedResponseLLSD(); } XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; SniffLoginKey((Uri)request.Params[2], requestData); bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") && (requestData.Contains("passwd") || requestData.Contains("web_login_key"))); string firstname = null; string lastname = null; if (GoodXML) { //make sure the user isn't already trying to log in firstname = (string)requestData["first"]; lastname = (string)requestData["last"]; loginUsername = firstname + " " + lastname; lock (_loginsProcessing) { if (_loginsProcessing.Contains(loginUsername)) { return logResponse.CreateAlreadyLoggedInResponse(); } else { _loginsProcessing.Add(loginUsername); } } } string startLocationRequest = "last"; UserProfileData userProfile; string clientChannel = "Unknown"; string clientVersion = "Unknown"; string clientPlatform = "Unknown"; string clientPlatformVer = "Unknown"; if (GoodXML) { if (requestData.Contains("start")) { startLocationRequest = (string)requestData["start"]; } m_log.InfoFormat( "[LOGIN BEGIN]: XMLRPC Received login request message from user '{0}' '{1}'", firstname, lastname); if (requestData.Contains("channel")) { clientChannel = (string)requestData["channel"]; } if (requestData.Contains("version")) { clientVersion = (string)requestData["version"]; } if (requestData.Contains("platform")) { clientPlatform = (string)requestData["platform"]; } if (requestData.Contains("platform_version")) { clientPlatformVer = (string)requestData["platform_version"]; } if (this.IsViewerBlacklisted(clientVersion)) { m_log.WarnFormat("[LOGIN]: Denying login, Client {0} is blacklisted", clientVersion); return logResponse.CreateViewerNotAllowedResponse(); } m_log.InfoFormat( "[LOGIN]: XMLRPC Client is {0} {1} on {2} {3}, start location is {4}", clientChannel, clientVersion, clientPlatform, clientPlatformVer, startLocationRequest); if (!TryAuthenticateXmlRpcLogin(request, firstname, lastname, out userProfile)) { return logResponse.CreateLoginFailedResponse(); } } else { m_log.Info("[LOGIN END]: XMLRPC login_to_simulator login message did not contain all the required data"); return logResponse.CreateGridErrorResponse(); } if (userProfile.GodLevel < m_minLoginLevel) { return logResponse.CreateLoginBlockedResponse(); } else { // If we already have a session... if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline) { // Force a refresh for this due to Commit below UUID userID = userProfile.ID; userProfile = m_userManager.GetUserProfile(userID,true); // on an error, return the former error we returned before recovery was supported. if (userProfile == null) return logResponse.CreateAlreadyLoggedInResponse(); //TODO: The following statements can cause trouble: // If agentOnline could not turn from true back to false normally // because of some problem, for instance, the crashment of server or client, // the user cannot log in any longer. userProfile.CurrentAgent.AgentOnline = false; userProfile.CurrentAgent.LogoutTime = Util.UnixTimeSinceEpoch(); m_userManager.CommitAgent(ref userProfile); // try to tell the region that their user is dead. LogOffUser(userProfile, " XMLRPC You were logged off because you logged in from another location"); // Don't reject the login. We've already cleaned it up, above. m_log.InfoFormat( "[LOGIN END]: XMLRPC Reset user {0} {1} that we believe is already logged in", firstname, lastname); // return logResponse.CreateAlreadyLoggedInResponse(); } // Otherwise... // Create a new agent session m_userManager.ResetAttachments(userProfile.ID); CreateAgent(userProfile, request); // We need to commit the agent right here, even though the userProfile info is not complete // at this point. There is another commit further down. // This is for the new sessionID to be stored so that the region can check it for session authentication. // CustomiseResponse->PrepareLoginToRegion CommitAgent(ref userProfile); try { UUID agentID = userProfile.ID; InventoryData inventData = null; try { inventData = GetInventorySkeleton(agentID); } catch (Exception e) { m_log.ErrorFormat( "[LOGIN END]: Error retrieving inventory skeleton of agent {0} - {1}", agentID, e); return logResponse.CreateLoginInventoryFailedResponse(); } if (inventData != null) { ArrayList AgentInventoryArray = inventData.InventoryArray; Hashtable InventoryRootHash = new Hashtable(); InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString(); ArrayList InventoryRoot = new ArrayList(); InventoryRoot.Add(InventoryRootHash); userProfile.RootInventoryFolderID = inventData.RootFolderID; logResponse.InventoryRoot = InventoryRoot; logResponse.InventorySkeleton = AgentInventoryArray; } // Inventory Library Section Hashtable InventoryLibRootHash = new Hashtable(); InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000"; ArrayList InventoryLibRoot = new ArrayList(); InventoryLibRoot.Add(InventoryLibRootHash); logResponse.InventoryLibRoot = InventoryLibRoot; logResponse.InventoryLibraryOwner = GetLibraryOwner(); logResponse.InventoryLibrary = GetInventoryLibrary(); logResponse.CircuitCode = Util.RandomClass.Next(); logResponse.Lastname = userProfile.SurName; logResponse.Firstname = userProfile.FirstName; logResponse.AgentID = agentID; logResponse.SessionID = userProfile.CurrentAgent.SessionID; logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; logResponse.Message = GetMessage(); logResponse.MapServerURI = m_MapServerURI; logResponse.ProfileServerURI = m_ProfileServerURI; logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID)); logResponse.StartLocation = startLocationRequest; // m_log.WarnFormat("[LOGIN END]: >>> Login response for {0} SSID={1}", logResponse.AgentID, logResponse.SecureSessionID); if (CustomiseResponse(logResponse, userProfile, startLocationRequest, clientVersion)) { userProfile.LastLogin = userProfile.CurrentAgent.LoginTime; CommitAgent(ref userProfile); // If we reach this point, then the login has successfully logged onto the grid if (StatsManager.UserStats != null) StatsManager.UserStats.AddSuccessfulLogin(); m_log.DebugFormat( "[LOGIN END]: XMLRPC Authentication of user {0} {1} successful. Sending response to client.", firstname, lastname); return logResponse.ToXmlRpcResponse(); } else { m_log.ErrorFormat("[LOGIN END]: XMLRPC informing user {0} {1} that login failed due to an unavailable region", firstname, lastname); return logResponse.CreateDeadRegionResponse(); } } catch (Exception e) { m_log.Error("[LOGIN END]: XMLRPC Login failed, " + e); m_log.Error(e.StackTrace); } } m_log.Info("[LOGIN END]: XMLRPC Login failed. Sending back blank XMLRPC response"); return response; } finally { if (loginUsername != null) { lock (_loginsProcessing) { _loginsProcessing.Remove(loginUsername); } } } } private bool IsViewerBlacklisted(string clientVersion) { foreach (string badClient in _badViewerStrings) { if (clientVersion.Contains(badClient)) { return true; } } return false; } protected virtual bool TryAuthenticateXmlRpcLogin( XmlRpcRequest request, string firstname, string lastname, out UserProfileData userProfile) { Hashtable requestData = (Hashtable)request.Params[0]; bool GoodLogin = false; userProfile = GetTheUser(firstname, lastname); if (userProfile == null) { m_log.Info("[LOGIN END]: XMLRPC Could not find a profile for " + firstname + " " + lastname); } else { if (requestData.Contains("passwd")) { string passwd = (string)requestData["passwd"]; GoodLogin = AuthenticateUser(userProfile, passwd); } if (!GoodLogin && (requestData.Contains("web_login_key"))) { try { UUID webloginkey = new UUID((string)requestData["web_login_key"]); GoodLogin = AuthenticateUser(userProfile, webloginkey); } catch (Exception e) { m_log.InfoFormat( "[LOGIN END]: XMLRPC Bad web_login_key: {0} for user {1} {2}, exception {3}", requestData["web_login_key"], firstname, lastname, e); } } } return GoodLogin; } protected virtual bool TryAuthenticateLLSDLogin(string firstname, string lastname, string passwd, out UserProfileData userProfile) { bool GoodLogin = false; userProfile = GetTheUser(firstname, lastname); if (userProfile == null) { m_log.Info("[LOGIN]: LLSD Could not find a profile for " + firstname + " " + lastname); return false; } GoodLogin = AuthenticateUser(userProfile, passwd); return GoodLogin; } public Hashtable ProcessHTMLLogin(Hashtable keysvals) { // Matches all unspecified characters // Currently specified,; lowercase letters, upper case letters, numbers, underline // period, space, parens, and dash. Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]"); Hashtable returnactions = new Hashtable(); int statuscode = 200; string firstname = String.Empty; string lastname = String.Empty; string location = String.Empty; string region = String.Empty; string grid = String.Empty; string channel = String.Empty; string version = String.Empty; string lang = String.Empty; string password = String.Empty; string errormessages = String.Empty; // the client requires the HTML form field be named 'username' // however, the data it sends when it loads the first time is 'firstname' // another one of those little nuances. if (keysvals.Contains("firstname")) firstname = wfcut.Replace((string)keysvals["firstname"], String.Empty, 99999); if (keysvals.Contains("username")) firstname = wfcut.Replace((string)keysvals["username"], String.Empty, 99999); if (keysvals.Contains("lastname")) lastname = wfcut.Replace((string)keysvals["lastname"], String.Empty, 99999); if (keysvals.Contains("location")) location = wfcut.Replace((string)keysvals["location"], String.Empty, 99999); if (keysvals.Contains("region")) region = wfcut.Replace((string)keysvals["region"], String.Empty, 99999); if (keysvals.Contains("grid")) grid = wfcut.Replace((string)keysvals["grid"], String.Empty, 99999); if (keysvals.Contains("channel")) channel = wfcut.Replace((string)keysvals["channel"], String.Empty, 99999); if (keysvals.Contains("version")) version = wfcut.Replace((string)keysvals["version"], String.Empty, 99999); if (keysvals.Contains("lang")) lang = wfcut.Replace((string)keysvals["lang"], String.Empty, 99999); if (keysvals.Contains("password")) password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999); // load our login form. string loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); if (keysvals.ContainsKey("show_login_form")) { UserProfileData user = GetTheUser(firstname, lastname); bool goodweblogin = false; if (user != null) goodweblogin = AuthenticateUser(user, password); if (goodweblogin) { UUID webloginkey = UUID.Random(); m_userManager.StoreWebLoginKey(user.ID, webloginkey); //statuscode = 301; // string redirectURL = "about:blank?redirect-http-hack=" + // HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" + // lastname + // "&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString()); //m_log.Info("[WEB]: R:" + redirectURL); returnactions["int_response_code"] = statuscode; //returnactions["str_redirect_location"] = redirectURL; //returnactions["str_response_string"] = "<HTML><BODY>GoodLogin</BODY></HTML>"; returnactions["str_response_string"] = webloginkey.ToString(); } else { errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again"; loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); returnactions["int_response_code"] = statuscode; returnactions["str_response_string"] = loginform; } } else { returnactions["int_response_code"] = statuscode; returnactions["str_response_string"] = loginform; } return returnactions; } public string GetLoginForm(string firstname, string lastname, string location, string region, string grid, string channel, string version, string lang, string password, string errormessages) { // inject our values in the form at the markers string loginform = String.Empty; string file = Path.Combine(Util.configDir(), "http_loginform.html"); if (!File.Exists(file)) { loginform = GetDefaultLoginForm(); } else { StreamReader sr = File.OpenText(file); loginform = sr.ReadToEnd(); sr.Close(); } loginform = loginform.Replace("[$firstname]", firstname); loginform = loginform.Replace("[$lastname]", lastname); loginform = loginform.Replace("[$location]", location); loginform = loginform.Replace("[$region]", region); loginform = loginform.Replace("[$grid]", grid); loginform = loginform.Replace("[$channel]", channel); loginform = loginform.Replace("[$version]", version); loginform = loginform.Replace("[$lang]", lang); loginform = loginform.Replace("[$password]", password); loginform = loginform.Replace("[$errors]", errormessages); return loginform; } public string GetDefaultLoginForm() { string responseString = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; responseString += "<html xmlns=\"http://www.w3.org/1999/xhtml\">"; responseString += "<head>"; responseString += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"; responseString += "<meta http-equiv=\"cache-control\" content=\"no-cache\">"; responseString += "<meta http-equiv=\"Pragma\" content=\"no-cache\">"; responseString += "<title>InWorldz Login</title>"; responseString += "<body><br />"; responseString += "<div id=\"login_box\">"; responseString += "<form action=\"/go.cgi\" method=\"GET\" id=\"login-form\">"; responseString += "<div id=\"message\">[$errors]</div>"; responseString += "<fieldset id=\"firstname\">"; responseString += "<legend>First Name:</legend>"; responseString += "<input type=\"text\" id=\"firstname_input\" size=\"15\" maxlength=\"100\" name=\"username\" value=\"[$firstname]\" />"; responseString += "</fieldset>"; responseString += "<fieldset id=\"lastname\">"; responseString += "<legend>Last Name:</legend>"; responseString += "<input type=\"text\" size=\"15\" maxlength=\"100\" name=\"lastname\" value=\"[$lastname]\" />"; responseString += "</fieldset>"; responseString += "<fieldset id=\"password\">"; responseString += "<legend>Password:</legend>"; responseString += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"; responseString += "<tr>"; responseString += "<td colspan=\"2\"><input type=\"password\" size=\"15\" maxlength=\"100\" name=\"password\" value=\"[$password]\" /></td>"; responseString += "</tr>"; responseString += "<tr>"; responseString += "<td valign=\"middle\"><input type=\"checkbox\" name=\"remember_password\" id=\"remember_password\" [$remember_password] style=\"margin-left:0px;\"/></td>"; responseString += "<td><label for=\"remember_password\">Remember password</label></td>"; responseString += "</tr>"; responseString += "</table>"; responseString += "</fieldset>"; responseString += "<input type=\"hidden\" name=\"show_login_form\" value=\"FALSE\" />"; responseString += "<input type=\"hidden\" name=\"method\" value=\"login\" />"; responseString += "<input type=\"hidden\" id=\"grid\" name=\"grid\" value=\"[$grid]\" />"; responseString += "<input type=\"hidden\" id=\"region\" name=\"region\" value=\"[$region]\" />"; responseString += "<input type=\"hidden\" id=\"location\" name=\"location\" value=\"[$location]\" />"; responseString += "<input type=\"hidden\" id=\"channel\" name=\"channel\" value=\"[$channel]\" />"; responseString += "<input type=\"hidden\" id=\"version\" name=\"version\" value=\"[$version]\" />"; responseString += "<input type=\"hidden\" id=\"lang\" name=\"lang\" value=\"[$lang]\" />"; responseString += "<div id=\"submitbtn\">"; responseString += "<input class=\"input_over\" type=\"submit\" value=\"Connect\" />"; responseString += "</div>"; responseString += "<div id=\"connecting\" style=\"visibility:hidden\"> Connecting...</div>"; responseString += "<div id=\"helplinks\"><!---"; responseString += "<a href=\"#join now link\" target=\"_blank\"></a> | "; responseString += "<a href=\"#forgot password link\" target=\"_blank\"></a>"; responseString += "---></div>"; responseString += "<div id=\"channelinfo\"> [$channel] | [$version]=[$lang]</div>"; responseString += "</form>"; responseString += "<script language=\"JavaScript\">"; responseString += "document.getElementById('firstname_input').focus();"; responseString += "</script>"; responseString += "</div>"; responseString += "</div>"; responseString += "</body>"; responseString += "</html>"; return responseString; } /// <summary> /// Saves a target agent to the database /// </summary> /// <param name="profile">The users profile</param> /// <returns>Successful?</returns> public bool CommitAgent(ref UserProfileData profile) { return m_userManager.CommitAgent(ref profile); } /// <summary> /// Checks a user against it's password hash /// </summary> /// <param name="profile">The users profile</param> /// <param name="password">The supplied password</param> /// <returns>Authenticated?</returns> public virtual bool AuthenticateUser(UserProfileData profile, string password) { bool passwordSuccess = false; //m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); // Web Login method seems to also occasionally send the hashed password itself // we do this to get our hash in a form that the server password code can consume // when the web-login-form submits the password in the clear (supposed to be over SSL!) if (!password.StartsWith("$1$")) password = "$1$" + Util.Md5Hash(password); password = password.Remove(0, 3); //remove $1$ string s = Util.Md5Hash(password + ":" + profile.PasswordSalt); // Testing... //m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash); //m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password); passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase) || profile.PasswordHash.Equals(password, StringComparison.InvariantCultureIgnoreCase)); return passwordSuccess; } public virtual bool AuthenticateUser(UserProfileData profile, UUID webloginkey) { bool passwordSuccess = false; m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); // Match web login key unless it's the default weblogin key UUID.Zero passwordSuccess = ((profile.WebLoginKey == webloginkey) && profile.WebLoginKey != UUID.Zero); return passwordSuccess; } /// <summary> /// /// </summary> /// <param name="profile"></param> /// <param name="request"></param> public void CreateAgent(UserProfileData profile, XmlRpcRequest request) { m_userManager.CreateAgent(profile, request); } public void CreateAgent(UserProfileData profile, OSD request) { m_userManager.CreateAgent(profile, request); } /// <summary> /// /// </summary> /// <param name="firstname"></param> /// <param name="lastname"></param> /// <returns></returns> public virtual UserProfileData GetTheUser(string firstname, string lastname) { // Login service must always force a refresh here, since local/VM User server may have updated data on logout. return m_userManager.GetUserProfile(firstname, lastname, true); } /// <summary> /// /// </summary> /// <returns></returns> public virtual string GetMessage() { return m_welcomeMessage; } private static LoginResponse.BuddyList ConvertFriendListItem(List<FriendListItem> LFL) { LoginResponse.BuddyList buddylistreturn = new LoginResponse.BuddyList(); foreach (FriendListItem fl in LFL) { LoginResponse.BuddyList.BuddyInfo buddyitem = new LoginResponse.BuddyList.BuddyInfo(fl.Friend); buddyitem.BuddyID = fl.Friend; buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms; buddyitem.BuddyRightsGiven = (int)fl.FriendPerms; buddylistreturn.AddNewBuddy(buddyitem); } return buddylistreturn; } /// <summary> /// Converts the inventory library skeleton into the form required by the rpc request. /// </summary> /// <returns></returns> protected virtual ArrayList GetInventoryLibrary() { Dictionary<UUID, InventoryFolderImpl> rootFolders = m_libraryRootFolder.RequestSelfAndDescendentFolders(); ArrayList folderHashes = new ArrayList(); foreach (InventoryFolderBase folder in rootFolders.Values) { Hashtable TempHash = new Hashtable(); TempHash["name"] = folder.Name; TempHash["parent_id"] = folder.ParentID.ToString(); TempHash["version"] = (Int32)folder.Version; TempHash["type_default"] = (Int32)folder.Type; TempHash["folder_id"] = folder.ID.ToString(); folderHashes.Add(TempHash); } return folderHashes; } /// <summary> /// /// </summary> /// <returns></returns> protected virtual ArrayList GetLibraryOwner() { //for now create random inventory library owner Hashtable TempHash = new Hashtable(); TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000"; ArrayList inventoryLibOwner = new ArrayList(); inventoryLibOwner.Add(TempHash); return inventoryLibOwner; } public class InventoryData { public ArrayList InventoryArray = null; public UUID RootFolderID = UUID.Zero; public InventoryData(ArrayList invList, UUID rootID) { InventoryArray = invList; RootFolderID = rootID; } } protected void SniffLoginKey(Uri uri, Hashtable requestData) { string uri_str = uri.ToString(); string[] parts = uri_str.Split(new char[] { '=' }); if (parts.Length > 1) { string web_login_key = parts[1]; requestData.Add("web_login_key", web_login_key); m_log.InfoFormat("[LOGIN]: Login with web_login_key {0}", web_login_key); } } protected bool PrepareLoginToREURI(Regex reURI, LoginResponse response, UserProfileData theUser, string startLocationRequest, string StartLocationType, string desc, string clientVersion) { string region; RegionInfo regionInfo = null; Match uriMatch = reURI.Match(startLocationRequest); if (uriMatch == null) { m_log.InfoFormat("[LOGIN]: Got {0} {1}, but can't process it", desc, startLocationRequest); return false; } region = uriMatch.Groups["region"].ToString(); regionInfo = RequestClosestRegion(region); if (regionInfo == null) { m_log.InfoFormat("[LOGIN]: Got {0} {1}, can't locate region {2}", desc, startLocationRequest, region); return false; } Vector3 newPos = new Vector3(float.Parse(uriMatch.Groups["x"].Value), float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value)); // m_log.WarnFormat("[LOGIN]: PrepareLoginToREURI for user {0} at {1} was {2}", theUser.ID, newPos, theUser.CurrentAgent.Position); theUser.CurrentAgent.Position = newPos; response.LookAt = "[r0,r1,r0]"; // can be: last, home, safe, url response.StartLocation = StartLocationType; return PrepareLoginToRegion(regionInfo, theUser, response, clientVersion); } protected bool PrepareNextRegion(LoginResponse response, UserProfileData theUser, List<string> theList, string startLocationRequest, string clientVersion) { Regex reURI = new Regex(@"^(?<region>[^&]+)/(?<x>\d+)/(?<y>\d+)/(?<z>\d+)$"); if ((startLocationRequest != "home") && (startLocationRequest != "last")) startLocationRequest = "safe"; foreach (string location in theList) { if (PrepareLoginToREURI(reURI, response, theUser, location, "safe", "default region", clientVersion)) return true; } return false; } // For new users' first-time logins protected bool PrepareNextDefaultLogin(LoginResponse response, UserProfileData theUser, string startLocationRequest, string clientVersion) { return PrepareNextRegion(response, theUser, _DefaultLoginsList, startLocationRequest, clientVersion); } // For returning users' where the preferred region is down protected bool PrepareNextDefaultRegion(LoginResponse response, UserProfileData theUser, string clientVersion) { return PrepareNextRegion(response, theUser, _DefaultRegionsList, "safe", clientVersion); } /// <summary> /// Customises the login response and fills in missing values. This method also tells the login region to /// expect a client connection. /// </summary> /// <param name="response">The existing response</param> /// <param name="theUser">The user profile</param> /// <param name="startLocationRequest">The requested start location</param> /// <returns>true on success, false if the region was not successfully told to expect a user connection</returns> public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest, string clientVersion) { // add active gestures to login-response AddActiveGestures(response, theUser); // HomeLocation RegionInfo homeInfo = null; // use the homeRegionID if it is stored already. If not, use the regionHandle as before UUID homeRegionId = theUser.HomeRegionID; ulong homeRegionHandle = theUser.HomeRegion; if (homeRegionId != UUID.Zero) { homeInfo = GetRegionInfo(homeRegionId); } else { homeInfo = GetRegionInfo(homeRegionHandle); } if (homeInfo != null) { response.Home = string.Format( "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", (homeInfo.RegionLocX * Constants.RegionSize), (homeInfo.RegionLocY * Constants.RegionSize), theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); } else { m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY); // Emergency mode: Home-region isn't available, so we can't request the region info. // Use the stored home regionHandle instead. // NOTE: If the home-region moves, this will be wrong until the users update their user-profile again ulong regionX = homeRegionHandle >> 32; ulong regionY = homeRegionHandle & 0xffffffff; response.Home = string.Format( "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", regionX, regionY, theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}", theUser.FirstName, theUser.SurName, regionX, regionY); } // StartLocation RegionInfo regionInfo = null; if (theUser.LastLogin == 0) { // New user first login if (PrepareNextDefaultLogin(response, theUser, startLocationRequest, clientVersion)) return true; } else { // Returning user login if (startLocationRequest == "home") { regionInfo = homeInfo; theUser.CurrentAgent.Position = theUser.HomeLocation; response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.HomeLookAt.X.ToString(), theUser.HomeLookAt.Y.ToString(), theUser.HomeLookAt.Z.ToString()); } else if (startLocationRequest == "last") { UUID lastRegion = theUser.CurrentAgent.Region; regionInfo = GetRegionInfo(lastRegion); response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.CurrentAgent.LookAt.X.ToString(), theUser.CurrentAgent.LookAt.Y.ToString(), theUser.CurrentAgent.LookAt.Z.ToString()); } else { // Logging in to a specific URL... try to find the region Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$"); if (PrepareLoginToREURI(reURI, response, theUser, startLocationRequest, "url", "Custom Login URL", clientVersion)) return true; } // Logging in to home or last... try to find the region if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response, clientVersion))) { return true; } // StartLocation not available, send him to a nearby region instead // regionInfo = m_gridService.RequestClosestRegion(String.Empty); //m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName); // Normal login failed, try to find an alternative region, starting with Home. if (homeInfo != null) { if ((regionInfo == null) || (regionInfo.RegionID != homeInfo.RegionID)) { regionInfo = homeInfo; theUser.CurrentAgent.Position = theUser.HomeLocation; response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.HomeLookAt.X.ToString(), theUser.HomeLookAt.Y.ToString(), theUser.HomeLookAt.Z.ToString()); m_log.InfoFormat("[LOGIN]: StartLocation not available, trying user's Home region {0}", regionInfo.RegionName); if (PrepareLoginToRegion(regionInfo, theUser, response, clientVersion)) return true; } } // No Home location available either, try to find a default region from the list if (PrepareNextDefaultRegion(response, theUser, clientVersion)) return true; } // No default regions available either. // Send him to global default region home location instead (e.g. 1000,1000) ulong defaultHandle = (((ulong)m_defaultHomeX * Constants.RegionSize) << 32) | ((ulong)m_defaultHomeY * Constants.RegionSize); if ((regionInfo != null) && (defaultHandle == regionInfo.RegionHandle)) { m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region"); return false; } m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); regionInfo = GetRegionInfo(defaultHandle); if (regionInfo == null) { m_log.ErrorFormat("[LOGIN]: No default region available. Aborting."); return false; } theUser.CurrentAgent.Position = new Vector3(128, 128, 0); response.StartLocation = "safe"; return PrepareLoginToRegion(regionInfo, theUser, response, clientVersion); } protected abstract RegionInfo RequestClosestRegion(string region); protected abstract RegionInfo GetRegionInfo(ulong homeRegionHandle); protected abstract RegionInfo GetRegionInfo(UUID homeRegionId); protected abstract bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, string clientVersion); /// <summary> /// Add active gestures of the user to the login response. /// </summary> /// <param name="response"> /// A <see cref="LoginResponse"/> /// </param> /// <param name="theUser"> /// A <see cref="UserProfileData"/> /// </param> protected void AddActiveGestures(LoginResponse response, UserProfileData theUser) { IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>(); IInventoryStorage inventory = inventorySelect.GetProvider(theUser.ID); List<InventoryItemBase> gestures = null; try { gestures = inventory.GetActiveGestureItems(theUser.ID); } catch (Exception e) { m_log.Debug("[LOGIN]: Unable to retrieve active gestures from inventory server. Reason: " + e.Message); } //m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count); ArrayList list = new ArrayList(); if (gestures != null) { foreach (InventoryItemBase gesture in gestures) { Hashtable item = new Hashtable(); item["item_id"] = gesture.ID.ToString(); item["asset_id"] = gesture.AssetID.ToString(); list.Add(item); } } response.ActiveGestures = list; } /// <summary> /// Get the initial login inventory skeleton (in other words, the folder structure) for the given user. /// </summary> /// <param name="userID"></param> /// <returns></returns> /// <exception cref='System.Exception'>This will be thrown if there is a problem with the inventory service</exception> protected InventoryData GetInventorySkeleton(UUID userID) { IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>(); IInventoryStorage inventory = inventorySelect.GetProvider(userID); List<InventoryFolderBase> folders = inventory.GetInventorySkeleton(userID); if (folders == null || folders.Count == 0) { throw new Exception( String.Format( "A root inventory folder for user {0} could not be retrieved from the inventory service", userID)); } UUID rootID = UUID.Zero; ArrayList AgentInventoryArray = new ArrayList(); Hashtable TempHash; foreach (InventoryFolderBase InvFolder in folders) { if (InvFolder.ParentID == UUID.Zero) { rootID = InvFolder.ID; } TempHash = new Hashtable(); TempHash["name"] = InvFolder.Name; TempHash["parent_id"] = InvFolder.ParentID.ToString(); TempHash["version"] = (Int32)InvFolder.Version; TempHash["type_default"] = (Int32)InvFolder.Type; TempHash["folder_id"] = InvFolder.ID.ToString(); AgentInventoryArray.Add(TempHash); } return new InventoryData(AgentInventoryArray, rootID); } protected virtual bool AllowLoginWithoutInventory() { return false; } public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; string authed = "FALSE"; if (requestData.Contains("avatar_uuid") && requestData.Contains("session_id")) { UUID guess_aid; // avatar ID UUID guess_sid; // session ID try { UUID.TryParse((string)requestData["avatar_uuid"], out guess_aid); if (guess_aid == UUID.Zero) { return Util.CreateUnknownUserErrorResponse(); } UUID.TryParse((string)requestData["session_id"], out guess_sid); if (guess_sid == UUID.Zero) { return Util.CreateUnknownUserErrorResponse(); } if (m_userManager.VerifySession(guess_aid, guess_sid)) { authed = "TRUE"; m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); } else { m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE for user {0}, refreshing caches", guess_aid); //purge the cache and retry m_userManager.FlushCachedInfo(guess_aid); if (m_userManager.VerifySession(guess_aid, guess_sid)) { authed = "TRUE"; m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); } else { m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE"); return Util.CreateUnknownUserErrorResponse(); } } } catch (Exception e) { m_log.ErrorFormat("[UserManager]: Unable to check auth session: {0}", e); return Util.CreateUnknownUserErrorResponse(); } } Hashtable responseData = new Hashtable(); responseData["auth_session"] = authed; response.Value = responseData; return response; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using OpenMetaverse; namespace OpenSim.Framework { /// <summary> /// Information about a particular user known to the userserver /// </summary> public class UserProfileData { /// <summary> /// A UNIX Timestamp (seconds since epoch) for the users creation /// </summary> private int m_created; /// <summary> /// The users last registered agent (filled in on the user server) /// </summary> private UserAgentData m_currentAgent; /// <summary> /// The first component of a users account name /// </summary> private string m_firstname; /// <summary> /// The coordinates inside the region of the home location /// </summary> private Vector3 m_homeLocation; /// <summary> /// Where the user will be looking when they rez. /// </summary> private Vector3 m_homeLookAt; private uint m_homeRegionX; private uint m_homeRegionY; /// <summary> /// The ID value for this user /// </summary> private UUID m_id; /// <summary> /// A UNIX Timestamp for the users last login date / time /// </summary> private int m_lastLogin; /// <summary> /// A salted hash containing the users password, in the format md5(md5(password) + ":" + salt) /// </summary> /// <remarks>This is double MD5'd because the client sends an unsalted MD5 to the loginserver</remarks> private string m_passwordHash; /// <summary> /// The salt used for the users hash, should be 32 bytes or longer /// </summary> private string m_passwordSalt; /// <summary> /// The about text listed in a users profile. /// </summary> private string m_profileAboutText = String.Empty; /// <summary> /// A uint mask containing the "I can do" fields of the users profile /// </summary> //private uint m_profileCanDoMask; /// <summary> /// The profile image for the users first life tab /// </summary> private UUID m_profileFirstImage; /// <summary> /// The first life about text listed in a users profile /// </summary> private string m_profileFirstText = String.Empty; /// <summary> /// The profile image for an avatar stored on the asset server /// </summary> private UUID m_profileImage; /// <summary> /// A uint mask containing the "I want to do" part of the users profile /// </summary> //private uint m_profileWantDoMask; // Profile window "I want to" mask private UUID m_rootInventoryFolderId; /// <summary> /// The second component of a users account name /// </summary> private string m_surname; /// <summary> /// A valid email address for the account. Useful for password reset requests. /// </summary> private string m_email = String.Empty; /// <summary> /// A URI to the users asset server, used for foreigners and large grids. /// </summary> private string m_userAssetUri = String.Empty; /// <summary> /// A URI to the users inventory server, used for foreigners and large grids /// </summary> private string m_userInventoryUri = String.Empty; /// <summary> /// The last used Web_login_key /// </summary> private UUID m_webLoginKey; // Data for estates and other goodies // to get away from per-machine configs a little // private int m_userFlags; private int m_godLevel; private string m_customType; private UUID m_partner; /* 12/09/2009 - Ele's Edit for maybe someday getting profile web url to work on the profile * listing! */ private string m_profileURL; /// <summary> /// The regionhandle of the users preferred home region. If /// multiple sims occupy the same spot, the grid may decide /// which region the user logs into /// </summary> public virtual ulong HomeRegion { get { return Utils.UIntsToLong( m_homeRegionX * (uint)Constants.RegionSize, m_homeRegionY * (uint)Constants.RegionSize); } set { m_homeRegionX = (uint) (value >> 40); m_homeRegionY = (((uint) (value)) >> 8); } } private UUID m_homeRegionId; /// <summary> /// The regionID of the users home region. This is unique; /// even if the position of the region changes within the /// grid, this will refer to the same region. /// </summary> public UUID HomeRegionID { get { return m_homeRegionId; } set { m_homeRegionId = value; } } // Property wrappers public UUID ID { get { return m_id; } set { m_id = value; } } public UUID WebLoginKey { get { return m_webLoginKey; } set { m_webLoginKey = value; } } public string FirstName { get { return m_firstname; } set { m_firstname = value; } } public string SurName { get { return m_surname; } set { m_surname = value; } } /// <value> /// The concatentation of the various name components. /// </value> public string Name { get { return String.Format("{0} {1}", m_firstname, m_surname); } } public string Email { get { return m_email; } set { m_email = value; } } public string PasswordHash { get { return m_passwordHash; } set { m_passwordHash = value; } } public string PasswordSalt { get { return m_passwordSalt; } set { m_passwordSalt = value; } } public uint HomeRegionX { get { return m_homeRegionX; } set { m_homeRegionX = value; } } public uint HomeRegionY { get { return m_homeRegionY; } set { m_homeRegionY = value; } } public Vector3 HomeLocation { get { return m_homeLocation; } set { m_homeLocation = value; } } // for handy serialization public float HomeLocationX { get { return m_homeLocation.X; } set { m_homeLocation.X = value; } } public float HomeLocationY { get { return m_homeLocation.Y; } set { m_homeLocation.Y = value; } } public float HomeLocationZ { get { return m_homeLocation.Z; } set { m_homeLocation.Z = value; } } public Vector3 HomeLookAt { get { return m_homeLookAt; } set { m_homeLookAt = value; } } // for handy serialization public float HomeLookAtX { get { return m_homeLookAt.X; } set { m_homeLookAt.X = value; } } public float HomeLookAtY { get { return m_homeLookAt.Y; } set { m_homeLookAt.Y = value; } } public float HomeLookAtZ { get { return m_homeLookAt.Z; } set { m_homeLookAt.Z = value; } } public int Created { get { return m_created; } set { m_created = value; } } public int LastLogin { get { return m_lastLogin; } set { m_lastLogin = value; } } public UUID RootInventoryFolderID { get { return m_rootInventoryFolderId; } set { m_rootInventoryFolderId = value; } } public string UserInventoryURI { get { return m_userInventoryUri; } set { m_userInventoryUri = value; } } public string UserAssetURI { get { return m_userAssetUri; } set { m_userAssetUri = value; } } public string AboutText { get { return m_profileAboutText; } set { m_profileAboutText = value; } } public string FirstLifeAboutText { get { return m_profileFirstText; } set { m_profileFirstText = value; } } public UUID Image { get { return m_profileImage; } set { m_profileImage = value; } } public UUID FirstLifeImage { get { return m_profileFirstImage; } set { m_profileFirstImage = value; } } public UserAgentData CurrentAgent { get { return m_currentAgent; } set { m_currentAgent = value; } } public int UserFlags { get { return m_userFlags; } set { m_userFlags = value; } } public int GodLevel { get { return m_godLevel; } set { m_godLevel = value; } } public string CustomType { get { return m_customType; } set { m_customType = value; } } public UUID Partner { get { return m_partner; } set { m_partner = value; } } // 12/09/2009 - Ele's edit for profile web url to work public string ProfileURL { get { return m_profileURL; } set { m_profileURL = value; } } } }
// Author: Ghalib Ghniem [email protected] // Created: 2015-04-12 // Last Modified: 2015-04-12 // using System; using System.Collections.ObjectModel; using System.Web.UI.WebControls; using System.Collections.Generic; using log4net; using mojoPortal.Business; using mojoPortal.Business.WebHelpers; using mojoPortal.Web.Framework; using mojoPortal.Web.AdminUI; using mojoPortal.Web; using iQuran.Business; using iQuran.Web.Helper; using Resources; using mojoPortal.Web.Editor; namespace iQuran.Web.UI.AdminUI { public partial class iVerseManager : NonCmsBasePage { private static readonly ILog log = LogManager.GetLogger(typeof(iVerseManager)); protected string AddNewPropertiesImage = "~/Data/SiteImages/add.gif"; protected string EditPropertiesImage = "~/Data/SiteImages/" + WebConfigSettings.EditPropertiesImage; protected string DeleteLinkImage = "~/Data/SiteImages/" + WebConfigSettings.DeleteLinkImage; private bool canAdministrate = false; protected bool IsUserAdmin = false; private SiteUser currentUser = null; private int quranID = 0; private int suraID = 0; private string quranLanguage = string.Empty; private bool isTranslation = false; #region Pager Properties private string BindByWhat = "all"; private string sortParam = string.Empty; private string sort = "VerseOrder"; private string searchParam = string.Empty; private string search = string.Empty; private string searchTitleParam = string.Empty; private string searchTitle = string.Empty; private bool searchIsActive = false; private int pageNumber = 1; private int pageSize = 0; private int totalPages = 0; #endregion protected void Page_Load(object sender, EventArgs e) { LoadSettings(); if (!this.canAdministrate) { SiteUtils.RedirectToAccessDeniedPage(this); return; } pageSize = 30; LoadPager(); if (!Page.IsPostBack) { PopulateLabels(); PopulateControls(); } //FilliQuran(); } private void LoadSettings() { if ((WebUser.IsInRole("iQuranManagers")) || (WebUser.IsInRole("iQuranContentsAdmins")) || (WebUser.IsAdmin)) this.canAdministrate = true; else this.canAdministrate = false; if (WebUser.IsAdmin) IsUserAdmin = true; SecurityHelper.DisableBrowserCache(); lnkAdminMenu.Visible = (WebUser.IsAdmin); AddClassToBody("administration"); AddClassToBody("rolemanager"); } private void LoadPager() { pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", 1); if (Page.Request.Params["sort"] != null) { sort = Page.Request.Params["sort"]; } if (Page.Request.Params["qid"] != null) { this.quranID = int.Parse(Page.Request.Params["qid"].ToString()); hdnQuranID.Value = this.quranID.ToString(); } if (Page.Request.Params["sid"] != null) { this.suraID = int.Parse(Page.Request.Params["sid"].ToString()); hdnSuraID.Value = this.suraID.ToString(); } //lblmessage string status1 = WebUtils.ParseStringFromQueryString("st", ""); if (status1.Trim() == "ok") { divMsg.Visible = true; lblmessage.Visible = true; lblmessage.Text = Resources.iQuranMessagesResources.SuccessfullDelete; } if (status1.Trim() == "no") { lblmessage.Visible = true; lblmessage.Text = Resources.iQuranMessagesResources.FailedDelete; } searchTitleParam = "searchtitle"; if ((Page.Request.Params[searchTitleParam] != null) && (Page.Request.Params[searchTitleParam].Length > 0)) { searchTitle = Page.Request.Params[searchTitleParam]; BindByWhat = "title"; search = "0"; } else { searchTitle = string.Empty; searchParam = "search"; if (Page.Request.Params[searchParam] != null) { search = Page.Request.Params[searchParam]; switch (search) { //0: all , 1.active , 2.notactive case "0": default: BindByWhat = "all"; break; case "1": searchIsActive = true; BindByWhat = "active"; break; case "2": searchIsActive = false; BindByWhat = "notactive"; break; } } else { search = "0"; BindByWhat = "all"; } } sortParam = "sort"; if (Page.Request.Params[sortParam] != null) sort = Page.Request.Params[sortParam]; else sort = "VerseOrder"; } private void PopulateLabels() { Title = SiteUtils.FormatPageTitle(siteSettings, Resources.iQuranResources.AdminMenuiVerseManagerAdminLink); spnTitle.InnerText = Title; lnkAdminMenu.Text = Resource.AdminMenuLink; lnkAdminMenu.ToolTip = Resource.AdminMenuLink; lnkAdminMenu.NavigateUrl = SiteRoot + "/Admin/AdminMenu.aspx"; lnkAdvanced.Text = Resources.iQuranResources.AdvancedLink; lnkAdvanced.ToolTip = Resources.iQuranResources.AdvancedToolsHeading; lnkAdvanced.NavigateUrl = SiteRoot + "/Admin/AccessQuran/iQuranAdvanced.aspx"; lnkiQuranManagerAdmin.Text = Resources.iQuranResources.AdminMenuiQuranManagerAdminLink; lnkiQuranManagerAdmin.ToolTip = Resources.iQuranResources.AdminMenuiQuranManagerAdminLink; lnkiQuranManagerAdmin.NavigateUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iQuranManager.aspx"; lnkiSuraManagerAdmin.Text = Resources.iQuranResources.AdminMenuiSuraManagerAdminLink; lnkiSuraManagerAdmin.ToolTip = Resources.iQuranResources.AdminMenuiSuraManagerAdminLink; lnkiSuraManagerAdmin.NavigateUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iSuraManager.aspx"; lnkiVerseManagerAdmin.Text = Resources.iQuranResources.AdminMenuiVerseManagerAdminLink; lnkiVerseManagerAdmin.ToolTip = Resources.iQuranResources.AdminMenuiVerseManagerAdminLink; lnkiVerseManagerAdmin.NavigateUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iVerseManager.aspx"; lnkAddNew.Text = Resources.iQuranResources.AddNewiVerseHeader; lnkAddNew.ToolTip = Resources.iQuranResources.AddNewiVerseHeader; lnkAddNew.Visible = (WebUser.IsInRole("iQuranManagers")) || (WebUser.IsAdmin); btnSearchTitle.AlternateText = Resources.iQuranResources.SearchByTitleHeader; btnSearchTitle.ToolTip = Resources.iQuranResources.SearchByTitleHeader; //lblmessage.Visible = false; //divMsg.Visible = false; } private void PopulateControls() { FilliQuran(); ddStatus.ClearSelection(); ddStatus.Items.FindByValue(search.ToString()).Selected = true; } private void FilliQuran() { //fill ddSelQuran this.ddSelQuran.DataSource = Quran.GetiQurans(this.SiteId); this.ddSelQuran.DataBind(); if (int.Parse(hdnQuranID.Value) > 0) this.quranID = int.Parse(hdnQuranID.Value); else this.quranID = int.Parse(ddSelQuran.SelectedItem.Value.ToString()); hdnQuranID.Value = this.quranID.ToString(); ddSelQuran.ClearSelection(); ddSelQuran.Items.FindByValue(this.quranID.ToString()).Selected = true; Quran q = new Quran(SiteId, this.quranID); this.quranLanguage = q.QLanguage; hdnQLang.Value = q.QLanguage; this.isTranslation = !q.IsDefault; if (this.quranID > 0) FilliSura(); } private void FilliSura() { //fill ddSelSura this.ddSelSura.DataSource = QuranSura.GetSuras(this.SiteId, this.quranID); this.ddSelSura.DataBind(); if (int.Parse(hdnSuraID.Value) > 0) this.suraID = int.Parse(hdnSuraID.Value); else this.suraID = int.Parse(ddSelSura.SelectedItem.Value.ToString()); hdnQuranID.Value = this.suraID.ToString(); ddSelSura.ClearSelection(); ddSelSura.Items.FindByValue(this.suraID.ToString()).Selected = true; if (this.suraID > 0) BindGrid(); } private void BindGrid() { lnkAddNew.NavigateUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iVerseEdit.aspx?qid=" + this.quranID + "&sid=" + this.suraID; //bool isAdmin = ((WebUser.IsInRole("iQuranManagers")) || (WebUser.IsInRole("iQuranContentsAdmins")) || (WebUser.IsAdmin)); // Get the Current Loged on UserID SiteUser siteUser = SiteUtils.GetCurrentSiteUser(); int userID = siteUser.UserId; List<QuranVerse> dataList = new List<QuranVerse>(); //0: all , 1.active , 2.notactive if (this.BindByWhat == "all") dataList = QuranVerse.GetPage_iVerse_All(siteSettings.SiteId, this.quranID, this.suraID, this.isTranslation, pageNumber, pageSize, out totalPages); //Search For Title if (this.BindByWhat == "title") dataList = QuranVerse.GetPage_iVerse_ByTitle(siteSettings.SiteId, this.quranID, this.suraID, this.isTranslation, this.searchTitle, pageNumber, pageSize, out totalPages); if ((this.BindByWhat == "active") || (this.BindByWhat == "notactive")) dataList = QuranVerse.GetPage_iVerse_ByActive(siteSettings.SiteId, this.quranID, this.suraID, searchIsActive, this.isTranslation, pageNumber, pageSize, out totalPages); string pageUrl = string.Empty; pageUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iVerseManager.aspx?" + "qid=" + this.quranID.ToInvariantString() + "&amp;sid=" + this.suraID.ToInvariantString() + "&amp;sort=" + this.sort + "&amp;search=" + this.search + "&amp;searchtitle=" + Server.UrlEncode(this.searchTitle) + "&amp;pagenumber={0}"; amsPager.PageURLFormat = pageUrl; amsPager.ShowFirstLast = true; amsPager.CurrentIndex = pageNumber; amsPager.PageSize = pageSize; amsPager.PageCount = totalPages; amsPager.Visible = (totalPages > 1); iQVGrid.DataSource = dataList; iQVGrid.PageIndex = pageNumber; iQVGrid.PageSize = pageSize; iQVGrid.DataBind(); if (iQVGrid.Rows.Count == 0) { lblmessage.Visible = true; divMsg.Visible = true; lblmessage.Text = Resources.iQuranMessagesResources.NoDataYet; } } private void SetRedirectString(bool withSuraID, bool withmsg, string Msg) { string redirectUrl = string.Empty; redirectUrl = SiteRoot + "/Admin/AccessQuran/iQuran/iVerseManager.aspx?" + "qid=" + int.Parse(hdnQuranID.Value.ToString()).ToInvariantString() + "&pagenumber=" + pageNumber.ToInvariantString() + "&sort=" + this.sort + "&search=" + this.search + "&searchtitle=" + Server.UrlEncode(this.searchTitle); if (withSuraID == true) redirectUrl += "&sid=" + int.Parse(hdnSuraID.Value.ToString()).ToInvariantString(); if (withmsg == true) redirectUrl += "&st=" + Msg; WebUtils.SetupRedirect(this, redirectUrl); } #region GRID EVENTS void iQVGrid_Sorting(object sender, GridViewSortEventArgs e) { this.sort = e.SortExpression; SetRedirectString(true,false,""); } protected void iQVGrid_RowDeleting(object sender, GridViewDeleteEventArgs e) { //DO Nothing; } void iQVGrid_RowCommand(object sender, GridViewCommandEventArgs e) { if (log.IsDebugEnabled) { log.Debug(this.PageTitle + " fired event iQVGrid_RowCommand"); } int iverseID = int.Parse(e.CommandArgument.ToString()); int siteid = siteSettings.SiteId; string dleteDate = String.Format(DateTime.Now.ToString(), "mm dd yyyy"); currentUser = SiteUtils.GetCurrentSiteUser(); int suraid = -1; QuranVerse iverse = null; // QuranVerseTranslation iverseTransl = null; if (this.hdnQLang.Value == "ar") iverse = new QuranVerse(siteid, int.Parse(hdnQuranID.Value), iverseID, false); else iverse = new QuranVerse(siteid, int.Parse(hdnQuranID.Value), iverseID, true); //iverseTransl = new QuranVerseTranslation(siteid, int.Parse(hdnQuranID.Value), iverseID); switch (e.CommandName) { case "delete": default: if (this.hdnQLang.Value == "ar") { QuranVerse.DeleteVerse(siteid, iverse.QuranID, iverse.SuraID, iverseID); suraid = iverse.SuraID; } else { QuranVerseTranslation iverseTransl = new QuranVerseTranslation(siteid, int.Parse(hdnQuranID.Value), iverseID); QuranVerse.DeleteVerse_Translation(siteid, iverseTransl.QuranID, iverseTransl.SuraID, iverseTransl.VerseID); suraid = iverseTransl.SuraID; } //iQVGrid.EditIndex = +1; //log it: log.Info("user " + currentUser.Name + " deleted Verse Version : " + iverse.QuranVerseTxt + " at: " + dleteDate); //BindGrid(); //lblmessage.Text = iQuranMessagesResources.DeletedMsg + "<br />"; //lblmessage.Visible = true; //divMsg.Visible = true; hdnSuraID.Value = suraid.ToString(); SetRedirectString(true, true, "ok"); break; } } #endregion #region SEARCH private void CheckSearchWhat() { if (txtSearchByTitle.Text.Trim() == string.Empty) this.searchTitle = string.Empty; else this.searchTitle = SecurityHelper.RemoveMarkup(txtSearchByTitle.Text); search = ddStatus.SelectedValue.ToString(); //0: all , 1.active , 2.notactive } protected void btnSearchTitle_Click(Object sender, EventArgs e) { if (txtSearchByTitle.Text.Trim() == string.Empty) return; this.searchTitle = SecurityHelper.RemoveMarkup(txtSearchByTitle.Text); this.search = "VerseOrder"; SetRedirectString(true, false, ""); } protected void ddStatus_SelectedIndexChanged(object sender, EventArgs e) { CheckSearchWhat(); SetRedirectString(true, false, ""); } protected void ddSelQuran_SelectedIndexChanged(object sender, EventArgs e) { //this.quranID = int.Parse(ddSelQuran.SelectedItem.Value.ToString()); //hdnQuranID.Value = this.quranID.ToString(); //if (this.quranID > 0) //{ // hdnSuraID.Value = "-1"; // FilliSura(); //} this.quranID = int.Parse(ddSelQuran.SelectedItem.Value.ToString()); hdnQuranID.Value = this.quranID.ToString(); this.suraID = -1; hdnSuraID.Value = "-1"; this.searchTitle = string.Empty; search = "0"; SetRedirectString(false, false, ""); } protected void ddSelSura_SelectedIndexChanged(object sender, EventArgs e) { this.quranID = int.Parse(ddSelQuran.SelectedItem.Value.ToString()); hdnQuranID.Value = this.quranID.ToString(); this.suraID = int.Parse(ddSelSura.SelectedItem.Value.ToString()); hdnSuraID.Value = this.suraID.ToString(); this.searchTitle = string.Empty; search = "0"; SetRedirectString(true, false, ""); } #endregion #region OnInit override protected void OnInit(EventArgs e) { base.OnInit(e); this.Load += new EventHandler(this.Page_Load); this.iQVGrid.Sorting += new GridViewSortEventHandler(iQVGrid_Sorting); this.iQVGrid.RowCommand += new GridViewCommandEventHandler(iQVGrid_RowCommand); this.iQVGrid.RowDeleting += new GridViewDeleteEventHandler(iQVGrid_RowDeleting); SuppressMenuSelection(); SuppressPageMenu(); } protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Threading; using ExtensionLoader; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.Packets; namespace Simian.Extensions { public class SceneManager : IExtension<Simian>, ISceneProvider { Simian server; DoubleDictionary<uint, UUID, SimulationObject> sceneObjects = new DoubleDictionary<uint, UUID, SimulationObject>(); int currentLocalID = 1; float[] heightmap = new float[256 * 256]; public event ObjectAddCallback OnObjectAdd; public event ObjectRemoveCallback OnObjectRemove; public event ObjectTransformCallback OnObjectTransform; public event ObjectFlagsCallback OnObjectFlags; public event ObjectImageCallback OnObjectImage; public event ObjectModifyCallback OnObjectModify; public event AvatarAppearanceCallback OnAvatarAppearance; public event TerrainUpdatedCallback OnTerrainUpdated; public float[] Heightmap { get { return heightmap; } set { if (value.Length != (256 * 256)) throw new ArgumentException("Heightmap must be 256x256"); heightmap = value; } } public float WaterHeight { get { return 35f; } } public SceneManager() { } public void Start(Simian server) { this.server = server; server.UDP.RegisterPacketCallback(PacketType.CompleteAgentMovement, new PacketCallback(CompleteAgentMovementHandler)); LoadTerrain(server.DataDir + "heightmap.tga"); } public void Stop() { } public bool ObjectAdd(object sender, Agent creator, SimulationObject obj, PrimFlags creatorFlags) { // Check if the object already exists in the scene if (sceneObjects.ContainsKey(obj.Prim.ID)) { Logger.Log(String.Format("Attempting to add duplicate object {0} to the scene", obj.Prim.ID), Helpers.LogLevel.Warning); return false; } // Assign a unique LocalID to this object obj.Prim.LocalID = (uint)Interlocked.Increment(ref currentLocalID); if (OnObjectAdd != null) { OnObjectAdd(sender, creator, obj, creatorFlags); } // Add the object to the scene dictionary sceneObjects.Add(obj.Prim.LocalID, obj.Prim.ID, obj); // Send an update out to the creator ObjectUpdatePacket updateToOwner = SimulationObject.BuildFullUpdate(obj.Prim, server.RegionHandle, 0, obj.Prim.Flags | creatorFlags); server.UDP.SendPacket(creator.AgentID, updateToOwner, PacketCategory.State); // Send an update out to everyone else ObjectUpdatePacket updateToOthers = SimulationObject.BuildFullUpdate(obj.Prim, server.RegionHandle, 0, obj.Prim.Flags); lock (server.Agents) { foreach (Agent recipient in server.Agents.Values) { if (recipient != creator) server.UDP.SendPacket(recipient.AgentID, updateToOthers, PacketCategory.State); } } return true; } public bool ObjectRemove(object sender, SimulationObject obj) { if (OnObjectRemove != null) { OnObjectRemove(sender, obj); } sceneObjects.Remove(obj.Prim.LocalID, obj.Prim.ID); KillObjectPacket kill = new KillObjectPacket(); kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); kill.ObjectData[0].ID = obj.Prim.LocalID; server.UDP.BroadcastPacket(kill, PacketCategory.State); return true; } public void ObjectTransform(object sender, SimulationObject obj, Vector3 position, Quaternion rotation, Vector3 velocity, Vector3 acceleration, Vector3 angularVelocity, Vector3 scale) { if (OnObjectTransform != null) { OnObjectTransform(sender, obj, position, rotation, velocity, acceleration, angularVelocity, scale); } // Update the object obj.Prim.Position = position; obj.Prim.Rotation = rotation; obj.Prim.Velocity = velocity; obj.Prim.Acceleration = acceleration; obj.Prim.AngularVelocity = angularVelocity; obj.Prim.Scale = scale; // Inform clients BroadcastObjectUpdate(obj); } public void ObjectFlags(object sender, SimulationObject obj, PrimFlags flags) { if (OnObjectFlags != null) { OnObjectFlags(sender, obj, flags); } // Update the object obj.Prim.Flags = flags; // Inform clients BroadcastObjectUpdate(obj); } public void ObjectImage(object sender, SimulationObject obj, string mediaURL, Primitive.TextureEntry textureEntry) { if (OnObjectImage != null) { OnObjectImage(sender, obj, mediaURL, textureEntry); } // Update the object obj.Prim.Textures = textureEntry; obj.Prim.MediaURL = mediaURL; // Inform clients BroadcastObjectUpdate(obj); } public void ObjectModify(object sender, SimulationObject obj, Primitive.ConstructionData data) { if (OnObjectModify != null) { OnObjectModify(sender, obj, data); } // Update the object obj.Prim.PrimData = data; // Inform clients BroadcastObjectUpdate(obj); } public void AvatarAppearance(object sender, Agent agent, Primitive.TextureEntry textures, byte[] visualParams) { if (OnAvatarAppearance != null) { OnAvatarAppearance(sender, agent, textures, visualParams); } // Update the avatar agent.Avatar.Textures = textures; if (visualParams != null) agent.VisualParams = visualParams; // Broadcast the object update ObjectUpdatePacket update = SimulationObject.BuildFullUpdate(agent.Avatar, server.RegionHandle, agent.State, agent.Flags); server.UDP.BroadcastPacket(update, PacketCategory.State); // Send the appearance packet to all other clients AvatarAppearancePacket appearance = BuildAppearancePacket(agent); lock (server.Agents) { foreach (Agent recipient in server.Agents.Values) { if (recipient != agent) server.UDP.SendPacket(recipient.AgentID, appearance, PacketCategory.State); } } } public bool TryGetObject(uint localID, out SimulationObject obj) { return sceneObjects.TryGetValue(localID, out obj); } public bool TryGetObject(UUID id, out SimulationObject obj) { return sceneObjects.TryGetValue(id, out obj); } void BroadcastObjectUpdate(SimulationObject obj) { ObjectUpdatePacket update = SimulationObject.BuildFullUpdate(obj.Prim, server.RegionHandle, 0, obj.Prim.Flags); server.UDP.BroadcastPacket(update, PacketCategory.State); } void CompleteAgentMovementHandler(Packet packet, Agent agent) { CompleteAgentMovementPacket request = (CompleteAgentMovementPacket)packet; // Create a representation for this agent Avatar avatar = new Avatar(); avatar.ID = agent.AgentID; avatar.LocalID = (uint)Interlocked.Increment(ref currentLocalID); avatar.Position = new Vector3(128f, 128f, 25f); avatar.Rotation = Quaternion.Identity; avatar.Scale = new Vector3(0.45f, 0.6f, 1.9f); avatar.PrimData.Material = Material.Flesh; avatar.PrimData.PCode = PCode.Avatar; // Create a default outfit for the avatar Primitive.TextureEntry te = new Primitive.TextureEntry(new UUID("c228d1cf-4b5d-4ba8-84f4-899a0796aa97")); avatar.Textures = te; // Set the avatar name NameValue[] name = new NameValue[2]; name[0] = new NameValue("FirstName", NameValue.ValueType.String, NameValue.ClassType.ReadWrite, NameValue.SendtoType.SimViewer, agent.FirstName); name[1] = new NameValue("LastName", NameValue.ValueType.String, NameValue.ClassType.ReadWrite, NameValue.SendtoType.SimViewer, agent.LastName); avatar.NameValues = name; // Link this avatar up with the corresponding agent agent.Avatar = avatar; // Give testers a provisionary balance of 1000L agent.Balance = 1000; // Add this avatar as an object in the scene if (ObjectAdd(this, agent, new SimulationObject(agent.Avatar, server), PrimFlags.None)) { // Send a response back to the client AgentMovementCompletePacket complete = new AgentMovementCompletePacket(); complete.AgentData.AgentID = agent.AgentID; complete.AgentData.SessionID = agent.SessionID; complete.Data.LookAt = Vector3.UnitX; complete.Data.Position = avatar.Position; complete.Data.RegionHandle = server.RegionHandle; complete.Data.Timestamp = Utils.DateTimeToUnixTime(DateTime.Now); complete.SimData.ChannelVersion = Utils.StringToBytes("Simian"); server.UDP.SendPacket(agent.AgentID, complete, PacketCategory.Transaction); // Send updates and appearances for every avatar to this new avatar SynchronizeStateTo(agent); //HACK: Notify everyone when someone logs on to the simulator OnlineNotificationPacket online = new OnlineNotificationPacket(); online.AgentBlock = new OnlineNotificationPacket.AgentBlockBlock[1]; online.AgentBlock[0] = new OnlineNotificationPacket.AgentBlockBlock(); online.AgentBlock[0].AgentID = agent.AgentID; server.UDP.BroadcastPacket(online, PacketCategory.State); } else { Logger.Log("Received a CompleteAgentMovement from an avatar already in the scene, " + agent.FullName, Helpers.LogLevel.Warning); } } // HACK: The reduction provider will deprecate this at some point void SynchronizeStateTo(Agent agent) { // Send the parcel overlay server.Parcels.SendParcelOverlay(agent); // Send object updates for objects and avatars sceneObjects.ForEach(delegate(SimulationObject obj) { ObjectUpdatePacket update = SimulationObject.BuildFullUpdate(obj.Prim, obj.Prim.RegionHandle, 0, obj.Prim.Flags); server.UDP.SendPacket(agent.AgentID, update, PacketCategory.State); }); // Send appearances for all avatars lock (server.Agents) { foreach (Agent otherAgent in server.Agents.Values) { if (otherAgent != agent) { // Send appearances for this avatar AvatarAppearancePacket appearance = BuildAppearancePacket(otherAgent); server.UDP.SendPacket(agent.AgentID, appearance, PacketCategory.State); } } } // Send terrain data SendLayerData(agent); } void LoadTerrain(string mapFile) { if (File.Exists(mapFile)) { lock (heightmap) { Bitmap bmp = LoadTGAClass.LoadTGA(mapFile); Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); IntPtr ptr = bmpData.Scan0; int bytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[bytes]; Marshal.Copy(ptr, rgbValues, 0, bytes); bmp.UnlockBits(bmpData); for (int i = 1, pos = 0; i < heightmap.Length; i++, pos += 3) heightmap[i] = (float)rgbValues[pos]; if (OnTerrainUpdated != null) OnTerrainUpdated(this); } } else { Logger.Log("Map file " + mapFile + " not found, defaulting to 25m", Helpers.LogLevel.Info); server.Scene.Heightmap = new float[65536]; for (int i = 0; i < server.Scene.Heightmap.Length; i++) server.Scene.Heightmap[i] = 25f; } } void SendLayerData(Agent agent) { lock (heightmap) { for (int y = 0; y < 16; y++) { for (int x = 0; x < 16; x++) { int[] patches = new int[1]; patches[0] = (y * 16) + x; LayerDataPacket layer = TerrainCompressor.CreateLandPacket(heightmap, patches); server.UDP.SendPacket(agent.AgentID, layer, PacketCategory.Terrain); } } } } static AvatarAppearancePacket BuildAppearancePacket(Agent agent) { AvatarAppearancePacket appearance = new AvatarAppearancePacket(); appearance.ObjectData.TextureEntry = agent.Avatar.Textures.ToBytes(); appearance.Sender.ID = agent.AgentID; appearance.Sender.IsTrial = false; appearance.VisualParam = new AvatarAppearancePacket.VisualParamBlock[218]; for (int i = 0; i < 218; i++) { appearance.VisualParam[i] = new AvatarAppearancePacket.VisualParamBlock(); appearance.VisualParam[i].ParamValue = agent.VisualParams[i]; } return appearance; } } }
#region Transition.cs file // // StaMa state machine controller library, https://github.com/StaMa-StateMachine/StaMa // // Copyright (c) 2005-2016, Roland Schneider. All rights reserved. // #endregion using System; using System.Diagnostics; #if STAMA_COMPATIBLE21 #pragma warning disable 0618 #endif namespace StaMa { /// <summary> /// Represents a transition with source state, target state and information when the transition shall be executed. /// </summary> /// <remarks> /// Instances of this class will be created through the <see cref="StateMachineTemplate"/>.<see cref="O:StaMa.StateMachineTemplate.Transition"/> methods. /// </remarks> [DebuggerDisplay("Name={this.Name}, Rank={1 + m_parentState.m_transitions.m_transitions.IndexOf(this)}")] public class Transition { private State m_parentState; private string m_name; private StateConfiguration m_sourceStateConfiguration; private StateConfiguration m_targetStateConfiguration; private object m_triggerEvent; private StateMachineGuardCallback m_guard; #if !STAMA_COMPATIBLE21 private StateMachineActionCallback m_transitionAction; #else private StateMachineActivityCallback m_transitionAction; #endif private Region m_leastCommonAncestor; private string[] m_sourceStates; private string[] m_targetStates; /// <summary> /// Initializes a new <see cref="Transition"/> instance. /// </summary> /// <param name="parentState"> /// The anchor <see cref="State"/> where the <see cref="Transition"/> is aggregated. /// </param> /// <param name="name"> /// The name of the <see cref="StaMa.Transition"/> to be created. Must be unique within the <see cref="StateMachineTemplate"/>. /// </param> /// <param name="sourceStates"> /// A list of names of the transition source states. /// </param> /// <param name="targetStates"> /// A list of names of the transition target states. /// </param> /// <param name="triggerEvent"> /// A <see cref="System.Object"/> that represents the trigger event that will execute the transition. /// See also <see cref="StateMachine.SendTriggerEvent(object)"/>. /// </param> /// <param name="guard"> /// A <see cref="StateMachineGuardCallback"/> delegate that provides additional conditions /// for the transition; otherwise, <c>null</c> if no addititional conditions are neccessary. /// </param> /// <param name="transitionAction"> /// A <see cref="StateMachineActionCallback"/> delegate that will be called when /// the transition is executed. /// May be <c>null</c> if no transition action is required. /// </param> /// <remarks> /// Instances of this class will be created through the <see cref="StateMachineTemplate"/>.<see cref="StateMachineTemplate.Transition(string, string, string, object)"/> method /// or one of its overloads. /// </remarks> internal protected Transition( State parentState, string name, string[] sourceStates, string[] targetStates, object triggerEvent, StateMachineGuardCallback guard, #if !STAMA_COMPATIBLE21 StateMachineActionCallback transitionAction) #else StateMachineActivityCallback transitionAction) #endif { if (sourceStates == null) { throw new ArgumentNullException("sourceStates"); } foreach (string sourceStateName in sourceStates) { if ((sourceStateName == null) || (sourceStateName.Length == 0)) { throw new ArgumentNullException("sourceStates", "The list of source states contains invalid items."); } } if (targetStates == null) { throw new ArgumentNullException("targetStates"); } foreach (string targetStateName in targetStates) { if ((targetStateName == null) || (targetStateName.Length == 0)) { throw new ArgumentNullException("targetStates", "The list of target states contains invalid items."); } } m_parentState = parentState; m_name = name; m_sourceStateConfiguration = null; m_targetStateConfiguration = null; m_sourceStates = sourceStates; m_targetStates = targetStates; m_triggerEvent = triggerEvent; m_guard = guard; m_transitionAction = transitionAction; m_leastCommonAncestor = null; } /// <summary> /// Gets name of the <see cref="Transition"/>. /// </summary> /// <value> /// An identifier which is unique within the embedding <see cref="StateMachineTemplate"/>. /// </value> public string Name { get { return m_name; } } /// <summary> /// Returns the name of the <see cref="Transition"/> as specified in the <see cref="StateMachineTemplate"/>.<see cref="O:StaMa.StateMachineTemplate.Transition"/> statement. /// </summary> /// <returns> /// A <see cref="string"/> containing the value of the <see cref="Name"/> property of the <see cref="Transition"/>. /// </returns> public override string ToString() { return this.Name; } /// <summary> /// Gets the anchor <see cref="State"/> where the <see cref="Transition"/> is aggregated. /// </summary> /// <remarks> /// Usually the <see cref="Parent"/> will be identical with the source <see cref="State"/>. /// In some cases a transition may be aggregated on a higher hierarchical level than the /// <see cref="SourceState"/> in order to raise the <see cref="Transition"/>s priority above other /// transitions that are handled premptive due to their hierarchy level. /// </remarks> public State Parent { get { return m_parentState; } } /// <summary> /// Gets the <see cref="StateConfiguration"/> that represents the /// source state of the <see cref="Transition"/>. /// </summary> /// <remarks> /// The <see cref="SourceState"/> will only reference a configuration of /// sub-<see cref="State"/> instances of the anchor <see cref="Parent"/> state. /// </remarks> public StateConfiguration SourceState { get { return m_sourceStateConfiguration; } } /// <summary> /// Gets the <see cref="StateConfiguration"/> that represents the /// target state of the <see cref="Transition"/>. /// </summary> /// <remarks> /// The <see cref="TargetState"/> could reference any configuration of /// <see cref="State"/> instances within the <see cref="StateMachineTemplate"/>. /// </remarks> public StateConfiguration TargetState { get { return m_targetStateConfiguration; } } /// <summary> /// Gets the trigger event on which the <see cref="Transition"/> will react. /// </summary> /// <value> /// A <see cref="object"/> instance that represents the trigger event or <c>null</c> for /// completion transitions. /// </value> /// <remarks> /// See also <see cref="StateMachine.SendTriggerEvent(object)"/>. /// </remarks> public object TriggerEvent { get { return m_triggerEvent; } } /// <summary> /// Gets the callback method that provides additional conditions /// for the transition. /// </summary> /// <value> /// A <see cref="StateMachineGuardCallback"/> delegate of <c>null</c> if no additional /// conditions are defined. /// </value> public StateMachineGuardCallback Guard { get { return m_guard; } } #if !STAMA_COMPATIBLE21 /// <summary> /// Gets the callback method that will be called when the transition is executed. /// </summary> /// <value> /// A <see cref="StateMachineActionCallback"/> delegate or /// <c>null</c> if no transition action is defined. /// </value> public StateMachineActionCallback TransitionAction #else /// <summary> /// Obsolete. The term "activity" is improper and has been replaced with "action". Please use the corresponding TransitionAction property instead. /// </summary> [Obsolete("The term \"activity\" is improper and has been replaced with \"action\". Please use the corresponding TransitionAction property instead.")] public StateMachineActivityCallback TransitionActivity #endif { get { return m_transitionAction; } } /// <summary> /// Gets the least common ancestor of the <see cref="SourceState"/> and /// the <see cref="TargetState"/> of the <see cref="Transition"/>. /// </summary> /// <value> /// The <see cref="Region"/> instance 'up' to which the <see cref="StateMachine"/> has to /// leave states and enter states during the state change initiated through this <see cref="Transition"/>. /// </value> public Region LeastCommonAncestor { get { return m_leastCommonAncestor; } } internal bool PassThrough(IStateMachineTemplateVisitor visitor) { bool continuePassThrough = visitor.Transition(this); return continuePassThrough; } internal void FinalFixup(StateMachineTemplate stateMachineTemplate) { // Make a state configuration for the source and target states try { m_sourceStateConfiguration = stateMachineTemplate.CreateStateConfiguration(m_sourceStates); } catch (Exception ex) { throw new StateMachineException(FrameworkAbstractionUtils.StringFormat("The state names for the source state of transition \"{0}\" do not form a valid StateConfiguration.", this.Name), ex); } try { m_targetStateConfiguration = stateMachineTemplate.CreateStateConfiguration(m_targetStates); } catch (Exception ex) { throw new StateMachineException(FrameworkAbstractionUtils.StringFormat("The state names for the target state of transition \"{0}\" do not form a valid StateConfiguration.", this.Name), ex); } // Ensure, that at least one of the transition source states is a substate of // the state, the transition is linked to (i.e. the transition parent). { State transiParentState = this.Parent; bool found = false; foreach (string stateName in m_sourceStates) { State state = stateMachineTemplate.FindState(stateName); if (state == null) { // Unknown state (stateName) throw new StateMachineException(FrameworkAbstractionUtils.StringFormat("The source State \"{1}\" of Transition \"{0}\" could not be found.", this.Name, stateName)); } while (state != null) { if (state == transiParentState) { found = true; break; } // Step up one level state = state.Parent.Parent; } if (found) { break; } } if (!found) { // If we come to this place we have tested all source states // and did not find any of them within the transition parent state. // Prevent this semantical meaningless situation. throw new StateMachineException(FrameworkAbstractionUtils.StringFormat("None of the source States of Transition \"{0}\" are within the transition source scope.", this.Name)); } } // Now we calculate the least common ancestor (LCA) between the transition source and target // The transition LCA defines which states (more precise: up to which region) to leave // and enter during a state change. // To find out the transition LCA, we do the following: // Start from the transition's parent state and walk the tree in direction to the root. // While walking search for a region that contains the target enveloping state. // This region contains both the transition parent state and the target enveloping state. // Start a new C# block to make some variables local. { State stateEnvelopeTarget = m_targetStateConfiguration.FindEnvelopeState(); m_leastCommonAncestor = null; // Start walking with the transi parent State state = this.Parent; while (state != null) { Region parentRegion = state.Parent; // Walk up to the tree from stateEnvelopeTarget State stateTarget = stateEnvelopeTarget; while (stateTarget != null) { Region regionTarget = stateTarget.Parent; if (regionTarget == parentRegion) { m_leastCommonAncestor = parentRegion; break; } // Step up one level with target stateTarget = regionTarget.Parent; } if (m_leastCommonAncestor != null) { break; } // Step up one level with source state = parentRegion.Parent; } if (m_leastCommonAncestor == null) { // Every state config joins at the root, so we never should reach this code throw new InvalidOperationException("Internal error: Couldn't find the least common ancestor for the transition."); } } } } } #if STAMA_COMPATIBLE21 #pragma warning restore 0618 #endif
using UnityEngine; using System.Collections; using Pathfinding; namespace Pathfinding { [AddComponentMenu("Pathfinding/GraphUpdateScene")] /** Helper class for easily updating graphs. * * \see \ref graph-updates * for an explanation of how to use this class. */ public class GraphUpdateScene : GraphModifier { /** Do some stuff at start */ public void Start () { //If firstApplied is true, that means the graph was scanned during Awake. //So we shouldn't apply it again because then we would end up applying it two times if (!firstApplied && applyOnStart) { Apply (); } } public override void OnPostScan () { if (applyOnScan) Apply (); } /** Points which define the region to update */ public Vector3[] points; /** Private cached convex hull of the #points */ private Vector3[] convexPoints; [HideInInspector] /** Use the convex hull (XZ space) of the points. */ public bool convex = true; [HideInInspector] /** Minumum height of the bounds of the resulting Graph Update Object. * Useful when all points are laid out on a plane but you still need a bounds with a height greater than zero since a * zero height graph update object would usually result in no nodes being updated. */ public float minBoundsHeight = 1; [HideInInspector] /** Penalty to add to nodes. * Be careful when setting negative values since if a node get's a negative penalty it will underflow and instead get * really large. In most cases a warning will be logged if that happens. */ public int penaltyDelta = 0; [HideInInspector] /** Set to true to set all targeted nodese walkability to #setWalkability */ public bool modifyWalkability = false; [HideInInspector] /** See #modifyWalkability */ public bool setWalkability = false; [HideInInspector] /** Apply this graph update object on start */ public bool applyOnStart = true; [HideInInspector] /** Apply this graph update object whenever a graph is rescanned */ public bool applyOnScan = true; /** Use world space for coordinates. * If true, the shape will not follow when moving around the transform. * * \see #ToggleUseWorldSpace */ [HideInInspector] public bool useWorldSpace = false; /** Update node's walkability and connectivity using physics functions. * For grid graphs, this will update the node's position and walkability exactly like when doing a scan of the graph. * If enabled for grid graphs, #modifyWalkability will be ignored. * * For Point Graphs, this will recalculate all connections which passes through the bounds of the resulting Graph Update Object * using raycasts (if enabled). * */ [HideInInspector] public bool updatePhysics = false; /** \copydoc Pathfinding::GraphUpdateObject::resetPenaltyOnPhysics */ [HideInInspector] public bool resetPenaltyOnPhysics = true; /** \copydoc Pathfinding::GraphUpdateObject::updateErosion */ [HideInInspector] public bool updateErosion = true; [HideInInspector] /** Lock all points to Y = #lockToYValue */ public bool lockToY = false; [HideInInspector] /** if #lockToY is enabled lock all points to this value */ public float lockToYValue = 0; #if ConfigureTagsAsMultiple /** Sets the value of the changed tags. This is a bitmask */ public TagMask tags = new TagMask (); #else [HideInInspector] /** If enabled, set all nodes' tags to #setTag */ public bool modifyTag = false; [HideInInspector] /** If #modifyTag is enabled, set all nodes' tags to this value */ public int setTag = 0; /** Private cached inversion of #setTag. * Used for InvertSettings() */ private int setTagInvert = 0; #endif /** Has apply been called yet. * Used to prevent applying twice when both applyOnScan and applyOnStart are enabled */ private bool firstApplied = false; /** Inverts all invertable settings for this GUS. * Namely: penalty delta, walkability, tags. * * Penalty delta will be changed to negative penalty delta.\n * #setWalkability will be inverted.\n * #setTag will be stored in a private variable, and the new value will be 0. When calling this function again, the saved * value will be the new value. * * Calling this function an even number of times without changing any settings in between will be identical to no change in settings. */ public virtual void InvertSettings () { setWalkability = !setWalkability; penaltyDelta = -penaltyDelta; if (setTagInvert == 0) { setTagInvert = setTag; setTag = 0; } else { setTag = setTagInvert; setTagInvert = 0; } } /** Recalculate convex points. * Will not do anything if not #convex is enabled */ public void RecalcConvex () { if (convex) convexPoints = Polygon.ConvexHull (points); else convexPoints = null; } /** Switches between using world space and using local space. * Changes point coordinates to stay the same in world space after the change. * * \see #useWorldSpace */ public void ToggleUseWorldSpace () { useWorldSpace = !useWorldSpace; if (points == null) return; convexPoints = null; Matrix4x4 matrix = useWorldSpace ? transform.localToWorldMatrix : transform.worldToLocalMatrix; for (int i=0;i<points.Length;i++) { points[i] = matrix.MultiplyPoint3x4 (points[i]); } } /** Lock all points to a specific Y value. * * \see lockToYValue */ public void LockToY () { if (points == null) return; for (int i=0;i<points.Length;i++) points[i].y = lockToYValue; } /** Apply the update. * Will only do anything if #applyOnScan is enabled */ public void Apply (AstarPath active) { if (applyOnScan) { Apply (); } } /** Calculates the bounds for this component. * This is a relatively expensive operation, it needs to go through all points and * sometimes do matrix multiplications. */ public Bounds GetBounds () { Bounds b; if (points == null || points.Length == 0) { if (collider != null) b = collider.bounds; else if (renderer != null) b = renderer.bounds; else { //Debug.LogWarning ("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached"); return new Bounds(Vector3.zero, Vector3.zero); } } else { Matrix4x4 matrix = Matrix4x4.identity; if (!useWorldSpace) { matrix = transform.localToWorldMatrix; } Vector3 min = matrix.MultiplyPoint3x4(points[0]); Vector3 max = matrix.MultiplyPoint3x4(points[0]); for (int i=0;i<points.Length;i++) { Vector3 p = matrix.MultiplyPoint3x4(points[i]); min = Vector3.Min (min,p); max = Vector3.Max (max,p); } b = new Bounds ((min+max)*0.5F,max-min); } if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z); return b; } /** Updates graphs with a created GUO. * Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape * representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs. * This will not update graphs directly. See AstarPath.UpdateGraph for more info. */ public void Apply () { if (AstarPath.active == null) { Debug.LogError ("There is no AstarPath object in the scene"); return; } GraphUpdateObject guo; if (points == null || points.Length == 0) { Bounds b; if (collider != null) b = collider.bounds; else if (renderer != null) b = renderer.bounds; else { Debug.LogWarning ("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached"); return; } if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z); guo = new GraphUpdateObject (b); } else { Pathfinding.GraphUpdateShape shape = new Pathfinding.GraphUpdateShape (); shape.convex = convex; Vector3[] worldPoints = points; if (!useWorldSpace) { worldPoints = new Vector3[points.Length]; Matrix4x4 matrix = transform.localToWorldMatrix; for (int i=0;i<worldPoints.Length;i++) worldPoints[i] = matrix.MultiplyPoint3x4 (points[i]); } shape.points = worldPoints; Bounds b = shape.GetBounds (); if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z); guo = new GraphUpdateObject (b); guo.shape = shape; } firstApplied = true; guo.modifyWalkability = modifyWalkability; guo.setWalkability = setWalkability; guo.addPenalty = penaltyDelta; guo.updatePhysics = updatePhysics; guo.updateErosion = updateErosion; guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics; #if ConfigureTagsAsMultiple guo.tags = tags; #else guo.modifyTag = modifyTag; guo.setTag = setTag; #endif AstarPath.active.UpdateGraphs (guo); } /** Draws some gizmos */ public void OnDrawGizmos () { OnDrawGizmos (false); } /** Draws some gizmos */ public void OnDrawGizmosSelected () { OnDrawGizmos (true); } /** Draws some gizmos */ public void OnDrawGizmos (bool selected) { Color c = selected ? new Color (227/255f,61/255f,22/255f,1.0f) : new Color (227/255f,61/255f,22/255f,0.9f); if (selected) { Gizmos.color = Color.Lerp (c, new Color (1,1,1,0.2f), 0.9f); Bounds b = GetBounds (); Gizmos.DrawCube (b.center, b.size); Gizmos.DrawWireCube (b.center, b.size); } if (points == null) return; if (convex) { c.a *= 0.5f; } Gizmos.color = c; Matrix4x4 matrix = useWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix; if (convex) { c.r -= 0.1f; c.g -= 0.2f; c.b -= 0.1f; Gizmos.color = c; } if (selected || !convex) { for (int i=0;i<points.Length;i++) { Gizmos.DrawLine (matrix.MultiplyPoint3x4(points[i]),matrix.MultiplyPoint3x4(points[(i+1)%points.Length])); } } if (convex) { if (convexPoints == null) RecalcConvex (); Gizmos.color = selected ? new Color (227/255f,61/255f,22/255f,1.0f) : new Color (227/255f,61/255f,22/255f,0.9f); for (int i=0;i<convexPoints.Length;i++) { Gizmos.DrawLine (matrix.MultiplyPoint3x4(convexPoints[i]),matrix.MultiplyPoint3x4(convexPoints[(i+1)%convexPoints.Length])); } } } } }
// // AbstractPlaylistSource.cs // // Author: // Aaron Bockover <[email protected]> // Gabriel Burt <[email protected]> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Hyena.Data; using Hyena.Data.Sqlite; using Hyena.Collections; using Hyena.Query; using Banshee.Base; using Banshee.ServiceStack; using Banshee.Database; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Query; namespace Banshee.Playlist { public abstract class AbstractPlaylistSource : DatabaseSource { protected int? dbid; protected abstract string SourceTable { get; } protected abstract string SourcePrimaryKey { get; } protected abstract string TrackJoinTable { get; } protected DateTime last_added = DateTime.MinValue; protected DateTime last_updated = DateTime.MinValue; protected DateTime last_removed = DateTime.MinValue; protected virtual string TrackCondition { get { return String.Format ( " {0}.TrackID = CoreTracks.TrackID AND {0}.{2} = {1}", TrackJoinTable, "{0}", SourcePrimaryKey ); } } protected virtual string JoinPrimaryKey { get { return "EntryID"; } } protected virtual bool CachesJoinTableEntries { get { return true; } } private bool is_temporary = false; public bool IsTemporary { get { return is_temporary; } set { is_temporary = value; } } public int? DbId { get { return dbid; } protected set { if (value != null && value != dbid) { dbid = value; } } } protected int primary_source_id; public int PrimarySourceId { get { return primary_source_id; } } public PrimarySource PrimarySource { get { return PrimarySource.GetById (primary_source_id); } set { primary_source_id = value.DbId; } } public override bool HasEditableTrackProperties { get { return PrimarySource == null || PrimarySource.HasEditableTrackProperties; } } private HyenaSqliteCommand count_updated_command; protected HyenaSqliteCommand CountUpdatedCommand { get { return count_updated_command ?? (count_updated_command = new HyenaSqliteCommand (String.Format ( @"SELECT COUNT(*) FROM {0} WHERE {1} = {2} AND TrackID IN ( SELECT TrackID FROM CoreTracks WHERE DateUpdatedStamp > ?)", TrackJoinTable, SourcePrimaryKey, dbid ))); } } private HyenaSqliteCommand count_removed_command; protected HyenaSqliteCommand CountRemovedCommand { get { return count_removed_command ?? (count_removed_command = new HyenaSqliteCommand (String.Format ( @"SELECT COUNT(*) FROM {0} WHERE {1} = {2} AND TrackID IN ( SELECT TrackID FROM CoreRemovedTracks WHERE DateRemovedStamp > ?)", TrackJoinTable, SourcePrimaryKey, dbid ))); } } public AbstractPlaylistSource (string generic_name, string name, PrimarySource parent) : base () { GenericName = generic_name; Name = name; if (parent != null) { primary_source_id = parent.DbId; SetParentSource (parent); } } public AbstractPlaylistSource (string generic_name, string name, int dbid, int sortColumn, int sortType, PrimarySource parent, bool is_temp) : base (generic_name, name, dbid.ToString (), 500, parent) { primary_source_id = parent.DbId; DbId = dbid; IsTemporary = is_temp; AfterInitialized (); } protected override void AfterInitialized () { DatabaseTrackModel.JoinTable = TrackJoinTable; DatabaseTrackModel.JoinPrimaryKey = JoinPrimaryKey; DatabaseTrackModel.JoinColumn = "TrackID"; DatabaseTrackModel.CachesJoinTableEntries = CachesJoinTableEntries; DatabaseTrackModel.AddCondition (String.Format (TrackCondition, dbid)); Properties.Set<string> ("SearchEntryDescription", Catalog.GetString ("Search this playlist")); base.AfterInitialized (); } public override string GetPluralItemCountString (int count) { return Parent == null ? base.GetPluralItemCountString (count) : Parent.GetPluralItemCountString (count); } public override void Rename (string newName) { base.Rename (newName); Save (); } public override bool CanRename { get { return (Parent is PrimarySource) ? !(Parent as PrimarySource).PlaylistsReadOnly : true; } } public override bool CanSearch { get { return true; } } public virtual bool CanUnmap { get { return (Parent is PrimarySource) ? !(Parent as PrimarySource).PlaylistsReadOnly : true; } } public bool ConfirmBeforeUnmap { get { return true; } } // We can delete tracks only if our parent can public override bool CanDeleteTracks { get { DatabaseSource ds = Parent as DatabaseSource; return ds != null && ds.CanDeleteTracks; } } public override void Save () { if (dbid == null || dbid <= 0) { Create (); TypeUniqueId = dbid.ToString (); Initialize (); AfterInitialized (); } else { Update (); } } // Have our parent handle deleting tracks public override void DeleteTracks (DatabaseTrackListModel model, Selection selection) { if (Parent is PrimarySource) { (Parent as PrimarySource).DeleteTracks (model, selection); } } public override bool ShowBrowser { get { return (Parent is DatabaseSource) ? (Parent as DatabaseSource).ShowBrowser : base.ShowBrowser; } } protected abstract void Create (); protected abstract void Update (); // Reserve strings in preparation for the forthcoming string freeze (BGO#389550) public void ReservedStrings () { Catalog.GetString ("The track's rating was set differently on the device and in Banshee"); } } }
using System; using System.Collections.Generic; using System.Linq; using Flunity.Internal; namespace Flunity { /// <summary> /// Container that represents animated timeline created in Adobe Flash /// </summary> public class MovieClip : DisplayContainer { public bool nestedAnimationEnabled; private TimeLine _timeLine; private MovieClipResource _resource; private Dictionary<int, Action> _frameActions; private DisplayObject[] _instances; public MovieClip(MovieClipResource resource) { Initialize(resource); } private void Initialize(MovieClipResource resource) { _resource = resource; _timeLine = _resource.timeLine; _instances = FlashResources.isReloadingPerformed ? ConstructFromResource() : ConstructInstances(); totalFrames = _timeLine.frames.Length; OnFrameChange(); } protected virtual DisplayObject[] ConstructInstances() { return ConstructFromResource(); } protected DisplayObject[] ConstructFromResource() { var count = _timeLine.instances.Length; var instances = new DisplayObject[count]; for (int i = 0; i < count; i++) { var instName = _timeLine.instances[i].name; var resourcePath = _timeLine.GetResourcePath(i); var resource = FlashResources.GetResource<IDisplayResource>(resourcePath); DisplayObject instance; if (resource != null) { instance = resource.CreateInstance(); } else if (resourcePath == "flash/text/TextField") { instance = new TextLabel() { text = ":-)" }; } else { var className = resourcePath .Replace("Placeholders/", "") .Replace("/", "."); var type = Type.GetType(className); if (type != null) instance = (DisplayObject) Activator.CreateInstance(type); else throw new Exception("Resource not found: " + resourcePath); } instance.name = instName; instances[i] = instance; var field = GetType().GetField(instName); if (field != null && field.FieldType.IsInstanceOfType(instance)) field.SetValue(this, instance); } return instances; } protected override void ResetDisplayObject() { if (_frameActions != null) _frameActions.Clear(); nestedAnimationEnabled = true; base.ResetDisplayObject(); } /// <summary> /// Goes to the frames with specified label. /// </summary> public MovieClip GotoLabel(string label) { var frameNum = GetFrameNum(label); if (frameNum >= 0) currentFrame = frameNum; return this; } /// <summary> /// Returns all labels in the current frame. No objects are allocated. /// </summary> public string[] CurrentLabels() { return _timeLine.frames[currentFrame].labels; } /// <summary> /// Returns labels from all frames. Allocates returning collection. /// </summary> public List<FrameLabel> GetAllLabels() { var labels = new List<FrameLabel>(); for (int i = 0; i < totalFrames; i++) { foreach (var label in _timeLine.frames[i].labels) { labels.Add(new FrameLabel { frame = i, name = label}); } } return labels; } /// <summary> /// Returns all labels in the specified frame. No objects are allocated. /// </summary> public string[] GetFrameLabels(int frameNum) { return (frameNum < 0 || frameNum >= totalFrames) ? new string[] { } : _timeLine.frames[frameNum].labels; } /// <summary> /// Assigns an action which will be invoked when <c>MovieClip</c> goes to the specified frame. /// </summary> public void SetFrameAction(int frameNum, Action action) { if (_frameActions == null) _frameActions = new Dictionary<int, Action>(); _frameActions[frameNum] = action; } /// <summary> /// Assigns an action which will be invoked when <c>MovieClip</c> goes to the frame /// which has specified label. /// </summary> public void SetLabelAction(string labelName, Action action) { for (int i = 0; i < totalFrames; i++) { if (_timeLine.frames[i].labels.Contains(labelName)) SetFrameAction(i, action); } } /// <summary> /// Returns frame which has specified label (-1 if not found) /// </summary> public int GetFrameNum(string labelName) { for (int i = 0; i < totalFrames; i++) { if (_timeLine.frames[i].labels.Contains(labelName)) return i; } return -1; } protected override void OnFrameChange() { UpdateInstances(); if (_frameActions != null) { Action frameAction; if (_frameActions.TryGetValue(currentFrame, out frameAction)) frameAction.Invoke(); } var labels = CurrentLabels(); for (int i = 0; i < labels.Length; i++) { if (stage != null) stage.events.DispatchFrameLabelEntered(this, labels[i]); } } private void UpdateInstances() { var frame = _timeLine.frames[currentFrame]; var itemNode = numChildren > 0 ? GetChildAt(0).node : null; var instanceIndex = 0; var instanceCount = frame.instances.Length; while (itemNode != null && instanceIndex < instanceCount) { var item = itemNode.Value; var instance = frame.instances[instanceIndex]; if (item.timelineInstanceId == instance.id) { instance.ApplyPropertiesTo(item, anchor); if (nestedAnimationEnabled && item.totalFrames > 1) item.StepForward(); instanceIndex++; itemNode = itemNode.Next; } else if (frame.HasInstance(item.timelineInstanceId)) { var newItem = GetChildItem(instance.id); instance.ApplyPropertiesTo(newItem, anchor); AddChildBefore(item, newItem); instanceIndex++; } else { var nextNode = itemNode.Next; if (item.timelineInstanceId >= 0) RemoveChild(item); itemNode = nextNode; } } while (instanceIndex < instanceCount) { var instance = frame.instances[instanceIndex]; var newItem = GetChildItem(instance.id); instance.ApplyPropertiesTo(newItem, anchor); AddChild(newItem); instanceIndex++; } while (itemNode != null) { var nextNode = itemNode.Next; var item = itemNode.Value; if (item.timelineInstanceId >= 0) RemoveChild(item); itemNode = nextNode; } } private DisplayObject GetChildItem(int instanceId) { DisplayObject displayObject = _instances[instanceId]; displayObject.currentFrame = 0; displayObject.timelineInstanceId = instanceId; return displayObject; } } }
namespace java.lang { [global::MonoJavaBridge.JavaClass()] public sealed partial class StringBuffer : java.lang.AbstractStringBuilder, java.io.Serializable, CharSequence { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static StringBuffer() { InitJNI(); } internal StringBuffer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _toString13224; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._toString13224)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._toString13224)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _append13225; public new global::java.lang.StringBuffer append(char[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13225, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13225, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13226; public new global::java.lang.StringBuffer append(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13226, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13226, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13227; public new global::java.lang.StringBuffer append(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13227, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13227, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13228; public new global::java.lang.StringBuffer append(java.lang.StringBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13228, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13228, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13229; public new global::java.lang.StringBuffer append(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13229, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13229, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } public java.lang.StringBuffer append(string arg0) { return append((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _append13230; public new global::java.lang.StringBuffer append(java.lang.CharSequence arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13230, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13230, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.StringBuffer; } public java.lang.StringBuffer append(string arg0, int arg1, int arg2) { return append((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1, arg2); } internal static global::MonoJavaBridge.MethodId _append13231; public new global::java.lang.StringBuffer append(char[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13231, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13231, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13232; public new global::java.lang.StringBuffer append(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13232, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13232, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13233; public new global::java.lang.StringBuffer append(char arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13233, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13233, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13234; public new global::java.lang.StringBuffer append(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13234, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13234, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13235; public new global::java.lang.StringBuffer append(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13235, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13235, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13236; public new global::java.lang.StringBuffer append(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13236, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13236, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _append13237; public new global::java.lang.StringBuffer append(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._append13237, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._append13237, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _indexOf13238; public sealed override int indexOf(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._indexOf13238, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._indexOf13238, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _indexOf13239; public sealed override int indexOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._indexOf13239, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._indexOf13239, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _length13240; public sealed override int length() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._length13240); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._length13240); } internal static global::MonoJavaBridge.MethodId _charAt13241; public sealed override char charAt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallCharMethod(this.JvmHandle, global::java.lang.StringBuffer._charAt13241, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._charAt13241, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _codePointAt13242; public sealed override int codePointAt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._codePointAt13242, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._codePointAt13242, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _codePointBefore13243; public sealed override int codePointBefore(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._codePointBefore13243, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._codePointBefore13243, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _codePointCount13244; public sealed override int codePointCount(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._codePointCount13244, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._codePointCount13244, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _offsetByCodePoints13245; public sealed override int offsetByCodePoints(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._offsetByCodePoints13245, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._offsetByCodePoints13245, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getChars13246; public sealed override void getChars(int arg0, int arg1, char[] arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.StringBuffer._getChars13246, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._getChars13246, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _lastIndexOf13247; public sealed override int lastIndexOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._lastIndexOf13247, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._lastIndexOf13247, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _lastIndexOf13248; public sealed override int lastIndexOf(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._lastIndexOf13248, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._lastIndexOf13248, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _substring13249; public sealed override global::java.lang.String substring(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._substring13249, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._substring13249, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _substring13250; public sealed override global::java.lang.String substring(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._substring13250, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._substring13250, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _subSequence13251; public sealed override global::java.lang.CharSequence subSequence(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._subSequence13251, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._subSequence13251, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _replace13252; public new global::java.lang.StringBuffer replace(int arg0, int arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._replace13252, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._replace13252, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _trimToSize13253; public sealed override void trimToSize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.StringBuffer._trimToSize13253); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._trimToSize13253); } internal static global::MonoJavaBridge.MethodId _ensureCapacity13254; public sealed override void ensureCapacity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.StringBuffer._ensureCapacity13254, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._ensureCapacity13254, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _capacity13255; public sealed override int capacity() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.StringBuffer._capacity13255); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._capacity13255); } internal static global::MonoJavaBridge.MethodId _setLength13256; public sealed override void setLength(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.StringBuffer._setLength13256, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._setLength13256, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setCharAt13257; public sealed override void setCharAt(int arg0, char arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.StringBuffer._setCharAt13257, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._setCharAt13257, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _appendCodePoint13258; public new global::java.lang.StringBuffer appendCodePoint(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._appendCodePoint13258, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._appendCodePoint13258, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _delete13259; public new global::java.lang.StringBuffer delete(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._delete13259, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._delete13259, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _deleteCharAt13260; public new global::java.lang.StringBuffer deleteCharAt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._deleteCharAt13260, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._deleteCharAt13260, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13261; public new global::java.lang.StringBuffer insert(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13261, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13261, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13262; public new global::java.lang.StringBuffer insert(int arg0, char arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13262, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13262, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13263; public new global::java.lang.StringBuffer insert(int arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13263, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13263, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13264; public new global::java.lang.StringBuffer insert(int arg0, java.lang.CharSequence arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13264, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13264, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.StringBuffer; } public java.lang.StringBuffer insert(int arg0, string arg1, int arg2, int arg3) { return insert(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1, arg2, arg3); } internal static global::MonoJavaBridge.MethodId _insert13265; public new global::java.lang.StringBuffer insert(int arg0, java.lang.CharSequence arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13265, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13265, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } public java.lang.StringBuffer insert(int arg0, string arg1) { return insert(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1); } internal static global::MonoJavaBridge.MethodId _insert13266; public new global::java.lang.StringBuffer insert(int arg0, char[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13266, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13266, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13267; public new global::java.lang.StringBuffer insert(int arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13267, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13267, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13268; public new global::java.lang.StringBuffer insert(int arg0, java.lang.Object arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13268, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13268, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13269; public new global::java.lang.StringBuffer insert(int arg0, char[] arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13269, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13269, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13270; public new global::java.lang.StringBuffer insert(int arg0, double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13270, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13270, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13271; public new global::java.lang.StringBuffer insert(int arg0, float arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13271, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13271, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _insert13272; public new global::java.lang.StringBuffer insert(int arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._insert13272, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._insert13272, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _reverse13273; public new global::java.lang.StringBuffer reverse() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.StringBuffer._reverse13273)) as java.lang.StringBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._reverse13273)) as java.lang.StringBuffer; } internal static global::MonoJavaBridge.MethodId _StringBuffer13274; public StringBuffer() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._StringBuffer13274); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _StringBuffer13275; public StringBuffer(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._StringBuffer13275, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _StringBuffer13276; public StringBuffer(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._StringBuffer13276, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _StringBuffer13277; public StringBuffer(java.lang.CharSequence arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.StringBuffer.staticClass, global::java.lang.StringBuffer._StringBuffer13277, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.StringBuffer.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/StringBuffer")); global::java.lang.StringBuffer._toString13224 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "toString", "()Ljava/lang/String;"); global::java.lang.StringBuffer._append13225 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "([CII)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13226 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13227 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13228 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(Ljava/lang/StringBuffer;)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13229 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(Ljava/lang/CharSequence;)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13230 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(Ljava/lang/CharSequence;II)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13231 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "([C)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13232 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(Z)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13233 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(C)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13234 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(I)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13235 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(J)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13236 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(F)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._append13237 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "append", "(D)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._indexOf13238 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "indexOf", "(Ljava/lang/String;I)I"); global::java.lang.StringBuffer._indexOf13239 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "indexOf", "(Ljava/lang/String;)I"); global::java.lang.StringBuffer._length13240 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "length", "()I"); global::java.lang.StringBuffer._charAt13241 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "charAt", "(I)C"); global::java.lang.StringBuffer._codePointAt13242 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "codePointAt", "(I)I"); global::java.lang.StringBuffer._codePointBefore13243 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "codePointBefore", "(I)I"); global::java.lang.StringBuffer._codePointCount13244 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "codePointCount", "(II)I"); global::java.lang.StringBuffer._offsetByCodePoints13245 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "offsetByCodePoints", "(II)I"); global::java.lang.StringBuffer._getChars13246 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "getChars", "(II[CI)V"); global::java.lang.StringBuffer._lastIndexOf13247 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "lastIndexOf", "(Ljava/lang/String;)I"); global::java.lang.StringBuffer._lastIndexOf13248 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "lastIndexOf", "(Ljava/lang/String;I)I"); global::java.lang.StringBuffer._substring13249 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "substring", "(I)Ljava/lang/String;"); global::java.lang.StringBuffer._substring13250 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "substring", "(II)Ljava/lang/String;"); global::java.lang.StringBuffer._subSequence13251 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "subSequence", "(II)Ljava/lang/CharSequence;"); global::java.lang.StringBuffer._replace13252 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "replace", "(IILjava/lang/String;)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._trimToSize13253 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "trimToSize", "()V"); global::java.lang.StringBuffer._ensureCapacity13254 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "ensureCapacity", "(I)V"); global::java.lang.StringBuffer._capacity13255 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "capacity", "()I"); global::java.lang.StringBuffer._setLength13256 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "setLength", "(I)V"); global::java.lang.StringBuffer._setCharAt13257 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "setCharAt", "(IC)V"); global::java.lang.StringBuffer._appendCodePoint13258 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "appendCodePoint", "(I)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._delete13259 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "delete", "(II)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._deleteCharAt13260 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "deleteCharAt", "(I)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13261 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(II)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13262 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(IC)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13263 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(IZ)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13264 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(ILjava/lang/CharSequence;II)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13265 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(ILjava/lang/CharSequence;)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13266 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(I[C)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13267 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(ILjava/lang/String;)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13268 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(ILjava/lang/Object;)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13269 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(I[CII)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13270 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(ID)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13271 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(IF)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._insert13272 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "insert", "(IJ)Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._reverse13273 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "reverse", "()Ljava/lang/StringBuffer;"); global::java.lang.StringBuffer._StringBuffer13274 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "<init>", "()V"); global::java.lang.StringBuffer._StringBuffer13275 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "<init>", "(I)V"); global::java.lang.StringBuffer._StringBuffer13276 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "<init>", "(Ljava/lang/String;)V"); global::java.lang.StringBuffer._StringBuffer13277 = @__env.GetMethodIDNoThrow(global::java.lang.StringBuffer.staticClass, "<init>", "(Ljava/lang/CharSequence;)V"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Runtime; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace UnitTests.General { [TestCategory("Elasticity"), TestCategory("Placement")] public class ElasticPlacementTests : TestClusterPerTest { private readonly List<IActivationCountBasedPlacementTestGrain> grains = new List<IActivationCountBasedPlacementTestGrain>(); private const int leavy = 300; private const int perSilo = 1000; protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.AddSiloBuilderConfigurator<SiloConfigurator>(); } private class SiloConfigurator : ISiloConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorage("MemoryStore") .AddMemoryGrainStorageAsDefault() .Configure<LoadSheddingOptions>(options => options.LoadSheddingEnabled = true); } } /// <summary> /// Test placement behaviour for newly added silos. The grain placement strategy should favor them /// until they reach a similar load as the other silos. /// </summary> [SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_CatchingUp() { logger.Info("\n\n\n----- Phase 1 -----\n\n"); AddTestGrains(perSilo).Wait(); AddTestGrains(perSilo).Wait(); var activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); AssertIsInRange(activationCounts[this.HostedCluster.Primary], perSilo, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], perSilo, leavy); SiloHandle silo3 = this.HostedCluster.StartAdditionalSilo(); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); logger.Info("\n\n\n----- Phase 2 -----\n\n"); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); logger.Info("-----------------------------------------------------------------"); activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); double expected = (6.0 * perSilo) / 3.0; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, leavy); AssertIsInRange(activationCounts[silo3], expected, leavy); logger.Info("\n\n\n----- Phase 3 -----\n\n"); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); logger.Info("-----------------------------------------------------------------"); activationCounts = await GetPerSiloActivationCounts(); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); expected = (9.0 * perSilo) / 3.0; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, leavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, leavy); AssertIsInRange(activationCounts[silo3], expected, leavy); logger.Info("-----------------------------------------------------------------"); logger.Info("Test finished OK. Expected per silo = {0}", expected); } /// <summary> /// This evaluates the how the placement strategy behaves once silos are stopped: The strategy should /// balance the activations from the stopped silo evenly among the remaining silos. /// </summary> [SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_StoppingSilos() { List<SiloHandle> runtimes = await this.HostedCluster.StartAdditionalSilosAsync(2); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); int stopLeavy = leavy; await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); await AddTestGrains(perSilo); var activationCounts = await GetPerSiloActivationCounts(); logger.Info("-----------------------------------------------------------------"); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); AssertIsInRange(activationCounts[this.HostedCluster.Primary], perSilo, stopLeavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], perSilo, stopLeavy); AssertIsInRange(activationCounts[runtimes[0]], perSilo, stopLeavy); AssertIsInRange(activationCounts[runtimes[1]], perSilo, stopLeavy); await this.HostedCluster.StopSiloAsync(runtimes[0]); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); await InvokeAllGrains(); activationCounts = await GetPerSiloActivationCounts(); logger.Info("-----------------------------------------------------------------"); LogCounts(activationCounts); logger.Info("-----------------------------------------------------------------"); double expected = perSilo * 1.33; AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, stopLeavy); AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, stopLeavy); AssertIsInRange(activationCounts[runtimes[1]], expected, stopLeavy); logger.Info("-----------------------------------------------------------------"); logger.Info("Test finished OK. Expected per silo = {0}", expected); } /// <summary> /// Do not place activation in case all silos are above 110 CPU utilization. /// </summary> [SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_AllSilosCPUTooHigh() { var taintedGrainPrimary = await GetGrainAtSilo(this.HostedCluster.Primary.SiloAddress); var taintedGrainSecondary = await GetGrainAtSilo(this.HostedCluster.SecondarySilos.First().SiloAddress); await taintedGrainPrimary.EnableOverloadDetection(false); await taintedGrainSecondary.EnableOverloadDetection(false); await taintedGrainPrimary.LatchCpuUsage(110.0f); await taintedGrainSecondary.LatchCpuUsage(110.0f); await Assert.ThrowsAsync<OrleansException>(() => this.AddTestGrains(1)); } /// <summary> /// Do not place activation in case all silos are above 110 CPU utilization or have overloaded flag set. /// </summary> [SkippableFact(Skip= "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")] public async Task ElasticityTest_AllSilosOverloaded() { var taintedGrainPrimary = await GetGrainAtSilo(this.HostedCluster.Primary.SiloAddress); var taintedGrainSecondary = await GetGrainAtSilo(this.HostedCluster.SecondarySilos.First().SiloAddress); await taintedGrainPrimary.LatchCpuUsage(110.0f); await taintedGrainSecondary.LatchOverloaded(); // OrleansException or GateWayTooBusyException var exception = await Assert.ThrowsAnyAsync<Exception>(() => this.AddTestGrains(1)); Assert.True(exception is OrleansException || exception is GatewayTooBusyException); } [Fact, TestCategory("Functional")] public async Task LoadAwareGrainShouldNotAttemptToCreateActivationsOnOverloadedSilo() { await ElasticityGrainPlacementTest( g => g.LatchOverloaded(), g => g.UnlatchOverloaded(), "LoadAwareGrainShouldNotAttemptToCreateActivationsOnOverloadedSilo", "A grain instantiated with the load-aware placement strategy should not attempt to create activations on an overloaded silo."); } [Fact, TestCategory("Functional")] public async Task LoadAwareGrainShouldNotAttemptToCreateActivationsOnBusySilos() { // a CPU usage of 110% will disqualify a silo from getting new grains. const float undesirability = (float)110.0; await ElasticityGrainPlacementTest( g => g.LatchCpuUsage(undesirability), g => g.UnlatchCpuUsage(), "LoadAwareGrainShouldNotAttemptToCreateActivationsOnBusySilos", "A grain instantiated with the load-aware placement strategy should not attempt to create activations on a busy silo."); } private async Task<IPlacementTestGrain> GetGrainAtSilo(SiloAddress silo) { while (true) { IPlacementTestGrain grain = this.GrainFactory.GetGrain<IRandomPlacementTestGrain>(Guid.NewGuid()); SiloAddress address = await grain.GetLocation(); if (address.Equals(silo)) return grain; } } private static void AssertIsInRange(int actual, double expected, int leavy) { Assert.True(expected - leavy <= actual && actual <= expected + leavy, String.Format("Expecting a value in the range between {0} and {1}, but instead got {2} outside the range.", expected - leavy, expected + leavy, actual)); } private async Task ElasticityGrainPlacementTest( Func<IPlacementTestGrain, Task> taint, Func<IPlacementTestGrain, Task> restore, string name, string assertMsg) { await this.HostedCluster.WaitForLivenessToStabilizeAsync(); logger.Info("********************** Starting the test {0} ******************************", name); var taintedSilo = this.HostedCluster.StartAdditionalSilo(); const long sampleSize = 10; var taintedGrain = await GetGrainAtSilo(taintedSilo.SiloAddress); var testGrains = Enumerable.Range(0, (int)sampleSize). Select( n => this.GrainFactory.GetGrain<IActivationCountBasedPlacementTestGrain>(Guid.NewGuid())); // make the grain's silo undesirable for new grains. taint(taintedGrain).Wait(); List<IPEndPoint> actual; try { actual = testGrains.Select( g => g.GetEndpoint().Result).ToList(); } finally { // i don't know if this necessary but to be safe, i'll restore the silo's desirability. logger.Info("********************** Finalizing the test {0} ******************************", name); restore(taintedGrain).Wait(); } var unexpected = taintedSilo.SiloAddress.Endpoint; Assert.True( actual.All( i => !i.Equals(unexpected)), assertMsg); } private Task AddTestGrains(int amount) { var promises = new List<Task>(); for (var i = 0; i < amount; i++) { IActivationCountBasedPlacementTestGrain grain = this.GrainFactory.GetGrain<IActivationCountBasedPlacementTestGrain>(Guid.NewGuid()); this.grains.Add(grain); // Make sure we activate grain: promises.Add(grain.Nop()); } return Task.WhenAll(promises); } private Task InvokeAllGrains() { var promises = new List<Task>(); foreach (var grain in grains) { promises.Add(grain.Nop()); } return Task.WhenAll(promises); } private async Task<Dictionary<SiloHandle, int>> GetPerSiloActivationCounts() { string fullTypeName = "UnitTests.Grains.ActivationCountBasedPlacementTestGrain"; IManagementGrain mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0); SimpleGrainStatistic[] stats = await mgmtGrain.GetSimpleGrainStatistics(); return this.HostedCluster.GetActiveSilos() .ToDictionary( s => s, s => stats .Where(stat => stat.SiloAddress.Equals(s.SiloAddress) && stat.GrainType == fullTypeName) .Select(stat => stat.ActivationCount).SingleOrDefault()); } private void LogCounts(Dictionary<SiloHandle, int> activationCounts) { var sb = new StringBuilder(); foreach (var silo in this.HostedCluster.GetActiveSilos()) { int count; activationCounts.TryGetValue(silo, out count); sb.AppendLine($"{silo.Name}.ActivationCount = {count}"); } logger.Info(sb.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Numerics.Hashing; namespace System.Drawing { /// <summary> /// <para> /// Stores the location and size of a rectangular region. /// </para> /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public struct RectangleF : IEquatable<RectangleF> { /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class. /// </summary> public static readonly RectangleF Empty = new RectangleF(); private float x; // Do not rename (binary serialization) private float y; // Do not rename (binary serialization) private float width; // Do not rename (binary serialization) private float height; // Do not rename (binary serialization) /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class with the specified location and size. /// </para> /// </summary> public RectangleF(float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; this.height = height; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class with the specified location /// and size. /// </para> /// </summary> public RectangleF(PointF location, SizeF size) { x = location.X; y = location.Y; width = size.Width; height = size.Height; } /// <summary> /// <para> /// Creates a new <see cref='System.Drawing.RectangleF'/> with /// the specified location and size. /// </para> /// </summary> public static RectangleF FromLTRB(float left, float top, float right, float bottom) => new RectangleF(left, top, right - left, bottom - top); /// <summary> /// <para> /// Gets or sets the coordinates of the upper-left corner of /// the rectangular region represented by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> [Browsable(false)] public PointF Location { get { return new PointF(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// <para> /// Gets or sets the size of this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> [Browsable(false)] public SizeF Size { get { return new SizeF(Width, Height); } set { Width = value.Width; Height = value.Height; } } /// <summary> /// <para> /// Gets or sets the x-coordinate of the /// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float X { get { return x; } set { x = value; } } /// <summary> /// <para> /// Gets or sets the y-coordinate of the /// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Y { get { return y; } set { y = value; } } /// <summary> /// <para> /// Gets or sets the width of the rectangular /// region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Width { get { return width; } set { width = value; } } /// <summary> /// <para> /// Gets or sets the height of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Height { get { return height; } set { height = value; } } /// <summary> /// <para> /// Gets the x-coordinate of the upper-left corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/> . /// </para> /// </summary> [Browsable(false)] public float Left => X; /// <summary> /// <para> /// Gets the y-coordinate of the upper-left corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> [Browsable(false)] public float Top => Y; /// <summary> /// <para> /// Gets the x-coordinate of the lower-right corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> [Browsable(false)] public float Right => X + Width; /// <summary> /// <para> /// Gets the y-coordinate of the lower-right corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> [Browsable(false)] public float Bottom => Y + Height; /// <summary> /// <para> /// Tests whether this <see cref='System.Drawing.RectangleF'/> has a <see cref='System.Drawing.RectangleF.Width'/> or a <see cref='System.Drawing.RectangleF.Height'/> of 0. /// </para> /// </summary> [Browsable(false)] public bool IsEmpty => (Width <= 0) || (Height <= 0); /// <summary> /// <para> /// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.RectangleF'/> with the same location and size of this /// <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public override bool Equals(object obj) => obj is RectangleF && Equals((RectangleF)obj); public bool Equals(RectangleF other) => this == other; /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.RectangleF'/> /// objects have equal location and size. /// </para> /// </summary> public static bool operator ==(RectangleF left, RectangleF right) => left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height; /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.RectangleF'/> /// objects differ in location or size. /// </para> /// </summary> public static bool operator !=(RectangleF left, RectangleF right) => !(left == right); /// <summary> /// <para> /// Determines if the specified point is contained within the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> public bool Contains(float x, float y) => X <= x && x < X + Width && Y <= y && y < Y + Height; /// <summary> /// <para> /// Determines if the specified point is contained within the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> public bool Contains(PointF pt) => Contains(pt.X, pt.Y); /// <summary> /// <para> /// Determines if the rectangular region represented by /// <paramref name="rect"/> is entirely contained within the rectangular region represented by /// this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> public bool Contains(RectangleF rect) => (X <= rect.X) && (rect.X + rect.Width <= X + Width) && (Y <= rect.Y) && (rect.Y + rect.Height <= Y + Height); /// <summary> /// Gets the hash code for this <see cref='System.Drawing.RectangleF'/>. /// </summary> public override int GetHashCode() => HashHelpers.Combine( HashHelpers.Combine(HashHelpers.Combine(X.GetHashCode(), Y.GetHashCode()), Width.GetHashCode()), Height.GetHashCode()); /// <summary> /// <para> /// Inflates this <see cref='System.Drawing.Rectangle'/> /// by the specified amount. /// </para> /// </summary> public void Inflate(float x, float y) { X -= x; Y -= y; Width += 2 * x; Height += 2 * y; } /// <summary> /// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount. /// </summary> public void Inflate(SizeF size) => Inflate(size.Width, size.Height); /// <summary> /// <para> /// Creates a <see cref='System.Drawing.Rectangle'/> /// that is inflated by the specified amount. /// </para> /// </summary> public static RectangleF Inflate(RectangleF rect, float x, float y) { RectangleF r = rect; r.Inflate(x, y); return r; } /// <summary> Creates a Rectangle that represents the intersection between this Rectangle and rect. /// </summary> public void Intersect(RectangleF rect) { RectangleF result = Intersect(rect, this); X = result.X; Y = result.Y; Width = result.Width; Height = result.Height; } /// <summary> /// Creates a rectangle that represents the intersection between a and /// b. If there is no intersection, null is returned. /// </summary> public static RectangleF Intersect(RectangleF a, RectangleF b) { float x1 = Math.Max(a.X, b.X); float x2 = Math.Min(a.X + a.Width, b.X + b.Width); float y1 = Math.Max(a.Y, b.Y); float y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); if (x2 >= x1 && y2 >= y1) { return new RectangleF(x1, y1, x2 - x1, y2 - y1); } return Empty; } /// <summary> /// Determines if this rectangle intersects with rect. /// </summary> public bool IntersectsWith(RectangleF rect) => (rect.X < X + Width) && (X < rect.X + rect.Width) && (rect.Y < Y + Height) && (Y < rect.Y + rect.Height); /// <summary> /// Creates a rectangle that represents the union between a and /// b. /// </summary> public static RectangleF Union(RectangleF a, RectangleF b) { float x1 = Math.Min(a.X, b.X); float x2 = Math.Max(a.X + a.Width, b.X + b.Width); float y1 = Math.Min(a.Y, b.Y); float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new RectangleF(x1, y1, x2 - x1, y2 - y1); } /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(PointF pos) => Offset(pos.X, pos.Y); /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(float x, float y) { X += x; Y += y; } /// <summary> /// Converts the specified <see cref='System.Drawing.Rectangle'/> to a /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public static implicit operator RectangleF(Rectangle r) => new RectangleF(r.X, r.Y, r.Width, r.Height); /// <summary> /// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/> of this <see cref='System.Drawing.RectangleF'/> to a /// human-readable string. /// </summary> public override string ToString() => "{X=" + X.ToString() + ",Y=" + Y.ToString() + ",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}"; } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; /// ****************************************************************************************************************** /// * Copyright (c) 2011 Dialect Software LLC * /// * This software is distributed under the terms of the Apache License http://www.apache.org/licenses/LICENSE-2.0 * /// * * /// ****************************************************************************************************************** namespace DialectSoftware.Networking { namespace Controls { /// <summary> /// Summary description for NetworkServerCtrl. /// </summary> public class NetworkServerCtrl : System.Windows.Forms.UserControl { /// <summary> /// Required designer variable. /// </summary> private System.Boolean started = false; private System.ComponentModel.Container components = null; private static System.Net.Sockets.TcpListener _server = null; private Security.Authentication.SSPI.SSPIAuthenticate _securityServer = null; private readonly System.Int32 _size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(long)); public delegate void ServerNetworkCallBack(AsyncNetworkAdapter Adapter, System.Byte[] Data); public event ServerNetworkCallBack _receive = null; public delegate void ServerNetworkErrorHandler(AsyncNetworkAdapter state, System.Exception e); public event ServerNetworkErrorHandler _errorHandler = null; public ServerNetworkCallBack Receive { set { if(this._receive != null) throw new InvalidOperationException("Only one delegate can be assigned."); this._receive += value; } } public ServerNetworkErrorHandler ErrorHandler { set { if(this._errorHandler != null) throw new InvalidOperationException("Only one delegate can be assigned."); this._errorHandler += value; } } public Security.Authentication.SSPI.SSPIAuthenticate SecurityServer { get{return _securityServer;} } public NetworkServerCtrl() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitializeComponent call } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(NetworkServerCtrl)); // // BuildServerCtrl // this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.Name = "BuildServerCtrl"; this.Size = new System.Drawing.Size(32, 32); this.Load += new System.EventHandler(this.NetworkServerCtrl_Load); } #endregion private void NetworkServerCtrl_Load(object sender, System.EventArgs e) { } private void NetworkServerCtrl_AsyncCallback(System.IAsyncResult result) { object[] args = {result}; ((System.Runtime.Remoting.Messaging.AsyncResult)result).AsyncDelegate.GetType().GetMethod("EndInvoke").Invoke(((System.Runtime.Remoting.Messaging.AsyncResult)result).AsyncDelegate,args); } private void NetworkServerCtrl_Error(AsyncNetworkAdapter state,System.Exception e) { if(this._errorHandler != null) _errorHandler.BeginInvoke(state,e,new System.AsyncCallback(NetworkServerCtrl_AsyncCallback),null); } public void Stop() { if(started) { _server.Stop(); started = !started; } } public void Accept(Int32 Port) { _server = new System.Net.Sockets.TcpListener(Port); _server.Start(); started = true; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ThreadProc)); } public void Send(AsyncNetworkAdapter state, byte[] Data, Int32 TimeOut,bool WriteRead) { System.IO.MemoryStream stream = new System.IO.MemoryStream(Data.Length + _size); stream.Write(System.BitConverter.GetBytes(Data.LongLength),0,_size); stream.Write(Data,0,Data.Length); stream.Flush(); stream.Seek(0,System.IO.SeekOrigin.Begin); if(WriteRead) ((AsyncTcpClientAdapter)state).BeginWrite((byte[])stream.GetBuffer().Clone(),new AsyncNetworkCallBack(Read),TimeOut); else ((AsyncTcpClientAdapter)state).BeginWrite((byte[])stream.GetBuffer().Clone(),new AsyncNetworkCallBack(End),TimeOut); stream.Close(); } private void ThreadProc(object stateInfo) { while(started) { try { System.Net.Sockets.TcpClient client = _server.AcceptTcpClient(); _securityServer = new Security.Authentication.SSPI.NTLM.AuthenticationServer(); AsyncTcpClientAdapter adapter = new AsyncTcpClientAdapter(client,new AsyncNetworkErrorCallBack(NetworkServerCtrl_Error)); Read(adapter); adapter = null; } catch { started = false; } } } private void Read(AsyncNetworkAdapter state) { if(((AsyncTcpClientAdapter)state).Status == AsyncNetworkStatus.Read || ((AsyncTcpClientAdapter)state).Status == AsyncNetworkStatus.ReadWrite) ((AsyncTcpClientAdapter)state).Read(_size,(int)TimeOut.Default); else ((AsyncTcpClientAdapter)state).BeginRead(new AsyncNetworkCallBack(ReadComplete),(int)TimeOut.Default); } private void End(AsyncNetworkAdapter state) { _receive.BeginInvoke(state,null,new System.AsyncCallback(NetworkServerCtrl_AsyncCallback),null); } private void ReadComplete(AsyncNetworkAdapter state) { if(state.Buffer.Length >= _size) { long length = System.BitConverter.ToInt64(state.Buffer,0); if(state.Buffer.LongLength < (length + _size)) { ((AsyncTcpClientAdapter)state).Read((length + _size) - state.Buffer.LongLength,(int)TimeOut.Default); } else { System.IO.MemoryStream stream = new System.IO.MemoryStream((int)length); stream.Write(state.Buffer,_size,(int)length); stream.Seek(0,System.IO.SeekOrigin.Begin); if(this._receive != null) _receive.BeginInvoke(state,(byte[])stream.GetBuffer().Clone(),new System.AsyncCallback(NetworkServerCtrl_AsyncCallback),null); stream.Close(); } } } protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.ComponentModel; using System.Xml; using log4net; using Axiom.MathLib; using Axiom.Core; using Axiom.Animating; using Multiverse.CollisionLib; using Multiverse.Config; namespace Multiverse.CollisionLib { abstract public class PathInterpolator { public PathInterpolator(long oid, long startTime, float speed, String terrainString, List<Vector3> path) { this.oid = oid; this.startTime = startTime; this.speed = speed; this.terrainString = terrainString; this.path = path; } // abstract public string ToString(); abstract public PathLocAndDir Interpolate(long systemTime); public Vector3 ZeroYIfOnTerrain(Vector3 loc, int pointIndex) { Debug.Assert(pointIndex >= 0 && pointIndex < terrainString.Length - 1); // If either the previous point was on terrain or the // current point is on terrain, then the path element is a if (terrainString[pointIndex] == 'T' || terrainString[pointIndex + 1] == 'T') loc.y = 0f; return loc; } public string StringPath() { string s = ""; for (int i=0; i<path.Count; i++) { Vector3 p = path[i]; if (s.Length > 0) s += ", "; s += "#" + i + ": " + terrainString[i] + p; } return s; } public long Oid { get { return oid; } } public float Speed { get { return speed; } } public string TerrainString { get { return terrainString; } } public long StartTime { get { return startTime; } } public float TotalTime { get { return totalTime; } } protected long oid; protected float speed; protected String terrainString; protected List<Vector3> path; protected float totalTime; // In seconds from start time protected long startTime; // In milliseconds - - server system time } // A PathSpline is a Catmull-Rom spline, which is related to a // BSpline. Paths produced by the pathing code are interpolated as // Catmull-Rom splines public class PathSpline : PathInterpolator { public PathSpline(long oid, long startTime, float speed, String terrainString, List<Vector3> path) : base(oid, startTime, speed, terrainString, path) { // Add two points before the zeroeth point, and one after the // count-1 point, to allow us to access from -2 to +1 points. // Add one point before the zeroeth point, and two after the // count-1 point, to allow us to access from -1 to +2 points. path.Insert(0, path[0]); Vector3 last = path[path.Count - 1]; path.Add(last); path.Add(last); int count = path.Count; timeVector = new float[count]; timeVector[0] = 0f; float t = 0; Vector3 curr = path[0]; for (int i=1; i<count; i++) { Vector3 next = path[i]; Vector3 diff = next - curr; float diffTime = diff.Length; t = t + diffTime / speed; timeVector[i] = t; curr = next; } totalTime = t; } public override string ToString() { return "[PathSpline oid = " + oid + "; speed = " + speed + "; timeVector = " + timeVector + "; path = " + StringPath() + "]"; } public override PathLocAndDir Interpolate(long systemTime) { float t = (float)(systemTime - startTime) / 1000f; if (t < 0) t = 0; else if (t >= totalTime) return null; // Find the point number whose time is less than or equal to t int count = path.Count; // A bit of trickiness - - the first two points and the last // point are dummies, inserted only to ensure that we have -2 // to +1 points at every real point. int pointNumber = -2; for (int i=0; i<count; i++) { if (timeVector[i] > t) { pointNumber = i - 1; break; } } if (pointNumber == -1) { pointNumber = 1; } Vector3 loc; Vector3 dir; float timeFraction = 0; // If we're beyond the last time, return the last point, and a // (0,0,0) direction if (pointNumber == -2) { loc = path[count - 1]; dir = new Vector3(0f, 0f, 0f); } else { float timeAtPoint = timeVector[pointNumber]; float timeSincePoint = t - timeAtPoint; timeFraction = timeSincePoint / (timeVector[pointNumber + 1] - timeAtPoint); loc = evalPoint(pointNumber, timeFraction); dir = evalDirection(loc, pointNumber, timeFraction) * speed; } // A bit tricky - - if there were n elements in the _original_ // path, there are n-1 characters in the terrain string. // We've added _three_ additional path elements, one before // and two after. int pathNumber = (pointNumber == -2 ? count - 4 : pointNumber); if (terrainString[pathNumber] == 'T' || terrainString[pathNumber + 1] == 'T') { loc.y = 0f; dir.y = 0f; } return new PathLocAndDir(loc, dir, speed * (totalTime - t)); } // Catmull-Rom spline is just like a B spline, only with a different basis protected float basisFactor(int degree, float t) { switch (degree) { case -1: return ((-t + 2f) * t-1f) * t / 2f; case 0: return (((3f * t-5f) * t) * t + 2f) / 2f; case 1: return ((-3f * t + 4f) * t + 1f) * t / 2f; case 2: return ((t-1f) * t * t) / 2f; } return 0f; //we only get here if an invalid i is specified } // evaluate a point on the spline. t is the time since we arrived // at point pointNumber. protected Vector3 evalPoint(int pointNumber, float t) { float px = 0; float py = 0; float pz = 0; for (int degree = -1; degree<=2; degree++) { float basis = basisFactor(degree, t); Vector3 pathPoint = path[pointNumber + degree]; px += basis * pathPoint.x; py += basis * pathPoint.y; pz += basis * pathPoint.z; } return new Vector3(px, py, pz); } // // evaluate a point on the spline. t is the time since we arrived // // at point pointNumber. // protected Vector3 evalPoint(int pointNumber, float t) { // Vector3 p0 = path[pointNumber - 2]; // Vector3 p1 = path[pointNumber - 1]; // Vector3 p2 = path[pointNumber]; // Vector3 p3 = path[pointNumber + 1]; // Vector3 q = 0.5f * ((p1 * 2f) + // (p2 - p0) * t + // (2 * p0 - 5 * p1 + 4 * p2 - p3) * t*t + // (3 * p1 - 3 * p2 + p3 - p0) * t * t * t); // return q; // } // .1 second protected float directionTimeOffset = .01f; // evaluate the direction on the spline. t is the time since we // arrived at point pointNumber. protected Vector3 evalDirection(Vector3 p, int pointNumber, float t) { Vector3 next = evalPoint(pointNumber, t + directionTimeOffset); Vector3 n = next - p; n.y = 0; n.Normalize(); return n; } protected float [] timeVector; } // A linear interpolator of a sequence of points public class PathLinear : PathInterpolator { // Create a logger for use in this class private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(PathLinear)); public PathLinear(long oid, long startTime, float speed, String terrainString, List<Vector3> path) : base(oid, startTime, speed, terrainString, path) { float cumm = 0f; Vector3 curr = path[0]; for (int i=1; i<path.Count; i++) { Vector3 next = path[i]; Vector3 diff = next - curr; diff.y = 0f; float dist = (next - curr).Length; float diffTime = dist / speed; cumm += diffTime; } totalTime = cumm; } // Evaluate the position and direction on the path. The // argument is the millisecond system time public override PathLocAndDir Interpolate(long systemTime) { float t = (float)(systemTime - startTime) / 1000f; if (t < 0) t = 0; else if (t >= totalTime) { log.DebugFormat("PathLinear.Interpolate: oid {0}, time has expired", oid); return null; } float cumm = 0f; Vector3 curr = path[0]; for (int i=1; i<path.Count; i++) { Vector3 next = path[i]; Vector3 diff = next - curr; diff.y = 0; // ZeroYIfOnTerrain(diff, i - 1); float dist = diff.Length; float diffTime = dist / speed; if (t <= cumm + diffTime) { float frac = (t - cumm) / diffTime; Vector3 loc = curr + (diff * frac); // ZeroYIfOnTerrain(curr + (diff * frac), i - 1); diff.Normalize(); Vector3 dir = diff * speed; log.DebugFormat("PathLinear.Interpolate: oid {0}, next {1}, curr {2}, diff {3}, diffTime {4}, frac {5}, loc {6}, dir {7}", oid, next, curr, diff, diffTime, frac, loc, dir); return new PathLocAndDir(loc, dir, speed * (totalTime - t)); } cumm += diffTime; curr = next; } // Didn't find the time, so return the last point, and a dir // of zero return new PathLocAndDir(path[path.Count - 1], new Vector3(0f, 0f, 0f), 0f); } public override String ToString() { return "[PathLinear oid = " + oid + "; speed = " + speed + "; path = " + StringPath() + "]"; } } // A class to encapsulate the return values from path // interpolators public class PathLocAndDir { public PathLocAndDir(Vector3 location, Vector3 direction, float lengthLeft) { this.location = location; this.direction = direction; this.lengthLeft = lengthLeft; } public Vector3 Location { get { return location; } } public Vector3 Direction { get { return direction; } } public float LengthLeft { get { return lengthLeft; } } public override string ToString() { return string.Format("[PathLocAndDir loc {0} dir {1} lengthLeft {2}]", location, direction, lengthLeft); } protected Vector3 location; protected Vector3 direction; protected float lengthLeft; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; namespace System.IO { // Provides methods for processing file system strings in a cross-platform manner. // Most of the methods don't do a complete parsing (such as examining a UNC hostname), // but they will handle most string operations. public static partial class Path { // Platform specific alternate directory separator character. // There is only one directory separator char on Unix, which is the same // as the alternate separator on Windows, so same definition is used for both. public static readonly char AltDirectorySeparatorChar = '/'; // Changes the extension of a file path. The path parameter // specifies a file path, and the extension parameter // specifies a file extension (with a leading period, such as // ".exe" or ".cs"). // // The function returns a file path with the same root, directory, and base // name parts as path, but with the file extension changed to // the specified extension. If path is null, the function // returns null. If path does not contain a file extension, // the new file extension is appended to the path. If extension // is null, any exsiting extension is removed from path. public static string ChangeExtension(string path, string extension) { if (path != null) { PathInternal.CheckInvalidPathChars(path); string s = path; for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { s = path.Substring(0, i); break; } if (IsDirectoryOrVolumeSeparator(ch)) break; } if (extension != null && path.Length != 0) { s = (extension.Length == 0 || extension[0] != '.') ? s + "." + extension : s + extension; } return s; } return null; } // Returns the directory path of a file path. This method effectively // removes the last element of the given file path, i.e. it returns a // string consisting of all characters up to but not including the last // backslash ("\") in the file path. The returned value is null if the file // path is null or if the file path denotes a root (such as "\", "C:", or // "\\server\share"). public static string GetDirectoryName(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); path = NormalizePath(path, fullCheck: false); int root = PathInternal.GetRootLength(path); int i = path.Length; if (i > root) { i = path.Length; if (i == root) return null; while (i > root && !PathInternal.IsDirectorySeparator(path[--i])) ; return path.Substring(0, i); } } return null; } public static char[] GetInvalidPathChars() { return (char[])PathInternal.InvalidPathChars.Clone(); } public static char[] GetInvalidFileNameChars() { return (char[])InvalidFileNameChars.Clone(); } // Returns the extension of the given path. The returned value includes the // period (".") character of the extension except when you have a terminal period when you get string.Empty, such as ".exe" or // ".cpp". The returned value is null if the given path is // null or if the given path does not include an extension. [Pure] public static string GetExtension(string path) { if (path == null) return null; PathInternal.CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { if (i != length - 1) return path.Substring(i, length - i); else return string.Empty; } if (IsDirectoryOrVolumeSeparator(ch)) break; } return string.Empty; } private static string GetFullPathInternal(string path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return NormalizePath(path, fullCheck: true); } [System.Security.SecuritySafeCritical] // auto-generated private static string NormalizePath(string path, bool fullCheck) { return NormalizePath(path, fullCheck, MaxPath); } [System.Security.SecuritySafeCritical] // auto-generated private static string NormalizePath(string path, bool fullCheck, bool expandShortPaths) { return NormalizePath(path, fullCheck, MaxPath, expandShortPaths); } [System.Security.SecuritySafeCritical] // auto-generated private static string NormalizePath(string path, bool fullCheck, int maxPathLength) { return NormalizePath(path, fullCheck, maxPathLength, expandShortPaths: true); } // Returns the name and extension parts of the given path. The resulting // string contains the characters of path that follow the last // separator in path. The resulting string is null if path is null. [Pure] public static string GetFileName(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (IsDirectoryOrVolumeSeparator(ch)) return path.Substring(i + 1, length - i - 1); } } return path; } [Pure] public static string GetFileNameWithoutExtension(string path) { if (path == null) return null; path = GetFileName(path); int i; return (i = path.LastIndexOf('.')) == -1 ? path : // No path extension found path.Substring(0, i); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. [Pure] public static string GetPathRoot(string path) { if (path == null) return null; path = NormalizePath(path, fullCheck: false); return path.Substring(0, PathInternal.GetRootLength(path)); } // Returns a cryptographically strong random 8.3 string that can be // used as either a folder name or a file name. public static string GetRandomFileName() { // 5 bytes == 40 bits == 40/5 == 8 chars in our encoding. // So 10 bytes provides 16 chars, of which we need 11 // for the 8.3 name. byte[] key = CreateCryptoRandomByteArray(10); // rndCharArray is expected to be 16 chars char[] rndCharArray = ToBase32StringSuitableForDirName(key).ToCharArray(); rndCharArray[8] = '.'; return new string(rndCharArray, 0, 12); } // Returns a unique temporary file name, and creates a 0-byte file by that // name on disk. [System.Security.SecuritySafeCritical] public static string GetTempFileName() { return InternalGetTempFileName(checkHost: true); } // Tests if a path includes a file extension. The result is // true if the characters that follow the last directory // separator ('\\' or '/') or volume separator (':') in the path include // a period (".") other than a terminal period. The result is false otherwise. [Pure] public static bool HasExtension(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { return i != path.Length - 1; } if (IsDirectoryOrVolumeSeparator(ch)) break; } } return false; } public static string Combine(string path1, string path2) { if (path1 == null || path2 == null) throw new ArgumentNullException((path1 == null) ? "path1" : "path2"); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); return CombineNoChecks(path1, path2); } public static string Combine(string path1, string path2, string path3) { if (path1 == null || path2 == null || path3 == null) throw new ArgumentNullException((path1 == null) ? "path1" : (path2 == null) ? "path2" : "path3"); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); PathInternal.CheckInvalidPathChars(path3); return CombineNoChecks(path1, path2, path3); } public static string Combine(params string[] paths) { if (paths == null) { throw new ArgumentNullException("paths"); } Contract.EndContractBlock(); int finalSize = 0; int firstComponent = 0; // We have two passes, the first calcuates how large a buffer to allocate and does some precondition // checks on the paths passed in. The second actually does the combination. for (int i = 0; i < paths.Length; i++) { if (paths[i] == null) { throw new ArgumentNullException("paths"); } if (paths[i].Length == 0) { continue; } PathInternal.CheckInvalidPathChars(paths[i]); if (IsPathRooted(paths[i])) { firstComponent = i; finalSize = paths[i].Length; } else { finalSize += paths[i].Length; } char ch = paths[i][paths[i].Length - 1]; if (!IsDirectoryOrVolumeSeparator(ch)) finalSize++; } StringBuilder finalPath = StringBuilderCache.Acquire(finalSize); for (int i = firstComponent; i < paths.Length; i++) { if (paths[i].Length == 0) { continue; } if (finalPath.Length == 0) { finalPath.Append(paths[i]); } else { char ch = finalPath[finalPath.Length - 1]; if (!IsDirectoryOrVolumeSeparator(ch)) { finalPath.Append(DirectorySeparatorChar); } finalPath.Append(paths[i]); } } return StringBuilderCache.GetStringAndRelease(finalPath); } private static string CombineNoChecks(string path1, string path2) { if (path2.Length == 0) return path1; if (path1.Length == 0) return path2; if (IsPathRooted(path2)) return path2; char ch = path1[path1.Length - 1]; return IsDirectoryOrVolumeSeparator(ch) ? path1 + path2 : path1 + DirectorySeparatorCharAsString + path2; } private static string CombineNoChecks(string path1, string path2, string path3) { if (path1.Length == 0) return CombineNoChecks(path2, path3); if (path2.Length == 0) return CombineNoChecks(path1, path3); if (path3.Length == 0) return CombineNoChecks(path1, path2); if (IsPathRooted(path3)) return path3; if (IsPathRooted(path2)) return CombineNoChecks(path2, path3); bool hasSep1 = IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); if (hasSep1 && hasSep2) { return path1 + path2 + path3; } else if (hasSep1) { return path1 + path2 + DirectorySeparatorCharAsString + path3; } else if (hasSep2) { return path1 + DirectorySeparatorCharAsString + path2 + path3; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + 2); sb.Append(path1) .Append(DirectorySeparatorChar) .Append(path2) .Append(DirectorySeparatorChar) .Append(path3); return StringBuilderCache.GetStringAndRelease(sb); } } private static readonly char[] s_Base32Char = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5'}; private static string ToBase32StringSuitableForDirName(byte[] buff) { // This routine is optimised to be used with buffs of length 20 Debug.Assert(((buff.Length % 5) == 0), "Unexpected hash length"); // For every 5 bytes, 8 characters are appended. StringBuilder sb = StringBuilderCache.Acquire(); // Create l char for each of the last 5 bits of each byte. // Consume 3 MSB bits 5 bytes at a time. int len = buff.Length; int i = 0; do { byte b0 = (i < len) ? buff[i++] : (byte)0; byte b1 = (i < len) ? buff[i++] : (byte)0; byte b2 = (i < len) ? buff[i++] : (byte)0; byte b3 = (i < len) ? buff[i++] : (byte)0; byte b4 = (i < len) ? buff[i++] : (byte)0; // Consume the 5 Least significant bits of each byte sb.Append(s_Base32Char[b0 & 0x1F]); sb.Append(s_Base32Char[b1 & 0x1F]); sb.Append(s_Base32Char[b2 & 0x1F]); sb.Append(s_Base32Char[b3 & 0x1F]); sb.Append(s_Base32Char[b4 & 0x1F]); // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4 sb.Append(s_Base32Char[( ((b0 & 0xE0) >> 5) | ((b3 & 0x60) >> 2))]); sb.Append(s_Base32Char[( ((b1 & 0xE0) >> 5) | ((b4 & 0x60) >> 2))]); // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4 b2 >>= 5; Debug.Assert(((b2 & 0xF8) == 0), "Unexpected set bits"); if ((b3 & 0x80) != 0) b2 |= 0x08; if ((b4 & 0x80) != 0) b2 |= 0x10; sb.Append(s_Base32Char[b2]); } while (i < len); return StringBuilderCache.GetStringAndRelease(sb); } } }
// Generated by UblXml2CSharp using System.Xml; using UblLarsen.Ubl2; using UblLarsen.Ubl2.Cac; using UblLarsen.Ubl2.Ext; using UblLarsen.Ubl2.Udt; namespace UblLarsen.Test.UblClass { internal class UBLInvoice20Enveloped { public static InvoiceType Create() { var doc = new InvoiceType { UBLExtensions = new UBLExtensionType[] { new UBLExtensionType { } }, UBLVersionID = "2.0", CustomizationID = "urn:oasis:names:specification:ubl:xpath:Invoice-2.0:sbs-1.0-draft", ProfileID = "bpid:urn:oasis:names:draft:bpss:ubl-2-sbs-invoice-notification-draft", ID = "A00095678", CopyIndicator = false, UUID = "849FBBCE-E081-40B4-906C-94C5FF9D1AC3", IssueDate = "2005-06-21", InvoiceTypeCode = "SalesInvoice", Note = new TextType[] { new TextType { Value = "sample" } }, TaxPointDate = "2005-06-21", OrderReference = new OrderReferenceType { ID = "AEG012345", SalesOrderID = "CON0095678", UUID = "6E09886B-DC6E-439F-82D1-7CCAC7F4E3B1", IssueDate = "2005-06-20" }, Signature = new SignatureType[] { new SignatureType { ID = "urn:oasis:names:specification:ubl:signature:Invoice", SignatureMethod = "urn:oasis:names:specification:ubl:dsig:enveloped", SignatoryParty = new PartyType { PartyIdentification = new PartyIdentificationType[] { new PartyIdentificationType { ID = "MyParty" } } } } }, AccountingSupplierParty = new SupplierPartyType { CustomerAssignedAccountID = "CO001", Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "Consortial" } }, PostalAddress = new AddressType { StreetName = "Busy Street", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Farthing", PostalZone = "AA99 1BB", CountrySubentity = "Heremouthshire", AddressLine = new AddressLineType[] { new AddressLineType { Line = "The Roundabout" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Farthing Purchasing Consortium", CompanyID = "175 269 2355", ExemptionReason = new TextType[] { new TextType { Value = "N/A" } }, TaxScheme = new TaxSchemeType { ID = "VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "Mrs Bouquet", Telephone = "0158 1233714", Telefax = "0158 1233856", ElectronicMail = "[email protected]" } } }, AccountingCustomerParty = new CustomerPartyType { CustomerAssignedAccountID = "XFB01", SupplierAssignedAccountID = "GT00978567", Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "IYT Corporation" } }, PostalAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Bridgtow District Council", CompanyID = "12356478", ExemptionReason = new TextType[] { new TextType { Value = "Local Authority" } }, TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "Mr Fred Churchill", Telephone = "0127 2653214", Telefax = "0127 2653215", ElectronicMail = "[email protected]" } } }, Delivery = new DeliveryType[] { new DeliveryType { ActualDeliveryDate = "2005-06-20", ActualDeliveryTime = "11:30:00.0Z", DeliveryAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } } } }, PaymentMeans = new PaymentMeansType[] { new PaymentMeansType { PaymentMeansCode = "20", PaymentDueDate = "2005-07-21", PayeeFinancialAccount = new FinancialAccountType { ID = "12345678", Name = "Farthing Purchasing Consortium", AccountTypeCode = "Current", CurrencyCode = "GBP", FinancialInstitutionBranch = new BranchType { ID = "10-26-58", Name = "Open Bank Ltd, Bridgstow Branch ", FinancialInstitution = new FinancialInstitutionType { ID = "10-26-58", Name = "Open Bank Ltd", Address = new AddressType { StreetName = "City Road", BuildingName = "Banking House", BuildingNumber = "12", CityName = "London", PostalZone = "AQ1 6TH", CountrySubentity = @"London ", AddressLine = new AddressLineType[] { new AddressLineType { Line = "5th Floor" } }, Country = new CountryType { IdentificationCode = "GB" } } }, Address = new AddressType { StreetName = "Busy Street", BuildingName = "The Mall", BuildingNumber = "152", CityName = "Farthing", PostalZone = "AA99 1BB", CountrySubentity = "Heremouthshire", AddressLine = new AddressLineType[] { new AddressLineType { Line = "West Wing" } }, Country = new CountryType { IdentificationCode = "GB" } } }, Country = new CountryType { IdentificationCode = "GB" } } } }, PaymentTerms = new PaymentTermsType[] { new PaymentTermsType { Note = new TextType[] { new TextType { Value = "Payable within 1 calendar month from the invoice date" } } } }, AllowanceCharge = new AllowanceChargeType[] { new AllowanceChargeType { ChargeIndicator = false, AllowanceChargeReasonCode = "17", MultiplierFactorNumeric = 0.10M, Amount = new AmountType { currencyID = "GBP", Value = 10.00M } } }, TaxTotal = new TaxTotalType[] { new TaxTotalType { TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxEvidenceIndicator = true, TaxSubtotal = new TaxSubtotalType[] { new TaxSubtotalType { TaxableAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxCategory = new TaxCategoryType { ID = "A", TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } } } } }, LegalMonetaryTotal = new MonetaryTotalType { LineExtensionAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxExclusiveAmount = new AmountType { currencyID = "GBP", Value = 90.00M }, AllowanceTotalAmount = new AmountType { currencyID = "GBP", Value = 10.00M }, PayableAmount = new AmountType { currencyID = "GBP", Value = 107.50M } }, InvoiceLine = new InvoiceLineType[] { new InvoiceLineType { ID = "A", InvoicedQuantity = new QuantityType { unitCode = "KGM", Value = 100M }, LineExtensionAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, OrderLineReference = new OrderLineReferenceType[] { new OrderLineReferenceType { LineID = "1", SalesOrderLineID = "A", LineStatusCode = "NoStatus", OrderReference = new OrderReferenceType { ID = "AEG012345", SalesOrderID = "CON0095678", UUID = "6E09886B-DC6E-439F-82D1-7CCAC7F4E3B1", IssueDate = "2005-06-20" } } }, TaxTotal = new TaxTotalType[] { new TaxTotalType { TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxEvidenceIndicator = true, TaxSubtotal = new TaxSubtotalType[] { new TaxSubtotalType { TaxableAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxCategory = new TaxCategoryType { ID = "A", Percent = 17.5M, TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } } } } }, Item = new ItemType { Description = new TextType[] { new TextType { Value = "Acme beeswax" } }, Name = "beeswax", BuyersItemIdentification = new ItemIdentificationType { ID = "6578489" }, SellersItemIdentification = new ItemIdentificationType { ID = "17589683" }, ItemInstance = new ItemInstanceType[] { new ItemInstanceType { LotIdentification = new LotIdentificationType { LotNumberID = "546378239", ExpiryDate = "2010-01-01" } } } }, Price = new PriceType { PriceAmount = new AmountType { currencyID = "GBP", Value = 1.00M }, BaseQuantity = new QuantityType { unitCode = "KGM", Value = 1M } } } } }; doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[] { new XmlQualifiedName("cbc","urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"), new XmlQualifiedName("cac","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"), new XmlQualifiedName("ext","urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"), }); return doc; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using QuantConnect.Util; using QuantConnect.Logging; using QuantConnect.Packets; using QuantConnect.Algorithm; using QuantConnect.Interfaces; using QuantConnect.Configuration; using System.Collections.Generic; using QuantConnect.AlgorithmFactory; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Brokerages.Backtesting; namespace QuantConnect.Lean.Engine.Setup { /// <summary> /// Backtesting setup handler processes the algorithm initialize method and sets up the internal state of the algorithm class. /// </summary> public class BacktestingSetupHandler : ISetupHandler { /// <summary> /// The worker thread instance the setup handler should use /// </summary> public WorkerThread WorkerThread { get; set; } /// <summary> /// Internal errors list from running the setup procedures. /// </summary> public List<Exception> Errors { get; set; } /// <summary> /// Maximum runtime of the algorithm in seconds. /// </summary> /// <remarks>Maximum runtime is a formula based on the number and resolution of symbols requested, and the days backtesting</remarks> public TimeSpan MaximumRuntime { get; protected set; } /// <summary> /// Starting capital according to the users initialize routine. /// </summary> /// <remarks>Set from the user code.</remarks> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public decimal StartingPortfolioValue { get; protected set; } /// <summary> /// Start date for analysis loops to search for data. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(DateTime)"/> public DateTime StartingDate { get; protected set; } /// <summary> /// Maximum number of orders for this backtest. /// </summary> /// <remarks>To stop algorithm flooding the backtesting system with hundreds of megabytes of order data we limit it to 100 per day</remarks> public int MaxOrders { get; protected set; } /// <summary> /// Initialize the backtest setup handler. /// </summary> public BacktestingSetupHandler() { MaximumRuntime = TimeSpan.FromSeconds(300); Errors = new List<Exception>(); StartingDate = new DateTime(1998, 01, 01); } /// <summary> /// Create a new instance of an algorithm from a physical dll path. /// </summary> /// <param name="assemblyPath">The path to the assembly's location</param> /// <param name="algorithmNodePacket">Details of the task required</param> /// <returns>A new instance of IAlgorithm, or throws an exception if there was an error</returns> public virtual IAlgorithm CreateAlgorithmInstance(AlgorithmNodePacket algorithmNodePacket, string assemblyPath) { string error; IAlgorithm algorithm; var debugNode = algorithmNodePacket as BacktestNodePacket; var debugging = debugNode != null && debugNode.IsDebugging || Config.GetBool("debugging", false); if (debugging && !BaseSetupHandler.InitializeDebugging(algorithmNodePacket, WorkerThread)) { throw new AlgorithmSetupException("Failed to initialize debugging"); } // Limit load times to 90 seconds and force the assembly to have exactly one derived type var loader = new Loader(debugging, algorithmNodePacket.Language, BaseSetupHandler.AlgorithmCreationTimeout, names => names.SingleOrAlgorithmTypeName(Config.Get("algorithm-type-name")), WorkerThread); var complete = loader.TryCreateAlgorithmInstanceWithIsolator(assemblyPath, algorithmNodePacket.RamAllocation, out algorithm, out error); if (!complete) throw new AlgorithmSetupException($"During the algorithm initialization, the following exception has occurred: {error}"); return algorithm; } /// <summary> /// Creates a new <see cref="BacktestingBrokerage"/> instance /// </summary> /// <param name="algorithmNodePacket">Job packet</param> /// <param name="uninitializedAlgorithm">The algorithm instance before Initialize has been called</param> /// <param name="factory">The brokerage factory</param> /// <returns>The brokerage instance, or throws if error creating instance</returns> public IBrokerage CreateBrokerage(AlgorithmNodePacket algorithmNodePacket, IAlgorithm uninitializedAlgorithm, out IBrokerageFactory factory) { factory = new BacktestingBrokerageFactory(); var optionMarketSimulation = new BasicOptionAssignmentSimulation(); return new BacktestingBrokerage(uninitializedAlgorithm, optionMarketSimulation); } /// <summary> /// Setup the algorithm cash, dates and data subscriptions as desired. /// </summary> /// <param name="parameters">The parameters object to use</param> /// <returns>Boolean true on successfully initializing the algorithm</returns> public bool Setup(SetupHandlerParameters parameters) { var algorithm = parameters.Algorithm; var job = parameters.AlgorithmNodePacket as BacktestNodePacket; if (job == null) { throw new ArgumentException("Expected BacktestNodePacket but received " + parameters.AlgorithmNodePacket.GetType().Name); } Log.Trace($"BacktestingSetupHandler.Setup(): Setting up job: UID: {job.UserId.ToStringInvariant()}, " + $"PID: {job.ProjectId.ToStringInvariant()}, Version: {job.Version}, Source: {job.RequestSource}" ); if (algorithm == null) { Errors.Add(new AlgorithmSetupException("Could not create instance of algorithm")); return false; } algorithm.Name = job.GetAlgorithmName(); //Make sure the algorithm start date ok. if (job.PeriodStart == default(DateTime)) { Errors.Add(new AlgorithmSetupException("Algorithm start date was never set")); return false; } var controls = job.Controls; var isolator = new Isolator(); var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromMinutes(5), () => { try { parameters.ResultHandler.SendStatusUpdate(AlgorithmStatus.Initializing, "Initializing algorithm..."); //Set our parameters algorithm.SetParameters(job.Parameters); algorithm.SetAvailableDataTypes(BaseSetupHandler.GetConfiguredDataFeeds()); //Algorithm is backtesting, not live: algorithm.SetLiveMode(false); //Set the source impl for the event scheduling algorithm.Schedule.SetEventSchedule(parameters.RealTimeHandler); // set the option chain provider algorithm.SetOptionChainProvider(new CachingOptionChainProvider(new BacktestingOptionChainProvider(parameters.DataProvider))); // set the future chain provider algorithm.SetFutureChainProvider(new CachingFutureChainProvider(new BacktestingFutureChainProvider(parameters.DataProvider))); // set the object store algorithm.SetObjectStore(parameters.ObjectStore); // before we call initialize BaseSetupHandler.LoadBacktestJobAccountCurrency(algorithm, job); //Initialise the algorithm, get the required data: algorithm.Initialize(); // set start and end date if present in the job if (job.PeriodStart.HasValue) { algorithm.SetStartDate(job.PeriodStart.Value); } if (job.PeriodFinish.HasValue) { algorithm.SetEndDate(job.PeriodFinish.Value); } // after we call initialize BaseSetupHandler.LoadBacktestJobCashAmount(algorithm, job); // finalize initialization algorithm.PostInitialize(); } catch (Exception err) { Errors.Add(new AlgorithmSetupException("During the algorithm initialization, the following exception has occurred: ", err)); } }, controls.RamAllocation, sleepIntervalMillis: 100, // entire system is waiting on this, so be as fast as possible workerThread: WorkerThread); if (Errors.Count > 0) { // if we already got an error just exit right away return false; } //Before continuing, detect if this is ready: if (!initializeComplete) return false; MaximumRuntime = TimeSpan.FromMinutes(job.Controls.MaximumRuntimeMinutes); BaseSetupHandler.SetupCurrencyConversions(algorithm, parameters.UniverseSelection); StartingPortfolioValue = algorithm.Portfolio.Cash; // we set the free portfolio value based on the initial total value and the free percentage value algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; // Get and set maximum orders for this job MaxOrders = job.Controls.BacktestingMaxOrders; algorithm.SetMaximumOrders(MaxOrders); //Starting date of the algorithm: StartingDate = algorithm.StartDate; //Put into log for debugging: Log.Trace("SetUp Backtesting: User: " + job.UserId + " ProjectId: " + job.ProjectId + " AlgoId: " + job.AlgorithmId); Log.Trace($"Dates: Start: {algorithm.StartDate.ToStringInvariant("d")} " + $"End: {algorithm.EndDate.ToStringInvariant("d")} " + $"Cash: {StartingPortfolioValue.ToStringInvariant("C")} " + $"MaximumRuntime: {MaximumRuntime} " + $"MaxOrders: {MaxOrders}"); return initializeComplete; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { } } // End Result Handler Thread: } // End Namespace
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Validation; namespace System.Collections.Immutable { public partial struct ImmutableArray<T> { /// <summary> /// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/> /// instance without allocating memory. /// </summary> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))] public sealed class Builder : IList<T>, IReadOnlyList<T> { /// <summary> /// The backing array for the builder. /// </summary> private T[] _elements; /// <summary> /// The number of initialized elements in the array. /// </summary> private int _count; /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> /// <param name="capacity">The initial capacity of the internal array.</param> internal Builder(int capacity) { Requires.Range(capacity >= 0, "capacity"); _elements = new T[capacity]; _count = 0; } /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> internal Builder() : this(8) { } /// <summary> /// Get and sets the length of the internal array. When set the internal array is /// reallocated to the given capacity if it is not already the specified length. /// </summary> public int Capacity { get { return _elements.Length; } set { if (value < _count) { throw new ArgumentException(SR.CapacityMustBeGreaterThanOrEqualToCount, paramName: "value"); } if (value != _elements.Length) { if (value > 0) { var temp = new T[value]; if (_count > 0) { Array.Copy(_elements, 0, temp, 0, _count); } _elements = temp; } else { _elements = ImmutableArray<T>.Empty.array; } } } } /// <summary> /// Gets or sets the length of the builder. /// </summary> /// <remarks> /// If the value is decreased, the array contents are truncated. /// If the value is increased, the added elements are initialized to the default value of type <typeparamref name="T"/>. /// </remarks> public int Count { get { return _count; } set { Requires.Range(value >= 0, "value"); if (value < _count) { // truncation mode // Clear the elements of the elements that are effectively removed. // PERF: Array.Clear works well for big arrays, // but may have too much overhead with small ones (which is the common case here) if (_count - value > 64) { Array.Clear(_elements, value, _count - value); } else { for (int i = value; i < this.Count; i++) { _elements[i] = default(T); } } } else if (value > _count) { // expansion this.EnsureCapacity(value); } _count = value; } } /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// </exception> public T this[int index] { get { if (index >= this.Count) { throw new IndexOutOfRangeException(); } return _elements[index]; } set { if (index >= this.Count) { throw new IndexOutOfRangeException(); } _elements[index] = value; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool ICollection<T>.IsReadOnly { get { return false; } } /// <summary> /// Returns an immutable copy of the current contents of this collection. /// </summary> /// <returns>An immutable array.</returns> public ImmutableArray<T> ToImmutable() { if (Count == 0) { return Empty; } return new ImmutableArray<T>(this.ToArray()); } /// <summary> /// Extracts the internal array as an <see cref="ImmutableArray{T}"/> and replaces it /// with a zero length array. /// </summary> /// <exception cref="InvalidOperationException">When <see cref="ImmutableArray{T}.Builder.Count"/> doesn't /// equal <see cref="ImmutableArray{T}.Builder.Capacity"/>.</exception> public ImmutableArray<T> MoveToImmutable() { if (Capacity != Count) { throw new InvalidOperationException(SR.CapacityMustEqualCountOnMove); } T[] temp = _elements; _elements = ImmutableArray<T>.Empty.array; _count = 0; return new ImmutableArray<T>(temp); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> public void Clear() { this.Count = 0; } /// <summary> /// Inserts an item to the <see cref="IList{T}"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="IList{T}"/>.</param> public void Insert(int index, T item) { Requires.Range(index >= 0 && index <= this.Count, "index"); this.EnsureCapacity(this.Count + 1); if (index < this.Count) { Array.Copy(_elements, index, _elements, index + 1, this.Count - index); } _count++; _elements[index] = item; } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> public void Add(T item) { this.EnsureCapacity(this.Count + 1); _elements[_count++] = item; } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(IEnumerable<T> items) { Requires.NotNull(items, "items"); int count; if (items.TryGetCount(out count)) { this.EnsureCapacity(this.Count + count); } foreach (var item in items) { this.Add(item); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(params T[] items) { Requires.NotNull(items, "items"); var offset = this.Count; this.Count += items.Length; Array.Copy(items, 0, _elements, offset, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(TDerived[] items) where TDerived : T { Requires.NotNull(items, "items"); var offset = this.Count; this.Count += items.Length; Array.Copy(items, 0, _elements, offset, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> /// <param name="length">The number of elements from the source array to add.</param> public void AddRange(T[] items, int length) { Requires.NotNull(items, "items"); Requires.Range(length >= 0 && length <= items.Length, "length"); var offset = this.Count; this.Count += length; Array.Copy(items, 0, _elements, offset, length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(ImmutableArray<T> items) { this.AddRange(items, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> /// <param name="length">The number of elements from the source array to add.</param> public void AddRange(ImmutableArray<T> items, int length) { Requires.Range(length >= 0, "length"); if (items.array != null) { this.AddRange(items.array, length); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T { if (items.array != null) { this.AddRange(items.array); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(Builder items) { Requires.NotNull(items, "items"); this.AddRange(items._elements, items.Count); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T { Requires.NotNull(items, "items"); this.AddRange(items._elements, items.Count); } /// <summary> /// Removes the specified element. /// </summary> /// <param name="element">The element.</param> /// <returns>A value indicating whether the specified element was found and removed from the collection.</returns> public bool Remove(T element) { int index = this.IndexOf(element); if (index >= 0) { this.RemoveAt(index); return true; } return false; } /// <summary> /// Removes the <see cref="IList{T}"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> public void RemoveAt(int index) { Requires.Range(index >= 0 && index < this.Count, "index"); if (index < this.Count - 1) { Array.Copy(_elements, index + 1, _elements, index, this.Count - index - 1); } this.Count--; } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> public bool Contains(T item) { return this.IndexOf(item) >= 0; } /// <summary> /// Creates a new array with the current contents of this Builder. /// </summary> public T[] ToArray() { T[] result = new T[this.Count]; Array.Copy(_elements, 0, result, 0, this.Count); return result; } /// <summary> /// Copies the current contents to the specified array. /// </summary> /// <param name="array">The array to copy to.</param> /// <param name="index">The starting index of the target array.</param> public void CopyTo(T[] array, int index) { Requires.NotNull(array, "array"); Requires.Range(index >= 0 && index + this.Count <= array.Length, "start"); Array.Copy(_elements, 0, array, index, this.Count); } /// <summary> /// Resizes the array to accommodate the specified capacity requirement. /// </summary> /// <param name="capacity">The required capacity.</param> private void EnsureCapacity(int capacity) { if (_elements.Length < capacity) { int newCapacity = Math.Max(_elements.Length * 2, capacity); Array.Resize(ref _elements, newCapacity); } } /// <summary> /// Determines the index of a specific item in the <see cref="IList{T}"/>. /// </summary> /// <param name="item">The object to locate in the <see cref="IList{T}"/>.</param> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> [Pure] public int IndexOf(T item) { return this.IndexOf(item, 0, _count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex) { return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex, int count) { return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer) { Requires.NotNull(equalityComparer, "equalityComparer"); if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex"); Requires.Range(count >= 0 && startIndex + count <= this.Count, "count"); if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(_elements, item, startIndex, count); } else { for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(_elements[i], item)) { return i; } } return -1; } } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item) { if (this.Count == 0) { return -1; } return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex) { if (this.Count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex"); return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex, int count) { return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer) { Requires.NotNull(equalityComparer, "equalityComparer"); if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex"); Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count"); if (equalityComparer == EqualityComparer<T>.Default) { return Array.LastIndexOf(_elements, item, startIndex, count); } else { for (int i = startIndex; i >= startIndex - count + 1; i--) { if (equalityComparer.Equals(item, _elements[i])) { return i; } } return -1; } } /// <summary> /// Reverses the order of elements in the collection. /// </summary> public void Reverse() { // The non-generic Array.Reverse is not used because it does not perform // well for non-primitive value types. // If/when a generic Array.Reverse<T> becomes available, the below code // can be deleted and replaced with a call to Array.Reverse<T>. int i = 0; int j = _count - 1; T[] array = _elements; while (i < j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } } /// <summary> /// Sorts the array. /// </summary> public void Sort() { if (Count > 1) { Array.Sort(_elements, 0, this.Count, Comparer<T>.Default); } } /// <summary> /// Sorts the array. /// </summary> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public void Sort(IComparer<T> comparer) { if (Count > 1) { Array.Sort(_elements, 0, _count, comparer); } } /// <summary> /// Sorts the array. /// </summary> /// <param name="index">The index of the first element to consider in the sort.</param> /// <param name="count">The number of elements to include in the sort.</param> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public void Sort(int index, int count, IComparer<T> comparer) { // Don't rely on Array.Sort's argument validation since our internal array may exceed // the bounds of the publicly addressable region. Requires.Range(index >= 0, "index"); Requires.Range(count >= 0 && index + count <= this.Count, "count"); if (count > 1) { Array.Sort(_elements, index, count, comparer); } } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> public IEnumerator<T> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return this[i]; } } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Adds items to this collection. /// </summary> /// <typeparam name="TDerived">The type of source elements.</typeparam> /// <param name="items">The source array.</param> /// <param name="length">The number of elements to add to this array.</param> private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T { this.EnsureCapacity(this.Count + length); var offset = this.Count; this.Count += length; var nodes = _elements; for (int i = 0; i < length; i++) { nodes[offset + i] = items[i]; } } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal sealed class ImmutableArrayBuilderDebuggerProxy<T> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableArray<T>.Builder _builder; /// <summary> /// Initializes a new instance of the <see cref="ImmutableArrayBuilderDebuggerProxy{T}"/> class. /// </summary> /// <param name="builder">The collection to display in the debugger</param> public ImmutableArrayBuilderDebuggerProxy(ImmutableArray<T>.Builder builder) { _builder = builder; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] A { get { return _builder.ToArray(); } } } }
// 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. /*============================================================ ** ** ** ** A specially designed handle wrapper to ensure we never leak ** an OS handle. The runtime treats this class specially during ** P/Invoke marshaling and finalization. Users should write ** subclasses of CriticalHandle for each distinct handle type. ** This class is similar to SafeHandle, but lacks the ref counting ** behavior on marshaling that prevents handle recycling errors ** or security holes. This lowers the overhead of using the handle ** considerably, but leaves the onus on the caller to protect ** themselves from any recycling effects. ** ** **** NOTE **** ** ** Since there are no ref counts tracking handle usage there is ** no thread safety either. Your application must ensure that ** usages of the handle do not cross with attempts to close the ** handle (or tolerate such crossings). Normal GC mechanics will ** prevent finalization until the handle class isn't used any more, ** but explicit Close or Dispose operations may be initiated at any ** time. ** ** Similarly, multiple calls to Close or Dispose on different ** threads at the same time may cause the ReleaseHandle method to be ** called more than once. ** ** In general (and as might be inferred from the lack of handle ** recycle protection) you should be very cautious about exposing ** CriticalHandle instances directly or indirectly to untrusted users. ** At a minimum you should restrict their ability to queue multiple ** operations against a single handle at the same time or block their ** access to Close and Dispose unless you are very comfortable with the ** semantics of passing an invalid (or possibly invalidated and ** reallocated) to the unamanged routines you marshal your handle to ** (and the effects of closing such a handle while those calls are in ** progress). The runtime cannot protect you from undefined program ** behvior that might result from such scenarios. You have been warned. ** ** ===========================================================*/ using System; using System.Reflection; using System.Threading; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.IO; /* Problems addressed by the CriticalHandle class: 1) Critical finalization - ensure we never leak OS resources in SQL. Done without running truly arbitrary & unbounded amounts of managed code. 2) Reduced graph promotion - during finalization, keep object graph small 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race condition (HandleRef) 4) Enforcement of the above via the type system - Don't use IntPtr anymore. Subclasses of CriticalHandle will implement the ReleaseHandle abstract method used to execute any code required to free the handle. This method will be prepared as a constrained execution region at instance construction time (along with all the methods in its statically determinable call graph). This implies that we won't get any inconvenient jit allocation errors or rude thread abort interrupts while releasing the handle but the user must still write careful code to avoid injecting fault paths of their own (see the CER spec for more details). In particular, any sub-methods you call should be decorated with a reliability contract of the appropriate level. In most cases this should be: ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success) Also, any P/Invoke methods should use the SuppressUnmanagedCodeSecurity attribute to avoid a runtime security check that can also inject failures (even if the check is guaranteed to pass). Subclasses must also implement the IsInvalid property so that the infrastructure can tell when critical finalization is actually required. Again, this method is prepared ahead of time. It's envisioned that direct subclasses of CriticalHandle will provide an IsInvalid implementation that suits the general type of handle they support (null is invalid, -1 is invalid etc.) and then these classes will be further derived for specific handle types. Most classes using CriticalHandle should not provide a finalizer. If they do need to do so (ie, for flushing out file buffers, needing to write some data back into memory, etc), then they can provide a finalizer that will be guaranteed to run before the CriticalHandle's critical finalizer. Subclasses are expected to be written as follows (note that SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods invoked as part of ReleaseHandle, in order to switch the security check from runtime to jit time and thus remove a possible failure path from the invocation of the method): internal sealed MyCriticalHandleSubclass : CriticalHandle { // Called by P/Invoke when returning CriticalHandles private MyCriticalHandleSubclass() : base(IntPtr.Zero) { } // Do not provide a finalizer - CriticalHandle's critical finalizer will // call ReleaseHandle for you. public override bool IsInvalid { get { return handle == IntPtr.Zero; } } [DllImport(Win32Native.KERNEL32), SuppressUnmanagedCodeSecurity, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern bool CloseHandle(IntPtr handle); override protected bool ReleaseHandle() { return CloseHandle(handle); } } Then elsewhere to create one of these CriticalHandles, define a method with the following type of signature (CreateFile follows this model). Note that when returning a CriticalHandle like this, P/Invoke will call your classes default constructor. [DllImport(Win32Native.KERNEL32)] private static extern MyCriticalHandleSubclass CreateHandle(int someState); */ namespace System.Runtime.InteropServices { // This class should not be serializable - it's a handle. We require unmanaged // code permission to subclass CriticalHandle to prevent people from writing a // subclass and suddenly being able to run arbitrary native code with the // same signature as CloseHandle. This is technically a little redundant, but // we'll do this to ensure we've cut off all attack vectors. Similarly, all // methods have a link demand to ensure untrusted code cannot directly edit // or alter a handle. [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] #endif public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable { // ! Do not add or rearrange fields as the EE depends on this layout. //------------------------------------------------------------------ #if DEBUG private String _stackTrace; // Where we allocated this CriticalHandle. #endif protected IntPtr handle; // This must be protected so derived classes can use out params. private bool _isClosed; // Set by SetHandleAsInvalid or Close/Dispose/finalization. // Creates a CriticalHandle class. Users must then set the Handle property or allow P/Invoke marshaling to set it implicitly. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected CriticalHandle(IntPtr invalidHandleValue) { handle = invalidHandleValue; _isClosed = false; #if DEBUG if (BCLDebug.SafeHandleStackTracesEnabled) _stackTrace = Environment.GetStackTrace(null, false); else _stackTrace = "For a stack trace showing who allocated this CriticalHandle, set SafeHandleStackTraces to 1 and rerun your app."; #endif } #if FEATURE_CORECLR // Adding an empty default constructor for annotation purposes private CriticalHandle(){} #endif [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] ~CriticalHandle() { Dispose(false); } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private void Cleanup() { if (IsClosed) return; _isClosed = true; if (IsInvalid) return; // Save last error from P/Invoke in case the implementation of // ReleaseHandle trashes it (important because this ReleaseHandle could // occur implicitly as part of unmarshaling another P/Invoke). int lastError = Marshal.GetLastWin32Error(); if (!ReleaseHandle()) FireCustomerDebugProbe(); Marshal.SetLastWin32Error(lastError); GC.SuppressFinalize(this); } [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private extern void FireCustomerDebugProbe(); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected void SetHandle(IntPtr handle) { this.handle = handle; } // Returns whether the handle has been explicitly marked as closed // (Close/Dispose) or invalid (SetHandleAsInvalid). public bool IsClosed { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return _isClosed; } } // Returns whether the handle looks like an invalid value (i.e. matches one // of the handle's designated illegal values). CriticalHandle itself doesn't // know what an invalid handle looks like, so this method is abstract and // must be provided by a derived type. public abstract bool IsInvalid { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get; } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void Close() { Dispose(true); } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void Dispose() { Dispose(true); } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected virtual void Dispose(bool disposing) { Cleanup(); } // This should only be called for cases when you know for a fact that // your handle is invalid and you want to record that information. // An example is calling a syscall and getting back ERROR_INVALID_HANDLE. // This method will normally leak handles! [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void SetHandleAsInvalid() { _isClosed = true; GC.SuppressFinalize(this); } // Implement this abstract method in your derived class to specify how to // free the handle. Be careful not write any code that's subject to faults // in this method (the runtime will prepare the infrastructure for you so // that no jit allocations etc. will occur, but don't allocate memory unless // you can deal with the failure and still free the handle). // The boolean returned should be true for success and false if a // catastrophic error occurred and you wish to trigger a diagnostic for // debugging purposes (the SafeHandleCriticalFailure MDA). [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected abstract bool ReleaseHandle(); } }
using Lucene.Net.Documents; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using Counter = Lucene.Net.Util.Counter; using DocValuesConsumer = Lucene.Net.Codecs.DocValuesConsumer; using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat; using IOUtils = Lucene.Net.Util.IOUtils; internal sealed class DocValuesProcessor : StoredFieldsConsumer { // TODO: somewhat wasteful we also keep a map here; would // be more efficient if we could "reuse" the map/hash // lookup DocFieldProcessor already did "above" private readonly IDictionary<string, DocValuesWriter> writers = new Dictionary<string, DocValuesWriter>(); private readonly Counter bytesUsed; public DocValuesProcessor(Counter bytesUsed) { this.bytesUsed = bytesUsed; } public override void StartDocument() { } [MethodImpl(MethodImplOptions.NoInlining)] internal override void FinishDocument() { } public override void AddField(int docID, IIndexableField field, FieldInfo fieldInfo) { DocValuesType dvType = field.IndexableFieldType.DocValueType; if (dvType != DocValuesType.NONE) { fieldInfo.DocValuesType = dvType; if (dvType == DocValuesType.BINARY) { AddBinaryField(fieldInfo, docID, field.GetBinaryValue()); } else if (dvType == DocValuesType.SORTED) { AddSortedField(fieldInfo, docID, field.GetBinaryValue()); } else if (dvType == DocValuesType.SORTED_SET) { AddSortedSetField(fieldInfo, docID, field.GetBinaryValue()); } else if (dvType == DocValuesType.NUMERIC) { if (field.NumericType != NumericFieldType.INT64) { throw new System.ArgumentException("illegal type " + field.NumericType + ": DocValues types must be " + NumericFieldType.INT64); } AddNumericField(fieldInfo, docID, field.GetInt64ValueOrDefault()); } else { Debug.Assert(false, "unrecognized DocValues.Type: " + dvType); } } } [MethodImpl(MethodImplOptions.NoInlining)] public override void Flush(SegmentWriteState state) { if (writers.Count > 0) { DocValuesFormat fmt = state.SegmentInfo.Codec.DocValuesFormat; DocValuesConsumer dvConsumer = fmt.FieldsConsumer(state); bool success = false; try { foreach (DocValuesWriter writer in writers.Values) { writer.Finish(state.SegmentInfo.DocCount); writer.Flush(state, dvConsumer); } // TODO: catch missing DV fields here? else we have // null/"" depending on how docs landed in segments? // but we can't detect all cases, and we should leave // this behavior undefined. dv is not "schemaless": its column-stride. writers.Clear(); success = true; } finally { if (success) { IOUtils.Dispose(dvConsumer); } else { IOUtils.DisposeWhileHandlingException(dvConsumer); } } } } internal void AddBinaryField(FieldInfo fieldInfo, int docID, BytesRef value) { DocValuesWriter writer; writers.TryGetValue(fieldInfo.Name, out writer); BinaryDocValuesWriter binaryWriter; if (writer == null) { binaryWriter = new BinaryDocValuesWriter(fieldInfo, bytesUsed); writers[fieldInfo.Name] = binaryWriter; } else if (!(writer is BinaryDocValuesWriter)) { throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to binary"); } else { binaryWriter = (BinaryDocValuesWriter)writer; } binaryWriter.AddValue(docID, value); } internal void AddSortedField(FieldInfo fieldInfo, int docID, BytesRef value) { DocValuesWriter writer; writers.TryGetValue(fieldInfo.Name, out writer); SortedDocValuesWriter sortedWriter; if (writer == null) { sortedWriter = new SortedDocValuesWriter(fieldInfo, bytesUsed); writers[fieldInfo.Name] = sortedWriter; } else if (!(writer is SortedDocValuesWriter)) { throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to sorted"); } else { sortedWriter = (SortedDocValuesWriter)writer; } sortedWriter.AddValue(docID, value); } internal void AddSortedSetField(FieldInfo fieldInfo, int docID, BytesRef value) { DocValuesWriter writer; writers.TryGetValue(fieldInfo.Name, out writer); SortedSetDocValuesWriter sortedSetWriter; if (writer == null) { sortedSetWriter = new SortedSetDocValuesWriter(fieldInfo, bytesUsed); writers[fieldInfo.Name] = sortedSetWriter; } else if (!(writer is SortedSetDocValuesWriter)) { throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to sorted"); } else { sortedSetWriter = (SortedSetDocValuesWriter)writer; } sortedSetWriter.AddValue(docID, value); } internal void AddNumericField(FieldInfo fieldInfo, int docID, long value) { DocValuesWriter writer; writers.TryGetValue(fieldInfo.Name, out writer); NumericDocValuesWriter numericWriter; if (writer == null) { numericWriter = new NumericDocValuesWriter(fieldInfo, bytesUsed, true); writers[fieldInfo.Name] = numericWriter; } else if (!(writer is NumericDocValuesWriter)) { throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to numeric"); } else { numericWriter = (NumericDocValuesWriter)writer; } numericWriter.AddValue(docID, value); } private string GetTypeDesc(DocValuesWriter obj) { if (obj is BinaryDocValuesWriter) { return "binary"; } else if (obj is NumericDocValuesWriter) { return "numeric"; } else { Debug.Assert(obj is SortedDocValuesWriter); return "sorted"; } } [MethodImpl(MethodImplOptions.NoInlining)] public override void Abort() { foreach (DocValuesWriter writer in writers.Values) { try { writer.Abort(); } #pragma warning disable 168 catch (Exception t) #pragma warning restore 168 { } } writers.Clear(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; namespace Internal.Cryptography.Pal { /// <summary> /// Provides an implementation of an X509Store which is backed by files in a directory. /// </summary> internal sealed class DirectoryBasedStoreProvider : IStorePal { // {thumbprint}.1.pfx to {thumbprint}.9.pfx private const int MaxSaveAttempts = 9; private const string PfxExtension = ".pfx"; // *.pfx ({thumbprint}.pfx or {thumbprint}.{ordinal}.pfx) private const string PfxWildcard = "*" + PfxExtension; // .*.pfx ({thumbprint}.{ordinal}.pfx) private const string PfxOrdinalWildcard = "." + PfxWildcard; private static string s_userStoreRoot; private readonly string _storePath; private readonly bool _readOnly; #if DEBUG static DirectoryBasedStoreProvider() { Debug.Assert( 0 == OpenFlags.ReadOnly, "OpenFlags.ReadOnly is not zero, read-only detection will not work"); } #endif internal DirectoryBasedStoreProvider(string storeName, OpenFlags openFlags) { if (string.IsNullOrEmpty(storeName)) { throw new CryptographicException(SR.Arg_EmptyOrNullString); } Debug.Assert(!X509Store.DisallowedStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)); _storePath = GetStorePath(storeName); if (0 != (openFlags & OpenFlags.OpenExistingOnly)) { if (!Directory.Exists(_storePath)) { throw new CryptographicException(SR.Cryptography_X509_StoreNotFound); } } // ReadOnly is 0x00, so it is implicit unless either ReadWrite or MaxAllowed // was requested. OpenFlags writeFlags = openFlags & (OpenFlags.ReadWrite | OpenFlags.MaxAllowed); if (writeFlags == OpenFlags.ReadOnly) { _readOnly = true; } } public void Dispose() { } public void CloneTo(X509Certificate2Collection collection) { Debug.Assert(collection != null); if (!Directory.Exists(_storePath)) { return; } var loadedCerts = new HashSet<X509Certificate2>(); foreach (string filePath in Directory.EnumerateFiles(_storePath, PfxWildcard)) { try { var cert = new X509Certificate2(filePath); // If we haven't already loaded a cert .Equal to this one, copy it to the collection. if (loadedCerts.Add(cert)) { collection.Add(cert); } else { cert.Dispose(); } } catch (CryptographicException) { // The file wasn't a certificate, move on to the next one. } } } public void Add(ICertificatePal certPal) { if (_readOnly) { // Windows compatibility: Remove only throws when it needs to do work, add throws always. throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly); } try { AddCertToStore(certPal); } catch (CryptographicException) { throw; } catch (Exception e) { throw new CryptographicException(SR.Cryptography_X509_StoreAddFailure, e); } } private void AddCertToStore(ICertificatePal certPal) { // This may well be the first time that we've added something to this store. Directory.CreateDirectory(_storePath); uint userId = Interop.Sys.GetEUid(); EnsureDirectoryPermissions(_storePath, userId); OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal; using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles())) { string thumbprint = copy.Thumbprint; bool findOpenSlot; // The odds are low that we'd have a thumbprint collision, but check anyways. string existingFilename = FindExistingFilename(copy, _storePath, out findOpenSlot); if (existingFilename != null) { if (!copy.HasPrivateKey) { return; } try { using (X509Certificate2 fromFile = new X509Certificate2(existingFilename)) { if (fromFile.HasPrivateKey) { // We have a private key, the file has a private key, we're done here. return; } } } catch (CryptographicException) { // We can't read this file anymore, but a moment ago it was this certificate, // so go ahead and overwrite it. } } string destinationFilename; FileMode mode = FileMode.CreateNew; if (existingFilename != null) { destinationFilename = existingFilename; mode = FileMode.Create; } else if (findOpenSlot) { destinationFilename = FindOpenSlot(thumbprint); } else { destinationFilename = Path.Combine(_storePath, thumbprint + PfxExtension); } using (FileStream stream = new FileStream(destinationFilename, mode)) { EnsureFilePermissions(stream, userId); byte[] pkcs12 = copy.Export(X509ContentType.Pkcs12); stream.Write(pkcs12, 0, pkcs12.Length); } } } public void Remove(ICertificatePal certPal) { OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal; using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles())) { string currentFilename; do { bool hadCandidates; currentFilename = FindExistingFilename(copy, _storePath, out hadCandidates); if (currentFilename != null) { if (_readOnly) { // Windows compatibility, the readonly check isn't done until after a match is found. throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly); } File.Delete(currentFilename); } } while (currentFilename != null); } } SafeHandle IStorePal.SafeHandle { get { return null; } } private static string FindExistingFilename(X509Certificate2 cert, string storePath, out bool hadCandidates) { hadCandidates = false; foreach (string maybeMatch in Directory.EnumerateFiles(storePath, cert.Thumbprint + PfxWildcard)) { hadCandidates = true; try { using (X509Certificate2 candidate = new X509Certificate2(maybeMatch)) { if (candidate.Equals(cert)) { return maybeMatch; } } } catch (CryptographicException) { // Contents weren't interpretable as a certificate, so it's not a match. } } return null; } private string FindOpenSlot(string thumbprint) { // We already know that {thumbprint}.pfx is taken, so start with {thumbprint}.1.pfx // We need space for {thumbprint} (thumbprint.Length) // And ".0.pfx" (6) // If MaxSaveAttempts is big enough to use more than one digit, we need that space, too (MaxSaveAttempts / 10) StringBuilder pathBuilder = new StringBuilder(thumbprint.Length + PfxOrdinalWildcard.Length + (MaxSaveAttempts / 10)); pathBuilder.Append(thumbprint); pathBuilder.Append('.'); int prefixLength = pathBuilder.Length; for (int i = 1; i <= MaxSaveAttempts; i++) { pathBuilder.Length = prefixLength; pathBuilder.Append(i); pathBuilder.Append(PfxExtension); string builtPath = Path.Combine(_storePath, pathBuilder.ToString()); if (!File.Exists(builtPath)) { return builtPath; } } throw new CryptographicException(SR.Cryptography_X509_StoreNoFileAvailable); } private static string GetStorePath(string storeName) { string directoryName = GetDirectoryName(storeName); if (s_userStoreRoot == null) { // Do this here instead of a static field initializer so that // the static initializer isn't capable of throwing the "home directory not found" // exception. s_userStoreRoot = PersistedFiles.GetUserFeatureDirectory( X509Persistence.CryptographyFeatureName, X509Persistence.X509StoresSubFeatureName); } return Path.Combine(s_userStoreRoot, directoryName); } private static string GetDirectoryName(string storeName) { Debug.Assert(storeName != null); try { string fileName = Path.GetFileName(storeName); if (!StringComparer.Ordinal.Equals(storeName, fileName)) { throw new CryptographicException(SR.Format(SR.Security_InvalidValue, nameof(storeName))); } } catch (IOException e) { throw new CryptographicException(e.Message, e); } return storeName.ToLowerInvariant(); } /// <summary> /// Checks the store directory has the correct permissions. /// </summary> /// <param name="path"> /// The path of the directory to check. /// </param> /// <param name="userId"> /// The current userId from GetEUid(). /// </param> private static void EnsureDirectoryPermissions(string path, uint userId) { Interop.Sys.FileStatus dirStat; if (Interop.Sys.Stat(path, out dirStat) != 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw new CryptographicException( SR.Cryptography_FileStatusError, new IOException(error.GetErrorMessage(), error.RawErrno)); } if (dirStat.Uid != userId) { throw new CryptographicException(SR.Format(SR.Cryptography_OwnerNotCurrentUser, path)); } if ((dirStat.Mode & (int)Interop.Sys.Permissions.S_IRWXU) != (int)Interop.Sys.Permissions.S_IRWXU) { throw new CryptographicException(SR.Format(SR.Cryptography_InvalidDirectoryPermissions, path)); } } /// <summary> /// Checks the file has the correct permissions and attempts to modify them if they're inappropriate. /// </summary> /// <param name="stream"> /// The file stream to check. /// </param> /// <param name="userId"> /// The current userId from GetEUid(). /// </param> private static void EnsureFilePermissions(FileStream stream, uint userId) { // Verify that we're creating files with u+rw and g-rw, o-rw. const Interop.Sys.Permissions requiredPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR; const Interop.Sys.Permissions forbiddenPermissions = Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; Interop.Sys.FileStatus stat; if (Interop.Sys.FStat(stream.SafeFileHandle, out stat) != 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw new CryptographicException( SR.Cryptography_FileStatusError, new IOException(error.GetErrorMessage(), error.RawErrno)); } if (stat.Uid != userId) { throw new CryptographicException(SR.Format(SR.Cryptography_OwnerNotCurrentUser, stream.Name)); } if ((stat.Mode & (int)requiredPermissions) != (int)requiredPermissions || (stat.Mode & (int)forbiddenPermissions) != 0) { if (Interop.Sys.FChMod(stream.SafeFileHandle, (int)requiredPermissions) < 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw new CryptographicException( SR.Format(SR.Cryptography_InvalidFilePermissions, stream.Name), new IOException(error.GetErrorMessage(), error.RawErrno)); } // Verify the chmod applied. if (Interop.Sys.FStat(stream.SafeFileHandle, out stat) != 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw new CryptographicException( SR.Cryptography_FileStatusError, new IOException(error.GetErrorMessage(), error.RawErrno)); } if ((stat.Mode & (int)requiredPermissions) != (int)requiredPermissions || (stat.Mode & (int)forbiddenPermissions) != 0) { throw new CryptographicException(SR.Format(SR.Cryptography_InvalidFilePermissions, stream.Name)); } } } internal sealed class UnsupportedDisallowedStore : IStorePal { private readonly bool _readOnly; internal UnsupportedDisallowedStore(OpenFlags openFlags) { // ReadOnly is 0x00, so it is implicit unless either ReadWrite or MaxAllowed // was requested. OpenFlags writeFlags = openFlags & (OpenFlags.ReadWrite | OpenFlags.MaxAllowed); if (writeFlags == OpenFlags.ReadOnly) { _readOnly = true; } string storePath = GetStorePath(X509Store.DisallowedStoreName); try { if (Directory.Exists(storePath)) { // If it has no files, leave it alone. foreach (string filePath in Directory.EnumerateFiles(storePath)) { string msg = SR.Format(SR.Cryptography_Unix_X509_DisallowedStoreNotEmpty, storePath); throw new CryptographicException(msg, new PlatformNotSupportedException(msg)); } } } catch (IOException) { // Suppress the exception, treat the store as empty. } } public void Dispose() { // Nothing to do. } public void CloneTo(X509Certificate2Collection collection) { // Never show any data. } public void Add(ICertificatePal cert) { if (_readOnly) { throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly); } throw new CryptographicException( SR.Cryptography_Unix_X509_NoDisallowedStore, new PlatformNotSupportedException(SR.Cryptography_Unix_X509_NoDisallowedStore)); } public void Remove(ICertificatePal cert) { // Remove never throws if it does no measurable work. // Since CloneTo always says the store is empty, no measurable work is ever done. } SafeHandle IStorePal.SafeHandle { get; } = null; } } }
#region Copyright & License // // Author: Ian Davis <[email protected]> Copyright (c) 2007, Ian Davs // // Portions of this software were developed for NUnit. See NOTICE.txt for more // information. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #endregion using System; using System.Collections; using System.Globalization; using System.Text; using Ensurance.Properties; namespace Ensurance { /// <summary> /// Static methods used in creating messages /// </summary> public class MsgUtils { private static readonly string ELLIPSIS = Resources.Ellipsis; /// <summary> /// Returns the representation of a type as used in NUnitLite. This is /// the same as Type.ToString() except for arrays, which are displayed /// with their declared sizes. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetTypeRepresentation( object obj ) { Array array = obj as Array; if ( array == null ) { return string.Format( CultureInfo.CurrentCulture, "<{0}>", obj.GetType() ); } StringBuilder sb = new StringBuilder(); Type elementType = array.GetType(); int nest = 0; while ( elementType.IsArray ) { elementType = elementType.GetElementType(); ++nest; } sb.Append( elementType.ToString() ); sb.Append( '[' ); for (int r = 0; r < array.Rank; r++) { if ( r > 0 ) { sb.Append( ',' ); } sb.Append( array.GetLength( r ) ); } sb.Append( ']' ); while ( --nest > 0 ) { sb.Append( "[]" ); } return string.Format( CultureInfo.CurrentCulture, "<{0}>", sb ); } /// <summary> /// Converts any control characters in a string to their escaped /// representation. /// </summary> /// <param name="s">The string to be converted</param> /// <returns>The converted string</returns> public static string ConvertWhitespace( string s ) { if ( s != null ) { s = s.Replace( "\\", "\\\\" ); s = s.Replace( "\r", "\\r" ); s = s.Replace( "\n", "\\n" ); s = s.Replace( "\t", "\\t" ); } return s; } /// <summary> /// Return the a string representation for a set of indices into an /// array /// </summary> /// <param name="indices">Array of indices for which a string is needed</param> public static string GetArrayIndicesAsString( int[] indices ) { StringBuilder sb = new StringBuilder(); sb.Append( '[' ); for (int r = 0; r < indices.Length; r++) { if ( r > 0 ) { sb.Append( ',' ); } sb.Append( indices[r].ToString( CultureInfo.CurrentCulture ) ); } sb.Append( ']' ); return sb.ToString(); } /// <summary> /// Get an array of indices representing the point in a collection or /// array corresponding to a single int index into the collection. /// </summary> /// <param name="collection">The collection to which the indices apply</param> /// <param name="index">Index in the collection</param> /// <returns>Array of indices</returns> public static int[] GetArrayIndicesFromCollectionIndex( ICollection collection, int index ) { Array array = collection as Array; if ( array == null || array.Rank == 1 ) { return new int[] {index}; } int[] result = new int[array.Rank]; for (int r = array.Rank; --r > 0;) { int l = array.GetLength( r ); result[r] = index % l; index /= l; } result[0] = index; return result; } /// <summary> /// Clip a string around a particular point, returning the clipped /// string with ellipses representing the removed parts /// </summary> /// <param name="s">The string to be clipped</param> /// <param name="maxStringLength">The maximum permitted length of the result string</param> /// <param name="mismatch">The point around which clipping is to occur</param> /// <returns>The clipped string</returns> public static string ClipString( string s, int maxStringLength, int mismatch ) { int clipLength = maxStringLength - ELLIPSIS.Length; if ( mismatch >= clipLength ) { int clipStart = mismatch - clipLength / 2; // Clip the expected value at start and at end if needed if ( s.Length - clipStart > maxStringLength ) { return ELLIPSIS + s.Substring( clipStart, clipLength - ELLIPSIS.Length ) + ELLIPSIS; } else { return ELLIPSIS + s.Substring( clipStart ); } } else if ( s.Length > maxStringLength ) { return s.Substring( 0, clipLength ) + ELLIPSIS; } else { return s; } } /// <summary> /// Shows the position two strings start to differ. Comparison /// starts at the start index. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The actual string</param> /// <param name="istart">The index in the strings at which comparison should start</param> /// <param name="ignoreCase">Boolean indicating whether case should be ignored</param> /// <returns>-1 if no mismatch found, or the index where mismatch found</returns> public static int FindMismatchPosition( string expected, string actual, int istart, bool ignoreCase ) { int length = Math.Min( expected.Length, actual.Length ); string s1 = ignoreCase ? expected.ToLower( CultureInfo.CurrentCulture ) : expected; string s2 = ignoreCase ? actual.ToLower( CultureInfo.CurrentCulture ) : actual; for (int i = istart; i < length; i++) { if ( s1[i] != s2[i] ) { return i; } } // // Strings have same content up to the length of the shorter string. // Mismatch occurs because string lengths are different, so show // that they start differing where the shortest string ends // if ( expected.Length != actual.Length ) { return length; } // // Same strings : We shouldn't get here // return -1; } } }
// <copyright file="LogRecordTest.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if !NET461 using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Microsoft.Extensions.Logging; using OpenTelemetry.Exporter; using OpenTelemetry.Logs; using OpenTelemetry.Tests; using OpenTelemetry.Trace; using Xunit; namespace OpenTelemetry.Logs.Tests { public sealed class LogRecordTest : IDisposable { private readonly ILogger logger; private readonly List<LogRecord> exportedItems = new List<LogRecord>(); private readonly ILoggerFactory loggerFactory; private readonly BaseExportProcessor<LogRecord> processor; private readonly BaseExporter<LogRecord> exporter; private OpenTelemetryLoggerOptions options; public LogRecordTest() { this.exporter = new InMemoryExporter<LogRecord>(this.exportedItems); this.processor = new TestLogRecordProcessor(this.exporter); this.loggerFactory = LoggerFactory.Create(builder => { builder.AddOpenTelemetry(options => { this.options = options; options .AddProcessor(this.processor); }); builder.AddFilter(typeof(LogRecordTest).FullName, LogLevel.Trace); }); this.logger = this.loggerFactory.CreateLogger<LogRecordTest>(); } [Fact] public void CheckCateogryNameForLog() { this.logger.LogInformation("Log"); var categoryName = this.exportedItems[0].CategoryName; Assert.Equal(typeof(LogRecordTest).FullName, categoryName); } [Theory] [InlineData(LogLevel.Trace)] [InlineData(LogLevel.Debug)] [InlineData(LogLevel.Information)] [InlineData(LogLevel.Warning)] [InlineData(LogLevel.Error)] [InlineData(LogLevel.Critical)] public void CheckLogLevel(LogLevel logLevel) { var message = $"Log {logLevel}"; this.logger.Log(logLevel, message); var logLevelRecorded = this.exportedItems[0].LogLevel; Assert.Equal(logLevel, logLevelRecorded); } [Fact] public void CheckStateForUnstructuredLog() { var message = "Hello, World!"; this.logger.LogInformation(message); var state = this.exportedItems[0].State as IReadOnlyList<KeyValuePair<string, object>>; // state only has {OriginalFormat} Assert.Equal(1, state.Count); Assert.Equal(message.ToString(), state.ToString()); } [Fact] public void CheckStateForUnstructuredLogWithStringInterpolation() { var message = $"Hello from potato {0.99}."; this.logger.LogInformation(message); var state = this.exportedItems[0].State as IReadOnlyList<KeyValuePair<string, object>>; // state only has {OriginalFormat} Assert.Equal(1, state.Count); Assert.Equal(message.ToString(), state.ToString()); } [Fact] public void CheckStateForStructuredLogWithTemplate() { var message = "Hello from {name} {price}."; this.logger.LogInformation(message, "tomato", 2.99); var state = this.exportedItems[0].State as IReadOnlyList<KeyValuePair<string, object>>; // state has name, price and {OriginalFormat} Assert.Equal(3, state.Count); // Check if state has name Assert.Contains(state, item => item.Key == "name"); Assert.Equal("tomato", state.First(item => item.Key == "name").Value); // Check if state has price Assert.Contains(state, item => item.Key == "price"); Assert.Equal(2.99, state.First(item => item.Key == "price").Value); // Check if state has OriginalFormat Assert.Contains(state, item => item.Key == "{OriginalFormat}"); Assert.Equal(message, state.First(item => item.Key == "{OriginalFormat}").Value); Assert.Equal($"Hello from tomato 2.99.", state.ToString()); } [Fact] public void CheckStateForStructuredLogWithStrongType() { var food = new Food { Name = "artichoke", Price = 3.99 }; this.logger.LogInformation("{food}", food); var state = this.exportedItems[0].State as IReadOnlyList<KeyValuePair<string, object>>; // state has food and {OriginalFormat} Assert.Equal(2, state.Count); // Check if state has food Assert.Contains(state, item => item.Key == "food"); var foodParameter = (Food)state.First(item => item.Key == "food").Value; Assert.Equal(food.Name, foodParameter.Name); Assert.Equal(food.Price, foodParameter.Price); // Check if state has OriginalFormat Assert.Contains(state, item => item.Key == "{OriginalFormat}"); Assert.Equal("{food}", state.First(item => item.Key == "{OriginalFormat}").Value); Assert.Equal(food.ToString(), state.ToString()); } [Fact] public void CheckStateForStructuredLogWithAnonymousType() { var anonymousType = new { Name = "pumpkin", Price = 5.99 }; this.logger.LogInformation("{food}", anonymousType); var state = this.exportedItems[0].State as IReadOnlyList<KeyValuePair<string, object>>; // state has food and {OriginalFormat} Assert.Equal(2, state.Count); // Check if state has food Assert.Contains(state, item => item.Key == "food"); var foodParameter = state.First(item => item.Key == "food").Value as dynamic; Assert.Equal(anonymousType.Name, foodParameter.Name); Assert.Equal(anonymousType.Price, foodParameter.Price); // Check if state has OriginalFormat Assert.Contains(state, item => item.Key == "{OriginalFormat}"); Assert.Equal("{food}", state.First(item => item.Key == "{OriginalFormat}").Value); Assert.Equal(anonymousType.ToString(), state.ToString()); } [Fact] public void CheckStateForStrucutredLogWithGeneralType() { var food = new Dictionary<string, object> { ["Name"] = "truffle", ["Price"] = 299.99, }; this.logger.LogInformation("{food}", food); var state = this.exportedItems[0].State as IReadOnlyList<KeyValuePair<string, object>>; // state only has food and {OriginalFormat} Assert.Equal(2, state.Count); // Check if state has food Assert.Contains(state, item => item.Key == "food"); var foodParameter = state.First(item => item.Key == "food").Value as Dictionary<string, object>; Assert.True(food.Count == foodParameter.Count && !food.Except(foodParameter).Any()); // Check if state has OriginalFormat Assert.Contains(state, item => item.Key == "{OriginalFormat}"); Assert.Equal("{food}", state.First(item => item.Key == "{OriginalFormat}").Value); var prevCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; try { Assert.Equal("[Name, truffle], [Price, 299.99]", state.ToString()); } finally { CultureInfo.CurrentCulture = prevCulture; } } [Fact] public void CheckStateForExceptionLogged() { var exceptionMessage = "Exception Message"; var exception = new Exception(exceptionMessage); var message = "Exception Occurred"; this.logger.LogInformation(exception, message); var state = this.exportedItems[0].State; var itemCount = state.GetType().GetProperty("Count").GetValue(state); // state only has {OriginalFormat} Assert.Equal(1, itemCount); var loggedException = this.exportedItems[0].Exception; Assert.NotNull(loggedException); Assert.Equal(exceptionMessage, loggedException.Message); Assert.Equal(message.ToString(), state.ToString()); } [Fact] public void CheckTraceIdForLogWithinDroppedActivity() { this.logger.LogInformation("Log within a dropped activity"); var logRecord = this.exportedItems[0]; Assert.Null(Activity.Current); Assert.Equal(default, logRecord.TraceId); Assert.Equal(default, logRecord.SpanId); Assert.Equal(default, logRecord.TraceFlags); } [Fact] public void CheckTraceIdForLogWithinActivityMarkedAsRecordOnly() { var sampler = new RecordOnlySampler(); var exportedActivityList = new List<Activity>(); var activitySourceName = "LogRecordTest"; var activitySource = new ActivitySource(activitySourceName); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(activitySourceName) .SetSampler(sampler) .AddInMemoryExporter(exportedActivityList) .Build(); using var activity = activitySource.StartActivity("Activity"); this.logger.LogInformation("Log within activity marked as RecordOnly"); var logRecord = this.exportedItems[0]; var currentActivity = Activity.Current; Assert.NotNull(Activity.Current); Assert.Equal(currentActivity.TraceId, logRecord.TraceId); Assert.Equal(currentActivity.SpanId, logRecord.SpanId); Assert.Equal(currentActivity.ActivityTraceFlags, logRecord.TraceFlags); } [Fact] public void CheckTraceIdForLogWithinActivityMarkedAsRecordAndSample() { var sampler = new AlwaysOnSampler(); var exportedActivityList = new List<Activity>(); var activitySourceName = "LogRecordTest"; var activitySource = new ActivitySource(activitySourceName); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(activitySourceName) .SetSampler(sampler) .AddInMemoryExporter(exportedActivityList) .Build(); using var activity = activitySource.StartActivity("Activity"); this.logger.LogInformation("Log within activity marked as RecordAndSample"); var logRecord = this.exportedItems[0]; var currentActivity = Activity.Current; Assert.NotNull(Activity.Current); Assert.Equal(currentActivity.TraceId, logRecord.TraceId); Assert.Equal(currentActivity.SpanId, logRecord.SpanId); Assert.Equal(currentActivity.ActivityTraceFlags, logRecord.TraceFlags); } [Fact] public void IncludeFormattedMessageTest() { this.logger.LogInformation("OpenTelemetry!"); var logRecord = this.exportedItems[0]; Assert.Null(logRecord.FormattedMessage); this.options.IncludeFormattedMessage = true; try { this.logger.LogInformation("OpenTelemetry!"); logRecord = this.exportedItems[1]; Assert.Equal("OpenTelemetry!", logRecord.FormattedMessage); this.logger.LogInformation("OpenTelemetry {Greeting} {Subject}!", "Hello", "World"); logRecord = this.exportedItems[2]; Assert.Equal("OpenTelemetry Hello World!", logRecord.FormattedMessage); } finally { this.options.IncludeFormattedMessage = false; } } [Fact] public void IncludeFormattedMessageTestWhenFormatterNull() { this.logger.Log(LogLevel.Information, default, "Hello World!", null, null); var logRecord = this.exportedItems[0]; Assert.Null(logRecord.FormattedMessage); this.options.IncludeFormattedMessage = true; try { // Pass null as formatter function this.logger.Log(LogLevel.Information, default, "Hello World!", null, null); logRecord = this.exportedItems[1]; Assert.Null(logRecord.FormattedMessage); var expectedFormattedMessage = "formatted message"; this.logger.Log(LogLevel.Information, default, "Hello World!", null, (state, ex) => expectedFormattedMessage); logRecord = this.exportedItems[2]; Assert.Equal(expectedFormattedMessage, logRecord.FormattedMessage); } finally { this.options.IncludeFormattedMessage = false; } } [Fact] public void IncludeScopesTest() { using var scope = this.logger.BeginScope("string_scope"); this.logger.LogInformation("OpenTelemetry!"); var logRecord = this.exportedItems[0]; List<object> scopes = new List<object>(); logRecord.ForEachScope<object>((scope, state) => scopes.Add(scope.Scope), null); Assert.Empty(scopes); this.options.IncludeScopes = true; try { this.logger.LogInformation("OpenTelemetry!"); logRecord = this.exportedItems[1]; int reachedDepth = -1; logRecord.ForEachScope<object>( (scope, state) => { reachedDepth++; scopes.Add(scope.Scope); foreach (KeyValuePair<string, object> item in scope) { Assert.Equal(string.Empty, item.Key); Assert.Equal("string_scope", item.Value); } }, null); Assert.Single(scopes); Assert.Equal(0, reachedDepth); Assert.Equal("string_scope", scopes[0]); scopes.Clear(); List<KeyValuePair<string, object>> expectedScope2 = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("item1", "value1"), new KeyValuePair<string, object>("item2", "value2"), }; using var scope2 = this.logger.BeginScope(expectedScope2); this.logger.LogInformation("OpenTelemetry!"); logRecord = this.exportedItems[2]; reachedDepth = -1; logRecord.ForEachScope<object>( (scope, state) => { scopes.Add(scope.Scope); if (reachedDepth++ == 1) { foreach (KeyValuePair<string, object> item in scope) { Assert.Contains(item, expectedScope2); } } }, null); Assert.Equal(2, scopes.Count); Assert.Equal(1, reachedDepth); Assert.Equal("string_scope", scopes[0]); Assert.Same(expectedScope2, scopes[1]); scopes.Clear(); KeyValuePair<string, object>[] expectedScope3 = new KeyValuePair<string, object>[] { new KeyValuePair<string, object>("item3", "value3"), new KeyValuePair<string, object>("item4", "value4"), }; using var scope3 = this.logger.BeginScope(expectedScope3); this.logger.LogInformation("OpenTelemetry!"); logRecord = this.exportedItems[3]; reachedDepth = -1; logRecord.ForEachScope<object>( (scope, state) => { scopes.Add(scope.Scope); if (reachedDepth++ == 2) { foreach (KeyValuePair<string, object> item in scope) { Assert.Contains(item, expectedScope3); } } }, null); Assert.Equal(3, scopes.Count); Assert.Equal(2, reachedDepth); Assert.Equal("string_scope", scopes[0]); Assert.Same(expectedScope2, scopes[1]); Assert.Same(expectedScope3, scopes[2]); } finally { this.options.IncludeScopes = false; } } [Fact] public void ParseStateValuesUsingStandardExtensionsTest() { // Tests state parsing with standard extensions. this.logger.LogInformation("{Product} {Year}!", "OpenTelemetry", 2021); var logRecord = this.exportedItems[0]; Assert.NotNull(logRecord.State); Assert.Null(logRecord.StateValues); this.options.ParseStateValues = true; try { var complex = new { Property = "Value" }; this.logger.LogInformation("{Product} {Year} {Complex}!", "OpenTelemetry", 2021, complex); logRecord = this.exportedItems[1]; Assert.Null(logRecord.State); Assert.NotNull(logRecord.StateValues); Assert.Equal(4, logRecord.StateValues.Count); Assert.Equal(new KeyValuePair<string, object>("Product", "OpenTelemetry"), logRecord.StateValues[0]); Assert.Equal(new KeyValuePair<string, object>("Year", 2021), logRecord.StateValues[1]); Assert.Equal(new KeyValuePair<string, object>("{OriginalFormat}", "{Product} {Year} {Complex}!"), logRecord.StateValues[3]); KeyValuePair<string, object> actualComplex = logRecord.StateValues[2]; Assert.Equal("Complex", actualComplex.Key); Assert.Same(complex, actualComplex.Value); } finally { this.options.ParseStateValues = false; } } [Fact] public void ParseStateValuesUsingStructTest() { // Tests struct IReadOnlyList<KeyValuePair<string, object>> parse path. this.options.ParseStateValues = true; try { this.logger.Log( LogLevel.Information, 0, new StructState(new KeyValuePair<string, object>("Key1", "Value1")), null, (s, e) => "OpenTelemetry!"); var logRecord = this.exportedItems[0]; Assert.Null(logRecord.State); Assert.NotNull(logRecord.StateValues); Assert.Equal(1, logRecord.StateValues.Count); Assert.Equal(new KeyValuePair<string, object>("Key1", "Value1"), logRecord.StateValues[0]); } finally { this.options.ParseStateValues = false; } } [Fact] public void ParseStateValuesUsingListTest() { // Tests ref IReadOnlyList<KeyValuePair<string, object>> parse path. this.options.ParseStateValues = true; try { this.logger.Log( LogLevel.Information, 0, new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("Key1", "Value1") }, null, (s, e) => "OpenTelemetry!"); var logRecord = this.exportedItems[0]; Assert.Null(logRecord.State); Assert.NotNull(logRecord.StateValues); Assert.Equal(1, logRecord.StateValues.Count); Assert.Equal(new KeyValuePair<string, object>("Key1", "Value1"), logRecord.StateValues[0]); } finally { this.options.ParseStateValues = false; } } [Fact] public void ParseStateValuesUsingIEnumerableTest() { // Tests IEnumerable<KeyValuePair<string, object>> parse path. this.options.ParseStateValues = true; try { this.logger.Log( LogLevel.Information, 0, new ListState(new KeyValuePair<string, object>("Key1", "Value1")), null, (s, e) => "OpenTelemetry!"); var logRecord = this.exportedItems[0]; Assert.Null(logRecord.State); Assert.NotNull(logRecord.StateValues); Assert.Equal(1, logRecord.StateValues.Count); Assert.Equal(new KeyValuePair<string, object>("Key1", "Value1"), logRecord.StateValues[0]); } finally { this.options.ParseStateValues = false; } } [Fact] public void ParseStateValuesUsingCustomTest() { // Tests unknown state parse path. this.options.ParseStateValues = true; try { CustomState state = new CustomState { Property = "Value", }; this.logger.Log( LogLevel.Information, 0, state, null, (s, e) => "OpenTelemetry!"); var logRecord = this.exportedItems[0]; Assert.Null(logRecord.State); Assert.NotNull(logRecord.StateValues); Assert.Equal(1, logRecord.StateValues.Count); KeyValuePair<string, object> actualState = logRecord.StateValues[0]; Assert.Equal(string.Empty, actualState.Key); Assert.Same(state, actualState.Value); } finally { this.options.ParseStateValues = false; } } public void Dispose() { this.loggerFactory?.Dispose(); } internal struct Food { public string Name { get; set; } public double Price { get; set; } } private struct StructState : IReadOnlyList<KeyValuePair<string, object>> { private readonly List<KeyValuePair<string, object>> list; public StructState(params KeyValuePair<string, object>[] items) { this.list = new List<KeyValuePair<string, object>>(items); } public int Count => this.list.Count; public KeyValuePair<string, object> this[int index] => this.list[index]; public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return this.list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.list.GetEnumerator(); } } private class ListState : IEnumerable<KeyValuePair<string, object>> { private readonly List<KeyValuePair<string, object>> list; public ListState(params KeyValuePair<string, object>[] items) { this.list = new List<KeyValuePair<string, object>>(items); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return this.list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.list.GetEnumerator(); } } private class CustomState { public string Property { get; set; } } private class TestLogRecordProcessor : SimpleExportProcessor<LogRecord> { public TestLogRecordProcessor(BaseExporter<LogRecord> exporter) : base(exporter) { } public override void OnEnd(LogRecord data) { data.BufferLogScopes(); base.OnEnd(data); } } } } #endif
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using EarLab.InheritedControls; using EarLab.Utilities; namespace EarLab.Controls { /// <summary> /// This class extends the System.Windows.Forms.ScrollBar class to have two theme-enabled autoscroll buttons. /// </summary> public class ExtendedScrollBar : System.Windows.Forms.UserControl { private System.ComponentModel.IContainer components; private NoKeyPressScrollBar hScrollBar; private System.Windows.Forms.PictureBox leftPictureBox; private System.Windows.Forms.PictureBox rightPictureBox; private string bitmapName; private Region leftPlayRegion, rightPlayRegion, stopRegion; private ExtendedScrollBarButtonMode buttonMode; private ExtendedScrollBarMovieDirection movieDirection; private System.Windows.Forms.ImageList stopImageList; private System.Windows.Forms.ImageList playImageList; private System.Windows.Forms.Timer autoscrollTimer; private int scrollAmount; private enum ExtendedScrollBarMovieDirection { Left, Right } private enum ExtendedScrollBarButtonMode { PlaySymbols, StopSymbols } private enum ExtendedScrollBarControlStyle { Normal, WinXP } /// <summary> /// Create a new ExtendedScrollBar. /// </summary> public ExtendedScrollBar() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); this.hScrollBar.SmallChange = 10; this.hScrollBar.LargeChange = 100; this.scrollAmount = this.hScrollBar.SmallChange; this.autoscrollTimer.Interval = 100; this.buttonMode = ExtendedScrollBarButtonMode.PlaySymbols; // create left play symbol this.leftPlayRegion = new Region(); this.leftPlayRegion.MakeEmpty(); this.leftPlayRegion.Union(new Rectangle(1, 4, 1, 1)); this.leftPlayRegion.Union(new Rectangle(2, 3, 1, 3)); this.leftPlayRegion.Union(new Rectangle(3, 2, 1, 5)); this.leftPlayRegion.Union(new Rectangle(4, 1, 1, 7)); this.leftPlayRegion.Union(new Rectangle(5, 0, 2, 9)); // create right play symbol this.rightPlayRegion = this.leftPlayRegion.Clone(); System.Drawing.Drawing2D.Matrix matrixTransform = new System.Drawing.Drawing2D.Matrix(); matrixTransform.RotateAt(45, new Point(4,4)); matrixTransform.RotateAt(45, new Point(5,5)); matrixTransform.RotateAt(45, new Point(4,4)); matrixTransform.RotateAt(45, new Point(4,4)); this.rightPlayRegion.Transform(matrixTransform); // create stop symbol this.stopRegion = new Region(); this.stopRegion.MakeEmpty(); this.stopRegion.Union(new Rectangle(1, 0, 1, 1)); this.stopRegion.Union(new Rectangle(7, 0, 1, 1)); this.stopRegion.Union(new Rectangle(0, 1, 3, 1)); this.stopRegion.Union(new Rectangle(6, 1, 3, 1)); this.stopRegion.Union(new Rectangle(1, 2, 3, 1)); this.stopRegion.Union(new Rectangle(5, 2, 3, 1)); this.stopRegion.Union(new Rectangle(2, 3, 5, 1)); this.stopRegion.Union(new Rectangle(3, 4, 3, 1)); this.stopRegion.Union(new Rectangle(2, 5, 5, 1)); this.stopRegion.Union(new Rectangle(5, 6, 3, 1)); this.stopRegion.Union(new Rectangle(1, 6, 3, 1)); this.stopRegion.Union(new Rectangle(6, 7, 3, 1)); this.stopRegion.Union(new Rectangle(0, 7, 3, 1)); this.stopRegion.Union(new Rectangle(7, 8, 1, 1)); this.stopRegion.Union(new Rectangle(1, 8, 1, 1)); this.CreateBitmaps(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.hScrollBar = new NoKeyPressScrollBar(); this.leftPictureBox = new System.Windows.Forms.PictureBox(); this.rightPictureBox = new System.Windows.Forms.PictureBox(); this.playImageList = new System.Windows.Forms.ImageList(this.components); this.stopImageList = new System.Windows.Forms.ImageList(this.components); this.autoscrollTimer = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // hScrollBar // this.hScrollBar.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.hScrollBar.Location = new System.Drawing.Point(17, 0); this.hScrollBar.Name = "hScrollBar"; this.hScrollBar.Size = new System.Drawing.Size(344, 17); this.hScrollBar.TabIndex = 0; //this.hScrollBar.ValueChanged += new System.EventHandler(this.hScrollBar_ValueChanged); this.hScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this.hScrollBar_Scroll); // // leftPictureBox // this.leftPictureBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.leftPictureBox.Location = new System.Drawing.Point(0, 0); this.leftPictureBox.Name = "leftPictureBox"; this.leftPictureBox.Size = new System.Drawing.Size(17, 17); this.leftPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.leftPictureBox.TabIndex = 1; this.leftPictureBox.TabStop = false; this.leftPictureBox.Click += new System.EventHandler(this.leftPictureBox_Click); this.leftPictureBox.EnabledChanged += new System.EventHandler(this.leftPictureBox_EnabledChanged); this.leftPictureBox.MouseEnter += new System.EventHandler(this.leftPictureBox_MouseEnter); this.leftPictureBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.leftPictureBox_MouseUp); this.leftPictureBox.DoubleClick += new System.EventHandler(this.leftPictureBox_DoubleClick); this.leftPictureBox.MouseLeave += new System.EventHandler(this.leftPictureBox_MouseLeave); this.leftPictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.leftPictureBox_MouseDown); // // rightPictureBox // this.rightPictureBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right))); this.rightPictureBox.Location = new System.Drawing.Point(361, 0); this.rightPictureBox.Name = "rightPictureBox"; this.rightPictureBox.Size = new System.Drawing.Size(17, 17); this.rightPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.rightPictureBox.TabIndex = 2; this.rightPictureBox.TabStop = false; this.rightPictureBox.Click += new System.EventHandler(this.rightPictureBox_Click); this.rightPictureBox.EnabledChanged += new System.EventHandler(this.rightPictureBox_EnabledChanged); this.rightPictureBox.MouseEnter += new System.EventHandler(this.rightPictureBox_MouseEnter); this.rightPictureBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.rightPictureBox_MouseUp); this.rightPictureBox.DoubleClick += new System.EventHandler(this.rightPictureBox_DoubleClick); this.rightPictureBox.MouseLeave += new System.EventHandler(this.rightPictureBox_MouseLeave); this.rightPictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.rightPictureBox_MouseDown); // // playImageList // this.playImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; this.playImageList.ImageSize = new System.Drawing.Size(17, 17); this.playImageList.TransparentColor = System.Drawing.Color.Transparent; // // stopImageList // this.stopImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; this.stopImageList.ImageSize = new System.Drawing.Size(17, 17); this.stopImageList.TransparentColor = System.Drawing.Color.Transparent; // // autoscrollTimer // this.autoscrollTimer.Tick += new System.EventHandler(this.autoscrollTimer_Tick); // // ExtendedScrollBar // this.Controls.Add(this.rightPictureBox); this.Controls.Add(this.leftPictureBox); this.Controls.Add(this.hScrollBar); this.Name = "ExtendedScrollBar"; this.Size = new System.Drawing.Size(378, 17); this.SystemColorsChanged += new System.EventHandler(this.ExtendedScrollBar_SystemColorsChanged); this.EnabledChanged += new System.EventHandler(this.ExtendedScrollBar_EnabledChanged); this.ResumeLayout(false); } #endregion #region Methods /// <summary> /// Create the bitmaps for the autoscroll buttons. /// </summary> private void CreateBitmaps() { // clear the lists if they have images in them already if (this.playImageList.Images.Count > 0) this.playImageList.Images.Clear(); if (this.stopImageList.Images.Count > 0) this.stopImageList.Images.Clear(); try { // make sure that the OS can handle xp themes if (Environment.OSVersion.Version.Major > 4 && Environment.OSVersion.Version.Minor > 0) { // we have to declare these seperately, else somehow they get linked and store the same info. string themePath = new String('\0', 256); string themeColor = new String('\0', 256); string themeSize = new String('\0', 256); // call the Themes API and get the current theme name, color, and size NativeMethods.GetCurrentThemeName(themePath, 256, themeColor, 256, themeSize, 256); // trim the trailing '\0' character off of the strings to get the actual resulting info themePath = themePath.TrimEnd('\0'); themeColor = themeColor.TrimEnd('\0'); themeSize = themeSize.TrimEnd('\0'); if (themePath.TrimEnd('\0') == "") { this.CreateBitmapsNormal(); return; } // luna style is wierd, "NormalColor" is actually stored as "Blue" in resources, stupid monkeys if (themeColor == "NormalColor" && themePath.IndexOf("Luna") >= 0) this.bitmapName = "BLUE"; else this.bitmapName = themePath.Substring(themePath.LastIndexOf('\\')+1, themePath.Length-themePath.LastIndexOf('\\')-10); // make sure that themes are actually turned on if (themePath != "" && themeColor != "") this.CreateBitmapsThemed(themePath); else this.CreateBitmapsNormal(); } else this.CreateBitmapsNormal(); } catch { this.CreateBitmapsNormal(); } } private void CreateBitmapsThemed(string themePath) { // extract the bitmaps we need out of the msstyle files for custom themes, praying that naming conventions are correct Bitmap buttonsBitmap, symbolsBitmap; System.IntPtr hModule = IntPtr.Zero; try { hModule = NativeMethods.LoadLibraryEx(themePath, System.IntPtr.Zero, NativeMethods.LOAD_LIBRARY_AS_DATAFILE); buttonsBitmap = Bitmap.FromResource(hModule, this.bitmapName.ToUpper() + "_SCROLLARROWS_BMP"); symbolsBitmap = Bitmap.FromResource(hModule, this.bitmapName.ToUpper() + "_SCROLLARROWGLYPHS_BMP"); } catch { this.CreateBitmapsNormal(); return; } finally { NativeMethods.FreeLibrary(hModule); // close it lest we do something super bad } Bitmap tempBitmap, symbolBitmap; for (int i=0;i<4;i++) { tempBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); symbolBitmap = new Bitmap(9, 9, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(tempBitmap).DrawImageUnscaled(buttonsBitmap, 0, -136-(i*17)); if (i != 3) Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(this.FindColor(ref symbolsBitmap, i)), this.leftPlayRegion); else Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(this.FindColor(ref symbolsBitmap, i)), this.leftPlayRegion); Graphics.FromImage(tempBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); this.playImageList.Images.Add(tempBitmap); } for (int i=4;i<8;i++) { tempBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); symbolBitmap = new Bitmap(9, 9, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(tempBitmap).DrawImageUnscaled(buttonsBitmap, 0, -136-(i*17)); if (i != 7) Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(this.FindColor(ref symbolsBitmap, i)), this.rightPlayRegion); else Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(this.FindColor(ref symbolsBitmap, i)), this.rightPlayRegion); Graphics.FromImage(tempBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); this.playImageList.Images.Add(tempBitmap); } for (int i=0;i<8;i++) { tempBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); symbolBitmap = new Bitmap(9, 9, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(tempBitmap).DrawImageUnscaled(buttonsBitmap, 0, -136-(i*17)); if (i != 3 || i != 7) Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(this.FindColor(ref symbolsBitmap, i)), this.stopRegion); else Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(this.FindColor(ref symbolsBitmap, i)), this.stopRegion); Graphics.FromImage(tempBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); this.stopImageList.Images.Add(tempBitmap); } this.leftPictureBox.BorderStyle = rightPictureBox.BorderStyle = BorderStyle.None; this.leftPictureBox_MouseLeave(this, new System.EventArgs()); this.rightPictureBox_MouseLeave(this, new System.EventArgs()); } private Color FindColor(ref Bitmap symbolBitmap, int bitmapIndex) { for (int i=0;i<9;i++) { for (int j=72+bitmapIndex*9;j<72+bitmapIndex*9+9;j++) { if (symbolBitmap.GetPixel(i,j).R != Color.Magenta.R || symbolBitmap.GetPixel(i,j).G != Color.Magenta.G || symbolBitmap.GetPixel(i,j).B != Color.Magenta.B) return symbolBitmap.GetPixel(i,j); } } return SystemColors.ControlText; } private void CreateBitmapsNormal() { Bitmap buttonBitmap, symbolBitmap; // draw the left play symbols buttonBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); symbolBitmap = new Bitmap(9, 9, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(buttonBitmap).FillRectangle(new SolidBrush(System.Drawing.SystemColors.Control), this.leftPictureBox.ClientRectangle); Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(SystemColors.ControlText), this.leftPlayRegion); Graphics.FromImage(buttonBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); for (int i=0;i<3;i++) this.playImageList.Images.Add(buttonBitmap); buttonBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(SystemColors.GrayText), this.leftPlayRegion); Graphics.FromImage(buttonBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); this.playImageList.Images.Add(buttonBitmap); // draw the right play symbols buttonBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); symbolBitmap = new Bitmap(9, 9, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(buttonBitmap).FillRectangle(new SolidBrush(System.Drawing.SystemColors.Control), this.rightPictureBox.ClientRectangle); Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(SystemColors.ControlText), this.rightPlayRegion); Graphics.FromImage(buttonBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); for (int i=0;i<3;i++) this.playImageList.Images.Add(buttonBitmap); buttonBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(SystemColors.GrayText), this.rightPlayRegion); Graphics.FromImage(buttonBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); this.playImageList.Images.Add(buttonBitmap); // draw the stop symbols (left and right are the same) buttonBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); symbolBitmap = new Bitmap(9, 9, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(buttonBitmap).FillRectangle(new SolidBrush(System.Drawing.SystemColors.Control), this.leftPictureBox.ClientRectangle); Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(SystemColors.ControlText), this.stopRegion); Graphics.FromImage(buttonBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); for (int i=0;i<3;i++) this.stopImageList.Images.Add(buttonBitmap); buttonBitmap = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics.FromImage(symbolBitmap).FillRegion(new SolidBrush(SystemColors.GrayText), this.stopRegion); Graphics.FromImage(buttonBitmap).DrawImage(symbolBitmap, 4, 4, 9, 9); this.stopImageList.Images.Add(buttonBitmap); // create copies of the left stop buttons for the right stop buttons to use for (int i=0; i<4; i++) this.stopImageList.Images.Add(this.stopImageList.Images[i]); this.leftPictureBox.BorderStyle = rightPictureBox.BorderStyle = BorderStyle.FixedSingle; this.leftPictureBox_MouseLeave(this, new System.EventArgs()); this.rightPictureBox_MouseLeave(this, new System.EventArgs()); } /// <summary> /// Handle the button click events of the two autoscroll buttons, and set timers and images appropriately. /// </summary> private void MovieButtonsClicked() { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) { this.leftPictureBox.Image = stopImageList.Images[0]; this.rightPictureBox.Image = stopImageList.Images[4]; this.buttonMode = ExtendedScrollBarButtonMode.StopSymbols; // start the auto-scroll timer this.autoscrollTimer.Start(); } else { this.leftPictureBox.Image = playImageList.Images[0]; this.rightPictureBox.Image = playImageList.Images[4]; this.buttonMode = ExtendedScrollBarButtonMode.PlaySymbols; // stop the auto-scroll timer if it is still active if (this.autoscrollTimer.Enabled) this.autoscrollTimer.Stop(); } } #endregion #region PictureBox Events private void rightPictureBox_MouseEnter(object sender, System.EventArgs e) { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) this.rightPictureBox.Image = playImageList.Images[5]; else this.rightPictureBox.Image = stopImageList.Images[5]; } private void rightPictureBox_MouseLeave(object sender, System.EventArgs e) { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) this.rightPictureBox.Image = playImageList.Images[4]; else this.rightPictureBox.Image = stopImageList.Images[4]; } private void rightPictureBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) this.rightPictureBox.Image = playImageList.Images[6]; else this.rightPictureBox.Image = stopImageList.Images[6]; } private void rightPictureBox_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) this.rightPictureBox.Image = playImageList.Images[4]; else this.rightPictureBox.Image = stopImageList.Images[4]; } private void rightPictureBox_EnabledChanged(object sender, System.EventArgs e) { if (rightPictureBox.Enabled) this.rightPictureBox.Image = playImageList.Images[4]; else this.rightPictureBox.Image = playImageList.Images[7]; } private void rightPictureBox_Click(object sender, System.EventArgs e) { this.movieDirection = ExtendedScrollBarMovieDirection.Right; this.MovieButtonsClicked(); } private void rightPictureBox_DoubleClick(object sender, System.EventArgs e) { this.movieDirection = ExtendedScrollBarMovieDirection.Right; this.MovieButtonsClicked(); } private void leftPictureBox_MouseEnter(object sender, System.EventArgs e) { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) this.leftPictureBox.Image = playImageList.Images[1]; else this.leftPictureBox.Image = stopImageList.Images[1]; } private void leftPictureBox_MouseLeave(object sender, System.EventArgs e) { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) this.leftPictureBox.Image = playImageList.Images[0]; else this.leftPictureBox.Image = stopImageList.Images[0]; } private void leftPictureBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) this.leftPictureBox.Image = playImageList.Images[2]; else this.leftPictureBox.Image = stopImageList.Images[2]; } private void leftPictureBox_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (this.buttonMode == ExtendedScrollBarButtonMode.PlaySymbols) this.leftPictureBox.Image = playImageList.Images[0]; else this.leftPictureBox.Image = stopImageList.Images[0]; } private void leftPictureBox_EnabledChanged(object sender, System.EventArgs e) { if (leftPictureBox.Enabled) this.leftPictureBox.Image = playImageList.Images[0]; else this.leftPictureBox.Image = playImageList.Images[3]; } private void leftPictureBox_Click(object sender, System.EventArgs e) { this.movieDirection = ExtendedScrollBarMovieDirection.Left; this.MovieButtonsClicked(); } private void leftPictureBox_DoubleClick(object sender, System.EventArgs e) { this.movieDirection = ExtendedScrollBarMovieDirection.Left; this.MovieButtonsClicked(); } #endregion #region ScrollBar Events /// <summary> /// Event thrown when scrollbar is scrolled using any of the buttons or thumb bar. /// </summary> public new event System.Windows.Forms.ScrollEventHandler Scroll; private void hScrollBar_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) { // we check on the scroll type due to a bug in .NET that causes dual scroll events to // be triggered for only 1 click of the scroll buttons if (e.Type == ScrollEventType.SmallIncrement || e.Type == ScrollEventType.SmallDecrement || e.Type == ScrollEventType.LargeIncrement || e.Type == ScrollEventType.LargeDecrement || e.Type == ScrollEventType.ThumbTrack ) { //System.Diagnostics.Debug.WriteLine(e.NewValue); if (this.Scroll != null) { //System.Diagnostics.Debug.WriteLine("Value: " + e.NewValue.ToString()); //System.Diagnostics.Debug.WriteLine("Min: " + this.hScrollBar.Minimum); //System.Diagnostics.Debug.WriteLine("Max: " + this.hScrollBar.Maximum); this.Scroll(this, e); } } } /// <summary> /// Event thrown when scrollbar current position (value) changes. /// </summary> // public event System.EventHandler ValueChanged; // private void hScrollBar_ValueChanged(object sender, System.EventArgs e) // { // if (this.ValueChanged != null) // this.ValueChanged(this, e); // } #endregion #region Timer Event /// <summary> /// Handles the Tick event of the scroll timer, causing autoscroll to occur. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">EventArgs of the event</param> private void autoscrollTimer_Tick(object sender, System.EventArgs e) { int newScroll; if (this.movieDirection == ExtendedScrollBarMovieDirection.Left) { newScroll = this.hScrollBar.Value - this.scrollAmount; if (newScroll <= this.hScrollBar.Minimum) { MovieButtonsClicked(); this.hScrollBar.Value = newScroll = this.hScrollBar.Minimum; } else this.hScrollBar.Value = newScroll; } else { newScroll = this.hScrollBar.Value + this.scrollAmount; if (newScroll >= this.hScrollBar.Maximum) { MovieButtonsClicked(); this.hScrollBar.Value = newScroll = this.hScrollBar.Maximum; } else this.hScrollBar.Value = newScroll; } // call the scroll event handler, to make sure a scroll event is thrown to any connected delegates this.hScrollBar_Scroll(this, new System.Windows.Forms.ScrollEventArgs(ScrollEventType.SmallIncrement, newScroll)); } #endregion #region Control Events /// <summary> /// Handles the SystemColorsChanged event of the ExtendedScrollBar, creating new bitmaps when new theme is activated. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">EventArgs of the event</param> private void ExtendedScrollBar_SystemColorsChanged(object sender, System.EventArgs e) { this.CreateBitmaps(); } /// <summary> /// Handles the EnableChanged event of the ExtendedScrollBar, makind sure to disable autoscroll if needed. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">EventArgs of the event</param> private void ExtendedScrollBar_EnabledChanged(object sender, System.EventArgs e) { // make sure we stop the scroll timer if it is active if (!this.Enabled && this.autoscrollTimer.Enabled) this.MovieButtonsClicked(); } #endregion #region Control Properties /// <summary> /// Gets or sets the auto-scrolling state of the extended scrollbar. /// </summary> public bool AutoScrolling { get { return this.autoscrollTimer.Enabled; } set { if (value == false && this.autoscrollTimer.Enabled) this.MovieButtonsClicked(); else if (value == true && !this.autoscrollTimer.Enabled) { this.MovieButtonsClicked(); } } } /// <summary> /// Gets or sets the current position (value) of the scrollbar. /// </summary> public int Value { get { return this.hScrollBar.Value; } set { this.hScrollBar.Value = value; } } /// <summary> /// Gets or sets the minimum value of the scrollbar. /// </summary> public int Minimum { get { return this.hScrollBar.Minimum; } set { this.hScrollBar.Minimum = value; } } /// <summary> /// Gets or sets the maximum value of the srollbar. /// </summary> public int Maximum { get { return this.hScrollBar.Maximum; } set { this.hScrollBar.Maximum = value; } } /// <summary> /// Gets or sets the value to be added or subtracted from the current scrollbar position (value) when the scrollbox is moved a short distance. /// </summary> public int SmallChange { get { return this.hScrollBar.SmallChange; } set { this.hScrollBar.SmallChange = value; } } /// <summary> /// Gets or sets the value to be added or subtracted from the current scrollbar position (value) when the scrollbox is moved a large distance. /// </summary> public int LargeChange { get { return this.hScrollBar.LargeChange; } set { this.hScrollBar.LargeChange = value; } } /// <summary> /// Gets or sets the time interval for the autoscroll function. /// </summary> public int TimerInterval { get { return this.autoscrollTimer.Interval; } set { this.autoscrollTimer.Interval = value; } } /// <summary> /// Gets or sets the amount (in pixels) that will be scrolled during an auto-scroll step. /// </summary> public int TimerAmount { get { return this.scrollAmount; } set { this.scrollAmount = Math.Abs(value); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Boy_Meets_Girl { /// <summary> /// This is the main type for your game /// </summary> public class Main : Microsoft.Xna.Framework.Game { #region variables GraphicsDeviceManager graphics; SpriteBatch spriteBatch; //Global variables. public static Random random; public const int width = 900; public const int height = 700; public static Color[] colors = new Color[] { Color.Red, Color.Blue, Color.Green, Color.White }; //Variables for game/display World world; BaseObject currentSelection; Vector2 spriteDimensions; //How large of a box to draw around each character. int indexSelected; //Which flower you've selected from your inventory. //Pure graphics SpriteFont titleScreen; SpriteFont flowerTexture; SpriteFont statsFont; Texture2D colorTexture; //Graphic dimensions - for spritefonts and positioning and the like. /// <summary> /// Width and height of the title /// </summary> Vector2 titleDimensions; /// <summary> /// Width and height of an on-screen character (for flowers and people). /// Static so it's accessible from world. /// </summary> public static Vector2 characterDimension; /// <summary> /// Width and height of a single character in the stats-font. /// </summary> Vector2 statsDimensions; #endregion public Main() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; //Set screen resolution and cursor. graphics.PreferredBackBufferHeight = height; graphics.PreferredBackBufferWidth = width; this.IsMouseVisible = true; //Set up global random. random = new Random(); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { //INITIALIZE YOUR BASE NOW! //This makes sure that the textures and fonts will be loaded in before they're measured. base.Initialize(); //Set up your spritefont and dimensions and stuff. titleDimensions = titleScreen.MeasureString("Boy Meets Girl"); characterDimension = flowerTexture.MeasureString("X"); statsDimensions = statsFont.MeasureString("X"); //Set up the game world. //You'll notice that the right and bottom margins are adjust to make sure nothing spawns half way on the screen. world = new World(20, (int)titleDimensions.Y, width - 40 - (int)characterDimension.X, height - (int)titleDimensions.Y - 100 - (int)characterDimension.Y, 0, 3); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Fonts and textures. titleScreen = Content.Load<SpriteFont>("TitleScreen"); flowerTexture = Content.Load<SpriteFont>("flowerSprite"); colorTexture = Content.Load<Texture2D>("ColorTexture"); statsFont = Content.Load <SpriteFont>("statsFont"); //Measure the font to make sure everything is cool on that front. spriteDimensions = flowerTexture.MeasureString("X"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { #region interface and buttons // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // Mouse tracking currentSelection = null; MouseState currentState = Mouse.GetState(); //Loop through all the game objects. See if you're overtop of any of them. for (int i = 0; i < world.objects.Count; ++i) { //Check position based on fontsize. if (currentState.X > world.objects[i].position.X && currentState.X < world.objects[i].position.X + spriteDimensions.X && currentState.Y > world.objects[i].position.Y && currentState.Y < world.objects[i].position.Y + spriteDimensions.Y) { currentSelection = world.objects[i]; break; //Forget you! I'll use break statements as much as I want while hacking! } } //Drag and drop interface. This can be fixed with some variables to make it more exact when selecting items. if (currentState.LeftButton == ButtonState.Pressed) { for (int i = 0; i < world.player.inventory.Count; i++) { //Check position based on fontsize. if (currentState.X > 500 + i * this.statsDimensions.X && currentState.X < 500 + i * this.statsDimensions.X + statsDimensions.X && currentState.Y > height - 100 && currentState.Y < height - 100 + statsDimensions.Y) { indexSelected = i; break; //Once again, unnecessary, but good for processer times. } } } else //On release. { if (indexSelected != -1) { //If you're over top of anothe person, (and it's not you, give them that flower). if (currentSelection != null && currentSelection != world.player) { world.player.giveFlower(currentSelection, world.player.inventory[indexSelected]); } //Either way, you don't have it selected. indexSelected = -1; } } //Button Presses KeyboardState currentKeyState = Keyboard.GetState(); Keys[] currentKeysDown = currentKeyState.GetPressedKeys(); //Run logic. world.player.movementX = 0; world.player.movementY = 0; foreach (Keys k in currentKeysDown) { if (k == Keys.W) { world.player.movementY = -1; } else if (k == Keys.S) { world.player.movementY = 1; } else if (k == Keys.A) { world.player.movementX = -1; } else if (k == Keys.D) { world.player.movementX = 1; } } #endregion #region gameLogic world.update(); #endregion base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.LightGray); spriteBatch.Begin(); #region interface //Draw title after measuring title. Vector2 dimensionsTitle = titleScreen.MeasureString("Boy Meets Girl"); spriteBatch.DrawString(titleScreen, "Boy Meets Girl", new Vector2((float)(.5 * Main.width - .5 * dimensionsTitle.X), 0), Color.Black); //Draw the background to the world. spriteBatch.Draw(colorTexture, new Rectangle(20, (int)titleDimensions.Y, width - 40, height - (int)titleDimensions.Y - 100), Color.Black); //Draw stats for mouseover. Very temp as far as position goes and what font is used. These will be moved to the bottom of the screen. if(currentSelection != null) { String[] toDisplay = currentSelection.getInfo(); //You'll need to do another dimension call in the future once this sprite is switched out, but that works back into margins. for(int i = 0; i < toDisplay.Length; i++) { spriteBatch.DrawString(statsFont, toDisplay[i], new Vector2(25, height - 100 + (this.statsDimensions.Y - 4)*i), Color.Black); } } //Draw your inventory. for (int i = 0; i < world.player.inventory.Count; i++) { if(indexSelected != i) //If the flower isn't selected. spriteBatch.DrawString(statsFont, "f", new Vector2(500 + i * this.statsDimensions.X, height - 100), colors[world.player.inventory[i]]); else //If the flower is selected. spriteBatch.DrawString(statsFont, "f", new Vector2(Mouse.GetState().X, Mouse.GetState().Y), colors[world.player.inventory[i]]); } #endregion #region objects for (int i = 0; i < world.objects.Count; i++) { spriteBatch.DrawString(flowerTexture, world.objects[i].graphic, world.objects[i].position, colors[world.objects[i].color]); } #endregion spriteBatch.End(); base.Draw(gameTime); } } }
//--------------------------------------------------------------------- // <copyright file="ProductInstallation.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; /// <summary> /// Represents a unique instance of a product that /// is either advertised, installed or unknown. /// </summary> internal class ProductInstallation : Installation { /// <summary> /// Gets the set of all products with a specified upgrade code. This method lists the /// currently installed and advertised products that have the specified UpgradeCode /// property in their Property table. /// </summary> /// <param name="upgradeCode">Upgrade code of related products</param> /// <returns>Enumeration of product codes</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msienumrelatedproducts.asp">MsiEnumRelatedProducts</a> /// </p></remarks> public static IEnumerable<ProductInstallation> GetRelatedProducts(string upgradeCode) { StringBuilder buf = new StringBuilder(40); for (uint i = 0; true; i++) { uint ret = NativeMethods.MsiEnumRelatedProducts(upgradeCode, 0, i, buf); if (ret == (uint) NativeMethods.Error.NO_MORE_ITEMS) break; if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } yield return new ProductInstallation(buf.ToString()); } } /// <summary> /// Enumerates all product installations on the system. /// </summary> /// <returns>An enumeration of product objects.</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msienumproducts.asp">MsiEnumProducts</a>, /// </p></remarks> public static IEnumerable<ProductInstallation> AllProducts { get { return GetProducts(null, null, UserContexts.All); } } /// <summary> /// Enumerates product installations based on certain criteria. /// </summary> /// <param name="productCode">ProductCode (GUID) of the product instances to be enumerated. Only /// instances of products within the scope of the context specified by the /// <paramref name="userSid"/> and <paramref name="context"/> parameters will be /// enumerated. This parameter may be set to null to enumerate all products in the specified /// context.</param> /// <param name="userSid">Specifies a security identifier (SID) that restricts the context /// of enumeration. A SID value other than s-1-1-0 is considered a user SID and restricts /// enumeration to the current user or any user in the system. The special SID string /// s-1-1-0 (Everyone) specifies enumeration across all users in the system. This parameter /// can be set to null to restrict the enumeration scope to the current user. When /// <paramref name="context"/> is set to the machine context only, /// <paramref name="userSid"/> must be null.</param> /// <param name="context">Specifies the user context.</param> /// <returns>An enumeration of product objects for enumerated product instances.</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msienumproductsex.asp">MsiEnumProductsEx</a> /// </p></remarks> public static IEnumerable<ProductInstallation> GetProducts( string productCode, string userSid, UserContexts context) { StringBuilder buf = new StringBuilder(40); UserContexts targetContext; StringBuilder targetSidBuf = new StringBuilder(40); for (uint i = 0; ; i++) { uint targetSidBufSize = (uint) targetSidBuf.Capacity; uint ret = NativeMethods.MsiEnumProductsEx( productCode, userSid, context, i, buf, out targetContext, targetSidBuf, ref targetSidBufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { targetSidBuf.Capacity = (int) ++targetSidBufSize; ret = NativeMethods.MsiEnumProductsEx( productCode, userSid, context, i, buf, out targetContext, targetSidBuf, ref targetSidBufSize); } if (ret == (uint) NativeMethods.Error.NO_MORE_ITEMS) { break; } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } yield return new ProductInstallation( buf.ToString(), targetSidBuf.ToString(), targetContext); } } private IDictionary<string, string> properties; /// <summary> /// Creates a new object for accessing information about a product installation on the current system. /// </summary> /// <param name="productCode">ProductCode (GUID) of the product.</param> /// <remarks><p> /// All available user contexts will be queried. /// </p></remarks> public ProductInstallation(string productCode) : this(productCode, null, UserContexts.All) { } /// <summary> /// Creates a new object for accessing information about a product installation on the current system. /// </summary> /// <param name="productCode">ProductCode (GUID) of the product.</param> /// <param name="userSid">The specific user, when working in a user context. This /// parameter may be null to indicate the current user. The parameter must be null /// when working in a machine context.</param> /// <param name="context">The user context. The calling process must have administrative /// privileges to get information for a product installed for a user other than the /// current user.</param> public ProductInstallation(string productCode, string userSid, UserContexts context) : base(productCode, userSid, context) { if (string.IsNullOrWhiteSpace(productCode)) { throw new ArgumentNullException("productCode"); } } internal ProductInstallation(IDictionary<string, string> properties) : base(properties["ProductCode"], null, UserContexts.None) { this.properties = properties; } /// <summary> /// Gets the set of published features for the product. /// </summary> /// <returns>Enumeration of published features for the product.</returns> /// <exception cref="InstallerException">The installer configuration data is corrupt</exception> /// <remarks><p> /// Because features are not ordered, any new feature has an arbitrary index, meaning /// this property can return features in any order. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msienumfeatures.asp">MsiEnumFeatures</a> /// </p></remarks> public IEnumerable<FeatureInstallation> Features { get { StringBuilder buf = new StringBuilder(256); for (uint i = 0; ; i++) { uint ret = NativeMethods.MsiEnumFeatures(this.ProductCode, i, buf, null); if (ret != 0) { break; } yield return new FeatureInstallation(buf.ToString(), this.ProductCode); } } } /// <summary> /// Gets the ProductCode (GUID) of the product. /// </summary> public string ProductCode { get { return this.InstallationCode; } } /// <summary> /// Gets a value indicating whether this product is installed on the current system. /// </summary> public override bool IsInstalled { get { return (this.State == InstallState.Default); } } /// <summary> /// Gets a value indicating whether this product is advertised on the current system. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public bool IsAdvertised { get { return (this.State == InstallState.Advertised); } } /// <summary> /// Checks whether the product is installed with elevated privileges. An application is called /// a "managed application" if elevated (system) privileges are used to install the application. /// </summary> /// <returns>True if the product is elevated; false otherwise</returns> /// <remarks><p> /// Note that this property does not take into account policies such as AlwaysInstallElevated, /// but verifies that the local system owns the product's registry data. /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public bool IsElevated { get { bool isElevated; uint ret = NativeMethods.MsiIsProductElevated(this.ProductCode, out isElevated); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return isElevated; } } /// <summary> /// Gets the source list of this product installation. /// </summary> internal override SourceList SourceList { get { return this.properties == null ? base.SourceList : null; } } internal InstallState State { get { if (this.properties != null) { return InstallState.Unknown; } else { int installState = NativeMethods.MsiQueryProductState(this.ProductCode); return (InstallState) installState; } } } internal override int InstallationType { get { const int MSICODE_PRODUCT = 0x00000000; return MSICODE_PRODUCT; } } /// <summary> /// The support link. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string HelpLink { get { return this["HelpLink"]; } } /// <summary> /// The support telephone. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string HelpTelephone { get { return this["HelpTelephone"]; } } /// <summary> /// Date and time the product was installed. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public DateTime InstallDate { get { try { return DateTime.ParseExact( this["InstallDate"], "yyyyMMdd", CultureInfo.InvariantCulture); } catch (FormatException) { return DateTime.MinValue; } } } /// <summary> /// The installed product name. /// </summary> public string ProductName { get { return this["InstalledProductName"]; } } /// <summary> /// The installation location. /// </summary> public string InstallLocation { get { return this["InstallLocation"]; } } /// <summary> /// The installation source. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811: Avoid uncalled private coded", Justification = "Common code for extensions.")] public string InstallSource { get { return this["InstallSource"]; } } /// <summary> /// The local cached package. /// </summary> public string LocalPackage { get { return this["LocalPackage"]; } } /// <summary> /// The publisher. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Publisher { get { return this["Publisher"]; } } /// <summary> /// URL about information. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public Uri UrlInfoAbout { get { string value = this["URLInfoAbout"]; if (!string.IsNullOrWhiteSpace(value)) { try { return new Uri(value); } catch (UriFormatException) { } } return null; } } /// <summary> /// The URL update information. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public Uri UrlUpdateInfo { get { string value = this["URLUpdateInfo"]; if (!string.IsNullOrWhiteSpace(value)) { try { return new Uri(value); } catch (UriFormatException) { } } return null; } } /// <summary> /// The product version. /// </summary> public Version ProductVersion { get { string ver = this["VersionString"]; return ProductInstallation.ParseVersion(ver); } } /// <summary> /// The product identifier. /// </summary> /// <remarks><p> /// For more information, see /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/productid.asp">ProductID</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string ProductId { get { return this["ProductID"]; } } /// <summary> /// The company that is registered to use the product. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string RegCompany { get { return this["RegCompany"]; } } /// <summary> /// The owner who is registered to use the product. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string RegOwner { get { return this["RegOwner"]; } } /// <summary> /// Transforms. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string AdvertisedTransforms { get { return this["Transforms"]; } } /// <summary> /// Product language. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string AdvertisedLanguage { get { return this["Language"]; } } /// <summary> /// Human readable product name. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string AdvertisedProductName { get { return this["ProductName"]; } } /// <summary> /// True if the product is advertised per-machine; /// false if it is per-user or not advertised. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public bool AdvertisedPerMachine { get { return this["AssignmentType"] == "1"; } } /// <summary> /// Identifier of the package that a product is installed from. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string AdvertisedPackageCode { get { return this["PackageCode"]; } } /// <summary> /// Version of the advertised product. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public Version AdvertisedVersion { get { string ver = this["Version"]; return ProductInstallation.ParseVersion(ver); } } /// <summary> /// Primary icon for the package. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string AdvertisedProductIcon { get { return this["ProductIcon"]; } } /// <summary> /// Name of the installation package for the advertised product. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string AdvertisedPackageName { get { return this["PackageName"]; } } /// <summary> /// True if the advertised product can be serviced by /// non-administrators without elevation. /// </summary> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public bool PrivilegedPatchingAuthorized { get { return this["AuthorizedLUAApp"] == "1"; } } /// <summary> /// Gets information about an installation of a product. /// </summary> /// <param name="propertyName">Name of the property being retrieved.</param> /// <exception cref="ArgumentOutOfRangeException">An unknown product or property was requested</exception> /// <exception cref="InstallerException">The installer configuration data is corrupt</exception> /// <remarks><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetproductinfo.asp">MsiGetProductInfo</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetproductinfoex.asp">MsiGetProductInfoEx</a> /// </p></remarks> public override string this[string propertyName] { get { if (this.properties != null) { string value = null; this.properties.TryGetValue(propertyName, out value); return value; } else { StringBuilder buf = new StringBuilder(40); uint bufSize = (uint) buf.Capacity; uint ret; if (this.Context == UserContexts.UserManaged || this.Context == UserContexts.UserUnmanaged || this.Context == UserContexts.Machine) { ret = NativeMethods.MsiGetProductInfoEx( this.ProductCode, this.UserSid, this.Context, propertyName, buf, ref bufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { buf.Capacity = (int) ++bufSize; ret = NativeMethods.MsiGetProductInfoEx( this.ProductCode, this.UserSid, this.Context, propertyName, buf, ref bufSize); } } else { ret = NativeMethods.MsiGetProductInfo( this.ProductCode, propertyName, buf, ref bufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { buf.Capacity = (int) ++bufSize; ret = NativeMethods.MsiGetProductInfo( this.ProductCode, propertyName, buf, ref bufSize); } } if (ret != 0) { return null; } return buf.ToString(); } } } /// <summary> /// Gets the installed state for a product feature. /// </summary> /// <param name="feature">The feature being queried; identifier from the /// Feature table</param> /// <returns>Installation state of the feature for the product instance: either /// <see cref="InstallState.Local"/>, <see cref="InstallState.Source"/>, /// or <see cref="InstallState.Advertised"/>.</returns> /// <remarks><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiqueryfeaturestate.asp">MsiQueryFeatureState</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiqueryfeaturestateex.asp">MsiQueryFeatureStateEx</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public InstallState GetFeatureState(string feature) { if (this.properties != null) { return InstallState.Unknown; } else { int installState; uint ret = NativeMethods.MsiQueryFeatureStateEx( this.ProductCode, this.UserSid, this.Context, feature, out installState); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return (InstallState) installState; } } /// <summary> /// Gets the installed state for a product component. /// </summary> /// <param name="component">The component being queried; GUID of the component /// as found in the ComponentId column of the Component table.</param> /// <returns>Installation state of the component for the product instance: either /// <see cref="InstallState.Local"/> or <see cref="InstallState.Source"/>.</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiquerycomponnetstate.asp">MsiQueryComponentState</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public InstallState GetComponentState(string component) { if (this.properties != null) { return InstallState.Unknown; } else { int installState; uint ret = NativeMethods.MsiQueryComponentState( this.ProductCode, this.UserSid, this.Context, component, out installState); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return (InstallState) installState; } } /// <summary> /// Obtains and stores the user information and product ID from an installation wizard. /// </summary> /// <remarks><p> /// This method is typically called by an application during the first run of the application. The application /// first gets the <see cref="ProductInstallation.ProductId"/> or <see cref="ProductInstallation.RegOwner"/>. /// If those properties are missing, the application calls CollectUserInfo. /// CollectUserInfo opens the product's installation package and invokes a wizard sequence that collects /// user information. Upon completion of the sequence, user information is registered. Since this API requires /// an authored user interface, the user interface level should be set to full by calling /// <see cref="Installer.SetInternalUI(InstallUIOptions)"/> as <see cref="InstallUIOptions.Full"/>. /// </p><p> /// The CollectUserInfo method invokes a FirstRun dialog from the product installation database. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msicollectuserinfo.asp">MsiCollectUserInfo</a> /// </p></remarks> [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void CollectUserInfo() { if (this.properties == null) { uint ret = NativeMethods.MsiCollectUserInfo(this.InstallationCode); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } } /// <summary> /// Some products might write some invalid/nonstandard version strings to the registry. /// This method tries to get the best data it can. /// </summary> /// <param name="ver">Version string retrieved from the registry.</param> /// <returns>Version object, or null if the version string is completely invalid.</returns> private static Version ParseVersion(string ver) { if (ver != null) { int dotCount = 0; for (int i = 0; i < ver.Length; i++) { char c = ver[i]; if (c == '.') dotCount++; else if (!Char.IsDigit(c)) { ver = ver.Substring(0, i); break; } } if (ver.Length > 0) { if (dotCount == 0) { ver = ver + ".0"; } else if (dotCount > 3) { string[] verSplit = ver.Split('.'); ver = String.Join(".", verSplit, 0, 4); } try { return new Version(ver); } catch (ArgumentException) { } } } return null; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Collections.ObjectModel { public abstract partial class KeyedCollection<TKey, TItem> : System.Collections.ObjectModel.Collection<TItem> { protected KeyedCollection() { } protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey> comparer) { } protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold) { } public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { throw null; } } protected System.Collections.Generic.IDictionary<TKey, TItem> Dictionary { get { throw null; } } public TItem this[TKey key] { get { throw null; } } protected void ChangeItemKey(TItem item, TKey newKey) { } protected override void ClearItems() { } public bool Contains(TKey key) { throw null; } protected abstract TKey GetKeyForItem(TItem item); protected override void InsertItem(int index, TItem item) { } public bool Remove(TKey key) { throw null; } protected override void RemoveItem(int index) { } protected override void SetItem(int index, TItem item) { } public bool TryGetValue(TKey key, out TItem item) { throw null; } } public partial class ObservableCollection<T> : System.Collections.ObjectModel.Collection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged { public ObservableCollection() { } public ObservableCollection(System.Collections.Generic.IEnumerable<T> collection) { } public ObservableCollection(System.Collections.Generic.List<T> list) { } public virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged { add { } remove { } } protected virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } } event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } } protected System.IDisposable BlockReentrancy() { throw null; } protected void CheckReentrancy() { } protected override void ClearItems() { } protected override void InsertItem(int index, T item) { } public void Move(int oldIndex, int newIndex) { } protected virtual void MoveItem(int oldIndex, int newIndex) { } protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { } protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, T item) { } } public partial class ReadOnlyDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public ReadOnlyDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } protected System.Collections.Generic.IDictionary<TKey, TValue> Dictionary { get { throw null; } } public TValue this[TKey key] { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { throw null; } } TValue System.Collections.Generic.IDictionary<TKey,TValue>.this[TKey key] { get { throw null; } set { } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey,TValue>.Keys { get { throw null; } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey,TValue>.Values { get { throw null; } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Keys { get { throw null; } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Values { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } bool System.Collections.IDictionary.IsReadOnly { get { throw null; } } object System.Collections.IDictionary.this[object key] { get { throw null; } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } } System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.ValueCollection Values { get { throw null; } } public bool ContainsKey(TKey key) { throw null; } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Clear() { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { throw null; } void System.Collections.Generic.IDictionary<TKey,TValue>.Add(TKey key, TValue value) { } bool System.Collections.Generic.IDictionary<TKey,TValue>.Remove(TKey key) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } void System.Collections.IDictionary.Clear() { } bool System.Collections.IDictionary.Contains(object key) { throw null; } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(TKey key, out TValue value) { throw null; } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { internal KeyCollection() { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TKey[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<TKey> GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { internal ValueCollection() { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TValue[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<TValue> GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } } public partial class ReadOnlyObservableCollection<T> : System.Collections.ObjectModel.ReadOnlyCollection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged { public ReadOnlyObservableCollection(System.Collections.ObjectModel.ObservableCollection<T> list) : base (default(System.Collections.Generic.IList<T>)) { } protected virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged { add { } remove { } } protected virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } } event System.Collections.Specialized.NotifyCollectionChangedEventHandler System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged { add { } remove { } } event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } } protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs args) { } protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args) { } } } namespace System.Collections.Specialized { public partial interface INotifyCollectionChanged { event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; } public enum NotifyCollectionChangedAction { Add = 0, Move = 3, Remove = 1, Replace = 2, Reset = 4, } public partial class NotifyCollectionChangedEventArgs : System.EventArgs { public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems, int startingIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int startingIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int index, int oldIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { } public System.Collections.Specialized.NotifyCollectionChangedAction Action { get { throw null; } } public System.Collections.IList NewItems { get { throw null; } } public int NewStartingIndex { get { throw null; } } public System.Collections.IList OldItems { get { throw null; } } public int OldStartingIndex { get { throw null; } } } public delegate void NotifyCollectionChangedEventHandler(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e); } namespace System.ComponentModel { public partial class DataErrorsChangedEventArgs : System.EventArgs { public DataErrorsChangedEventArgs(string propertyName) { } public virtual string PropertyName { get { throw null; } } } public partial interface INotifyDataErrorInfo { bool HasErrors { get; } event System.EventHandler<System.ComponentModel.DataErrorsChangedEventArgs> ErrorsChanged; System.Collections.IEnumerable GetErrors(string propertyName); } public partial interface INotifyPropertyChanged { event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; } public partial interface INotifyPropertyChanging { event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; } public partial class PropertyChangedEventArgs : System.EventArgs { public PropertyChangedEventArgs(string propertyName) { } public virtual string PropertyName { get { throw null; } } } public delegate void PropertyChangedEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e); public partial class PropertyChangingEventArgs : System.EventArgs { public PropertyChangingEventArgs(string propertyName) { } public virtual string PropertyName { get { throw null; } } } public delegate void PropertyChangingEventHandler(object sender, System.ComponentModel.PropertyChangingEventArgs e); [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class TypeConverterAttribute : System.Attribute { public static readonly System.ComponentModel.TypeConverterAttribute Default; public TypeConverterAttribute() { } public TypeConverterAttribute(string typeName) { } public TypeConverterAttribute(System.Type type) { } public string ConverterTypeName { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)] public sealed partial class TypeDescriptionProviderAttribute : System.Attribute { public TypeDescriptionProviderAttribute(string typeName) { } public TypeDescriptionProviderAttribute(System.Type type) { } public string TypeName { get { throw null; } } } } namespace System.Reflection { public partial interface ICustomTypeProvider { System.Type GetCustomType(); } } namespace System.Windows.Input { [System.ComponentModel.TypeConverterAttribute("System.Windows.Input.CommandConverter, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")] [System.Windows.Markup.ValueSerializerAttribute("System.Windows.Input.CommandValueSerializer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")] public partial interface ICommand { event System.EventHandler CanExecuteChanged; bool CanExecute(object parameter); void Execute(object parameter); } } namespace System.Windows.Markup { [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=true)] public sealed partial class ValueSerializerAttribute : System.Attribute { public ValueSerializerAttribute(string valueSerializerTypeName) { } public ValueSerializerAttribute(System.Type valueSerializerType) { } public System.Type ValueSerializerType { get { throw null; } } public string ValueSerializerTypeName { get { throw null; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using NationalInstruments.UI; using NationalInstruments.UI.WindowsForms; using Analysis.EDM; using EDMConfig; namespace EDMBlockHead { public partial class LiveViewer : Form { private Controller controller; int blockCount = 1; double clusterVariance = 0; double clusterVarianceNormed = 0; double blocksPerDay = 240; private double initPumpPD = 1; private double initProbePD = 1; public LiveViewer(Controller c) { InitializeComponent(); controller = c; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); UpdateStatusText("EDMErr\t" + "normedErr\t" + "B\t" + "DB\t" + "DB/SIG" + "\t" + Environment.NewLine); } protected override void OnClosing(CancelEventArgs e) { Hide(); e.Cancel = true; } //public void Clear() //{ //} public void AddDBlock(DemodulatedBlock dblock) { QuickEDMAnalysis analysis = QuickEDMAnalysis.AnalyseDBlock(dblock); //Append LiveViewer text with edm errors, B, DB & DB/SIG AppendStatusText( (Math.Pow(10, 26) * analysis.RawEDMErr).ToString("G3") + "\t" + (Math.Pow(10, 26) * analysis.RawEDMErrNormed).ToString("G3") + "\t\t" + (analysis.BValAndErr[0]).ToString("N2") + "\t" + (analysis.DBValAndErr[0]).ToString("N2") + "\t" + (analysis.DBValAndErr[0] / analysis.SIGValAndErr[0]).ToString("N3") + Environment.NewLine); // Rollings values of edm error clusterVariance = ((clusterVariance * (blockCount - 1)) + analysis.RawEDMErr * analysis.RawEDMErr) / blockCount; double edmPerDay = Math.Sqrt(clusterVariance / blocksPerDay); clusterVarianceNormed = ((clusterVarianceNormed * (blockCount - 1)) + analysis.RawEDMErrNormed * analysis.RawEDMErrNormed) / blockCount; double edmPerDayNormed = Math.Sqrt(clusterVarianceNormed / blocksPerDay); UpdateClusterStatusText( "errorPerDay: " + edmPerDay.ToString("E3") + "\terrorPerDayNormed: " + edmPerDayNormed.ToString("E3") + Environment.NewLine + "block count: " + blockCount); //Update Plots AppendToSigScatter(new double[] { blockCount }, new double[] { analysis.SIGValAndErr[0] }); AppendToBScatter(new double[] { blockCount }, new double[] { analysis.BValAndErrNormed[0] }); AppendToBNormedScatter(new double[] { blockCount }, new double[] { 10.0*analysis.BDBValAndErrNormed[0] }); // Factor of 10 is to make {B} and {B}/{dB} scales comparable AppendToDBScatter(new double[] { blockCount }, new double[] { analysis.DBValAndErr[0] }); AppendToEDMScatter(new double[] { blockCount }, new double[] { Math.Pow(10, 26) * analysis.RawEDMErr }); AppendToEDMNormedScatter(new double[] { blockCount }, new double[] { Math.Pow(10, 26) * analysis.RawEDMErrNormed }); AppendSigmaToSIGScatter(new double[] { blockCount }, new double[] { analysis.SIGValAndErr[0] + analysis.SIGValAndErr[1] }, new double[] { analysis.SIGValAndErr[0] - analysis.SIGValAndErr[1] }); AppendSigmaToBScatter(new double[] { blockCount }, new double[] { analysis.BValAndErr[0] + analysis.BValAndErr[1] }, new double[] { analysis.BValAndErr[0] - analysis.BValAndErr[1] }); AppendSigmaToDBScatter(new double[] { blockCount }, new double[] { analysis.DBValAndErr[0] + analysis.DBValAndErr[1] }, new double[] { analysis.DBValAndErr[0] - analysis.DBValAndErr[1] }); AppendToNorthLeakageScatter(new double[] { blockCount }, new double[] { analysis.NorthCurrentValAndError[0] }); AppendToSouthLeakageScatter(new double[] { blockCount }, new double[] { analysis.SouthCurrentValAndError[0] }); AppendToNorthLeakageErrorScatter(new double[] { blockCount }, new double[] { analysis.NorthCurrentValAndError[1] }); AppendToSouthLeakageErrorScatter(new double[] { blockCount }, new double[] { analysis.SouthCurrentValAndError[1] }); AppendToNorthECorrLeakageScatter(new double[] { blockCount }, new double[] { analysis.NorthECorrCurrentValAndError[0] }); AppendToSouthECorrLeakageScatter(new double[] { blockCount }, new double[] { analysis.SouthECorrCurrentValAndError[0] }); AppendToMagNoiseScatter(new double[] { blockCount }, new double[] { analysis.MagValandErr[1] }); AppendToRfCurrentScatter(new double[] {blockCount }, new double[] {analysis.rfCurrent[0]}); AppendToLF1Scatter(new double[] { blockCount }, new double[] { analysis.LFValandErr[0] }); AppendToRF1AScatter(new double[] { blockCount }, new double[] { analysis.rf1AmpAndErrNormed[0] }); AppendToRF2AScatter(new double[] { blockCount }, new double[] { analysis.rf2AmpAndErrNormed[0] }); AppendToRF1FScatter(new double[] { blockCount }, new double[] { analysis.rf1FreqAndErrNormed[0] }); AppendToRF2FScatter(new double[] { blockCount }, new double[] { analysis.rf2FreqAndErrNormed[0] }); AppendToRF1ADBDBScatter(new double[] { blockCount }, new double[] { analysis.RF1ADBDB[0] }); AppendToRF2ADBDBScatter(new double[] { blockCount }, new double[] { analysis.RF2ADBDB[0] }); AppendToRF1FDBDBScatter(new double[] { blockCount }, new double[] { analysis.RF1FDBDB[0] }); AppendToRF2FDBDBScatter(new double[] { blockCount }, new double[] { analysis.RF2FDBDB[0] }); if (blockCount == 1) { initProbePD = analysis.probePD[0]; initPumpPD = analysis.pumpPD[0]; } AppendTopProbePDScatter(new double[] { blockCount }, new double[] { analysis.probePD[0] / initProbePD }); AppendTopPumpPDScatter(new double[] { blockCount }, new double[] { analysis.pumpPD[0] / initPumpPD }); AppendToLF1DBDBScatter(new double[] { blockCount }, new double[] { analysis.LF1DBDB[0] }); AppendToLF2DBDBScatter(new double[] { blockCount }, new double[] { analysis.LF2DBDB[0] }); AppendSigmaToLF1Scatter(new double[] { blockCount }, new double[] { analysis.LF1DBDB[0] + analysis.LF1DBDB[1] }, new double[] { analysis.LF1DBDB[0] - analysis.LF1DBDB[1] }); AppendSigmaToLF2Scatter(new double[] { blockCount }, new double[] { analysis.LF2DBDB[0] + analysis.LF2DBDB[1] }, new double[] { analysis.LF2DBDB[0] - analysis.LF2DBDB[1] }); blockCount = blockCount + 1; } private void resetEdmErrRunningMeans() { blockCount = 1; clusterVariance = 0; clusterVarianceNormed = 0; UpdateClusterStatusText("errorPerDay: " + 0 + "\terrorPerDayNormed: " + 0 + Environment.NewLine + "block count: " + 0); UpdateStatusText("EDMErr\t" + "normedErr\t" + "B\t" + "DB\t" + "DB/SIG" + "\t" + Environment.NewLine); ClearSIGScatter(); ClearBScatter(); ClearDBScatter(); ClearEDMErrScatter(); ClearLeakageScatters(); ClearMagNoiseScatterGraph(); ClearRfCurrentScatterGraph(); ClearLF1Graph(); ClearRFxAGraph(); ClearRFxFGraph(); ClearRFxFDBDBGraph(); ClearRFxADBDBGraph(); ClearPDScatter(); ClearLF1DBDBGraph(); } #region UI methods private void UpdateStatusText(string newText) { SetTextBox(statusText, newText); } private void AppendStatusText(string newText) { SetTextBox(statusText, statusText.Text + newText); } private void UpdateClusterStatusText(string newText) { SetTextBox(clusterStatusText, newText); } private void AppendToSigScatter(double[] x, double[] y) { PlotXYAppend(sigScatterGraph, sigPlot, x, y); } private void AppendToBScatter(double[] x, double[] y) { PlotXYAppend(bScatterGraph, bPlot, x, y); } private void AppendToBNormedScatter(double[] x, double[] y) { PlotXYAppend(bScatterGraph, bDBNLPlot, x, y); } private void AppendToDBScatter(double[] x, double[] y) { PlotXYAppend(dbScatterGraph, dbPlot, x, y); } private void AppendToNorthLeakageScatter(double[] x, double[] y) { PlotXYAppend(leakageGraph, northLeakagePlot, x, y); } private void AppendToSouthLeakageScatter(double[] x, double[] y) { PlotXYAppend(leakageGraph, southLeakagePlot, x, y); } private void AppendToNorthECorrLeakageScatter(double[] x, double[] y) { PlotXYAppend(eCorrLeakageScatterGraph, nECorrLeakagePlot, x, y); } private void AppendToSouthECorrLeakageScatter(double[] x, double[] y) { PlotXYAppend(eCorrLeakageScatterGraph, sECorrLeakagePlot, x, y); } private void AppendToEDMScatter(double[] x, double[] y) { PlotXYAppend(edmErrorScatterGraph, edmErrorPlot, x, y); } private void AppendToEDMNormedScatter(double[] x, double[] y) { PlotXYAppend(edmErrorScatterGraph, edmNormedErrorPlot, x, y); } private void AppendSigmaToSIGScatter(double[] x, double[] yPlusSigma, double[] yMinusSigma) { PlotXYAppend(sigScatterGraph, sigSigmaHi, x, yPlusSigma); PlotXYAppend(sigScatterGraph, sigSigmaLo, x, yMinusSigma); } private void AppendSigmaToBScatter(double[] x, double[] yPlusSigma, double[] yMinusSigma) { PlotXYAppend(bScatterGraph, bSigmaHi, x, yPlusSigma); PlotXYAppend(bScatterGraph, bSigmaLo, x, yMinusSigma); } private void AppendSigmaToDBScatter(double[] x, double[] yPlusSigma, double[] yMinusSigma) { PlotXYAppend(dbScatterGraph, dbSigmaHi, x, yPlusSigma); PlotXYAppend(dbScatterGraph, dbSigmaLo, x, yMinusSigma); } private void AppendToNorthLeakageErrorScatter(double[] x, double[] y) { PlotXYAppend(leakageErrorGraph, northLeakageVariancePlot, x, y); } private void AppendToSouthLeakageErrorScatter(double[] x, double[] y) { PlotXYAppend(leakageErrorGraph, southLeakageVariancePlot, x, y); } private void AppendToMagNoiseScatter(double[] x, double[] y) { PlotXYAppend(magNoiseGraph, magNoisePlot, x, y); } private void AppendToRfCurrentScatter(double[] x, double[] y) { PlotXYAppend(rfCurrentGraph, rfCurrentPlot, x, y); } private void AppendToLF1Scatter(double[] x, double[] y) { PlotXYAppend(lf1ScatterGraph, lf1Plot, x, y); } private void AppendToLF1DBDBScatter(double[] x, double[] y) { PlotXYAppend(lfxdbdbScatterGraph, lf1dbdbScatterPlot, x, y); } private void AppendToRF1FDBDBScatter(double[] x, double[] y) { PlotXYAppend(rfxfdbdbScatterGraph, rf1fdbdbScatterPlot, x, y); } private void AppendToRF2FDBDBScatter(double[] x, double[] y) { PlotXYAppend(rfxfdbdbScatterGraph, rf2fdbdbScatterPlot, x, y); } private void AppendToRF1ADBDBScatter(double[] x, double[] y) { PlotXYAppend(rfxadbdbScatterGraph, rf1adbdbScatterPlot, x, y); } private void AppendToRF2ADBDBScatter(double[] x, double[] y) { PlotXYAppend(rfxadbdbScatterGraph, rf2adbdbScatterPlot, x, y); } private void AppendToLF2DBDBScatter(double[] x, double[] y) { PlotXYAppend(lfxdbdbScatterGraph, lf2dbdbScatterPlot, x, y); } private void AppendSigmaToLF1Scatter(double[] x, double[] yPlusSigma, double[] yMinusSigma) { PlotXYAppend(lfxdbdbScatterGraph, lf1SigmaHi, x, yPlusSigma); PlotXYAppend(lfxdbdbScatterGraph, lf1SigmaLo, x, yMinusSigma); } private void AppendSigmaToLF2Scatter(double[] x, double[] yPlusSigma, double[] yMinusSigma) { PlotXYAppend(lfxdbdbScatterGraph, lf2SigmaHi, x, yPlusSigma); PlotXYAppend(lfxdbdbScatterGraph, lf2SigmaLo, x, yMinusSigma); } private void AppendToRF1AScatter(double[] x, double[] y) { PlotXYAppend(rfAmpScatterGraph, rf1aScatterPlot, x, y); } private void AppendToRF2AScatter(double[] x, double[] y) { PlotXYAppend(rfAmpScatterGraph, rf2aScatterPlot, x, y); } private void AppendToRF1FScatter(double[] x, double[] y) { PlotXYAppend(rfFreqScatterGraph, rf1fScatterPlot, x, y); } private void AppendToRF2FScatter(double[] x, double[] y) { PlotXYAppend(rfFreqScatterGraph, rf2fScatterPlot, x, y); } private void AppendTopProbePDScatter(double[] x, double[] y) { PlotXYAppend(photoDiodeScatterGraph, probePDScatterPlot, x, y); } private void AppendTopPumpPDScatter(double[] x, double[] y) { PlotXYAppend(photoDiodeScatterGraph, pumpPDScatterPlot, x, y); } private void ClearPDScatter() { ClearNIGraph(photoDiodeScatterGraph); } private void ClearSIGScatter() { ClearNIGraph(sigScatterGraph); } private void ClearBScatter() { ClearNIGraph(bScatterGraph); } private void ClearDBScatter() { ClearNIGraph(dbScatterGraph); } private void ClearEDMErrScatter() { ClearNIGraph(edmErrorScatterGraph); } private void ClearLeakageScatters() { ClearNIGraph(leakageGraph); ClearNIGraph(leakageErrorGraph); ClearNIGraph(eCorrLeakageScatterGraph); } private void ClearMagNoiseScatterGraph() { ClearNIGraph(magNoiseGraph); } private void ClearRfCurrentScatterGraph() { ClearNIGraph(rfCurrentGraph); } private void ClearLF1Graph() { ClearNIGraph(lf1ScatterGraph); } private void ClearLF1DBDBGraph() { ClearNIGraph(lfxdbdbScatterGraph); } private void ClearRFxFDBDBGraph() { ClearNIGraph(rfxfdbdbScatterGraph); } private void ClearRFxADBDBGraph() { ClearNIGraph(rfxadbdbScatterGraph); } private void ClearRFxAGraph() { ClearNIGraph(rfAmpScatterGraph); } private void ClearRFxFGraph() { ClearNIGraph(rfFreqScatterGraph); } #endregion #region Click Handler private void resetRunningMeans_Click(object sender, EventArgs e) { resetEdmErrRunningMeans(); } #endregion #region Thread safe handlers private void SetTextBox(TextBox textBox, string text) { textBox.Invoke(new SetTextDelegate(SetTextHelper), new object[] { textBox, text }); } private delegate void SetTextDelegate(TextBox textBox, string text); private void SetTextHelper(TextBox textBox, string text) { textBox.Text = text; } private delegate void PlotXYDelegate(double[] x, double[] y); private void PlotXYAppend(Graph graph, ScatterPlot plot, double[] x, double[] y) { graph.Invoke(new PlotXYDelegate(plot.PlotXYAppend), new Object[] { x, y }); } private void PlotXY(Graph graph, ScatterPlot plot, double[] x, double[] y) { graph.Invoke(new PlotXYDelegate(plot.PlotXY), new Object[] { x, y }); } private delegate void ClearDataDelegate(); private void ClearNIGraph(Graph graph) { graph.Invoke(new ClearDataDelegate(graph.ClearData)); } #endregion } }
/** SpriteStudioPlayer Common structures Copyright(C) Web Technology Corp. */ //#define _BUILD_UNIFIED_SHADERS using UnityEngine; [System.Serializable] public class SsPoint : SsInterpolatable { public int X; public int Y; public override string ToString() { return "X: " + X + ", Y: " + Y; } static public SsPoint[] CreateArray(int num) { var a = new SsPoint[num]; for (int i = 0; i < a.Length; ++i) a[i] = new SsPoint(); return a; } public SsPoint() {} public SsPoint(SsPoint r) { X = r.X; Y = r.Y; } public SsPoint Clone() { return new SsPoint(this); } public SsInterpolatable GetInterpolated(SsCurveParams curve, float time, SsInterpolatable start, SsInterpolatable end, int startTime, int endTime) { var v = new SsPoint(); return v.Interpolate(curve, time, start, end, startTime, endTime); } public SsInterpolatable Interpolate(SsCurveParams curve, float time, SsInterpolatable start_, SsInterpolatable end_, int startTime, int endTime) { var start = (SsPoint)start_; var end = (SsPoint)end_; X = SsInterpolation.Interpolate(curve, time, start.X, end.X, startTime, endTime); Y = SsInterpolation.Interpolate(curve, time, start.Y, end.Y, startTime, endTime); return this; } public void Scale(float s) { X = (int)((float)X * s); Y = (int)((float)Y * s); } } [System.Serializable] public class SsRect : SsInterpolatable { public int Left; public int Top; public int Right; public int Bottom; static public SsRect[] CreateArray(int num) { var a = new SsRect[num]; for (int i = 0; i < a.Length; ++i) a[i] = new SsRect(); return a; } static public explicit operator UnityEngine.Rect(SsRect s) { var d = new UnityEngine.Rect(); d.xMin = s.Left; d.xMax = s.Right; d.yMin = s.Top; d.yMax = s.Bottom; return d; } public SsRect() {} public SsRect(SsRect r) { Left = r.Left; Top = r.Top; Right = r.Right; Bottom = r.Bottom; } public SsRect Clone() { return new SsRect(this); } public int Width {get {return Right - Left;}} public int Height {get {return Bottom - Top;}} public Vector2 WH() { return new Vector2(Right - Left, Bottom - Top); } public override string ToString() { return "Left: " + Left + ", Top: " + Top + ", Right: " + Right + ", Bottom: " + Bottom; } public SsInterpolatable GetInterpolated(SsCurveParams curve, float time, SsInterpolatable start, SsInterpolatable end, int startTime, int endTime) { var v = new SsRect(); return v.Interpolate(curve, time, start, end, startTime, endTime); } public SsInterpolatable Interpolate(SsCurveParams curve, float time, SsInterpolatable start_, SsInterpolatable end_, int startTime, int endTime) { var start = (SsRect)start_; var end = (SsRect)end_; Left = SsInterpolation.Interpolate(curve, time, start.Left, end.Left, startTime, endTime); Top = SsInterpolation.Interpolate(curve, time, start.Top, end.Top, startTime, endTime); Right = SsInterpolation.Interpolate(curve, time, start.Right, end.Right, startTime, endTime); Bottom = SsInterpolation.Interpolate(curve, time, start.Bottom, end.Bottom, startTime, endTime); return this; } } [System.Serializable] public class SsColorRef : SsInterpolatable { public byte R; public byte G; public byte B; public byte A; public SsColorRef(SsColorRef r) { R = r.R; G = r.G; B = r.B; A = r.A; } static public SsColorRef[] CreateArray(int num) { var a = new SsColorRef[num]; for (int i = 0; i < a.Length; ++i) a[i] = new SsColorRef(); return a; } public SsColorRef() {} public SsColorRef Clone() { return new SsColorRef(this); } // get normalized color static public explicit operator UnityEngine.Color(SsColorRef s) { var d = new UnityEngine.Color(); d.r = (float)s.R / 255; d.g = (float)s.G / 255; d.b = (float)s.B / 255; d.a = (float)s.A / 255; return d; } public override string ToString() { return "R: " + R + ", G: " + G + ", B: " + B + ", A: " + A; } public SsInterpolatable GetInterpolated(SsCurveParams curve, float time, SsInterpolatable start, SsInterpolatable end, int startTime, int endTime) { var v = new SsColorRef(); return v.Interpolate(curve, time, start, end, startTime, endTime); } public SsInterpolatable Interpolate(SsCurveParams curve, float time, SsInterpolatable start_, SsInterpolatable end_, int startTime, int endTime) { var start = (SsColorRef)start_; var end = (SsColorRef)end_; int r = SsInterpolation.Interpolate(curve, time, (int)start.R, (int)end.R, startTime, endTime); int g = SsInterpolation.Interpolate(curve, time, (int)start.G, (int)end.G, startTime, endTime); int b = SsInterpolation.Interpolate(curve, time, (int)start.B, (int)end.B, startTime, endTime); int a = SsInterpolation.Interpolate(curve, time, (int)start.A, (int)end.A, startTime, endTime); R = (byte)Mathf.Clamp(r, 0, 255); G = (byte)Mathf.Clamp(g, 0, 255); B = (byte)Mathf.Clamp(b, 0, 255); A = (byte)Mathf.Clamp(a, 0, 255); return this; } } [System.Serializable] public class SsImageFile { public string path; public Texture2D texture; public Material[] materials; public int width; public int height; public int bpp; #if _BUILD_UNIFIED_SHADERS public bool useUnifiedShader; #endif public Material GetMaterial(SsShaderType t) { if (materials == null) return null; int index = SsShaderManager.ToSerial(t); if (index >= materials.Length) return null; return materials[index]; } static public SsImageFile invalidInstance; static SsImageFile() { invalidInstance = new SsImageFile(); invalidInstance.path = "INVALID"; invalidInstance.width = 8; invalidInstance.height = 8; invalidInstance.bpp = 8; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using PocoDemo.Web.Areas.HelpPage.ModelDescriptions; using PocoDemo.Web.Areas.HelpPage.Models; namespace PocoDemo.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Concurrent; namespace Whitelog.Core.Binary.Serializer.MemoryBuffer { internal class ThreadStaticBuffer { public class Buffer : IBuffer { private byte[] m_buffer; private int m_length; private readonly RawDataSerializer m_rawDataSerializer = new RawDataSerializer(); public Buffer(int size) { m_buffer = new byte[size]; m_rawDataSerializer.Init(this); } public void SetLength(int length) { m_length = length; } public byte[] IncressSize(int length, int required) { var buffer = new byte[required]; System.Buffer.BlockCopy(m_buffer, 0, buffer, 0, length); m_length = length; m_buffer = buffer; return m_buffer; } public int Length { get { return m_length; } } byte[] IRawData.Buffer { get { return m_buffer; } } public DateTime DateTime { get; set; } public void Dispose() { m_length = 0; m_rawDataSerializer.Reset(); } public ISerializer AttachedSerializer { get { return m_rawDataSerializer; } } } } internal class ThreadStaticBuffer1 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer1(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } internal class ThreadStaticBuffer2 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer2(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } internal class ThreadStaticBuffer3 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer3(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } internal class ThreadStaticBuffer4 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer4(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } internal class ThreadStaticBuffer5 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer5(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } internal class ThreadStaticBuffer6 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer6(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } internal class ThreadStaticBuffer7 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer7(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } internal class ThreadStaticBuffer8 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer8(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } internal class ThreadStaticBuffer9 : IBufferAllocator { [ThreadStatic] private static IBuffer m_buffer; private ConcurrentQueue<IBufferAllocator> m_bufferAllocators; public ThreadStaticBuffer9(ConcurrentQueue<IBufferAllocator> bufferAllocators) { m_bufferAllocators = bufferAllocators; } public int BufferSize { get { return BufferDefaults.Size; } } public IBuffer Allocate() { if (m_buffer == null) { m_buffer = new ThreadStaticBuffer.Buffer(BufferSize); } return m_buffer; } public void Dispose() { m_bufferAllocators.Enqueue(this); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.CloudTrace.v1 { /// <summary>The CloudTrace Service.</summary> public class CloudTraceService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudTraceService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudTraceService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "cloudtrace"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://cloudtrace.googleapis.com/"; #else "https://cloudtrace.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://cloudtrace.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud Trace API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>Write Trace data for a project or application</summary> public static string TraceAppend = "https://www.googleapis.com/auth/trace.append"; /// <summary>Read Trace data for a project or application</summary> public static string TraceReadonly = "https://www.googleapis.com/auth/trace.readonly"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud Trace API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>Write Trace data for a project or application</summary> public const string TraceAppend = "https://www.googleapis.com/auth/trace.append"; /// <summary>Read Trace data for a project or application</summary> public const string TraceReadonly = "https://www.googleapis.com/auth/trace.readonly"; } /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get; } } /// <summary>A base abstract class for CloudTrace requests.</summary> public abstract class CloudTraceBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new CloudTraceBaseServiceRequest instance.</summary> protected CloudTraceBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudTrace parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; Traces = new TracesResource(service); } /// <summary>Gets the Traces resource.</summary> public virtual TracesResource Traces { get; } /// <summary>The "traces" collection of methods.</summary> public class TracesResource { private const string Resource = "traces"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TracesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Gets a single trace by its ID.</summary> /// <param name="projectId">Required. ID of the Cloud project where the trace data is stored.</param> /// <param name="traceId">Required. ID of the trace to return.</param> public virtual GetRequest Get(string projectId, string traceId) { return new GetRequest(service, projectId, traceId); } /// <summary>Gets a single trace by its ID.</summary> public class GetRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v1.Data.Trace> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string projectId, string traceId) : base(service) { ProjectId = projectId; TraceId = traceId; InitParameters(); } /// <summary>Required. ID of the Cloud project where the trace data is stored.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Required. ID of the trace to return.</summary> [Google.Apis.Util.RequestParameterAttribute("traceId", Google.Apis.Util.RequestParameterType.Path)] public virtual string TraceId { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/projects/{projectId}/traces/{traceId}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add("traceId", new Google.Apis.Discovery.Parameter { Name = "traceId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Returns a list of traces that match the specified filter conditions.</summary> /// <param name="projectId">Required. ID of the Cloud project where the trace data is stored.</param> public virtual ListRequest List(string projectId) { return new ListRequest(service, projectId); } /// <summary>Returns a list of traces that match the specified filter conditions.</summary> public class ListRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v1.Data.ListTracesResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string projectId) : base(service) { ProjectId = projectId; InitParameters(); } /// <summary>Required. ID of the Cloud project where the trace data is stored.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary> /// End of the time interval (inclusive) during which the trace data was collected from the application. /// </summary> [Google.Apis.Util.RequestParameterAttribute("endTime", Google.Apis.Util.RequestParameterType.Query)] public virtual object EndTime { get; set; } /// <summary> /// Optional. A filter against labels for the request. By default, searches use prefix matching. To /// specify exact match, prepend a plus symbol (`+`) to the search term. Multiple terms are ANDed. /// Syntax: * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with /// `NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is exactly /// `NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with `NAME_PREFIX`. * /// `+span:NAME`: Return traces where any span's name is exactly `NAME`. * `latency:DURATION`: Return /// traces whose overall latency is greater or equal to than `DURATION`. Accepted units are nanoseconds /// (`ns`), milliseconds (`ms`), and seconds (`s`). Default is `ms`. For example, `latency:24ms` returns /// traces whose overall latency is greater than or equal to 24 milliseconds. * `label:LABEL_KEY`: /// Return all traces containing the specified label key (exact match, case-sensitive) regardless of the /// key:value pair's value (including empty values). * `LABEL_KEY:VALUE_PREFIX`: Return all traces /// containing the specified label key (exact match, case-sensitive) whose value starts with /// `VALUE_PREFIX`. Both a key and a value must be specified. * `+LABEL_KEY:VALUE`: Return all traces /// containing a key:value pair exactly matching the specified text. Both a key and a value must be /// specified. * `method:VALUE`: Equivalent to `/http/method:VALUE`. * `url:VALUE`: Equivalent to /// `/http/url:VALUE`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary> /// Optional. Field used to sort the returned traces. Can be one of the following: * `trace_id` * `name` /// (`name` field of root span in the trace) * `duration` (difference between `end_time` and /// `start_time` fields of the root span) * `start` (`start_time` field of the root span) Descending /// order can be specified by appending `desc` to the sort field (for example, `name desc`). Only one /// sort field is permitted. /// </summary> [Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)] public virtual string OrderBy { get; set; } /// <summary> /// Optional. Maximum number of traces to return. If not specified or &amp;lt;= 0, the implementation /// selects a reasonable value. The implementation may return fewer traces than the requested page size. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// Token identifying the page of results to return. If provided, use the value of the `next_page_token` /// field from a previous request. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary> /// Start of the time interval (inclusive) during which the trace data was collected from the /// application. /// </summary> [Google.Apis.Util.RequestParameterAttribute("startTime", Google.Apis.Util.RequestParameterType.Query)] public virtual object StartTime { get; set; } /// <summary>Optional. Type of data returned for traces in the list. Default is `MINIMAL`.</summary> [Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<ViewEnum> View { get; set; } /// <summary>Optional. Type of data returned for traces in the list. Default is `MINIMAL`.</summary> public enum ViewEnum { /// <summary>Default is `MINIMAL` if unspecified.</summary> [Google.Apis.Util.StringValueAttribute("VIEW_TYPE_UNSPECIFIED")] VIEWTYPEUNSPECIFIED = 0, /// <summary> /// Minimal view of the trace record that contains only the project and trace IDs. /// </summary> [Google.Apis.Util.StringValueAttribute("MINIMAL")] MINIMAL = 1, /// <summary> /// Root span view of the trace record that returns the root spans along with the minimal trace /// data. /// </summary> [Google.Apis.Util.StringValueAttribute("ROOTSPAN")] ROOTSPAN = 2, /// <summary> /// Complete view of the trace record that contains the actual trace data. This is equivalent to /// calling the REST `get` or RPC `GetTrace` method using the ID of each listed trace. /// </summary> [Google.Apis.Util.StringValueAttribute("COMPLETE")] COMPLETE = 3, } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/projects/{projectId}/traces"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add("endTime", new Google.Apis.Discovery.Parameter { Name = "endTime", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter { Name = "orderBy", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("startTime", new Google.Apis.Discovery.Parameter { Name = "startTime", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("view", new Google.Apis.Discovery.Parameter { Name = "view", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary> /// Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send matches that /// of an existing trace, any fields in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the ID does not match, a new trace /// is created. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">Required. ID of the Cloud project where the trace data is stored.</param> public virtual PatchTracesRequest PatchTraces(Google.Apis.CloudTrace.v1.Data.Traces body, string projectId) { return new PatchTracesRequest(service, body, projectId); } /// <summary> /// Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send matches that /// of an existing trace, any fields in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the ID does not match, a new trace /// is created. /// </summary> public class PatchTracesRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v1.Data.Empty> { /// <summary>Constructs a new PatchTraces request.</summary> public PatchTracesRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudTrace.v1.Data.Traces body, string projectId) : base(service) { ProjectId = projectId; Body = body; InitParameters(); } /// <summary>Required. ID of the Cloud project where the trace data is stored.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudTrace.v1.Data.Traces Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "patchTraces"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "PATCH"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/projects/{projectId}/traces"; /// <summary>Initializes PatchTraces parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.CloudTrace.v1.Data { /// <summary> /// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical /// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc /// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON /// object `{}`. /// </summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response message for the `ListTraces` method.</summary> public class ListTracesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// If defined, indicates that there are more traces that match the request and that this value should be passed /// to the next request to continue retrieving additional traces. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>List of trace records as specified by the view parameter.</summary> [Newtonsoft.Json.JsonPropertyAttribute("traces")] public virtual System.Collections.Generic.IList<Trace> Traces { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A trace describes how long it takes for an application to perform an operation. It consists of a set of spans, /// each of which represent a single timed event within the operation. /// </summary> public class Trace : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Project ID of the Cloud project where the trace data is stored.</summary> [Newtonsoft.Json.JsonPropertyAttribute("projectId")] public virtual string ProjectId { get; set; } /// <summary>Collection of spans in the trace.</summary> [Newtonsoft.Json.JsonPropertyAttribute("spans")] public virtual System.Collections.Generic.IList<TraceSpan> Spans { get; set; } /// <summary> /// Globally unique identifier for the trace. This identifier is a 128-bit numeric value formatted as a 32-byte /// hex string. For example, `382d4f4c6b7bb2f4a972559d9085001d`. The numeric value should not be zero. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("traceId")] public virtual string TraceId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A span represents a single timed event within a trace. Spans can be nested and form a trace tree. Often, a trace /// contains a root span that describes the end-to-end latency of an operation and, optionally, one or more subspans /// for its suboperations. Spans do not need to be contiguous. There may be gaps between spans in a trace. /// </summary> public class TraceSpan : Google.Apis.Requests.IDirectResponseSchema { /// <summary>End time of the span in nanoseconds from the UNIX epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual object EndTime { get; set; } /// <summary> /// Distinguishes between spans generated in a particular context. For example, two spans with the same name may /// be distinguished using `RPC_CLIENT` and `RPC_SERVER` to identify queueing latency associated with the span. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary> /// Collection of labels associated with the span. Label keys must be less than 128 bytes. Label values must be /// less than 16 kilobytes (10MB for `/stacktrace` values). Some predefined label keys exist, or you may create /// your own. When creating your own, we recommend the following formats: * `/category/product/key` for agents /// of well-known products (e.g. `/db/mongodb/read_size`). * `short_host/path/key` for domain-specific keys /// (e.g. `foo.com/myproduct/bar`) Predefined labels include: * `/agent` * `/component` * `/error/message` * /// `/error/name` * `/http/client_city` * `/http/client_country` * `/http/client_protocol` * /// `/http/client_region` * `/http/host` * `/http/method` * `/http/path` * `/http/redirected_url` * /// `/http/request/size` * `/http/response/size` * `/http/route` * `/http/status_code` * `/http/url` * /// `/http/user_agent` * `/pid` * `/stacktrace` * `/tid` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("labels")] public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; } /// <summary> /// Name of the span. Must be less than 128 bytes. The span name is sanitized and displayed in the Trace tool in /// the Google Cloud Platform Console. The name may be a method name or some other per-call site name. For the /// same executable and the same call point, a best practice is to use a consistent name, which makes it easier /// to correlate cross-trace spans. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Optional. ID of the parent span, if any.</summary> [Newtonsoft.Json.JsonPropertyAttribute("parentSpanId")] public virtual System.Nullable<ulong> ParentSpanId { get; set; } /// <summary> /// Identifier for the span. Must be a 64-bit integer other than 0 and unique within a trace. For example, /// `2205310701640571284`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("spanId")] public virtual System.Nullable<ulong> SpanId { get; set; } /// <summary>Start time of the span in nanoseconds from the UNIX epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual object StartTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>List of new or updated traces.</summary> public class Traces : Google.Apis.Requests.IDirectResponseSchema { /// <summary>List of traces.</summary> [Newtonsoft.Json.JsonPropertyAttribute("traces")] public virtual System.Collections.Generic.IList<Trace> TracesValue { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// The MIT License (MIT) // // Copyright (c) 2015 FPT Software // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /* * Copyright 2012-2014 Jeremy Feinstein * Copyright 2013-2014 Tomasz Cielecki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Android.Content; using Android.Graphics; using Android.OS; using Android.Support.V4.View; using Android.Util; using Android.Views; using Android.Views.Animations; using Android.Widget; namespace SlidingMenuSharp { public delegate void PageSelectedEventHandler(object sender, PageSelectedEventArgs e); public delegate void PageScrolledEventHandler(object sender, PageScrolledEventArgs e); public delegate void PageScrollStateChangedEventHandler(object sender, PageScrollStateChangedEventArgs e); public class CustomViewAbove : ViewGroup { private new const string Tag = "CustomViewAbove"; private const bool UseCache = false; private const int MaxSettleDuration = 600; // ms private const int MinDistanceForFling = 25; // dips private readonly IInterpolator _interpolator = new CVAInterpolator(); private class CVAInterpolator : Java.Lang.Object, IInterpolator { public float GetInterpolation(float t) { t -= 1.0f; return t * t * t * t * t + 1.0f; } } private View _content; private int _curItem; private Scroller _scroller; private bool _scrollingCacheEnabled; private bool _scrolling; private bool _isBeingDragged; private bool _isUnableToDrag; private int _touchSlop; private float _initialMotionX; /** * Position of the last motion event. */ private float _lastMotionX; private float _lastMotionY; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ protected int ActivePointerId = InvalidPointer; /** * Sentinel value for no current active pointer. * Used by {@link #ActivePointerId}. */ private const int InvalidPointer = -1; /** * Determines speed during touch scrolling */ protected VelocityTracker VelocityTracker; private int _minimumVelocity; protected int MaximumVelocity; private int _flingDistance; private CustomViewBehind _viewBehind; // private int mMode; private bool _enabled = true; private readonly IList<View> _ignoredViews = new List<View>(); private bool _quickReturn; private float _scrollX; public PageSelectedEventHandler PageSelected; public PageScrolledEventHandler PageScrolled; public PageScrollStateChangedEventHandler PageScrollState; public EventHandler Closed; public EventHandler Opened; public CustomViewAbove(Context context) : this(context, null) { } public CustomViewAbove(Context context, IAttributeSet attrs) : base(context, attrs) { InitCustomViewAbove(); } void InitCustomViewAbove() { TouchMode = TouchMode.Margin; SetWillNotDraw(false); DescendantFocusability = DescendantFocusability.AfterDescendants; Focusable = true; _scroller = new Scroller(Context, _interpolator); var configuration = ViewConfiguration.Get(Context); _touchSlop = ViewConfigurationCompat.GetScaledPagingTouchSlop(configuration); _minimumVelocity = configuration.ScaledMinimumFlingVelocity; MaximumVelocity = configuration.ScaledMaximumFlingVelocity; var density = Context.Resources.DisplayMetrics.Density; _flingDistance = (int) (MinDistanceForFling*density); PageSelected += (sender, args) => { if (_viewBehind == null) return; switch (args.Position) { case 0: case 2: _viewBehind.ChildrenEnabled = true; break; case 1: _viewBehind.ChildrenEnabled = false; break; } }; } public void SetCurrentItem(int item) { SetCurrentItemInternal(item, true, false); } public void SetCurrentItem(int item, bool smoothScroll) { SetCurrentItemInternal(item, smoothScroll, false); } public int GetCurrentItem() { return _curItem; } void SetCurrentItemInternal(int item, bool smoothScroll, bool always, int velocity = 0) { if (!always && _curItem == item) { ScrollingCacheEnabled = false; return; } item = _viewBehind.GetMenuPage(item); var dispatchSelected = _curItem != item; _curItem = item; var destX = GetDestScrollX(_curItem); if (dispatchSelected && PageSelected != null) { PageSelected(this, new PageSelectedEventArgs { Position = item }); } if (smoothScroll) { SmoothScrollTo(destX, 0, velocity); } else { CompleteScroll(); ScrollTo(destX, 0); } } public void AddIgnoredView(View v) { if (!_ignoredViews.Contains(v)) _ignoredViews.Add(v); } public void RemoveIgnoredView(View v) { _ignoredViews.Remove(v); } public void ClearIgnoredViews() { _ignoredViews.Clear(); } static float DistanceInfluenceForSnapDuration(float f) { f -= 0.5f; f *= 0.3f*(float)Math.PI/2.0f; return FloatMath.Sin(f); } public int GetDestScrollX(int page) { switch (page) { case 0: case 2: return _viewBehind.GetMenuLeft(_content, page); case 1: return _content.Left; } return 0; } private int LeftBound { get { return _viewBehind.GetAbsLeftBound(_content); } } private int RightBound { get { return _viewBehind.GetAbsRightBound(_content); } } public int ContentLeft { get { return _content.Left + _content.PaddingLeft; } } public bool IsMenuOpen { get { return _curItem == 0 || _curItem == 2; } } private bool IsInIgnoredView(MotionEvent ev) { var rect = new Rect(); foreach (var v in _ignoredViews) { v.GetHitRect(rect); if (rect.Contains((int) ev.GetX(), (int) ev.GetY())) return true; } return false; } public int BehindWidth { get { return _viewBehind == null ? 0 : _viewBehind.BehindWidth; } } public int GetChildWidth(int i) { switch (i) { case 0: return BehindWidth; case 1: return _content.Width; default: return 0; } } public bool IsSlidingEnabled { get { return _enabled; } set { _enabled = value; } } void SmoothScrollTo(int x, int y, int velocity = 0) { if (ChildCount == 0) { ScrollingCacheEnabled = false; return; } var sx = ScrollX; var sy = ScrollY; var dx = x - sx; var dy = y - sy; if (dx == 0 && dy == 0) { CompleteScroll(); if (IsMenuOpen) { if (null != Opened) Opened(this, EventArgs.Empty); } else { if (null != Closed) Closed(this, EventArgs.Empty); } return; } ScrollingCacheEnabled = true; _scrolling = true; var width = BehindWidth; var halfWidth = width / 2; var distanceRatio = Math.Min(1f, 1.0f * Math.Abs(dx) / width); var distance = halfWidth + halfWidth * DistanceInfluenceForSnapDuration(distanceRatio); int duration; velocity = Math.Abs(velocity); if (velocity > 0) duration = (int)(4 * Math.Round(1000 * Math.Abs(distance / velocity))); else { var pageDelta = (float) Math.Abs(dx) / width; duration = (int) ((pageDelta + 1) * 100); } duration = Math.Min(duration, MaxSettleDuration); _scroller.StartScroll(sx, sy, dx, dy, duration); Invalidate(); } public View Content { get { return _content; } set { if (_content != null) RemoveView(_content); _content = value; AddView(_content); } } public CustomViewBehind CustomViewBehind { set { _viewBehind = value; } } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { var width = GetDefaultSize(0, widthMeasureSpec); var height = GetDefaultSize(0, heightMeasureSpec); SetMeasuredDimension(width, height); var contentWidth = GetChildMeasureSpec(widthMeasureSpec, 0, width); var contentHeight = GetChildMeasureSpec(heightMeasureSpec, 0, height); _content.Measure(contentWidth, contentHeight); } protected override void OnSizeChanged(int w, int h, int oldw, int oldh) { base.OnSizeChanged(w, h, oldw, oldh); if (w == oldw) return; CompleteScroll(); ScrollTo(GetDestScrollX(_curItem), ScrollY); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { var width = r - l; var height = b - t; _content.Layout(0, 0, width, height); } public int AboveOffset { set { _content.SetPadding(value, _content.PaddingTop, _content.PaddingRight, _content.PaddingBottom); } } public override void ComputeScroll() { if (!_scroller.IsFinished) { if (_scroller.ComputeScrollOffset()) { var oldX = ScrollX; var oldY = ScrollY; var x = _scroller.CurrX; var y = _scroller.CurrY; if (oldX != x ||oldY != y) { ScrollTo(x, y); OnPageScrolled(x); } Invalidate(); return; } } CompleteScroll(); } protected void OnPageScrolled(int xpos) { var widthWithMargin = Width; var position = xpos / widthWithMargin; var offsetPixels = xpos % widthWithMargin; var offset = (float)offsetPixels / widthWithMargin; if (null != PageScrolled) PageScrolled(this, new PageScrolledEventArgs { Position = position, PositionOffset = offset, PositionOffsetPixels = offsetPixels }); } private void CompleteScroll() { var needPopulate = _scrolling; if (needPopulate) { ScrollingCacheEnabled = false; _scroller.AbortAnimation(); var oldX = ScrollX; var oldY = ScrollY; var x = _scroller.CurrX; var y = _scroller.CurrY; if (oldX != x || oldY != y) ScrollTo(x, y); if (IsMenuOpen) { if (null != Opened) Opened(this, EventArgs.Empty); } else { if (null != Closed) Closed(this, EventArgs.Empty); } } _scrolling = false; } public TouchMode TouchMode { get; set; } private bool ThisTouchAllowed(MotionEvent ev) { var x = (int) (ev.GetX() + _scrollX); if (IsMenuOpen) { return _viewBehind.MenuOpenTouchAllowed(_content, _curItem, x); } switch (TouchMode) { case TouchMode.Fullscreen: return !IsInIgnoredView(ev); case TouchMode.None: return false; case TouchMode.Margin: return _viewBehind.MarginTouchAllowed(_content, x); } return false; } private bool ThisSlideAllowed(float dx) { var allowed = IsMenuOpen ? _viewBehind.MenuOpenSlideAllowed(dx) : _viewBehind.MenuClosedSlideAllowed(dx); #if DEBUG Log.Verbose(Tag, "this slide allowed" + allowed + " dx: " + dx); #endif return allowed; } private int GetPointerIndex(MotionEvent ev, int id) { var activePointerIndex = MotionEventCompat.FindPointerIndex(ev, id); if (activePointerIndex == -1) ActivePointerId = InvalidPointer; return activePointerIndex; } public override bool OnInterceptTouchEvent(MotionEvent ev) { if (!_enabled) return false; var action = (int) ev.Action & MotionEventCompat.ActionMask; #if DEBUG if (action == (int) MotionEventActions.Down) Log.Verbose(Tag, "Recieved ACTION_DOWN"); #endif if (action == (int) MotionEventActions.Cancel || action == (int) MotionEventActions.Up || (action != (int) MotionEventActions.Down && _isUnableToDrag)) { EndDrag(); return false; } switch (action) { case (int) MotionEventActions.Move: DetermineDrag(ev); break; case (int) MotionEventActions.Down: var index = MotionEventCompat.GetActionIndex(ev); ActivePointerId = MotionEventCompat.GetPointerId(ev, index); if (ActivePointerId == InvalidPointer) break; _lastMotionX = _initialMotionX = MotionEventCompat.GetX(ev, index); _lastMotionY = MotionEventCompat.GetY(ev, index); if (ThisTouchAllowed(ev)) { _isBeingDragged = false; _isUnableToDrag = false; if (IsMenuOpen && _viewBehind.MenuTouchInQuickReturn(_content, _curItem, ev.GetX() + _scrollX)) _quickReturn = true; } else _isUnableToDrag = true; break; case (int) MotionEventActions.PointerUp: OnSecondaryPointerUp(ev); break; } if (!_isBeingDragged) { if (VelocityTracker == null) VelocityTracker = VelocityTracker.Obtain(); VelocityTracker.AddMovement(ev); } return _isBeingDragged || _quickReturn; } public override bool OnTouchEvent(MotionEvent ev) { if (!_enabled) return false; if (!_isBeingDragged && !ThisTouchAllowed(ev)) return false; if (VelocityTracker == null) VelocityTracker = VelocityTracker.Obtain(); VelocityTracker.AddMovement(ev); var action = (int)ev.Action & MotionEventCompat.ActionMask; switch (action) { case (int) MotionEventActions.Down: CompleteScroll(); var index = MotionEventCompat.GetActionIndex(ev); ActivePointerId = MotionEventCompat.GetPointerId(ev, index); _lastMotionX = _initialMotionX = ev.GetX(); break; case (int) MotionEventActions.Move: if (!_isBeingDragged) { DetermineDrag(ev); if (_isUnableToDrag) return false; } if (_isBeingDragged) { var activePointerIndex = GetPointerIndex(ev, ActivePointerId); if (ActivePointerId == InvalidPointer) break; var x = MotionEventCompat.GetX(ev, activePointerIndex); var deltaX = _lastMotionX - x; _lastMotionX = x; var oldScrollX = ScrollX; var scrollX = oldScrollX + deltaX; var leftBound = LeftBound; var rightBound = RightBound; if (scrollX < leftBound) scrollX = leftBound; else if (scrollX > rightBound) scrollX = rightBound; _lastMotionX += scrollX - (int) scrollX; ScrollTo((int) scrollX, ScrollY); OnPageScrolled((int)scrollX); } break; case (int) MotionEventActions.Up: if (_isBeingDragged) { var velocityTracker = VelocityTracker; velocityTracker.ComputeCurrentVelocity(1000, MaximumVelocity); var initialVelocity = (int) VelocityTrackerCompat.GetXVelocity(velocityTracker, ActivePointerId); var scrollX = ScrollX; var pageOffset = (float) (scrollX - GetDestScrollX(_curItem)) / BehindWidth; var activePointerIndex = GetPointerIndex(ev, ActivePointerId); if (ActivePointerId != InvalidPointer) { var x = MotionEventCompat.GetX(ev, activePointerIndex); var totalDelta = (int) (x - _initialMotionX); var nextPage = DetermineTargetPage(pageOffset, initialVelocity, totalDelta); SetCurrentItemInternal(nextPage, true, true, initialVelocity); } else SetCurrentItemInternal(_curItem, true, true, initialVelocity); ActivePointerId = InvalidPointer; EndDrag(); } else if (_quickReturn && _viewBehind.MenuTouchInQuickReturn(_content, _curItem, ev.GetX() + _scrollX)) { SetCurrentItem(1); EndDrag(); } break; case (int) MotionEventActions.Cancel: if (_isBeingDragged) { SetCurrentItemInternal(_curItem, true, true); ActivePointerId = InvalidPointer; EndDrag(); } break; case MotionEventCompat.ActionPointerDown: var indexx = MotionEventCompat.GetActionIndex(ev); _lastMotionX = MotionEventCompat.GetX(ev, indexx); ActivePointerId = MotionEventCompat.GetPointerId(ev, indexx); break; case MotionEventCompat.ActionPointerUp: OnSecondaryPointerUp(ev); var pointerIndex = GetPointerIndex(ev, ActivePointerId); if (ActivePointerId == InvalidPointer) break; _lastMotionX = MotionEventCompat.GetX(ev, pointerIndex); break; } return true; } private void DetermineDrag(MotionEvent ev) { var activePointerId = ActivePointerId; var pointerIndex = GetPointerIndex(ev, activePointerId); if (activePointerId == InvalidPointer || pointerIndex == InvalidPointer) return; var x = MotionEventCompat.GetX(ev, pointerIndex); var dx = x - _lastMotionX; var xDiff = Math.Abs(dx); var y = MotionEventCompat.GetY(ev, pointerIndex); var dy = y - _lastMotionY; var yDiff = Math.Abs(dy); if (xDiff > (IsMenuOpen ? _touchSlop / 2 : _touchSlop) && xDiff > yDiff && ThisSlideAllowed(dx)) { StartDrag(); _lastMotionX = x; _lastMotionY = y; _scrollingCacheEnabled = true; } else if (xDiff > _touchSlop) _isUnableToDrag = true; } public override void ScrollTo(int x, int y) { base.ScrollTo(x, y); _scrollX = x; _viewBehind.ScrollBehindTo(_content, x, y); #if __ANDROID_11__ ((SlidingMenu) Parent).ManageLayers(PercentOpen); #endif } private int DetermineTargetPage(float pageOffset, int velocity, int deltaX) { var targetPage = _curItem; if (Math.Abs(deltaX) > _flingDistance && Math.Abs(velocity) > _minimumVelocity) { if (velocity > 0 && deltaX > 0) targetPage -= 1; else if (velocity < 0 && deltaX < 0) targetPage += 1; } else targetPage = (int) Math.Round(_curItem + pageOffset); return targetPage; } public float PercentOpen { get { return Math.Abs(_scrollX - _content.Left) / BehindWidth; } } protected override void DispatchDraw(Canvas canvas) { base.DispatchDraw(canvas); _viewBehind.DrawShadow(_content, canvas); _viewBehind.DrawFade(_content, canvas, PercentOpen); _viewBehind.DrawSelector(_content, canvas, PercentOpen); } private void OnSecondaryPointerUp(MotionEvent ev) { #if DEBUG Log.Verbose(Tag, "OnSecondaryPointerUp called"); #endif var pointerIndex = MotionEventCompat.GetActionIndex(ev); var pointerId = MotionEventCompat.GetPointerId(ev, pointerIndex); if (pointerId == ActivePointerId) { var newPointerIndex = pointerIndex == 0 ? 1 : 0; _lastMotionX = MotionEventCompat.GetX(ev, newPointerIndex); ActivePointerId = MotionEventCompat.GetPointerId(ev, newPointerIndex); if (VelocityTracker != null) VelocityTracker.Clear(); } } private void StartDrag() { _isBeingDragged = true; _quickReturn = false; } private void EndDrag() { _quickReturn = false; _isBeingDragged = false; _isUnableToDrag = false; ActivePointerId = InvalidPointer; if (VelocityTracker == null) return; VelocityTracker.Recycle(); VelocityTracker = null; } private bool ScrollingCacheEnabled { set { if (_scrollingCacheEnabled != value) { _scrollingCacheEnabled = value; if (UseCache) { var size = ChildCount; for (var i = 0; i < size; ++i) { var child = GetChildAt(i); if (child.Visibility != ViewStates.Gone) child.DrawingCacheEnabled = value; } } } } } protected bool CanScroll(View v, bool checkV, int dx, int x, int y) { var viewGroup = v as ViewGroup; if (viewGroup != null) { var scrollX = v.ScrollX; var scrollY = v.ScrollY; var count = viewGroup.ChildCount; for (var i = count - 1; i >= 0; i--) { var child = viewGroup.GetChildAt(i); if (x + scrollX >= child.Left && x + scrollX < child.Right && y + scrollY >= child.Top && y + scrollY < child.Bottom && CanScroll(child, true, dx, x + scrollX - child.Left, y + scrollY - child.Top)) return true; } } return checkV && ViewCompat.CanScrollHorizontally(v, -dx); } public override bool DispatchKeyEvent(KeyEvent e) { return base.DispatchKeyEvent(e) || ExecuteKeyEvent(e); } public bool ExecuteKeyEvent(KeyEvent ev) { var handled = false; if (ev.Action == KeyEventActions.Down) { switch (ev.KeyCode) { case Keycode.DpadLeft: handled = ArrowScroll(FocusSearchDirection.Left); break; case Keycode.DpadRight: handled = ArrowScroll(FocusSearchDirection.Right); break; case Keycode.Tab: if ((int)Build.VERSION.SdkInt >= 11) { if (KeyEventCompat.HasNoModifiers(ev)) handled = ArrowScroll(FocusSearchDirection.Forward); #if __ANDROID_11__ else if (ev.IsMetaPressed) handled = ArrowScroll(FocusSearchDirection.Backward); #endif } break; } } return handled; } public bool ArrowScroll(FocusSearchDirection direction) { var currentFocused = FindFocus(); var handled = false; var nextFocused = FocusFinder.Instance.FindNextFocus(this, currentFocused == this ? null : currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == FocusSearchDirection.Left) handled = nextFocused.RequestFocus(); else if (direction == FocusSearchDirection.Right) { if (currentFocused != null && nextFocused.Left <= currentFocused.Left) handled = PageRight(); else handled = nextFocused.RequestFocus(); } } else if (direction == FocusSearchDirection.Left || direction == FocusSearchDirection.Backward) handled = PageLeft(); else if (direction == FocusSearchDirection.Right || direction == FocusSearchDirection.Forward) handled = PageRight(); if (handled) PlaySoundEffect(SoundEffectConstants.GetContantForFocusDirection(direction)); return handled; } bool PageLeft() { if (_curItem > 0) { SetCurrentItem(_curItem-1, true); return true; } return false; } bool PageRight() { if (_curItem < 1) { SetCurrentItem(_curItem+1, true); return true; } return false; } } }
using System; using System.Diagnostics; using HANDLE = System.IntPtr; using System.Text; namespace Core { public partial class DataEx { #if !APICORE const int APICORE = 1; // Disable the API redefinition in sqlite3ext.h #endif #region OMIT_LOAD_EXTENSION #if !OMIT_LOAD_EXTENSION #if !ENABLE_COLUMN_METADATA #endif #if OMIT_AUTHORIZATION #endif #if OMIT_UTF16 static string sqlite3_errmsg16( sqlite3 db ) { return ""; } static void sqlite3_result_text16( sqlite3_context pCtx, string z, int n, dxDel xDel ) { } #endif #if OMIT_COMPLETE #endif #if OMIT_DECLTYPE #endif #if OMIT_PROGRESS_CALLBACK static void sqlite3_progress_handler(sqlite3 db, int nOps, dxProgress xProgress, object pArg){} #endif #if OMIT_VIRTUALTABLE #endif #if OMIT_SHARED_CACHE #endif #if OMIT_TRACE #endif #if OMIT_GET_TABLE public static int sqlite3_get_table(sqlite3 db, string zSql, ref string[] pazResult, ref int pnRow, ref int pnColumn, ref string pzErrmsg) { return 0; } #endif #if OMIT_INCRBLOB #endif public class core_api_routines { public Context context_db_handle; } static core_api_routines g_apis = new core_api_routines(); public static RC LoadExtension_(Context ctx, string fileName, string procName, ref string errMsgOut) { if (errMsgOut != null) errMsgOut = null; // Ticket #1863. To avoid a creating security problems for older applications that relink against newer versions of SQLite, the // ability to run load_extension is turned off by default. One must call core_enable_load_extension() to turn on extension // loading. Otherwise you get the following error. if ((ctx.Flags & Context.FLAG.LoadExtension) == 0) { errMsgOut = C._mprintf("not authorized"); return RC.ERROR; } if (procName == null) procName = "sqlite3_extension_init"; VSystem vfs = ctx.Vfs; HANDLE handle = (HANDLE)vfs.DlOpen(fileName); StringBuilder errmsg = new StringBuilder(100); int msgLength = 300; if (handle == IntPtr.Zero) { errMsgOut = string.Empty; C.__snprintf(errmsg, msgLength, "unable to open shared library [%s]", fileName); vfs.DlError(msgLength - 1, errmsg.ToString()); return RC.ERROR; } Func<Context, StringBuilder, core_api_routines, RC> init = (Func<Context, StringBuilder, core_api_routines, RC>)vfs.DlSym(handle, procName); Debugger.Break(); if (init == null) { msgLength += procName.Length; C.__snprintf(errmsg, msgLength, "no entry point [%s] in shared library [%s]", procName, fileName); vfs.DlError(msgLength - 1, errMsgOut = errmsg.ToString()); vfs.DlClose(handle); return RC.ERROR; } else if (init(ctx, errmsg, g_apis) != 0) { errMsgOut = C._mprintf("error during initialization: %s", errmsg.ToString()); C._tagfree(ctx, ref errmsg); vfs.DlClose(handle); return RC.ERROR; } // Append the new shared library handle to the db.aExtension array. object[] handles = new object[ctx.Extensions.length + 1]; if (handles == null) return RC.NOMEM; if (ctx.Extensions.length > 0) Array.Copy(ctx.Extensions.data, handles, ctx.Extensions.length); C._tagfree(ctx, ref ctx.Extensions.data); ctx.Extensions.data = handles; ctx.Extensions[ctx.Extensions.length++] = handle; return RC.OK; } public static RC LoadExtension(Context ctx, string fileName, string procName, ref string errMsg) { MutexEx.Enter(ctx.Mutex); RC rc = LoadExtension_(ctx, fileName, procName, ref errMsg); rc = ApiExit(ctx, rc); MutexEx.Leave(ctx.Mutex); return rc; } public static void CloseExtensions(Context ctx) { Debug.Assert(MutexEx.Held(ctx.Mutex)); for (int i = 0; i < ctx.Extensions.length; i++) ctx.Vfs.DlClose((HANDLE)ctx.Extensions[i]); C._tagfree(ctx, ref ctx.Extensions.data); } public static RC EnableLoadExtension(Context ctx, bool onoff) { MutexEx.Enter(ctx.Mutex); if (onoff) ctx.Flags |= Context.FLAG.LoadExtension; else ctx.Flags &= ~Context.FLAG.LoadExtension; MutexEx.Leave(ctx.Mutex); return RC.OK; } #else const core_api_routines g_apis = null; #endif #endregion public class AutoExtList_t { public int ExtsLength = 0; // Number of entries in aExt[] public Func<Context, string, core_api_routines, RC>[] Exts = null; // Pointers to the extension init functions public AutoExtList_t(int extsLength, Func<Context, string, core_api_routines, RC>[] exts) { ExtsLength = extsLength; Exts = exts; } } static AutoExtList_t g_autoext = new AutoExtList_t(0, null); static RC AutoExtension(Func<Context, string, core_api_routines, RC> init) { RC rc = RC.OK; #if !OMIT_AUTOINIT rc = Initialize(); if (rc != 0) return rc; else #endif { #if THREADSAFE MutexEx mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER); #endif MutexEx.Enter(mutex); int i; for (i = 0; i < g_autoext.ExtsLength; i++) if (g_autoext.Exts[i] == init) break; if (i == g_autoext.ExtsLength) { Array.Resize(ref g_autoext.Exts, g_autoext.ExtsLength + 1); g_autoext.Exts[g_autoext.ExtsLength] = init; g_autoext.ExtsLength++; } MutexEx.Leave(mutex); Debug.Assert((rc & (RC)0xff) == rc); return rc; } } public static void ResetAutoExtension() { #if !OMIT_AUTOINIT if (Initialize() == RC.OK) #endif { #if THREADSAFE MutexEx mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER); #endif MutexEx.Enter(mutex); g_autoext.Exts = null; g_autoext.ExtsLength = 0; MutexEx.Leave(mutex); } } public static void AutoLoadExtensions(Context ctx) { if (g_autoext.ExtsLength == 0) return; // Common case: early out without every having to acquire a mutex bool go = true; for (int i = 0; go; i++) { string errmsg = null; #if THREADSAFE MutexEx mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER); #endif MutexEx.Enter(mutex); Func<Context, string, core_api_routines, RC> init; if (i >= g_autoext.ExtsLength) { init = null; go = false; } else init = g_autoext.Exts[i]; MutexEx.Leave(mutex); errmsg = null; RC rc; if (init != null && (rc = init(ctx, errmsg, g_apis)) != 0) { Error(ctx, rc, "automatic extension loading failed: %s", errmsg); go = false; } C._tagfree(ctx, ref errmsg); } } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Security.IPIntelligenceBlacklistCategoryBinding", Namespace="urn:iControl")] public partial class SecurityIPIntelligenceBlacklistCategory : iControlInterface { public SecurityIPIntelligenceBlacklistCategory() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_ip_ttl //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] public void add_ip_ttl( string [] categories, string [] [] ip_ttls ) { this.Invoke("add_ip_ttl", new object [] { categories, ip_ttls}); } public System.IAsyncResult Beginadd_ip_ttl(string [] categories,string [] [] ip_ttls, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_ip_ttl", new object[] { categories, ip_ttls}, callback, asyncState); } public void Endadd_ip_ttl(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] public void create( string [] categories ) { this.Invoke("create", new object [] { categories}); } public System.IAsyncResult Begincreate(string [] categories, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { categories}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_blacklist_categories //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] public void delete_all_blacklist_categories( ) { this.Invoke("delete_all_blacklist_categories", new object [0]); } public System.IAsyncResult Begindelete_all_blacklist_categories(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_blacklist_categories", new object[0], callback, asyncState); } public void Enddelete_all_blacklist_categories(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_blacklist_category //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] public void delete_blacklist_category( string [] categories ) { this.Invoke("delete_blacklist_category", new object [] { categories}); } public System.IAsyncResult Begindelete_blacklist_category(string [] categories, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_blacklist_category", new object[] { categories}, callback, asyncState); } public void Enddelete_blacklist_category(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_default_match_direction //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SecurityIPIntelligenceBlacklistCategoryIPIntelligenceClassMatchDirection [] get_default_match_direction( string [] categories ) { object [] results = this.Invoke("get_default_match_direction", new object [] { categories}); return ((SecurityIPIntelligenceBlacklistCategoryIPIntelligenceClassMatchDirection [])(results[0])); } public System.IAsyncResult Beginget_default_match_direction(string [] categories, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_match_direction", new object[] { categories}, callback, asyncState); } public SecurityIPIntelligenceBlacklistCategoryIPIntelligenceClassMatchDirection [] Endget_default_match_direction(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SecurityIPIntelligenceBlacklistCategoryIPIntelligenceClassMatchDirection [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] categories ) { object [] results = this.Invoke("get_description", new object [] { categories}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] categories, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { categories}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // is_predefined //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_predefined( string [] categories ) { object [] results = this.Invoke("is_predefined", new object [] { categories}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_predefined(string [] categories, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_predefined", new object[] { categories}, callback, asyncState); } public bool [] Endis_predefined(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // remove_ip_ttl //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] public void remove_ip_ttl( string [] categories, string [] [] ip_ttls ) { this.Invoke("remove_ip_ttl", new object [] { categories, ip_ttls}); } public System.IAsyncResult Beginremove_ip_ttl(string [] categories,string [] [] ip_ttls, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_ip_ttl", new object[] { categories, ip_ttls}, callback, asyncState); } public void Endremove_ip_ttl(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_match_direction //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] public void set_default_match_direction( string [] categories, SecurityIPIntelligenceBlacklistCategoryIPIntelligenceClassMatchDirection [] directions ) { this.Invoke("set_default_match_direction", new object [] { categories, directions}); } public System.IAsyncResult Beginset_default_match_direction(string [] categories,SecurityIPIntelligenceBlacklistCategoryIPIntelligenceClassMatchDirection [] directions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_match_direction", new object[] { categories, directions}, callback, asyncState); } public void Endset_default_match_direction(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligenceBlacklistCategory", RequestNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory", ResponseNamespace="urn:iControl:Security/IPIntelligenceBlacklistCategory")] public void set_description( string [] categories, string [] descriptions ) { this.Invoke("set_description", new object [] { categories, descriptions}); } public System.IAsyncResult Beginset_description(string [] categories,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { categories, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Security.IPIntelligenceBlacklistCategory.IPIntelligenceClassMatchDirection", Namespace = "urn:iControl")] public enum SecurityIPIntelligenceBlacklistCategoryIPIntelligenceClassMatchDirection { IP_INTELLIGENCE_MATCH_DIRECTION_UNKNOWN, IP_INTELLIGENCE_MATCH_DIRECTION_SOURCE, IP_INTELLIGENCE_MATCH_DIRECTION_DESTINATION, IP_INTELLIGENCE_MATCH_DIRECTION_SOURCE_AND_DESTINATION, } //======================================================================= // Structs //======================================================================= }
#region License, Terms and Conditions // // ProductFamilyAttributes.cs // // Authors: Kori Francis <twitter.com/djbyter>, David Ball // Copyright (C) 2013 Clinical Support Systems, Inc. All rights reserved. // // THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #endregion namespace ChargifyNET { #region Imports using System; using System.Diagnostics; using System.Xml; using Json; #endregion /// <summary> /// Class representing basic attributes for a customer /// </summary> [DebuggerDisplay("Name: {Name}, Handle: {Handle}")] [Serializable] public class ProductFamilyAttributes : ChargifyBase, IProductFamilyAttributes { #region Field Keys internal const string NameKey = "name"; internal const string DescriptionKey = "description"; internal const string HandleKey = "handle"; internal const string AccountingCodeKey = "accounting_code"; #endregion #region Constructors /// <summary> /// Default constructor /// </summary> public ProductFamilyAttributes() { } /// <summary> /// Constructor, all values specified. /// </summary> /// <param name="name">The name of the product family</param> /// <param name="description">The description of the product family</param> /// <param name="accountingCode">The accounting code of the product family</param> /// <param name="handle">The handle of the product family</param> public ProductFamilyAttributes(string name, string description, string accountingCode, string handle) : this() { Name = name; Description = description; AccountingCode = accountingCode; Handle = handle; } /// <summary> /// Constructor /// </summary> /// <param name="productFamilyAttributesXml">The XML which corresponds to this classes members, to be parsed</param> public ProductFamilyAttributes(string productFamilyAttributesXml) { // get the XML into an XML document XmlDocument doc = new XmlDocument(); doc.LoadXml(productFamilyAttributesXml); if (doc.ChildNodes.Count == 0) throw new ArgumentException("XML not valid", nameof(productFamilyAttributesXml)); // loop through the child nodes of this node foreach (XmlNode elementNode in doc.ChildNodes) { switch (elementNode.Name) { case "product_family_attributes": case "product_family": LoadFromNode(elementNode); break; } } // if we get here, then no info was found throw new ArgumentException("XML does not contain information", nameof(productFamilyAttributesXml)); } /// <summary> /// Constructor /// </summary> /// <param name="productFamilyAttributesNode">The product family XML node</param> internal ProductFamilyAttributes(XmlNode productFamilyAttributesNode) { if (productFamilyAttributesNode == null) throw new ArgumentNullException(nameof(productFamilyAttributesNode)); if (productFamilyAttributesNode.Name != "product_family") throw new ArgumentException("Not a vaild product family attributes node", nameof(productFamilyAttributesNode)); if (productFamilyAttributesNode.ChildNodes.Count == 0) throw new ArgumentException("XML not valid", nameof(productFamilyAttributesNode)); LoadFromNode(productFamilyAttributesNode); } /// <summary> /// Constructor /// </summary> /// <param name="productFamilyAttributesObject">The product family JSON object</param> public ProductFamilyAttributes(JsonObject productFamilyAttributesObject) { if (productFamilyAttributesObject == null) throw new ArgumentNullException(nameof(productFamilyAttributesObject)); if (productFamilyAttributesObject.Keys.Count <= 0) throw new ArgumentException("Not a vaild product family attributes object", nameof(productFamilyAttributesObject)); LoadFromJson(productFamilyAttributesObject); } /// <summary> /// Load data from a JsonObject /// </summary> /// <param name="obj">The JsonObject containing product family attribute data</param> private void LoadFromJson(JsonObject obj) { foreach (string key in obj.Keys) { switch (key) { case NameKey: Name = obj.GetJSONContentAsString(key); break; case DescriptionKey: Description = obj.GetJSONContentAsString(key); break; case HandleKey: Handle = obj.GetJSONContentAsString(key); break; case AccountingCodeKey: AccountingCode = obj.GetJSONContentAsString(key); break; } } } /// <summary> /// Load data from a product family node /// </summary> /// <param name="customerNode">The product family node</param> private void LoadFromNode(XmlNode customerNode) { foreach (XmlNode dataNode in customerNode.ChildNodes) { switch (dataNode.Name) { case NameKey: Name = dataNode.GetNodeContentAsString(); break; case DescriptionKey: Description = dataNode.GetNodeContentAsString(); break; case HandleKey: Handle = dataNode.GetNodeContentAsString(); break; case AccountingCodeKey: AccountingCode = dataNode.GetNodeContentAsString(); break; } } } #endregion #region IComparable<IProductFamilyAttributes> Members /// <summary> /// Compare this instance to another (by Handle) /// </summary> /// <param name="other">The other instance to compare against</param> /// <returns>The result of the comparison</returns> public int CompareTo(IProductFamilyAttributes other) { return string.Compare(Handle, other.Handle, StringComparison.InvariantCultureIgnoreCase); } #endregion #region IComparable<ProductFamilyAttributes> Members /// <summary> /// Compare this instance to another (by Handle) /// </summary> /// <param name="other">The other instance to compare against</param> /// <returns>The result of the comparison</returns> public int CompareTo(ProductFamilyAttributes other) { return string.Compare(Handle, other.Handle, StringComparison.InvariantCultureIgnoreCase); } #endregion #region IProductFamilyAttribute Members /// <summary> /// The accounting code of the product family /// </summary> public string AccountingCode { get; set; } /// <summary> /// The descrition of the product family /// </summary> public string Description { get; set; } /// <summary> /// The handle of the product family /// </summary> public string Handle { get; set; } /// <summary> /// The name of the product family /// </summary> public string Name { get; set; } #endregion } }
using System; using System.Collections; using System.IO; using NUnit.Framework; using Raksha.Asn1.Cmp; using Raksha.Tsp; using Raksha.Utilities; using Raksha.Utilities.Encoders; using Raksha.X509; using Raksha.X509.Store; namespace Raksha.Tests.Tsp { [TestFixture] public class ParseTest { private static readonly byte[] sha1Request = Base64.Decode("MDACAQEwITAJBgUrDgMCGgUABBT5UbEBmJssO3RxcQtOePxNvfoMpgIIC+GvYW2mtZQ="); private static readonly byte[] sha1noNonse = Base64.Decode("MCYCAQEwITAJBgUrDgMCGgUABBT5UbEBmJssO3RxcQtOePxNvfoMpg=="); private static readonly byte[] md5Request = Base64.Decode("MDoCAQEwIDAMBggqhkiG9w0CBQUABBDIl9FBCvjyx0+6EbHbUR6eBgkrBgEEAakHBQECCDQluayIxIzn"); private static readonly byte[] ripemd160Request = Base64.Decode("MD8CAQEwITAJBgUrJAMCAQUABBSq03a/mk50Yd9lMF+BSqOp/RHGQQYJKwYBBAGpBwUBAgkA4SZs9NfqISMBAf8="); private static readonly byte[] sha1Response = Base64.Decode( "MIICbDADAgEAMIICYwYJKoZIhvcNAQcCoIICVDCCAlACAQMxCzAJBgUrDgMC" + "GgUAMIHaBgsqhkiG9w0BCRABBKCBygSBxzCBxAIBAQYEKgMEATAhMAkGBSsO" + "AwIaBQAEFPlRsQGYmyw7dHFxC054/E29+gymAgEEGA8yMDA0MTIwOTA3NTIw" + "NVowCgIBAYACAfSBAWQBAf8CCAvhr2FtprWUoGmkZzBlMRgwFgYDVQQDEw9F" + "cmljIEguIEVjaGlkbmExJDAiBgkqhkiG9w0BCQEWFWVyaWNAYm91bmN5Y2Fz" + "dGxlLm9yZzEWMBQGA1UEChMNQm91bmN5IENhc3RsZTELMAkGA1UEBhMCQVUx" + "ggFfMIIBWwIBATAqMCUxFjAUBgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJBgNV" + "BAYTAkFVAgECMAkGBSsOAwIaBQCggYwwGgYJKoZIhvcNAQkDMQ0GCyqGSIb3" + "DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0wNDEyMDkwNzUyMDVaMCMGCSqGSIb3" + "DQEJBDEWBBTGR1cbm94tWbcpDWrH+bD8UYePsTArBgsqhkiG9w0BCRACDDEc" + "MBowGDAWBBS37aLzFcheqeJ5cla0gjNWHGKbRzANBgkqhkiG9w0BAQEFAASB" + "gBrc9CJ3xlcTQuWQXJUqPEn6f6vfJAINKsn22z8LIfS/2p/CTFU6+W/bz8j8" + "j+8uWEJe8okTsI0FflljIsspqOPTB/RrnXteajbkuk/rLmz1B2g/qWBGAzPI" + "D214raBc1a7Bpd76PkvSSdjqrEaaskd+7JJiPr9l9yeSoh1AIt0N"); private static readonly byte[] sha1noNonseResponse = Base64.Decode( "MIICYjADAgEAMIICWQYJKoZIhvcNAQcCoIICSjCCAkYCAQMxCzAJBgUrDgMC" + "GgUAMIHQBgsqhkiG9w0BCRABBKCBwASBvTCBugIBAQYEKgMEATAhMAkGBSsO" + "AwIaBQAEFPlRsQGYmyw7dHFxC054/E29+gymAgECGA8yMDA0MTIwOTA3MzQx" + "MlowCgIBAYACAfSBAWQBAf+gaaRnMGUxGDAWBgNVBAMTD0VyaWMgSC4gRWNo" + "aWRuYTEkMCIGCSqGSIb3DQEJARYVZXJpY0Bib3VuY3ljYXN0bGUub3JnMRYw" + "FAYDVQQKEw1Cb3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVTGCAV8wggFbAgEB" + "MCowJTEWMBQGA1UEChMNQm91bmN5IENhc3RsZTELMAkGA1UEBhMCQVUCAQIw" + "CQYFKw4DAhoFAKCBjDAaBgkqhkiG9w0BCQMxDQYLKoZIhvcNAQkQAQQwHAYJ" + "KoZIhvcNAQkFMQ8XDTA0MTIwOTA3MzQxMlowIwYJKoZIhvcNAQkEMRYEFMNA" + "xlscHYiByHL9DIEh3FewIhgSMCsGCyqGSIb3DQEJEAIMMRwwGjAYMBYEFLft" + "ovMVyF6p4nlyVrSCM1YcYptHMA0GCSqGSIb3DQEBAQUABIGAaj46Tarrg7V7" + "z13bbetrGv+xy159eE8kmIW9nPegru3DuK/GmbMx9W3l0ydx0zdXRwYi6NZc" + "nNqbEZQZ2L1biJVTflgWq4Nxu4gPGjH/BGHKdH/LyW4eDcXZR39AkNBMnDAK" + "EmhhJo1/Tc+S/WkV9lnHJCPIn+TAijBUO6EiTik="); private static readonly byte[] md5Response = Base64.Decode( "MIICcDADAgEAMIICZwYJKoZIhvcNAQcCoIICWDCCAlQCAQMxCzAJBgUrDgMC" + "GgUAMIHeBgsqhkiG9w0BCRABBKCBzgSByzCByAIBAQYJKwYBBAGpBwUBMCAw" + "DAYIKoZIhvcNAgUFAAQQyJfRQQr48sdPuhGx21EengIBAxgPMjAwNDEyMDkw" + "NzQ2MTZaMAoCAQGAAgH0gQFkAQH/Agg0JbmsiMSM56BppGcwZTEYMBYGA1UE" + "AxMPRXJpYyBILiBFY2hpZG5hMSQwIgYJKoZIhvcNAQkBFhVlcmljQGJvdW5j" + "eWNhc3RsZS5vcmcxFjAUBgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJBgNVBAYT" + "AkFVMYIBXzCCAVsCAQEwKjAlMRYwFAYDVQQKEw1Cb3VuY3kgQ2FzdGxlMQsw" + "CQYDVQQGEwJBVQIBAjAJBgUrDgMCGgUAoIGMMBoGCSqGSIb3DQEJAzENBgsq" + "hkiG9w0BCRABBDAcBgkqhkiG9w0BCQUxDxcNMDQxMjA5MDc0NjE2WjAjBgkq" + "hkiG9w0BCQQxFgQUFpRpaiRUUjiY7EbefbWLKDIY0XMwKwYLKoZIhvcNAQkQ" + "AgwxHDAaMBgwFgQUt+2i8xXIXqnieXJWtIIzVhxim0cwDQYJKoZIhvcNAQEB" + "BQAEgYBTwKsLLrQm+bvKV7Jwto/cMQh0KsVB5RoEeGn5CI9XyF2Bm+JRcvQL" + "Nm7SgSOBVt4A90TqujxirNeyQnXRiSnFvXd09Wet9WIQNpwpiGlE7lCrAhuq" + "/TAUe79VIpoQZDtyhbh0Vzxl24yRoechabC0zuPpOWOzrA4YC3Hv1J2tAA=="); private static readonly byte[] signingCert = Base64.Decode( "MIICWjCCAcOgAwIBAgIBAjANBgkqhkiG9w0BAQQFADAlMRYwFAYDVQQKEw1Cb3Vu" + "Y3kgQ2FzdGxlMQswCQYDVQQGEwJBVTAeFw0wNDEyMDkwNzEzMTRaFw0wNTAzMTkw" + "NzEzMTRaMGUxGDAWBgNVBAMTD0VyaWMgSC4gRWNoaWRuYTEkMCIGCSqGSIb3DQEJ" + "ARYVZXJpY0Bib3VuY3ljYXN0bGUub3JnMRYwFAYDVQQKEw1Cb3VuY3kgQ2FzdGxl" + "MQswCQYDVQQGEwJBVTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqGAFO3dK" + "jB7Ca7u5Z3CabsbGr2Exg+3sztSPiRCIba03es4295EhtDF5bXQvrW2R1Bg72vED" + "5tWaQjVDetvDfCzVC3ErHLTVk3OgpLIP1gf2T0LcOH2pTh2LP9c5Ceta+uggK8zK" + "9sYUUnzGPSAZxrqHIIAlPIgqk0BMV+KApyECAwEAAaNaMFgwHQYDVR0OBBYEFO4F" + "YoqogtB9MjD0NB5x5HN3TrGUMB8GA1UdIwQYMBaAFPXAecuwLqNkCxYVLE/ngFQR" + "7RLIMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMIMA0GCSqGSIb3DQEBBAUAA4GBADGi" + "D5/qmGvcBgswEM/z2dF4lOxbTNKUW31ZHiU8CXlN0IkFtNbBLBTbJOQIAUnNEabL" + "T7aYgj813OZKUbJTx4MuGChhot/TEP7hKo/xz9OnXLsqYDKbqbo8iLOode+SI7II" + "+yYghOtqvx32cL2Qmffi1LaMbhJP+8NbsIxowdRC"); private static readonly byte[] unacceptablePolicy = Base64.Decode( "MDAwLgIBAjAkDCJSZXF1ZXN0ZWQgcG9saWN5IGlzIG5vdCBzdXBwb3J0ZWQuAwMAAAE="); private static readonly byte[] generalizedTime = Base64.Decode( "MIIKPTADAgEAMIIKNAYJKoZIhvcNAQcCoIIKJTCCCiECAQMxCzAJBgUrDgMC" + "GgUAMIIBGwYLKoZIhvcNAQkQAQSgggEKBIIBBjCCAQICAQEGCisGAQQBhFkK" + "AwEwITAJBgUrDgMCGgUABBQAAAAAAAAAAAAAAAAAAAAAAAAAAAICUC8YEzIw" + "MDUwMzEwMTA1ODQzLjkzM1owBIACAfQBAf8CAWSggaikgaUwgaIxCzAJBgNV" + "BAYTAkdCMRcwFQYDVQQIEw5DYW1icmlkZ2VzaGlyZTESMBAGA1UEBxMJQ2Ft" + "YnJpZGdlMSQwIgYDVQQKExtuQ2lwaGVyIENvcnBvcmF0aW9uIExpbWl0ZWQx" + "JzAlBgNVBAsTHm5DaXBoZXIgRFNFIEVTTjozMjJBLUI1REQtNzI1QjEXMBUG" + "A1UEAxMOZGVtby1kc2UyMDAtMDGgggaFMIID2TCCA0KgAwIBAgICAIswDQYJ" + "KoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAkdCMRcwFQYDVQQIEw5DYW1icmlk" + "Z2VzaGlyZTESMBAGA1UEBxMJQ2FtYnJpZGdlMSQwIgYDVQQKExtuQ2lwaGVy" + "IENvcnBvcmF0aW9uIExpbWl0ZWQxGDAWBgNVBAsTD1Byb2R1Y3Rpb24gVEVT" + "VDEQMA4GA1UEAxMHVEVTVCBDQTAeFw0wNDA2MTQxNDIzNTlaFw0wNTA2MTQx" + "NDIzNTlaMIGiMQswCQYDVQQGEwJHQjEXMBUGA1UECBMOQ2FtYnJpZGdlc2hp" + "cmUxEjAQBgNVBAcTCUNhbWJyaWRnZTEkMCIGA1UEChMbbkNpcGhlciBDb3Jw" + "b3JhdGlvbiBMaW1pdGVkMScwJQYDVQQLEx5uQ2lwaGVyIERTRSBFU046MzIy" + "QS1CNURELTcyNUIxFzAVBgNVBAMTDmRlbW8tZHNlMjAwLTAxMIGfMA0GCSqG" + "SIb3DQEBAQUAA4GNADCBiQKBgQC7zUamCeLIApddx1etW5YEFrL1WXnlCd7j" + "mMFI6RpSq056LBkF1z5LgucLY+e/c3u2Nw+XJuS3a2fKuBD7I1s/6IkVtIb/" + "KLDjjafOnottKhprH8K41siJUeuK3PRzfZ5kF0vwB3rNvWPCBJmp7kHtUQw3" + "RhIsJTYs7Wy8oVFHVwIDAQABo4IBMDCCASwwCQYDVR0TBAIwADAWBgNVHSUB" + "Af8EDDAKBggrBgEFBQcDCDAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5l" + "cmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFDlEe9Pd0WwQrtnEmFRI2Vmt" + "b+lCMIG5BgNVHSMEgbEwga6AFNy1VPweOQLC65bs6/0RcUYB19vJoYGSpIGP" + "MIGMMQswCQYDVQQGEwJHQjEXMBUGA1UECBMOQ2FtYnJpZGdlc2hpcmUxEjAQ" + "BgNVBAcTCUNhbWJyaWRnZTEkMCIGA1UEChMbbkNpcGhlciBDb3Jwb3JhdGlv" + "biBMaW1pdGVkMRgwFgYDVQQLEw9Qcm9kdWN0aW9uIFRFU1QxEDAOBgNVBAMT" + "B1RFU1QgQ0GCAQAwDQYJKoZIhvcNAQEFBQADgYEASEMlrpRE1RYZPxP3530e" + "hOYUDjgQbw0dwpPjQtLWkeJrePMzDBAbuWwpRI8dOzKP3Rnrm5rxJ7oLY2S0" + "A9ZfV+iwFKagEHFytfnPm2Y9AeNR7a3ladKd7NFMw+5Tbk7Asbetbb+NJfCl" + "9YzHwxLGiQbpKxgc+zYOjq74eGLKtcKhggKkMIICDQIBATCB0qGBqKSBpTCB" + "ojELMAkGA1UEBhMCR0IxFzAVBgNVBAgTDkNhbWJyaWRnZXNoaXJlMRIwEAYD" + "VQQHEwlDYW1icmlkZ2UxJDAiBgNVBAoTG25DaXBoZXIgQ29ycG9yYXRpb24g" + "TGltaXRlZDEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNOOjMyMkEtQjVERC03" + "MjVCMRcwFQYDVQQDEw5kZW1vLWRzZTIwMC0wMaIlCgEBMAkGBSsOAwIaBQAD" + "FQDaLe88TQvM+iMKmIXMmDSyPCZ/+KBmMGSkYjBgMQswCQYDVQQGEwJVUzEk" + "MCIGA1UEChMbbkNpcGhlciBDb3Jwb3JhdGlvbiBMaW1pdGVkMRgwFgYDVQQL" + "Ew9Qcm9kdWN0aW9uIFRlc3QxETAPBgNVBAMTCFRlc3QgVE1DMA0GCSqGSIb3" + "DQEBBQUAAgjF2jVbAAAAADAiGA8yMDA1MDMxMDAyNTQxOVoYDzIwMDUwMzEz" + "MDI1NDE5WjCBjTBLBgorBgEEAYRZCgQBMT0wOzAMAgTF2jVbAgQAAAAAMA8C" + "BAAAAAACBAAAaLkCAf8wDAIEAAAAAAIEAAKV/DAMAgTF3inbAgQAAAAAMD4G" + "CisGAQQBhFkKBAIxMDAuMAwGCisGAQQBhFkKAwGgDjAMAgQAAAAAAgQAB6Eg" + "oQ4wDAIEAAAAAAIEAAPQkDANBgkqhkiG9w0BAQUFAAOBgQB1q4d3GNWk7oAT" + "WkpYmZaTFvapMhTwAmAtSGgFmNOZhs21iHWl/X990/HEBsduwxohfrd8Pz64" + "hV/a76rpeJCVUfUNmbRIrsurFx6uKwe2HUHKW8grZWeCD1L8Y1pKQdrD41gu" + "v0msfOXzLWW+xe5BcJguKclN8HmT7s2odtgiMTGCAmUwggJhAgEBMIGTMIGM" + "MQswCQYDVQQGEwJHQjEXMBUGA1UECBMOQ2FtYnJpZGdlc2hpcmUxEjAQBgNV" + "BAcTCUNhbWJyaWRnZTEkMCIGA1UEChMbbkNpcGhlciBDb3Jwb3JhdGlvbiBM" + "aW1pdGVkMRgwFgYDVQQLEw9Qcm9kdWN0aW9uIFRFU1QxEDAOBgNVBAMTB1RF" + "U1QgQ0ECAgCLMAkGBSsOAwIaBQCgggEnMBoGCSqGSIb3DQEJAzENBgsqhkiG" + "9w0BCRABBDAjBgkqhkiG9w0BCQQxFgQUi1iYx5H3ACnvngWZTPfdxGswkSkw" + "geMGCyqGSIb3DQEJEAIMMYHTMIHQMIHNMIGyBBTaLe88TQvM+iMKmIXMmDSy" + "PCZ/+DCBmTCBkqSBjzCBjDELMAkGA1UEBhMCR0IxFzAVBgNVBAgTDkNhbWJy" + "aWRnZXNoaXJlMRIwEAYDVQQHEwlDYW1icmlkZ2UxJDAiBgNVBAoTG25DaXBo" + "ZXIgQ29ycG9yYXRpb24gTGltaXRlZDEYMBYGA1UECxMPUHJvZHVjdGlvbiBU" + "RVNUMRAwDgYDVQQDEwdURVNUIENBAgIAizAWBBSpS/lH6bN/wf3E2z2X29vF" + "2U7YHTANBgkqhkiG9w0BAQUFAASBgGvDVsgsG5I5WKjEDVHvdRwUx+8Cp10l" + "zGF8o1h7aK5O3zQ4jLayYHea54E5+df35gG7Z3eoOy8E350J7BvHiwDLTqe8" + "SoRlGs9VhL6LMmCcERfGSlSn61Aa15iXZ8eHMSc5JTeJl+kqy4I3FPP4m2ai" + "8wy2fQhn7hUM8Ntg7Y2s"); private static readonly byte[] v2SigningCertResponse = Base64.Decode( "MIIPPTADAgEAMIIPNAYJKoZIhvcNAQcCoIIPJTCCDyECAQMxDzANBglghkgBZQMEAgEFADCB6QYL" + "KoZIhvcNAQkQAQSggdkEgdYwgdMCAQEGBgQAj2cBATAxMA0GCWCGSAFlAwQCAQUABCBcU0GN08TA" + "LUFi7AAwQwVkSXqGu9tAzvJ7EXW7SMXHHQIRAM7Fa7g6tMvZI3dgllwMfpcYDzIwMDcxMjExMTAy" + "MTU5WjADAgEBAgYBFsi5OlmgYqRgMF4xCzAJBgNVBAYTAkRFMSQwIgYDVQQKDBtEZXV0c2NoZSBS" + "ZW50ZW52ZXJzaWNoZXJ1bmcxEzARBgNVBAsMClFDIFJvb3QgQ0ExFDASBgNVBAMMC1FDIFJvb3Qg" + "VFNQoIILQjCCBwkwggXxoAMCAQICAwN1pjANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJERTEk" + "MCIGA1UECgwbRGV1dHNjaGUgUmVudGVudmVyc2ljaGVydW5nMRMwEQYDVQQLDApRQyBSb290IENB" + "MB4XDTA3MTEyMDE2MDcyMFoXDTEyMDcyNzIwMjExMVowXjELMAkGA1UEBhMCREUxJDAiBgNVBAoM" + "G0RldXRzY2hlIFJlbnRlbnZlcnNpY2hlcnVuZzETMBEGA1UECwwKUUMgUm9vdCBDQTEUMBIGA1UE" + "AwwLUUMgUm9vdCBUU1AwggEkMA0GCSqGSIb3DQEBAQUAA4IBEQAwggEMAoIBAQCv1vO+EtGnJNs0" + "atv76BAJXs4bmO8yzVwe3RUtgeu5z9iefh8P46i1g3EL2CD15NcTfoHksr5KudNY30olfjHG7lIu" + "MO3R5sAcrGDPP7riZJnaI6VD/e6kVR569VBid5z105fJAB7mID7+Bn7pdRwDW3Fy2CzfofXGuvrO" + "GPNEWq8x8kqqf75DB5nAs5QP8H41obkdkap2ttHkkPZCiMghTs8iHfpJ0STn47MKq+QrUmuATMZi" + "XrdEfb7f3TBMjO0UVJF64Mh+kC9GtUEHlcm0Tq2Pk5XIUxWEyL94rZ4UWcVdSVE7IjggV2MifMNx" + "geZO3SwsDZk71AhDBy30CSzBAgUAx3HB5aOCA+IwggPeMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMI" + "MBMGA1UdIwQMMAqACECefuBmflfeMBgGCCsGAQUFBwEDBAwwCjAIBgYEAI5GAQEwUAYIKwYBBQUH" + "AQEERDBCMEAGCCsGAQUFBzABhjRodHRwOi8vb2NzcC1yb290cWMudGMuZGV1dHNjaGUtcmVudGVu" + "dmVyc2ljaGVydW5nLmRlMHcGA1UdIARwMG4wbAYNKwYBBAGBrTwBCAEBAzBbMFkGCCsGAQUFBwIB" + "Fk1odHRwOi8vd3d3LmRldXRzY2hlLXJlbnRlbnZlcnNpY2hlcnVuZy1idW5kLmRlL3N0YXRpYy90" + "cnVzdGNlbnRlci9wb2xpY3kuaHRtbDCCATwGA1UdHwSCATMwggEvMHygeqB4hnZsZGFwOi8vZGly" + "LnRjLmRldXRzY2hlLXJlbnRlbnZlcnNpY2hlcnVuZy5kZS9vdT1RQyUyMFJvb3QlMjBDQSxjbj1Q" + "dWJsaWMsbz1EUlYsYz1ERT9hdHRybmFtZT1jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0MIGuoIGr" + "oIGohoGlaHR0cDovL2Rpci50Yy5kZXV0c2NoZS1yZW50ZW52ZXJzaWNoZXJ1bmcuZGU6ODA4OS9z" + "ZXJ2bGV0L0Rpclh3ZWIvQ2EveC5jcmw/ZG49b3UlM0RRQyUyMFJvb3QlMjBDQSUyQ2NuJTNEUHVi" + "bGljJTJDbyUzRERSViUyQ2MlM0RERSZhdHRybmFtZT1jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0" + "MIIBLQYDVR0SBIIBJDCCASCGdGxkYXA6Ly9kaXIudGMuZGV1dHNjaGUtcmVudGVudmVyc2ljaGVy" + "dW5nLmRlL2NuPTE0NTUxOCxvdT1RQyUyMFJvb3QlMjBDQSxjbj1QdWJsaWMsbz1EUlYsYz1ERT9h" + "dHRybmFtZT1jQUNlcnRpZmljYXRlhoGnaHR0cDovL2Rpci50Yy5kZXV0c2NoZS1yZW50ZW52ZXJz" + "aWNoZXJ1bmcuZGU6ODA4OS9zZXJ2bGV0L0Rpclh3ZWIvQ2EveC5jZXI/ZG49Y24lM0QxNDU1MTgl" + "MkNvdSUzRFFDJTIwUm9vdCUyMENBJTJDY24lM0RQdWJsaWMlMkNvJTNERFJWJTJDYyUzRERFJmF0" + "dHJuYW1lPWNBQ2VydGlmaWNhdGUwDgYDVR0PAQH/BAQDAgZAMDsGA1UdCQQ0MDIwMAYDVQQDMSkT" + "J1FDIFRTUCBEZXV0c2NoZSBSZW50ZW52ZXJzaWNoZXJ1bmcgMTpQTjAMBgNVHRMBAf8EAjAAMA0G" + "CSqGSIb3DQEBCwUAA4IBAQCCrWe3Pd3ioX7d8phXvVAa859Rvgf0k3pZ6R4GMj8h/k6MNjNIrdAs" + "wgUVkBbXMLLBk0smsvTdFIVtTBdp1urb9l7vXjDA4MckXBOXPcz4fN8Oswk92d+fM9XU1jKVPsFG" + "PV6j8lAqfq5jwaRxOnS96UBGLKG+NdcrEyiMp/ZkpqnEQZZfu2mkeq6CPahnbBTZqsE0jgY351gU" + "9T6SFVvLIFH7cOxJqsoxPqv5YEcgiXPpOyyu2rpQqKYBYcnerF6/zx5hmWHxTd7MWaTHm0gJI/Im" + "d8esbW+xyaJuAVUcBA+sDmSe8AAoRVxwBRY+xi9ApaJHpmwT+0n2K2GsL3wIMIIEMTCCAxmgAwIB" + "AgIDAjhuMA0GCSqGSIb3DQEBCwUAMEgxCzAJBgNVBAYTAkRFMSQwIgYDVQQKDBtEZXV0c2NoZSBS" + "ZW50ZW52ZXJzaWNoZXJ1bmcxEzARBgNVBAsMClFDIFJvb3QgQ0EwHhcNMDcwNzI3MjAyMTExWhcN" + "MTIwNzI3MjAyMTExWjBIMQswCQYDVQQGEwJERTEkMCIGA1UECgwbRGV1dHNjaGUgUmVudGVudmVy" + "c2ljaGVydW5nMRMwEQYDVQQLDApRQyBSb290IENBMIIBJDANBgkqhkiG9w0BAQEFAAOCAREAMIIB" + "DAKCAQEAzuhBdo9c84DdzsggjWOgfC4jJ2jYqpsOpBo3DVyem+5R26QK4feZdyFnaGvyG+TLcdLO" + "iCecGmrRGD+ey4IhjCONb7hsQQhJWTyDEtBblzYB0yjY8+9fnNeR61W+M/KlMgC6Rw/w+zwzklTM" + "MWwIbxLHm8l9jTSKFjAWTwjE8bCzpUCwN8+4JbFTwjwOJ5lsVA5Xa34wpgr6lgL3WrVTV1NSprqR" + "ZYDWg477tht0KkyOJt3guF3RONKBBuTO2qCbpUeI8m4v3tznoopYbV5Gp5wu5gqd6lTfgju3ldql" + "bxtuCLZd0nAI5rLEOPItDKl4vPXllmmtGIrtDZlwr86cbwIFAJvMJpGjggEgMIIBHDAPBgNVHRMB" + "Af8EBTADAQH/MBEGA1UdDgQKBAhAnn7gZn5X3jB3BgNVHSAEcDBuMGwGDSsGAQQBga08AQgBAQEw" + "WzBZBggrBgEFBQcCARZNaHR0cDovL3d3dy5kZXV0c2NoZS1yZW50ZW52ZXJzaWNoZXJ1bmctYnVu" + "ZC5kZS9zdGF0aWMvdHJ1c3RjZW50ZXIvcG9saWN5Lmh0bWwwUwYDVR0JBEwwSjBIBgNVBAMxQRM/" + "UUMgV3VyemVsemVydGlmaXppZXJ1bmdzc3RlbGxlIERldXRzY2hlIFJlbnRlbnZlcnNpY2hlcnVu" + "ZyAxOlBOMBgGCCsGAQUFBwEDBAwwCjAIBgYEAI5GAQEwDgYDVR0PAQH/BAQDAgIEMA0GCSqGSIb3" + "DQEBCwUAA4IBAQBNGs7Dnc1yzzpZrkuC+oLv+NhbORTEYNgpaOetB1JQ1EbUBoPuNN4ih0ngy/uJ" + "D2O+h4JsNkmELgaehLWyFwATqCYZY4cTAGVoEwgn93x3aW8JbMDQf+YEJDSDsXcm4oIDFPqv5M6o" + "HZUWfsPka3mxKivfKtWhooTz1/+BEGReVQ2oOAvlwXlkEab9e3GOqXQUcLPYDTl8BQxiYhtQtf3d" + "kORiUkuGiGX1YJ5JnZnG3ElMjPgOl8rOiYU7oj9uv1HVb5sdAwuVw0BR/eiMVDBT8DNyfoJmPeQQ" + "A9pXtoAYO0Ya7wNNmCY2Y63YfBlRCF+9VQv2RZ4TdO1KGWwxR98OMYIC1zCCAtMCAQEwTzBIMQsw" + "CQYDVQQGEwJERTEkMCIGA1UECgwbRGV1dHNjaGUgUmVudGVudmVyc2ljaGVydW5nMRMwEQYDVQQL" + "DApRQyBSb290IENBAgMDdaYwDQYJYIZIAWUDBAIBBQCgggFZMBoGCSqGSIb3DQEJAzENBgsqhkiG" + "9w0BCRABBDAvBgkqhkiG9w0BCQQxIgQgO7FFODWWwF5RUjo6wjIkgkD5u7dH+NICiCpSgRRqd/Aw" + "ggEIBgsqhkiG9w0BCRACLzGB+DCB9TCB8jB3BCAMMZqK/5pZxOb3ruCbcgxStaTDwDHaf2glEo6P" + "+89t8TBTMEykSjBIMQswCQYDVQQGEwJERTEkMCIGA1UECgwbRGV1dHNjaGUgUmVudGVudmVyc2lj" + "aGVydW5nMRMwEQYDVQQLDApRQyBSb290IENBAgMDdaYwdwQgl7vwI+P47kpxhWLoIdEco7UfGwZ2" + "X4el3jaZ67q5/9IwUzBMpEowSDELMAkGA1UEBhMCREUxJDAiBgNVBAoMG0RldXRzY2hlIFJlbnRl" + "bnZlcnNpY2hlcnVuZzETMBEGA1UECwwKUUMgUm9vdCBDQQIDAjhuMA0GCSqGSIb3DQEBCwUABIIB" + "AIOYgpDI0BaeG4RF/EB5QzkUqAZ9nX6w895+m2hHyRKrAKdj3913j5QI+aEVIG3DVbFaAfdKeKfn" + "xsTW48aWs6aARtPAc+1OXwoGUSYElOFqqVpSeTaXe+kjY5bsLSQeETB+EPvXl8EcKTaxTRCNOqJU" + "XbnyYRgWTI55A2jH6IsQQVHc5DaIcmbdI8iATaRTHY5eUeVuI+Q/3RMVBFAb5qRhM61Ddcrjq058" + "C0uiH9G2IB5QRyu6RsCUgrkeMTMBqlIBlnDBy+EgLouDU4Dehxy5uzEl5DBKZEewZpQZOTO/kAgL" + "WruAAg/Lj4r0f9vN12wRlHoS2UKDjrE1DnUBbrM="); public string Name { get { return "ParseTest"; } } private static void requestParse( byte[] request, string algorithm) { TimeStampRequest req = new TimeStampRequest(request); if (!req.MessageImprintAlgOid.Equals(algorithm)) { Assert.Fail("failed to get expected algorithm - got " + req.MessageImprintAlgOid + " not " + algorithm); } if (request != sha1Request && request != sha1noNonse) { if (!req.ReqPolicy.Equals(TspTestUtil.EuroPkiTsaTestPolicy.Id)) { Assert.Fail("" + algorithm + " failed policy check."); } if (request == ripemd160Request) { if (!req.CertReq) { Assert.Fail("" + algorithm + " failed certReq check."); } } } Assert.AreEqual(1, req.Version, "version not 1"); Assert.IsNull(req.GetCriticalExtensionOids(), "critical extensions found when none expected"); Assert.IsNull(req.GetNonCriticalExtensionOids(), "non-critical extensions found when none expected"); if (request != sha1noNonse) { if (req.Nonce == null) { Assert.Fail("" + algorithm + " nonse not found when one expected."); } } else { if (req.Nonce != null) { Assert.Fail("" + algorithm + " nonse not found when one not expected."); } } try { req.Validate(TspAlgorithms.Allowed, null, null); } catch (Exception) { Assert.Fail("validation exception."); } if (!Arrays.AreEqual(req.GetEncoded(), request)) { Assert.Fail("" + algorithm + " failed encode check."); } } private static void responseParse( byte[] request, byte[] response, string algorithm) { TimeStampRequest req = new TimeStampRequest(request); TimeStampResponse resp = new TimeStampResponse(response); resp.Validate(req); X509Certificate cert = new X509CertificateParser().ReadCertificate(signingCert); resp.TimeStampToken.Validate(cert); } private static void unacceptableResponseParse( byte[] response) { TimeStampResponse resp = new TimeStampResponse(response); if (resp.Status != (int) PkiStatus.Rejection) { Assert.Fail("request not rejected."); } if (resp.GetFailInfo().IntValue != PkiFailureInfo.UnacceptedPolicy) { Assert.Fail("request not rejected."); } } private static void generalizedTimeParse( byte[] response) { TimeStampResponse resp = new TimeStampResponse(response); if (resp.Status != (int) PkiStatus.Granted) { Assert.Fail("request not rejected."); } } [Test] public void TestSha1() { requestParse(sha1Request, TspAlgorithms.Sha1); requestParse(sha1noNonse, TspAlgorithms.Sha1); responseParse(sha1Request, sha1Response, TspAlgorithms.Sha1); responseParse(sha1noNonse, sha1noNonseResponse, TspAlgorithms.Sha1); } [Test] public void TestMD5() { requestParse(md5Request, TspAlgorithms.MD5); responseParse(md5Request, md5Response, TspAlgorithms.MD5); } [Test] public void TestRipeMD160() { requestParse(ripemd160Request, TspAlgorithms.RipeMD160); } [Test] public void TestUnacceptable() { unacceptableResponseParse(unacceptablePolicy); } [Test] public void TestGeneralizedTime() { generalizedTimeParse(generalizedTime); } [Test] public void TestV2SigningResponseParse() { v2SigningResponseParse(v2SigningCertResponse); } private void v2SigningResponseParse( byte[] encoded) { TimeStampResponse response = new TimeStampResponse(encoded); IX509Store store = response.TimeStampToken.GetCertificates("Collection"); X509Certificate cert = (X509Certificate) new ArrayList(store.GetMatches(response.TimeStampToken.SignerID))[0]; response.TimeStampToken.Validate(cert); } // public static void parse( // byte[] encoded, // bool tokenPresent) // { // TimeStampResponse response = new TimeStampResponse(encoded); // // if (tokenPresent && response.TimeStampToken == null) // { // Assert.Fail("token not found when expected."); // } // } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Security; using System.Reflection; using System.Runtime.Loader; using System.Security; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using PathType = System.IO.Path; namespace Microsoft.PowerShell.Commands { /// <summary> /// Languages supported for code generation. /// </summary> public enum Language { /// <summary> /// The C# programming language. /// </summary> CSharp } /// <summary> /// Types supported for the OutputAssembly parameter. /// </summary> public enum OutputAssemblyType { /// <summary> /// A Dynamically linked library (DLL). /// </summary> Library, /// <summary> /// An executable application that targets the console subsystem. /// </summary> ConsoleApplication, /// <summary> /// An executable application that targets the graphical subsystem. /// </summary> WindowsApplication } /// <summary> /// Adds a new type to the Application Domain. /// This version is based on CodeAnalysis (Roslyn). /// </summary> [Cmdlet(VerbsCommon.Add, "Type", DefaultParameterSetName = FromSourceParameterSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096601")] [OutputType(typeof(Type))] public sealed class AddTypeCommand : PSCmdlet { #region Parameters /// <summary> /// The source code of this generated type. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromSourceParameterSetName)] [ValidateTrustedData] public string TypeDefinition { get { return _sourceCode; } set { _sourceCode = value; } } /// <summary> /// The name of the type (class) used for auto-generated types. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromMemberParameterSetName)] [ValidateTrustedData] public string Name { get; set; } /// <summary> /// The source code of this generated method / member. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = FromMemberParameterSetName)] public string[] MemberDefinition { get { return new string[] { _sourceCode }; } set { _sourceCode = string.Empty; if (value != null) { _sourceCode = string.Join("\n", value); } } } private string _sourceCode; /// <summary> /// The namespace used for the auto-generated type. /// </summary> [Parameter(ParameterSetName = FromMemberParameterSetName)] [AllowNull] [Alias("NS")] public string Namespace { get; set; } = "Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes"; /// <summary> /// Any using statements required by the auto-generated type. /// </summary> [Parameter(ParameterSetName = FromMemberParameterSetName)] [ValidateNotNull()] [Alias("Using")] public string[] UsingNamespace { get; set; } = Array.Empty<string>(); /// <summary> /// The path to the source code or DLL to load. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromPathParameterSetName)] [ValidateTrustedData] public string[] Path { get { return _paths; } set { if (value == null) { _paths = null; return; } string[] pathValue = value; List<string> resolvedPaths = new(); // Verify that the paths are resolved and valid foreach (string path in pathValue) { // Try to resolve the path Collection<string> newPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(path, out ProviderInfo _); // If it didn't resolve, add the original back // for a better error message. if (newPaths.Count == 0) { resolvedPaths.Add(path); } else { resolvedPaths.AddRange(newPaths); } } ProcessPaths(resolvedPaths); } } /// <summary> /// The literal path to the source code or DLL to load. /// </summary> [Parameter(Mandatory = true, ParameterSetName = FromLiteralPathParameterSetName)] [Alias("PSPath", "LP")] [ValidateTrustedData] public string[] LiteralPath { get { return _paths; } set { if (value == null) { _paths = null; return; } List<string> resolvedPaths = new(); foreach (string path in value) { string literalPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); resolvedPaths.Add(literalPath); } ProcessPaths(resolvedPaths); } } private void ProcessPaths(List<string> resolvedPaths) { // Validate file extensions. // Make sure we don't mix source files from different languages (if we support any other languages in future). string activeExtension = null; foreach (string path in resolvedPaths) { string currentExtension = PathType.GetExtension(path).ToUpperInvariant(); switch (currentExtension) { case ".CS": Language = Language.CSharp; break; case ".DLL": _loadAssembly = true; break; // Throw an error if it is an unrecognized extension default: ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.FileExtensionNotSupported, currentExtension)), "EXTENSION_NOT_SUPPORTED", ErrorCategory.InvalidArgument, currentExtension); ThrowTerminatingError(errorRecord); break; } if (activeExtension == null) { activeExtension = currentExtension; } else if (!string.Equals(activeExtension, currentExtension, StringComparison.OrdinalIgnoreCase)) { // All files must have the same extension otherwise throw. ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.MultipleExtensionsNotSupported)), "MULTIPLE_EXTENSION_NOT_SUPPORTED", ErrorCategory.InvalidArgument, currentExtension); ThrowTerminatingError(errorRecord); } } _paths = resolvedPaths.ToArray(); } private string[] _paths; /// <summary> /// The name of the assembly to load. /// </summary> [Parameter(Mandatory = true, ParameterSetName = FromAssemblyNameParameterSetName)] [Alias("AN")] [ValidateTrustedData] public string[] AssemblyName { get; set; } private bool _loadAssembly = false; /// <summary> /// The language used to compile the source code. /// Default is C#. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] public Language Language { get; set; } = Language.CSharp; /// <summary> /// Any reference DLLs to use in the compilation. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] [Alias("RA")] public string[] ReferencedAssemblies { get { return _referencedAssemblies; } set { if (value != null) { _referencedAssemblies = value; } } } private string[] _referencedAssemblies = Array.Empty<string>(); /// <summary> /// The path to the output assembly. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] [Alias("OA")] public string OutputAssembly { get { return _outputAssembly; } set { _outputAssembly = value; if (_outputAssembly != null) { _outputAssembly = _outputAssembly.Trim(); // Try to resolve the path ProviderInfo provider = null; Collection<string> newPaths = new(); try { newPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_outputAssembly, out provider); } // Ignore the ItemNotFound -- we handle it. catch (ItemNotFoundException) { } ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.OutputAssemblyDidNotResolve, _outputAssembly)), "INVALID_OUTPUT_ASSEMBLY", ErrorCategory.InvalidArgument, _outputAssembly); // If it resolved to a non-standard provider, // generate an error. if (!string.Equals("FileSystem", provider.Name, StringComparison.OrdinalIgnoreCase)) { ThrowTerminatingError(errorRecord); return; } // If it resolved to more than one path, // generate an error. if (newPaths.Count > 1) { ThrowTerminatingError(errorRecord); return; } // It didn't resolve to any files. They may // want to create the file. else if (newPaths.Count == 0) { // We can't create one with wildcard characters if (WildcardPattern.ContainsWildcardCharacters(_outputAssembly)) { ThrowTerminatingError(errorRecord); } // Create the file else { _outputAssembly = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_outputAssembly); } } // It resolved to a single file else { _outputAssembly = newPaths[0]; } } } } private string _outputAssembly = null; /// <summary> /// The output type of the assembly. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] [Alias("OT")] public OutputAssemblyType OutputType { get; set; } = OutputAssemblyType.Library; /// <summary> /// Flag to pass the resulting types along. /// </summary> [Parameter()] public SwitchParameter PassThru { get; set; } /// <summary> /// Flag to ignore warnings during compilation. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] public SwitchParameter IgnoreWarnings { get; set; } /// <summary> /// Roslyn command line parameters. /// https://github.com/dotnet/roslyn/blob/master/docs/compilers/CSharp/CommandLine.md /// /// Parser options: /// langversion:string - language version from: /// [enum]::GetNames([Microsoft.CodeAnalysis.CSharp.LanguageVersion]) /// define:symbol list - preprocessor symbols: /// /define:UNIX,DEBUG - CSharp /// /// Compilation options: /// optimize{+|-} - optimization level /// parallel{+|-} - concurrent build /// warnaserror{+|-} - report warnings to errors /// warnaserror{+|-}:strings - report specific warnings to errors /// warn:number - warning level (0-4) for CSharp /// nowarn - disable all warnings /// nowarn:strings - disable a list of individual warnings /// usings:strings - ';'-delimited usings for CSharp /// /// Emit options: /// platform:string - limit which platforms this code can run on; must be x86, x64, Itanium, arm, AnyCPU32BitPreferred or anycpu (default) /// delaysign{+|-} - delay-sign the assembly using only the public portion of the strong name key /// keyfile:file - specifies a strong name key file /// keycontainer:string - specifies a strong name key container /// highentropyva{+|-} - enable high-entropy ASLR. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] [ValidateNotNullOrEmpty] public string[] CompilerOptions { get; set; } #endregion Parameters #region GererateSource private string GenerateTypeSource(string typeNamespace, string typeName, string sourceCodeText, Language language) { string usingSource = string.Format( CultureInfo.InvariantCulture, GetUsingTemplate(language), GetUsingSet(language)); string typeSource = string.Format( CultureInfo.InvariantCulture, GetMethodTemplate(language), typeName, sourceCodeText); if (!string.IsNullOrEmpty(typeNamespace)) { return usingSource + string.Format( CultureInfo.InvariantCulture, GetNamespaceTemplate(language), typeNamespace, typeSource); } else { return usingSource + typeSource; } } // Get the -FromMember template for a given language private static string GetMethodTemplate(Language language) { switch (language) { case Language.CSharp: return " public class {0}\n" + " {{\n" + " {1}\n" + " }}\n"; } throw PSTraceSource.NewNotSupportedException(); } // Get the -FromMember namespace template for a given language private static string GetNamespaceTemplate(Language language) { switch (language) { case Language.CSharp: return "namespace {0}\n" + "{{\n" + "{1}\n" + "}}\n"; } throw PSTraceSource.NewNotSupportedException(); } // Get the -FromMember namespace template for a given language private static string GetUsingTemplate(Language language) { switch (language) { case Language.CSharp: return "using System;\n" + "using System.Runtime.InteropServices;\n" + "{0}" + "\n"; } throw PSTraceSource.NewNotSupportedException(); } // Generate the code for the using statements private string GetUsingSet(Language language) { StringBuilder usingNamespaceSet = new(); switch (language) { case Language.CSharp: foreach (string namespaceValue in UsingNamespace) { usingNamespaceSet.Append("using " + namespaceValue + ";\n"); } break; default: throw PSTraceSource.NewNotSupportedException(); } return usingNamespaceSet.ToString(); } #endregion GererateSource /// <summary> /// Prevent code compilation in ConstrainedLanguage mode. /// </summary> protected override void BeginProcessing() { // Prevent code compilation in ConstrainedLanguage mode, or NoLanguage mode under system lock down. if (SessionState.LanguageMode == PSLanguageMode.ConstrainedLanguage || (SessionState.LanguageMode == PSLanguageMode.NoLanguage && SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)) { ThrowTerminatingError( new ErrorRecord( new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), nameof(AddTypeStrings.CannotDefineNewType), ErrorCategory.PermissionDenied, targetObject: null)); } // 'ConsoleApplication' and 'WindowsApplication' types are currently not working in .NET Core if (OutputType != OutputAssemblyType.Library) { ThrowTerminatingError( new ErrorRecord( new PSNotSupportedException(AddTypeStrings.AssemblyTypeNotSupported), nameof(AddTypeStrings.AssemblyTypeNotSupported), ErrorCategory.NotImplemented, targetObject: OutputType)); } } /// <summary> /// Generate and load the type(s). /// </summary> protected override void EndProcessing() { // Generate an error if they've specified an output // assembly type without an output assembly if (string.IsNullOrEmpty(_outputAssembly) && this.MyInvocation.BoundParameters.ContainsKey(nameof(OutputType))) { ErrorRecord errorRecord = new( new Exception( string.Format( CultureInfo.CurrentCulture, AddTypeStrings.OutputTypeRequiresOutputAssembly)), "OUTPUTTYPE_REQUIRES_ASSEMBLY", ErrorCategory.InvalidArgument, OutputType); ThrowTerminatingError(errorRecord); return; } if (_loadAssembly) { // File extension is ".DLL" (ParameterSetName = FromPathParameterSetName or FromLiteralPathParameterSetName). LoadAssemblies(_paths); } else if (ParameterSetName == FromAssemblyNameParameterSetName) { LoadAssemblies(AssemblyName); } else { // Process a source code from files or strings. SourceCodeProcessing(); } } #region LoadAssembly // We now ship .NET Core's reference assemblies with PowerShell, so that Add-Type can work // in a predictable way and won't be broken when we move to newer version of .NET Core. // The reference assemblies are located at '$PSHOME\ref' for pwsh. // // For applications that host PowerShell, the 'ref' folder will be deployed to the 'publish' // folder, not where 'System.Management.Automation.dll' is located. So here we should use // the entry assembly's location to construct the path to the 'ref' folder. // For pwsh, the entry assembly is 'pwsh.dll', so the entry assembly's location is still // $PSHOME. // However, 'Assembly.GetEntryAssembly()' returns null when the managed code is called from // unmanaged code (PowerShell WSMan remoting scenario), so in that case, we continue to use // the location of 'System.Management.Automation.dll'. private static readonly string s_netcoreAppRefFolder = PathType.Combine( PathType.GetDirectoryName( (Assembly.GetEntryAssembly() ?? typeof(PSObject).Assembly).Location), "ref"); // Path to the folder where .NET Core runtime assemblies are located. private static readonly string s_frameworkFolder = PathType.GetDirectoryName(typeof(object).Assembly.Location); // These assemblies are always automatically added to ReferencedAssemblies. private static readonly Lazy<PortableExecutableReference[]> s_autoReferencedAssemblies = new(InitAutoIncludedRefAssemblies); // A HashSet of assembly names to be ignored if they are specified in '-ReferencedAssemblies' private static readonly Lazy<HashSet<string>> s_refAssemblyNamesToIgnore = new(InitRefAssemblyNamesToIgnore); // These assemblies are used, when ReferencedAssemblies parameter is not specified. private static readonly Lazy<IEnumerable<PortableExecutableReference>> s_defaultAssemblies = new(InitDefaultRefAssemblies); private bool InMemory { get { return string.IsNullOrEmpty(_outputAssembly); } } // These dictionaries prevent reloading already loaded and unchanged code. // We don't worry about unbounded growing of the cache because in .Net Core 2.0 we can not unload assemblies. // TODO: review if we will be able to unload assemblies after migrating to .Net Core 2.1. private static readonly HashSet<string> s_sourceTypesCache = new(); private static readonly Dictionary<int, Assembly> s_sourceAssemblyCache = new(); private static readonly string s_defaultSdkDirectory = Utils.DefaultPowerShellAppBase; private const ReportDiagnostic defaultDiagnosticOption = ReportDiagnostic.Error; private static readonly string[] s_writeInformationTags = new string[] { "PSHOST" }; private int _syntaxTreesHash; private const string FromMemberParameterSetName = "FromMember"; private const string FromSourceParameterSetName = "FromSource"; private const string FromPathParameterSetName = "FromPath"; private const string FromLiteralPathParameterSetName = "FromLiteralPath"; private const string FromAssemblyNameParameterSetName = "FromAssemblyName"; private void LoadAssemblies(IEnumerable<string> assemblies) { foreach (string assemblyName in assemblies) { // CoreCLR doesn't allow re-load TPA assemblies with different API (i.e. we load them by name and now want to load by path). // LoadAssemblyHelper helps us avoid re-loading them, if they already loaded. Assembly assembly = LoadAssemblyHelper(assemblyName) ?? Assembly.LoadFrom(ResolveAssemblyName(assemblyName, false)); if (PassThru) { WriteTypes(assembly); } } } /// <summary> /// Initialize the list of reference assemblies that will be used when '-ReferencedAssemblies' is not specified. /// </summary> private static IEnumerable<PortableExecutableReference> InitDefaultRefAssemblies() { // Define number of reference assemblies distributed with PowerShell. const int maxPowershellRefAssemblies = 160; const int capacity = maxPowershellRefAssemblies + 1; var defaultRefAssemblies = new List<PortableExecutableReference>(capacity); foreach (string file in Directory.EnumerateFiles(s_netcoreAppRefFolder, "*.dll", SearchOption.TopDirectoryOnly)) { defaultRefAssemblies.Add(MetadataReference.CreateFromFile(file)); } // Add System.Management.Automation.dll defaultRefAssemblies.Add(MetadataReference.CreateFromFile(typeof(PSObject).Assembly.Location)); // We want to avoid reallocating the internal array, so we assert if the list capacity has increased. Diagnostics.Assert( defaultRefAssemblies.Capacity <= capacity, $"defaultRefAssemblies was resized because of insufficient initial capacity! A capacity of {defaultRefAssemblies.Count} is required."); return defaultRefAssemblies; } /// <summary> /// Initialize the set of assembly names that should be ignored when they are specified in '-ReferencedAssemblies'. /// - System.Private.CoreLib.ni.dll - the runtime dll that contains most core/primitive types /// - System.Private.Uri.dll - the runtime dll that contains 'System.Uri' and related types /// Referencing these runtime dlls may cause ambiguous type identity or other issues. /// - System.Runtime.dll - the corresponding reference dll will be automatically included /// - System.Runtime.InteropServices.dll - the corresponding reference dll will be automatically included. /// </summary> private static HashSet<string> InitRefAssemblyNamesToIgnore() { return new HashSet<string>(StringComparer.OrdinalIgnoreCase) { PathType.GetFileName(typeof(object).Assembly.Location), PathType.GetFileName(typeof(Uri).Assembly.Location), PathType.GetFileName(GetReferenceAssemblyPathBasedOnType(typeof(object))), PathType.GetFileName(GetReferenceAssemblyPathBasedOnType(typeof(SecureString))) }; } /// <summary> /// Initialize the list of reference assemblies that will be automatically added when '-ReferencedAssemblies' is specified. /// </summary> private static PortableExecutableReference[] InitAutoIncludedRefAssemblies() { return new PortableExecutableReference[] { MetadataReference.CreateFromFile(GetReferenceAssemblyPathBasedOnType(typeof(object))), MetadataReference.CreateFromFile(GetReferenceAssemblyPathBasedOnType(typeof(SecureString))) }; } /// <summary> /// Get the path of reference assembly where the type is declared. /// </summary> private static string GetReferenceAssemblyPathBasedOnType(Type type) { string refAsmFileName = PathType.GetFileName(ClrFacade.GetAssemblies(type.FullName).First().Location); return PathType.Combine(s_netcoreAppRefFolder, refAsmFileName); } private string ResolveAssemblyName(string assembly, bool isForReferenceAssembly) { ErrorRecord errorRecord; // if it's a path, resolve it if (assembly.Contains(PathType.DirectorySeparatorChar) || assembly.Contains(PathType.AltDirectorySeparatorChar)) { if (PathType.IsPathRooted(assembly)) { return assembly; } else { var paths = SessionState.Path.GetResolvedPSPathFromPSPath(assembly); if (paths.Count > 0) { return paths[0].Path; } else { errorRecord = new ErrorRecord( new Exception( string.Format(ParserStrings.ErrorLoadingAssembly, assembly)), "ErrorLoadingAssembly", ErrorCategory.InvalidOperation, assembly); ThrowTerminatingError(errorRecord); return null; } } } string refAssemblyDll = assembly; if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { // It could be a short assembly name or a full assembly name, but we // always want the short name to find the corresponding assembly file. var assemblyName = new AssemblyName(assembly); refAssemblyDll = assemblyName.Name + ".dll"; } // We look up in reference/framework only when it's for resolving reference assemblies. // In case of 'Add-Type -AssemblyName' scenario, we don't attempt to resolve against framework assemblies because // 1. Explicitly loading a framework assembly usually is not necessary in PowerShell 6+. // 2. A user should use assembly name instead of path if they want to explicitly load a framework assembly. if (isForReferenceAssembly) { // If it's for resolving a reference assembly, then we look in NetCoreApp ref assemblies first string netcoreAppRefPath = PathType.Combine(s_netcoreAppRefFolder, refAssemblyDll); if (File.Exists(netcoreAppRefPath)) { return netcoreAppRefPath; } // Look up the assembly in the framework folder. This may happen when assembly is not part of // NetCoreApp, but comes from an additional package, such as 'Json.Net'. string frameworkPossiblePath = PathType.Combine(s_frameworkFolder, refAssemblyDll); if (File.Exists(frameworkPossiblePath)) { return frameworkPossiblePath; } // The assembly name may point to a third-party assembly that is already loaded at run time. if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { Assembly result = LoadAssemblyHelper(assembly); if (result != null) { return result.Location; } } } // Look up the assembly in the current folder var resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(refAssemblyDll); if (resolvedPaths.Count > 0) { string currentFolderPath = resolvedPaths[0].Path; if (File.Exists(currentFolderPath)) { return currentFolderPath; } } errorRecord = new ErrorRecord( new Exception( string.Format(ParserStrings.ErrorLoadingAssembly, assembly)), "ErrorLoadingAssembly", ErrorCategory.InvalidOperation, assembly); ThrowTerminatingError(errorRecord); return null; } // LoadWithPartialName is deprecated, so we have to write the closest approximation possible. // However, this does give us a massive usability improvement, as users can just say // Add-Type -AssemblyName Forms (instead of System.Windows.Forms) // This is just long, not unmaintainable. private static Assembly LoadAssemblyHelper(string assemblyName) { Assembly loadedAssembly = null; // First try by strong name try { loadedAssembly = Assembly.Load(new AssemblyName(assemblyName)); } // Generates a FileNotFoundException if you can't load the strong type. // So we'll try from the short name. catch (System.IO.FileNotFoundException) { } // File load exception can happen, when we trying to load from the incorrect assembly name // or file corrupted. catch (System.IO.FileLoadException) { } return loadedAssembly; } private IEnumerable<PortableExecutableReference> GetPortableExecutableReferences() { if (ReferencedAssemblies.Length > 0) { var tempReferences = new List<PortableExecutableReference>(s_autoReferencedAssemblies.Value); foreach (string assembly in ReferencedAssemblies) { if (string.IsNullOrWhiteSpace(assembly)) { continue; } string resolvedAssemblyPath = ResolveAssemblyName(assembly, true); // Ignore some specified reference assemblies string fileName = PathType.GetFileName(resolvedAssemblyPath); if (s_refAssemblyNamesToIgnore.Value.Contains(fileName)) { WriteVerbose(StringUtil.Format(AddTypeStrings.ReferenceAssemblyIgnored, resolvedAssemblyPath)); continue; } tempReferences.Add(MetadataReference.CreateFromFile(resolvedAssemblyPath)); } return tempReferences; } else { return s_defaultAssemblies.Value; } } private void WriteTypes(Assembly assembly) { WriteObject(assembly.GetTypes(), true); } #endregion LoadAssembly #region SourceCodeProcessing private static OutputKind OutputAssemblyTypeToOutputKind(OutputAssemblyType outputType) { switch (outputType) { case OutputAssemblyType.Library: return OutputKind.DynamicallyLinkedLibrary; default: throw PSTraceSource.NewNotSupportedException(); } } private CommandLineArguments ParseCompilerOption(IEnumerable<string> args) { string sdkDirectory = s_defaultSdkDirectory; string baseDirectory = this.SessionState.Path.CurrentLocation.Path; switch (Language) { case Language.CSharp: return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory); default: throw PSTraceSource.NewNotSupportedException(); } } private SyntaxTree ParseSourceText(SourceText sourceText, ParseOptions parseOptions, string path = "") { switch (Language) { case Language.CSharp: return CSharpSyntaxTree.ParseText(sourceText, (CSharpParseOptions)parseOptions, path); default: throw PSTraceSource.NewNotSupportedException(); } } private CompilationOptions GetDefaultCompilationOptions() { switch (Language) { case Language.CSharp: return new CSharpCompilationOptions(OutputAssemblyTypeToOutputKind(OutputType)); default: throw PSTraceSource.NewNotSupportedException(); } } private bool isSourceCodeUpdated(List<SyntaxTree> syntaxTrees, out Assembly assembly) { Diagnostics.Assert(syntaxTrees.Count != 0, "syntaxTrees should contains a source code."); _syntaxTreesHash = SyntaxTreeArrayGetHashCode(syntaxTrees); if (s_sourceAssemblyCache.TryGetValue(_syntaxTreesHash, out Assembly hashedAssembly)) { assembly = hashedAssembly; return false; } else { assembly = null; return true; } } private void SourceCodeProcessing() { ParseOptions parseOptions = null; CompilationOptions compilationOptions = null; EmitOptions emitOptions = null; if (CompilerOptions != null) { var arguments = ParseCompilerOption(CompilerOptions); HandleCompilerErrors(arguments.Errors); parseOptions = arguments.ParseOptions; compilationOptions = arguments.CompilationOptions.WithOutputKind(OutputAssemblyTypeToOutputKind(OutputType)); emitOptions = arguments.EmitOptions; } else { parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); compilationOptions = GetDefaultCompilationOptions(); } if (!IgnoreWarnings.IsPresent) { compilationOptions = compilationOptions.WithGeneralDiagnosticOption(defaultDiagnosticOption); } SourceText sourceText; List<SyntaxTree> syntaxTrees = new(); switch (ParameterSetName) { case FromPathParameterSetName: case FromLiteralPathParameterSetName: foreach (string filePath in _paths) { using (var sourceFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { sourceText = SourceText.From(sourceFile); syntaxTrees.Add(ParseSourceText(sourceText, parseOptions, path: filePath)); } } break; case FromMemberParameterSetName: _sourceCode = GenerateTypeSource(Namespace, Name, _sourceCode, Language); sourceText = SourceText.From(_sourceCode); syntaxTrees.Add(ParseSourceText(sourceText, parseOptions)); break; case FromSourceParameterSetName: sourceText = SourceText.From(_sourceCode); syntaxTrees.Add(ParseSourceText(sourceText, parseOptions)); break; default: Diagnostics.Assert(false, "Invalid parameter set: {0}", this.ParameterSetName); break; } if (!string.IsNullOrEmpty(_outputAssembly) && !PassThru.IsPresent) { CompileToAssembly(syntaxTrees, compilationOptions, emitOptions); } else { // if the source code was already compiled and loaded and not changed // we get the assembly from the cache. if (isSourceCodeUpdated(syntaxTrees, out Assembly assembly)) { CompileToAssembly(syntaxTrees, compilationOptions, emitOptions); } else { WriteVerbose(AddTypeStrings.AlreadyCompiledandLoaded); if (PassThru) { WriteTypes(assembly); } } } } private void CompileToAssembly(List<SyntaxTree> syntaxTrees, CompilationOptions compilationOptions, EmitOptions emitOptions) { IEnumerable<PortableExecutableReference> references = GetPortableExecutableReferences(); Compilation compilation = null; switch (Language) { case Language.CSharp: compilation = CSharpCompilation.Create( PathType.GetRandomFileName(), syntaxTrees: syntaxTrees, references: references, options: (CSharpCompilationOptions)compilationOptions); break; default: throw PSTraceSource.NewNotSupportedException(); } DoEmitAndLoadAssembly(compilation, emitOptions); } private void CheckDuplicateTypes(Compilation compilation, out ConcurrentBag<string> newTypes) { AllNamedTypeSymbolsVisitor visitor = new(); visitor.Visit(compilation.Assembly.GlobalNamespace); foreach (var symbolName in visitor.DuplicateSymbols) { ErrorRecord errorRecord = new( new Exception( string.Format(AddTypeStrings.TypeAlreadyExists, symbolName)), "TYPE_ALREADY_EXISTS", ErrorCategory.InvalidOperation, symbolName); WriteError(errorRecord); } if (!visitor.DuplicateSymbols.IsEmpty) { ErrorRecord errorRecord = new( new InvalidOperationException(AddTypeStrings.CompilerErrors), "COMPILER_ERRORS", ErrorCategory.InvalidData, null); ThrowTerminatingError(errorRecord); } newTypes = visitor.UniqueSymbols; return; } // Visit symbols in all namespaces and collect duplicates. private sealed class AllNamedTypeSymbolsVisitor : SymbolVisitor { public readonly ConcurrentBag<string> DuplicateSymbols = new(); public readonly ConcurrentBag<string> UniqueSymbols = new(); public override void VisitNamespace(INamespaceSymbol symbol) { // Main cycle. // For large files we could use symbol.GetMembers().AsParallel().ForAll(s => s.Accept(this)); foreach (var member in symbol.GetMembers()) { member.Accept(this); } } public override void VisitNamedType(INamedTypeSymbol symbol) { // It is namespace-fully-qualified name var symbolFullName = symbol.ToString(); if (s_sourceTypesCache.TryGetValue(symbolFullName, out _)) { DuplicateSymbols.Add(symbolFullName); } else { UniqueSymbols.Add(symbolFullName); } } } private static void CacheNewTypes(ConcurrentBag<string> newTypes) { foreach (var typeName in newTypes) { s_sourceTypesCache.Add(typeName); } } private void CacheAssembly(Assembly assembly) { s_sourceAssemblyCache.Add(_syntaxTreesHash, assembly); } private void DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOptions) { EmitResult emitResult; CheckDuplicateTypes(compilation, out ConcurrentBag<string> newTypes); if (InMemory) { using (var ms = new MemoryStream()) { emitResult = compilation.Emit(peStream: ms, options: emitOptions); HandleCompilerErrors(emitResult.Diagnostics); if (emitResult.Success) { // TODO: We could use Assembly.LoadFromStream() in future. // See https://github.com/dotnet/corefx/issues/26994 ms.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); CacheNewTypes(newTypes); CacheAssembly(assembly); if (PassThru) { WriteTypes(assembly); } } } } else { using (var fs = new FileStream(_outputAssembly, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) { emitResult = compilation.Emit(peStream: fs, options: emitOptions); } HandleCompilerErrors(emitResult.Diagnostics); if (emitResult.Success && PassThru) { Assembly assembly = Assembly.LoadFrom(_outputAssembly); CacheNewTypes(newTypes); CacheAssembly(assembly); WriteTypes(assembly); } } } private void HandleCompilerErrors(ImmutableArray<Diagnostic> compilerDiagnostics) { if (compilerDiagnostics.Length > 0) { bool IsError = false; foreach (var diagnisticRecord in compilerDiagnostics) { // We shouldn't specify input and output files in CompilerOptions parameter // so suppress errors from Roslyn default command line parser: // CS1562: Outputs without source must have the /out option specified // CS2008: No inputs specified // BC2008: No inputs specified // // On emit phase some warnings (like CS8019/BS50001) don't suppressed // and present in diagnostic report with DefaultSeverity equal to Hidden // so we skip them explicitly here too. if (diagnisticRecord.IsSuppressed || diagnisticRecord.DefaultSeverity == DiagnosticSeverity.Hidden || string.Equals(diagnisticRecord.Id, "CS2008", StringComparison.InvariantCulture) || string.Equals(diagnisticRecord.Id, "CS1562", StringComparison.InvariantCulture) || string.Equals(diagnisticRecord.Id, "BC2008", StringComparison.InvariantCulture)) { continue; } if (!IsError) { IsError = diagnisticRecord.Severity == DiagnosticSeverity.Error || (diagnisticRecord.IsWarningAsError && diagnisticRecord.Severity == DiagnosticSeverity.Warning); } string errorText = BuildErrorMessage(diagnisticRecord); if (diagnisticRecord.Severity == DiagnosticSeverity.Warning) { WriteWarning(errorText); } else if (diagnisticRecord.Severity == DiagnosticSeverity.Info) { WriteInformation(errorText, s_writeInformationTags); } else { ErrorRecord errorRecord = new( new Exception(errorText), "SOURCE_CODE_ERROR", ErrorCategory.InvalidData, diagnisticRecord); WriteError(errorRecord); } } if (IsError) { ErrorRecord errorRecord = new( new InvalidOperationException(AddTypeStrings.CompilerErrors), "COMPILER_ERRORS", ErrorCategory.InvalidData, null); ThrowTerminatingError(errorRecord); } } } private static string BuildErrorMessage(Diagnostic diagnisticRecord) { var location = diagnisticRecord.Location; if (location.SourceTree == null) { // For some error types (linker?) we don't have related source code. return diagnisticRecord.ToString(); } else { var text = location.SourceTree.GetText(); var textLines = text.Lines; var lineSpan = location.GetLineSpan(); // FileLinePositionSpan type. var errorLineNumber = lineSpan.StartLinePosition.Line; // This is typical Roslyn diagnostic message which contains // a message number, a source context and an error position. var diagnisticMessage = diagnisticRecord.ToString(); var errorLineString = textLines[errorLineNumber].ToString(); var errorPosition = lineSpan.StartLinePosition.Character; StringBuilder sb = new(diagnisticMessage.Length + errorLineString.Length * 2 + 4); sb.AppendLine(diagnisticMessage); sb.AppendLine(errorLineString); for (var i = 0; i < errorLineString.Length; i++) { if (!char.IsWhiteSpace(errorLineString[i])) { // We copy white chars from the source string. sb.Append(errorLineString, 0, i); // then pad up to the error position. sb.Append(' ', Math.Max(0, errorPosition - i)); // then put "^" into the error position. sb.AppendLine("^"); break; } } return sb.ToString(); } } private static int SyntaxTreeArrayGetHashCode(IEnumerable<SyntaxTree> sts) { // We use our extension method EnumerableExtensions.SequenceGetHashCode<T>(). List<int> stHashes = new(); foreach (var st in sts) { stHashes.Add(SyntaxTreeGetHashCode(st)); } return stHashes.SequenceGetHashCode<int>(); } private static int SyntaxTreeGetHashCode(SyntaxTree st) { int hash; if (string.IsNullOrEmpty(st.FilePath)) { // If the file name does not exist, the source text is set by the user using parameters. // In this case, we assume that the source text is of a small size and we can re-allocate by ToString(). hash = st.ToString().GetHashCode(); } else { // If the file was modified, the write time stamp was also modified // so we do not need to calculate the entire file hash. var updateTime = File.GetLastWriteTimeUtc(st.FilePath); hash = Utils.CombineHashCodes(st.FilePath.GetHashCode(), updateTime.GetHashCode()); } return hash; } #endregion SourceCodeProcessing } }
using System; using EventHandlerList = System.ComponentModel.EventHandlerList; using BitSet = antlr.collections.impl.BitSet; using AST = antlr.collections.AST; using ASTArray = antlr.collections.impl.ASTArray; using antlr.debug; using MessageListener = antlr.debug.MessageListener; using ParserListener = antlr.debug.ParserListener; using ParserMatchListener = antlr.debug.ParserMatchListener; using ParserTokenListener = antlr.debug.ParserTokenListener; using SemanticPredicateListener = antlr.debug.SemanticPredicateListener; using SyntacticPredicateListener = antlr.debug.SyntacticPredicateListener; using TraceListener = antlr.debug.TraceListener; /* private Vector messageListeners; private Vector newLineListeners; private Vector matchListeners; private Vector tokenListeners; private Vector semPredListeners; private Vector synPredListeners; private Vector traceListeners; */ namespace antlr { /*ANTLR Translator Generator * Project led by Terence Parr at http://www.jGuru.com * Software rights: http://www.antlr.org/license.html * * $Id:$ */ // // ANTLR C# Code Generator by Micheal Jordan // Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com // Anthony Oguntimehin // // With many thanks to Eric V. Smith from the ANTLR list. // public abstract class Parser : IParserDebugSubject { // Used to store event delegates private EventHandlerList events_ = new EventHandlerList(); protected internal EventHandlerList Events { get { return events_; } } // The unique keys for each event that Parser [objects] can generate internal static readonly object EnterRuleEventKey = new object(); internal static readonly object ExitRuleEventKey = new object(); internal static readonly object DoneEventKey = new object(); internal static readonly object ReportErrorEventKey = new object(); internal static readonly object ReportWarningEventKey = new object(); internal static readonly object NewLineEventKey = new object(); internal static readonly object MatchEventKey = new object(); internal static readonly object MatchNotEventKey = new object(); internal static readonly object MisMatchEventKey = new object(); internal static readonly object MisMatchNotEventKey = new object(); internal static readonly object ConsumeEventKey = new object(); internal static readonly object LAEventKey = new object(); internal static readonly object SemPredEvaluatedEventKey = new object(); internal static readonly object SynPredStartedEventKey = new object(); internal static readonly object SynPredFailedEventKey = new object(); internal static readonly object SynPredSucceededEventKey = new object(); protected internal ParserSharedInputState inputState; /*Nesting level of registered handlers */ // protected int exceptionLevel = 0; /*Table of token type to token names */ protected internal string[] tokenNames; /*AST return value for a rule is squirreled away here */ protected internal AST returnAST; /*AST support code; parser and treeparser delegate to this object */ protected internal ASTFactory astFactory = new ASTFactory(); private bool ignoreInvalidDebugCalls = false; /*Used to keep track of indentdepth for traceIn/Out */ protected internal int traceDepth = 0; public Parser() { inputState = new ParserSharedInputState(); } public Parser(ParserSharedInputState state) { inputState = state; } /// <summary> /// /// </summary> public event TraceEventHandler EnterRule { add { Events.AddHandler(EnterRuleEventKey, value); } remove { Events.RemoveHandler(EnterRuleEventKey, value); } } public event TraceEventHandler ExitRule { add { Events.AddHandler(ExitRuleEventKey, value); } remove { Events.RemoveHandler(ExitRuleEventKey, value); } } public event TraceEventHandler Done { add { Events.AddHandler(DoneEventKey, value); } remove { Events.RemoveHandler(DoneEventKey, value); } } public event MessageEventHandler ErrorReported { add { Events.AddHandler(ReportErrorEventKey, value); } remove { Events.RemoveHandler(ReportErrorEventKey, value); } } public event MessageEventHandler WarningReported { add { Events.AddHandler(ReportWarningEventKey, value); } remove { Events.RemoveHandler(ReportWarningEventKey, value); } } public event MatchEventHandler MatchedToken { add { Events.AddHandler(MatchEventKey, value); } remove { Events.RemoveHandler(MatchEventKey, value); } } public event MatchEventHandler MatchedNotToken { add { Events.AddHandler(MatchNotEventKey, value); } remove { Events.RemoveHandler(MatchNotEventKey, value); } } public event MatchEventHandler MisMatchedToken { add { Events.AddHandler(MisMatchEventKey, value); } remove { Events.RemoveHandler(MisMatchEventKey, value); } } public event MatchEventHandler MisMatchedNotToken { add { Events.AddHandler(MisMatchNotEventKey, value); } remove { Events.RemoveHandler(MisMatchNotEventKey, value); } } public event TokenEventHandler ConsumedToken { add { Events.AddHandler(ConsumeEventKey, value); } remove { Events.RemoveHandler(ConsumeEventKey, value); } } public event TokenEventHandler TokenLA { add { Events.AddHandler(LAEventKey, value); } remove { Events.RemoveHandler(LAEventKey, value); } } public event SemanticPredicateEventHandler SemPredEvaluated { add { Events.AddHandler(SemPredEvaluatedEventKey, value); } remove { Events.RemoveHandler(SemPredEvaluatedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredStarted { add { Events.AddHandler(SynPredStartedEventKey, value); } remove { Events.RemoveHandler(SynPredStartedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredFailed { add { Events.AddHandler(SynPredFailedEventKey, value); } remove { Events.RemoveHandler(SynPredFailedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredSucceeded { add { Events.AddHandler(SynPredSucceededEventKey, value); } remove { Events.RemoveHandler(SynPredSucceededEventKey, value); } } public virtual void addMessageListener(MessageListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addMessageListener() is only valid if parser built for debugging"); } public virtual void addParserListener(ParserListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserListener() is only valid if parser built for debugging"); } public virtual void addParserMatchListener(ParserMatchListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserMatchListener() is only valid if parser built for debugging"); } public virtual void addParserTokenListener(ParserTokenListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserTokenListener() is only valid if parser built for debugging"); } public virtual void addSemanticPredicateListener(SemanticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addSemanticPredicateListener() is only valid if parser built for debugging"); } public virtual void addSyntacticPredicateListener(SyntacticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addSyntacticPredicateListener() is only valid if parser built for debugging"); } public virtual void addTraceListener(TraceListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addTraceListener() is only valid if parser built for debugging"); } /*Get another token object from the token stream */ public abstract void consume(); /*Consume tokens until one matches the given token */ public virtual void consumeUntil(int tokenType) { while (LA(1) != Token.EOF_TYPE && LA(1) != tokenType) { consume(); } } /*Consume tokens until one matches the given token set */ public virtual void consumeUntil(BitSet bset) { while (LA(1) != Token.EOF_TYPE && !bset.member(LA(1))) { consume(); } } protected internal virtual void defaultDebuggingSetup(TokenStream lexer, TokenBuffer tokBuf) { // by default, do nothing -- we're not debugging } /*Get the AST return value squirreled away in the parser */ public virtual AST getAST() { return returnAST; } public virtual ASTFactory getASTFactory() { return astFactory; } public virtual string getFilename() { return inputState.filename; } public virtual ParserSharedInputState getInputState() { return inputState; } public virtual void setInputState(ParserSharedInputState state) { inputState = state; } public virtual void resetState() { traceDepth = 0; inputState.reset(); } public virtual string getTokenName(int num) { return tokenNames[num]; } public virtual string[] getTokenNames() { return tokenNames; } public virtual bool isDebugMode() { return false; } /*Return the token type of the ith token of lookahead where i=1 * is the current token being examined by the parser (i.e., it * has not been matched yet). */ public abstract int LA(int i); /*Return the ith token of lookahead */ public abstract IToken LT(int i); // Forwarded to TokenBuffer public virtual int mark() { return inputState.input.mark(); } /*Make sure current lookahead symbol matches token type <tt>t</tt>. * Throw an exception upon mismatch, which is catch by either the * error handler or by the syntactic predicate. */ public virtual void match(int t) { if (LA(1) != t) throw new MismatchedTokenException(tokenNames, LT(1), t, false, getFilename()); else consume(); } /*Make sure current lookahead symbol matches the given set * Throw an exception upon mismatch, which is catch by either the * error handler or by the syntactic predicate. */ public virtual void match(BitSet b) { if (!b.member(LA(1))) throw new MismatchedTokenException(tokenNames, LT(1), b, false, getFilename()); else consume(); } public virtual void matchNot(int t) { if (LA(1) == t) throw new MismatchedTokenException(tokenNames, LT(1), t, true, getFilename()); else consume(); } /// <summary> /// @deprecated as of 2.7.2. This method calls System.exit() and writes /// directly to stderr, which is usually not appropriate when /// a parser is embedded into a larger application. Since the method is /// <code>static</code>, it cannot be overridden to avoid these problems. /// ANTLR no longer uses this method internally or in generated code. /// </summary> /// [Obsolete("De-activated since version 2.7.2.6 as it cannot be overidden.", true)] public static void panic() { System.Console.Error.WriteLine("Parser: panic"); System.Environment.Exit(1); } public virtual void removeMessageListener(MessageListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeMessageListener() is only valid if parser built for debugging"); } public virtual void removeParserListener(ParserListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserListener() is only valid if parser built for debugging"); } public virtual void removeParserMatchListener(ParserMatchListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserMatchListener() is only valid if parser built for debugging"); } public virtual void removeParserTokenListener(ParserTokenListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserTokenListener() is only valid if parser built for debugging"); } public virtual void removeSemanticPredicateListener(SemanticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("removeSemanticPredicateListener() is only valid if parser built for debugging"); } public virtual void removeSyntacticPredicateListener(SyntacticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("removeSyntacticPredicateListener() is only valid if parser built for debugging"); } public virtual void removeTraceListener(TraceListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeTraceListener() is only valid if parser built for debugging"); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(RecognitionException ex) { Console.Error.WriteLine(ex); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(string s) { if (getFilename() == null) { Console.Error.WriteLine("error: " + s); } else { Console.Error.WriteLine(getFilename() + ": error: " + s); } } /*Parser warning-reporting function can be overridden in subclass */ public virtual void reportWarning(string s) { if (getFilename() == null) { Console.Error.WriteLine("warning: " + s); } else { Console.Error.WriteLine(getFilename() + ": warning: " + s); } } public virtual void recover(RecognitionException ex, BitSet tokenSet) { consume(); consumeUntil(tokenSet); } public virtual void rewind(int pos) { inputState.input.rewind(pos); } /// <summary> /// Specify an object with support code (shared by Parser and TreeParser. /// Normally, the programmer does not play with this, using /// <see cref="setASTNodeClass"/> instead. /// </summary> /// <param name="f"></param> public virtual void setASTFactory(ASTFactory f) { astFactory = f; } /// <summary> /// Specify the type of node to create during tree building. /// </summary> /// <param name="cl">Fully qualified AST Node type name.</param> public virtual void setASTNodeClass(string cl) { astFactory.setASTNodeType(cl); } /// <summary> /// Specify the type of node to create during tree building. /// use <see cref="setASTNodeClass"/> now to be consistent with /// Token Object Type accessor. /// </summary> /// <param name="nodeType">Fully qualified AST Node type name.</param> [Obsolete("Replaced by setASTNodeClass(string) since version 2.7.1", true)] public virtual void setASTNodeType(string nodeType) { setASTNodeClass(nodeType); } public virtual void setDebugMode(bool debugMode) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("setDebugMode() only valid if parser built for debugging"); } public virtual void setFilename(string f) { inputState.filename = f; } public virtual void setIgnoreInvalidDebugCalls(bool Value) { ignoreInvalidDebugCalls = Value; } /*Set or change the input token buffer */ public virtual void setTokenBuffer(TokenBuffer t) { inputState.input = t; } public virtual void traceIndent() { for (int i = 0; i < traceDepth; i++) Console.Out.Write(" "); } public virtual void traceIn(string rname) { traceDepth += 1; traceIndent(); Console.Out.WriteLine("> " + rname + "; LA(1)==" + LT(1).getText() + ((inputState.guessing > 0)?" [guessing]":"")); } public virtual void traceOut(string rname) { traceIndent(); Console.Out.WriteLine("< " + rname + "; LA(1)==" + LT(1).getText() + ((inputState.guessing > 0)?" [guessing]":"")); traceDepth -= 1; } } }
using System; using System.Collections.Generic; using System.Linq; using Haven; using Haven.Utils; using OpenTK; using SharpHaven.Graphics; using SharpHaven.Input; namespace SharpHaven.UI.Widgets { public abstract class Widget : TreeNode<Widget>, IDisposable { private readonly IWidgetHost host; private Rect bounds; private bool isDisposed; private bool isFocused; private bool isHovered; private MouseCursor cursor; protected Widget(IWidgetHost host) { this.host = host; Visible = true; } protected Widget(Widget parent) : this(parent.Host) { parent.AddChild(this); } #region Events public event Action<KeyEvent> KeyDown; public event Action<KeyEvent> KeyUp; public event Action<KeyPressEvent> KeyPress; public event Action<MouseButtonEvent> MouseButtonDown; public event Action<MouseButtonEvent> MouseButtonUp; public event Action<MouseMoveEvent> MouseMove; public event Action<MouseWheelEvent> MouseWheel; #endregion #region Properties protected IWidgetHost Host { get { return host; } } private IEnumerable<Widget> ReversedChildren { get { for (var child = LastChild; child != null; child = child.Previous) yield return child; } } public int X { get { return Position.X; } set { Position = new Point2D(value, Y); } } public int Y { get { return Position.Y; } set { Position = new Point2D(X, value); } } public Point2D Position { get { return bounds.Location; } set { bounds.Location = value; OnPositionChanged(); } } public int Width { get { return Size.X; } set { Size = new Point2D(value, Height); } } public int Height { get { return Size.Y; } set { Size = new Point2D(Width, value); } } public Point2D Size { get { return bounds.Size; } set { bounds.Size = value; OnSizeChanged(); } } public virtual MouseCursor Cursor { get { return cursor ?? Parent?.Cursor; } set { cursor = value; } } public Rect Bounds { get { return bounds; } } public int Margin { get; set; } public bool Visible { get; set; } public bool IsFocusable { get; set; } public bool IsFocused { get { return isFocused; } set { if (isFocused == value) return; isFocused = value; OnFocusChanged(); } } public bool IsHovered { get { return isHovered; } set { if (isHovered == value) return; isHovered = value; OnHoverChanged(); } } public virtual Tooltip Tooltip { get; set; } #endregion #region Public Methods public IEnumerable<Widget> GetChildrenAt(Point2D p) { var result = new List<Widget>(); p = new Point2D(p.X - X - Margin, p.Y - Y - Margin); foreach (var widget in ReversedChildren) { if (widget.Visible) { result.AddRange(widget.GetChildrenAt(p)); if (widget.CheckHit(p.X, p.Y)) result.Add(widget); } } return result; } public Widget GetChildAt(Point2D p) { p = new Point2D(p.X - X - Margin, p.Y - Y - Margin); foreach (var widget in ReversedChildren) { if (widget.Visible) { var child = widget.GetChildAt(p); if (child != null) return child; if (widget.CheckHit(p.X, p.Y)) return widget; } } return null; } public void Dispose() { if (isDisposed) return; OnDispose(); isDisposed = true; } public void Draw(DrawingContext dc) { dc.PushMatrix(); dc.Translate(X, Y); // draw itself OnDraw(dc); // draw all children dc.Translate(Margin, Margin); foreach (var widget in Children.Where(x => x.Visible)) widget.Draw(dc); dc.PopMatrix(); } public void HandleMouseButtonDown(MouseButtonEvent e) { OnMouseButtonDown(e); if (!e.Handled && Parent != null) Parent.OnMouseButtonDown(e); } public void HandleMouseButtonUp(MouseButtonEvent e) { OnMouseButtonUp(e); if (!e.Handled && Parent != null) Parent.OnMouseButtonUp(e); } public void HandleMouseMove(MouseMoveEvent e) { OnMouseMove(e); } public void HandleMouseWheel(MouseWheelEvent e) { OnMouseWheel(e); if (!e.Handled && Parent != null) Parent.HandleMouseWheel(e); } public void HandleKeyDown(KeyEvent e) { OnKeyDown(e); if (!e.Handled && Parent != null) Parent.HandleKeyDown(e); } public void HandleKeyUp(KeyEvent e) { OnKeyUp(e); if (!e.Handled && Parent != null) Parent.HandleKeyUp(e); } public void HandleKeyPress(KeyPressEvent e) { OnKeyPress(e); if (!e.Handled && Parent != null) Parent.HandleKeyPress(e); } public void HandleDrop(DropEvent e) { OnDrop(e); if (!e.Handled && Parent != null) Parent.OnDrop(e); } #endregion #region Protected Methods public Point2D MapFromScreen(Point2D p) { return MapFromScreen(p.X, p.Y); } public Point2D MapFromScreen(int x, int y) { for (var widget = this; widget != null; widget = widget.Parent) { x -= (widget.X + widget.Margin); y -= (widget.Y + widget.Margin); } return new Point2D(x, y); } protected virtual bool CheckHit(int x, int y) { return Bounds.Contains(x, y); } protected virtual void OnMouseButtonDown(MouseButtonEvent e) { MouseButtonDown.Raise(e); } protected virtual void OnMouseButtonUp(MouseButtonEvent e) { MouseButtonUp.Raise(e); } protected virtual void OnMouseMove(MouseMoveEvent e) { MouseMove.Raise(e); } protected virtual void OnMouseWheel(MouseWheelEvent e) { MouseWheel.Raise(e); } protected virtual void OnKeyDown(KeyEvent e) { KeyDown.Raise(e); } protected virtual void OnKeyUp(KeyEvent e) { KeyUp.Raise(e); } protected virtual void OnKeyPress(KeyPressEvent e) { KeyPress.Raise(e); } protected virtual void OnDraw(DrawingContext dc) { } protected virtual void OnDispose() { } protected virtual void OnFocusChanged() { } protected virtual void OnHoverChanged() { } protected virtual void OnPositionChanged() { } protected virtual void OnSizeChanged() { } protected virtual void OnDrop(DropEvent e) { } #endregion } }
using System; using NBitcoin.BouncyCastle.Crypto.Parameters; namespace NBitcoin.BouncyCastle.Crypto.Modes { /** * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. */ public class CfbBlockCipher : IBlockCipher { private byte[] IV; private byte[] cfbV; private byte[] cfbOutV; private bool encrypting; private readonly int blockSize; private readonly IBlockCipher cipher; /** * Basic constructor. * * @param cipher the block cipher to be used as the basis of the * feedback mode. * @param blockSize the block size in bits (note: a multiple of 8) */ public CfbBlockCipher( IBlockCipher cipher, int bitBlockSize) { this.cipher = cipher; this.blockSize = bitBlockSize / 8; this.IV = new byte[cipher.GetBlockSize()]; this.cfbV = new byte[cipher.GetBlockSize()]; this.cfbOutV = new byte[cipher.GetBlockSize()]; } /** * return the underlying block cipher that we are wrapping. * * @return the underlying block cipher that we are wrapping. */ public IBlockCipher GetUnderlyingCipher() { return cipher; } /** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * An IV which is too short is handled in FIPS compliant fashion. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { this.encrypting = forEncryption; if (parameters is ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV) parameters; byte[] iv = ivParam.GetIV(); int diff = IV.Length - iv.Length; Array.Copy(iv, 0, IV, diff, iv.Length); Array.Clear(IV, 0, diff); parameters = ivParam.Parameters; } Reset(); // if it's null, key is to be reused. if (parameters != null) { cipher.Init(true, parameters); } } /** * return the algorithm name and mode. * * @return the name of the underlying algorithm followed by "/CFB" * and the block size in bits. */ public string AlgorithmName { get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); } } public bool IsPartialBlockOkay { get { return true; } } /** * return the block size we are operating at. * * @return the block size we are operating at (in bytes). */ public int GetBlockSize() { return blockSize; } /** * Process one block of input from the array in and write it to * the out array. * * @param in the array containing the input data. * @param inOff offset into the in array the data starts at. * @param out the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { return (encrypting) ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff); } /** * Do the appropriate processing for CFB mode encryption. * * @param in the array containing the data to be encrypted. * @param inOff offset into the in array the data starts at. * @param out the array the encrypted data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int EncryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + blockSize) > outBytes.Length) { throw new DataLengthException("output buffer too short"); } cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); // // XOR the cfbV with the plaintext producing the ciphertext // for (int i = 0; i < blockSize; i++) { outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]); } // // change over the input block. // Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize); Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize); return blockSize; } /** * Do the appropriate processing for CFB mode decryption. * * @param in the array containing the data to be decrypted. * @param inOff offset into the in array the data starts at. * @param out the array the encrypted data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int DecryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + blockSize) > outBytes.Length) { throw new DataLengthException("output buffer too short"); } cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); // // change over the input block. // Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize); Array.Copy(input, inOff, cfbV, cfbV.Length - blockSize, blockSize); // // XOR the cfbV with the ciphertext producing the plaintext // for (int i = 0; i < blockSize; i++) { outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]); } return blockSize; } /** * reset the chaining vector back to the IV and reset the underlying * cipher. */ public void Reset() { Array.Copy(IV, 0, cfbV, 0, IV.Length); cipher.Reset(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using JsonLD.Util; using Newtonsoft.Json.Linq; namespace JsonLD.Util { internal class URL { public string href = string.Empty; public string protocol = string.Empty; public string host = string.Empty; public string auth = string.Empty; public string user = string.Empty; public string password = string.Empty; public string hostname = string.Empty; public string port = string.Empty; public string relative = string.Empty; public string path = string.Empty; public string directory = string.Empty; public string file = string.Empty; public string query = string.Empty; public string hash = string.Empty; public string pathname = null; public string normalizedPath = null; public string authority = null; private static Regex parser = new Regex("^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)"); // things not populated by the regex (NOTE: i don't think it matters if // these are null or "" to start with) public static URL Parse(string url) { URL rval = new URL(); rval.href = url; MatchCollection matches = parser.Matches(url); if (matches.Count > 0) { var matcher = matches[0]; if (matcher.Groups[1] != null) { rval.protocol = matcher.Groups[1].Value; } if (matcher.Groups[2].Value != null) { rval.host = matcher.Groups[2].Value; } if (matcher.Groups[3].Value != null) { rval.auth = matcher.Groups[3].Value; } if (matcher.Groups[4].Value != null) { rval.user = matcher.Groups[4].Value; } if (matcher.Groups[5].Value != null) { rval.password = matcher.Groups[5].Value; } if (matcher.Groups[6].Value != null) { rval.hostname = matcher.Groups[6].Value; } if (matcher.Groups[7].Value != null) { rval.port = matcher.Groups[7].Value; } if (matcher.Groups[8].Value != null) { rval.relative = matcher.Groups[8].Value; } if (matcher.Groups[9].Value != null) { rval.path = matcher.Groups[9].Value; } if (matcher.Groups[10].Value != null) { rval.directory = matcher.Groups[10].Value; } if (matcher.Groups[11].Value != null) { rval.file = matcher.Groups[11].Value; } if (matcher.Groups[12].Value != null) { rval.query = matcher.Groups[12].Value; } if (matcher.Groups[13].Value != null) { rval.hash = matcher.Groups[13].Value; } // normalize to node.js API if (!string.Empty.Equals(rval.host) && string.Empty.Equals(rval.path)) { rval.path = "/"; } rval.pathname = rval.path; ParseAuthority(rval); rval.normalizedPath = RemoveDotSegments(rval.pathname, !string.Empty.Equals(rval.authority)); if (!string.Empty.Equals(rval.query)) { rval.path += "?" + rval.query; } if (!string.Empty.Equals(rval.protocol)) { rval.protocol += ":"; } if (!string.Empty.Equals(rval.hash)) { rval.hash = "#" + rval.hash; } return rval; } return rval; } /// <summary>Removes dot segments from a URL path.</summary> /// <remarks>Removes dot segments from a URL path.</remarks> /// <param name="path">the path to remove dot segments from.</param> /// <param name="hasAuthority">true if the URL has an authority, false if not.</param> public static string RemoveDotSegments(string path, bool hasAuthority) { string rval = string.Empty; if (path.IndexOf("/") == 0) { rval = "/"; } // RFC 3986 5.2.4 (reworked) IList<string> input = new List<string>(System.Linq.Enumerable.ToList(path.Split("/" ))); if (path.EndsWith("/")) { // javascript .split includes a blank entry if the string ends with // the delimiter, java .split does not so we need to add it manually input.Add(string.Empty); } IList<string> output = new List<string>(); for (int i = 0; i < input.Count; i++) { if (".".Equals(input[i]) || (string.Empty.Equals(input[i]) && input.Count - i > 1 )) { // input.remove(0); continue; } if ("..".Equals(input[i])) { // input.remove(0); if (hasAuthority || (output.Count > 0 && !"..".Equals(output[output.Count - 1]))) { // [].pop() doesn't fail, to replicate this we need to check // that there is something to remove if (output.Count > 0) { output.RemoveAt(output.Count - 1); } } else { output.Add(".."); } continue; } output.Add(input[i]); } // input.remove(0); if (output.Count > 0) { rval += output[0]; for (int i_1 = 1; i_1 < output.Count; i_1++) { rval += "/" + output[i_1]; } } return rval; } public static string RemoveBase(JToken baseobj, string iri) { if (baseobj.IsNull()) { return iri; } URL @base; if (baseobj.Type == JTokenType.String) { @base = URL.Parse((string)baseobj); } else { throw new Exception("Arrgggghhh!"); //@base = (URL)baseobj; } // establish base root string root = string.Empty; if (!string.Empty.Equals(@base.href)) { root += (@base.protocol) + "//" + @base.authority; } else { // support network-path reference with empty base if (iri.IndexOf("//") != 0) { root += "//"; } } // IRI not relative to base if (iri.IndexOf(root) != 0) { return iri; } // remove root from IRI and parse remainder URL rel = URL.Parse(JsonLD.JavaCompat.Substring(iri, root.Length)); // remove path segments that match IList<string> baseSegments = new List<string>(System.Linq.Enumerable.ToList(@base .normalizedPath.Split("/"))); baseSegments = baseSegments.Where(seg => seg != "").ToList(); if (@base.normalizedPath.EndsWith("/")) { baseSegments.Add(string.Empty); } IList<string> iriSegments = new List<string>(System.Linq.Enumerable.ToList(rel.normalizedPath .Split("/"))); iriSegments = iriSegments.Where(seg => seg != "").ToList(); if (rel.normalizedPath.EndsWith("/")) { iriSegments.Add(string.Empty); } while (baseSegments.Count > 0 && iriSegments.Count > 0) { if (!baseSegments[0].Equals(iriSegments[0])) { break; } if (baseSegments.Count > 0) { baseSegments.RemoveAt(0); } if (iriSegments.Count > 0) { iriSegments.RemoveAt(0); } } // use '../' for each non-matching base segment string rval = string.Empty; if (baseSegments.Count > 0) { // don't count the last segment if it isn't a path (doesn't end in // '/') // don't count empty first segment, it means base began with '/' if ([email protected]("/") || string.Empty.Equals(baseSegments[0])) { baseSegments.RemoveAt(baseSegments.Count - 1); } for (int i = 0; i < baseSegments.Count; ++i) { rval += "../"; } } // prepend remaining segments if (iriSegments.Count > 0) { rval += iriSegments[0]; } for (int i_1 = 1; i_1 < iriSegments.Count; i_1++) { rval += "/" + iriSegments[i_1]; } // add query and hash if (!string.Empty.Equals(rel.query)) { rval += "?" + rel.query; } if (!string.Empty.Equals(rel.hash)) { rval += rel.hash; } if (string.Empty.Equals(rval)) { rval = "./"; } return rval; } public static string Resolve(string baseUri, string pathToResolve) { // TODO: some input will need to be normalized to perform the expected // result with java // TODO: we can do this without using java URI! if (baseUri == null) { return pathToResolve; } if (pathToResolve == null || string.Empty.Equals(pathToResolve.Trim())) { return baseUri; } try { Uri uri = new Uri(baseUri); // query string parsing if (pathToResolve.StartsWith("?")) { // drop fragment from uri if it has one if (uri.Fragment != null) { uri = new Uri(uri.Scheme + "://" + uri.Authority + uri.AbsolutePath); } // add query to the end manually (as URI.resolve does it wrong) return uri.ToString() + pathToResolve; } uri = new Uri(uri, pathToResolve); // java doesn't discard unnecessary dot segments string path = uri.AbsolutePath; if (path != null) { path = URL.RemoveDotSegments(uri.AbsolutePath, true); } // TODO(sblom): This line is wrong, but works. return new Uri(uri.Scheme + "://" + uri.Authority + path + uri.Query + uri.Fragment).ToString (); } catch { return pathToResolve; } } /// <summary>Parses the authority for the pre-parsed given URL.</summary> /// <remarks>Parses the authority for the pre-parsed given URL.</remarks> /// <param name="parsed">the pre-parsed URL.</param> private static void ParseAuthority(URL parsed) { // parse authority for unparsed relative network-path reference if (parsed.href.IndexOf(":") == -1 && parsed.href.IndexOf("//") == 0 && string.Empty .Equals(parsed.host)) { // must parse authority from pathname parsed.pathname = JsonLD.JavaCompat.Substring(parsed.pathname, 2); int idx = parsed.pathname.IndexOf("/"); if (idx == -1) { parsed.authority = parsed.pathname; parsed.pathname = string.Empty; } else { parsed.authority = JsonLD.JavaCompat.Substring(parsed.pathname, 0, idx); parsed.pathname = JsonLD.JavaCompat.Substring(parsed.pathname, idx); } } else { // construct authority parsed.authority = parsed.host; if (!string.Empty.Equals(parsed.auth)) { parsed.authority = parsed.auth + "@" + parsed.authority; } } } } }