context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type OnenoteResourceRequest. /// </summary> public partial class OnenoteResourceRequest : BaseRequest, IOnenoteResourceRequest { /// <summary> /// Constructs a new OnenoteResourceRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public OnenoteResourceRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified OnenoteResource using POST. /// </summary> /// <param name="onenoteResourceToCreate">The OnenoteResource to create.</param> /// <returns>The created OnenoteResource.</returns> public System.Threading.Tasks.Task<OnenoteResource> CreateAsync(OnenoteResource onenoteResourceToCreate) { return this.CreateAsync(onenoteResourceToCreate, CancellationToken.None); } /// <summary> /// Creates the specified OnenoteResource using POST. /// </summary> /// <param name="onenoteResourceToCreate">The OnenoteResource to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created OnenoteResource.</returns> public async System.Threading.Tasks.Task<OnenoteResource> CreateAsync(OnenoteResource onenoteResourceToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<OnenoteResource>(onenoteResourceToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified OnenoteResource. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified OnenoteResource. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<OnenoteResource>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified OnenoteResource. /// </summary> /// <returns>The OnenoteResource.</returns> public System.Threading.Tasks.Task<OnenoteResource> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified OnenoteResource. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The OnenoteResource.</returns> public async System.Threading.Tasks.Task<OnenoteResource> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<OnenoteResource>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified OnenoteResource using PATCH. /// </summary> /// <param name="onenoteResourceToUpdate">The OnenoteResource to update.</param> /// <returns>The updated OnenoteResource.</returns> public System.Threading.Tasks.Task<OnenoteResource> UpdateAsync(OnenoteResource onenoteResourceToUpdate) { return this.UpdateAsync(onenoteResourceToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified OnenoteResource using PATCH. /// </summary> /// <param name="onenoteResourceToUpdate">The OnenoteResource to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated OnenoteResource.</returns> public async System.Threading.Tasks.Task<OnenoteResource> UpdateAsync(OnenoteResource onenoteResourceToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<OnenoteResource>(onenoteResourceToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IOnenoteResourceRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IOnenoteResourceRequest Expand(Expression<Func<OnenoteResource, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IOnenoteResourceRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IOnenoteResourceRequest Select(Expression<Func<OnenoteResource, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="onenoteResourceToInitialize">The <see cref="OnenoteResource"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(OnenoteResource onenoteResourceToInitialize) { } } }
// Copyright (c) 2021 Alachisoft // // 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 Alachisoft.NCache.IO; using Alachisoft.NCache.Serialization.Surrogates; using Alachisoft.NCache.Common; namespace Alachisoft.NCache.Serialization.Formatters { /// <summary> /// Serializes and deserializes an object, or an entire graph of connected objects, in binary format. /// Uses the compact serialization framework to achieve better stream size and cpu time utlization. /// </summary> /// <remarks> /// <para> /// The basic idea behind space conservation is that every 'known type' is assigned a 2-byte /// type handle by the system. Native .NET serialization stores the complete type information /// with serialized object data, which includes assembly, version and tokens etc. Instead of storing /// such information only a type handle is stored, which lets the system uniquely identify 'known types'. /// /// A known type is a type that is registered with the <see cref="TypeSurrogateProvider"/>. Moreover /// surrogate types take care of serializing only the required information. Information related to fields /// and attributes is not stored as in case of native serialization. /// </para> /// <para> /// From performance's perspective reflection is avoided by using surrogates for types. A type surrogate /// is intimate with the internals of a type and therefore does not need reflection to guess /// object schema. /// </para> /// For types that are not known to the system the formatter reverts to the default .NET /// serialization scheme. /// </remarks> public class CompactBinaryFormatter { /// <summary> /// Serializes an object and returns its binary representation. /// </summary> /// <param name="graph">object to serialize</param> /// <returns>binary form of object</returns> static public byte[] ToByteBuffer(object graph,string cacheContext) { using(MemoryStream stream = new MemoryStream()) { Serialize(stream, graph,cacheContext); return stream.ToArray(); } } /// <summary> /// Deserializes the binary representation of an object. /// </summary> /// <param name="buffer">binary representation of the object</param> /// <returns>deserialized object</returns> static public object FromByteBuffer(byte[] buffer,string cacheContext, System.Runtime.Serialization.SerializationBinder binder = null) { using(MemoryStream stream = new MemoryStream(buffer)) { return Deserialize(stream,cacheContext,binder); } } /// <summary> /// Serializes an object into the specified stream. /// </summary> /// <param name="stream">specified stream</param> /// <param name="graph">object</param> static public void Serialize(Stream stream, object graph,string cacheContext) { using(CompactBinaryWriter writer = new CompactBinaryWriter(stream)) { Serialize(writer, graph,cacheContext); } } /// <summary> /// Serializes an object into the specified stream. /// </summary> /// <param name="stream">specified stream</param> /// <param name="graph">object</param> static public void Serialize(Stream stream, object graph, string cacheContext,bool closeStream) { CompactBinaryWriter writer = new CompactBinaryWriter(stream); Serialize(writer, graph, cacheContext); writer.Dispose(closeStream); } /// <summary> /// Serializes an object into the specified stream. /// </summary> /// <param name="stream">specified stream</param> /// <param name="graph">object</param> static public void Serialize(Stream stream, object graph, string cacheContext, bool closeStream,MemoryManager objManager) { CompactBinaryWriter writer = new CompactBinaryWriter(stream); writer.Context.MemManager = objManager; Serialize(writer, graph, cacheContext); writer.Dispose(closeStream); } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="stream">specified stream</param> /// <returns>deserialized object</returns> static public object Deserialize(Stream stream,string cacheContext, System.Runtime.Serialization.SerializationBinder binder = null) { using(CompactBinaryReader reader = new CompactBinaryReader(stream)) { reader.Context.Binder = binder; return Deserialize(reader,cacheContext, false); } } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="stream">specified stream</param> /// <returns>deserialized object</returns> static public object Deserialize(Stream stream, string cacheContext, bool closeStream) { object obj; CompactBinaryReader reader = new CompactBinaryReader(stream); obj = Deserialize(reader, cacheContext, false); reader.Dispose(closeStream); return obj; } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="stream">specified stream</param> /// <returns>deserialized object</returns> static public object Deserialize(Stream stream, string cacheContext, bool closeStream,MemoryManager memManager) { object obj; CompactBinaryReader reader = new CompactBinaryReader(stream); reader.Context.MemManager = memManager; obj = Deserialize(reader, cacheContext, false); reader.Dispose(closeStream); return obj; } /// <summary> /// Serializes an object into the specified compact binary writer. /// </summary> /// <param name="writer">specified compact binary writer</param> /// <param name="graph">object</param> static internal void Serialize(CompactBinaryWriter writer, object graph,string cacheContext) { // Find an appropriate surrogate for the object ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForObject(graph,cacheContext); // write type handle writer.Context.CacheContext = cacheContext; writer.Write(surrogate.TypeHandle); surrogate.Write(writer, graph); } /// <summary> /// Deserializes an object from the specified compact binary writer. /// </summary> /// <param name="reader">Stream containing reader</param> /// <param name="cacheContext">Name of the cache</param> /// <param name="skip">True to skip the bytes returning null</param> static internal object Deserialize(CompactBinaryReader reader,string cacheContext, bool skip) { // read type handle short handle = reader.ReadInt16(); reader.Context.CacheContext = cacheContext; // Find an appropriate surrogate by handle ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle,cacheContext); if (surrogate == null) { surrogate = TypeSurrogateSelector.GetSurrogateForSubTypeHandle(handle, reader.ReadInt16(), cacheContext); } if(surrogate == null) { throw new CompactSerializationException("Type handle " + handle + "is not registered with Compact Serialization Framework"); } if (!skip) { return surrogate.Read(reader); } else { surrogate.Skip(reader); 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. using System.Data.Common; using System.IO; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class ReaderTest { [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void TestMain() { string connectionString = DataTestUtility.TcpConnStr; string tempTable = DataTestUtility.GetUniqueName("T", "[", "]"); string tempKey = DataTestUtility.GetUniqueName("K", "[", "]"); DbProviderFactory provider = SqlClientFactory.Instance; try { using (DbConnection con = provider.CreateConnection()) { con.ConnectionString = connectionString; con.Open(); using (DbCommand cmd = provider.CreateCommand()) { cmd.Connection = con; DbTransaction tx; #region <<Create temp table>> cmd.CommandText = "SELECT LastName, FirstName, Title, Address, City, Region, PostalCode, Country into " + tempTable + " from Employees where EmployeeID=0"; cmd.ExecuteNonQuery(); #endregion tx = con.BeginTransaction(); cmd.Transaction = tx; cmd.CommandText = "insert into " + tempTable + "(LastName, FirstName, Title, Address, City, Region, PostalCode, Country) values ('Doe', 'Jane' , 'Ms.', 'One Microsoft Way', 'Redmond', 'WA', '98052', 'USA')"; cmd.ExecuteNonQuery(); cmd.CommandText = "insert into " + tempTable + "(LastName, FirstName, Title, Address, City, Region, PostalCode, Country) values ('Doe', 'John' , 'Mr.', NULL, NULL, NULL, NULL, NULL)"; cmd.ExecuteNonQuery(); tx.Commit(); cmd.Transaction = null; string parameterName = "@p1"; DbParameter p1 = cmd.CreateParameter(); p1.ParameterName = parameterName; p1.Value = "Doe"; cmd.Parameters.Add(p1); cmd.CommandText = "select * from " + tempTable + " where LastName = " + parameterName; // Test GetValue + IsDBNull using (DbDataReader rdr = cmd.ExecuteReader()) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA", "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)" }; while (rdr.Read()) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNull(i)) { actualResult.Append("(NULL)"); } else { actualResult.Append(rdr.GetValue(i)); } } DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } // Test GetFieldValue<T> + IsDBNull using (DbDataReader rdr = cmd.ExecuteReader()) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA", "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)" }; while (rdr.Read()) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNull(i)) { actualResult.Append("(NULL)"); } else { if (rdr.GetFieldType(i) == typeof(bool)) { actualResult.Append(rdr.GetFieldValue<bool>(i)); } else if (rdr.GetFieldType(i) == typeof(decimal)) { actualResult.Append(rdr.GetFieldValue<decimal>(i)); } else if (rdr.GetFieldType(i) == typeof(int)) { actualResult.Append(rdr.GetFieldValue<int>(i)); } else { actualResult.Append(rdr.GetFieldValue<string>(i)); } } } DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } // Test GetFieldValueAsync<T> + IsDBNullAsync using (DbDataReader rdr = cmd.ExecuteReaderAsync().Result) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA", "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)" }; while (rdr.ReadAsync().Result) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNullAsync(i).Result) { actualResult.Append("(NULL)"); } else { if (rdr.GetFieldType(i) == typeof(bool)) { actualResult.Append(rdr.GetFieldValueAsync<bool>(i).Result); } else if (rdr.GetFieldType(i) == typeof(decimal)) { actualResult.Append(rdr.GetFieldValueAsync<decimal>(i).Result); } else if (rdr.GetFieldType(i) == typeof(int)) { actualResult.Append(rdr.GetFieldValue<int>(i)); } else { actualResult.Append(rdr.GetFieldValueAsync<string>(i).Result); } } } DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } } // GetStream byte[] correctBytes = { 0x12, 0x34, 0x56, 0x78 }; string queryString; string correctBytesAsString = "0x12345678"; queryString = string.Format("SELECT CAST({0} AS BINARY(20)), CAST({0} AS IMAGE), CAST({0} AS VARBINARY(20))", correctBytesAsString); using (var command = provider.CreateCommand()) { command.CommandText = queryString; command.Connection = con; using (var reader = command.ExecuteReader()) { reader.Read(); for (int i = 0; i < reader.FieldCount; i++) { byte[] buffer = new byte[256]; Stream stream = reader.GetStream(i); int bytesRead = stream.Read(buffer, 0, buffer.Length); for (int j = 0; j < correctBytes.Length; j++) { Assert.True(correctBytes[j] == buffer[j], "ERROR: Bytes do not match"); } } } } // GetTextReader string[] correctStrings = { "Hello World", "\uFF8A\uFF9B\uFF70\uFF9C\uFF70\uFF99\uFF84\uFF9E" }; string[] collations = { "Latin1_General_CI_AS", "Japanese_CI_AS" }; for (int j = 0; j < collations.Length; j++) { string substring = string.Format("(N'{0}' COLLATE {1})", correctStrings[j], collations[j]); queryString = string.Format("SELECT CAST({0} AS CHAR(20)), CAST({0} AS NCHAR(20)), CAST({0} AS NTEXT), CAST({0} AS NVARCHAR(20)), CAST({0} AS TEXT), CAST({0} AS VARCHAR(20))", substring); using (var command = provider.CreateCommand()) { command.CommandText = queryString; command.Connection = con; using (var reader = command.ExecuteReader()) { reader.Read(); for (int i = 0; i < reader.FieldCount; i++) { char[] buffer = new char[256]; TextReader textReader = reader.GetTextReader(i); int charsRead = textReader.Read(buffer, 0, buffer.Length); string stringRead = new string(buffer, 0, charsRead); Assert.True(stringRead == (string)reader.GetValue(i), "ERROR: Strings to not match"); } } } } } } finally { using (DbConnection con = provider.CreateConnection()) { con.ConnectionString = connectionString; con.Open(); using (DbCommand cmd = provider.CreateCommand()) { cmd.Connection = con; cmd.CommandText = "drop table " + tempTable; cmd.ExecuteNonQuery(); } } } } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static async Task TestConcurrentLoadSync() { ConcurrentLoadContext context = new ConcurrentLoadContext( providerFactory: SqlClientFactory.Instance, connectionString: DataTestUtility.TcpConnStr, mode: ConcurrentLoadContext.Mode.Sync, warmupSeconds: 1, executionSeconds: 60, threadCount: Environment.ProcessorCount * 4 ); var (transactionPerSecond, average, stdDeviation) = await context.Run(); Assert.InRange(transactionPerSecond, 1, int.MaxValue); Assert.True(average > 0); Assert.True(stdDeviation != 0); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static async Task TestConcurrentLoadAsync() { ConcurrentLoadContext context = new ConcurrentLoadContext( providerFactory: SqlClientFactory.Instance, connectionString: DataTestUtility.TcpConnStr, mode: ConcurrentLoadContext.Mode.Async, warmupSeconds: 1, executionSeconds: 60, threadCount: Environment.ProcessorCount * 4 ); var (transactionPerSecond, average, stdDeviation) = await context.Run(); Assert.InRange(transactionPerSecond, 1, int.MaxValue); Assert.True(average > 0); Assert.True(stdDeviation != 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Internal.TypeSystem; namespace Internal.JitInterface { internal unsafe partial class CorInfoImpl { private struct IntrinsicKey { public string MethodName; public string TypeNamespace; public string TypeName; public bool Equals(IntrinsicKey other) { return (MethodName == other.MethodName) && (TypeNamespace == other.TypeNamespace) && (TypeName == other.TypeName); } public override int GetHashCode() { return MethodName.GetHashCode() + ((TypeNamespace != null) ? TypeNamespace.GetHashCode() : 0) + ((TypeName != null) ? TypeName.GetHashCode() : 0); } } private class IntrinsicEntry { public IntrinsicKey Key; public CorInfoIntrinsics Id; } private class IntrinsicHashtable : LockFreeReaderHashtable<IntrinsicKey, IntrinsicEntry> { protected override bool CompareKeyToValue(IntrinsicKey key, IntrinsicEntry value) { return key.Equals(value.Key); } protected override bool CompareValueToValue(IntrinsicEntry value1, IntrinsicEntry value2) { return value1.Key.Equals(value2.Key); } protected override IntrinsicEntry CreateValueFromKey(IntrinsicKey key) { Debug.Assert(false, "CreateValueFromKey not supported"); return null; } protected override int GetKeyHashCode(IntrinsicKey key) { return key.GetHashCode(); } protected override int GetValueHashCode(IntrinsicEntry value) { return value.Key.GetHashCode(); } public void Add(CorInfoIntrinsics id, string methodName, string typeNamespace, string typeName) { var entry = new IntrinsicEntry(); entry.Id = id; entry.Key.MethodName = methodName; entry.Key.TypeNamespace = typeNamespace; entry.Key.TypeName = typeName; AddOrGetExisting(entry); } } static IntrinsicHashtable InitializeIntrinsicHashtable() { IntrinsicHashtable table = new IntrinsicHashtable(); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sin, "Sin", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cos, "Cos", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sqrt, "Sqrt", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Abs, "Abs", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Round, "Round", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cosh, "Cosh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sinh, "Sinh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tan, "Tan", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tanh, "Tanh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Asin, "Asin", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Acos, "Acos", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan, "Atan", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan2, "Atan2", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Log10, "Log10", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Pow, "Pow", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Exp, "Exp", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Ceiling, "Ceiling", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Floor, "Floor", "System", "Math"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetChar, null, null, null); // unused // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_GetDimLength, "GetLength", "System", "Array"); // not handled table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Get, "Get", null, null); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Address, "Address", null, null); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Set, "Set", null, null); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StringGetChar, "get_Chars", "System", "String"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StringLength, "get_Length", "System", "String"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray, "InitializeArray", "System.Runtime.CompilerServices", "RuntimeHelpers"); //table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetTypeFromHandle, "GetTypeFromHandle", "System", "Type"); // RuntimeTypeHandle has to be RuntimeType table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal, "GetValueInternal", "System", "RuntimeTypeHandle"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeEQ, "op_Equality", "System", "Type"); // not in .NET Core // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeNEQ, "op_Inequality", "System", "Type"); // not in .NET Core table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Object_GetType, "GetType", "System", "Object"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContext, "GetStubContext", "System.StubHelpers", "StubHelpers"); // interop-specific // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr, "GetStubContextAddr", "System.StubHelpers", "StubHelpers"); // interop-specific // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetNDirectTarget, "GetNDirectTarget", "System.StubHelpers", "StubHelpers"); // interop-specific // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedAdd32, "Add", System.Threading", "Interlocked"); // unused // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedAdd64, "Add", System.Threading", "Interlocked"); // unused table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32, "ExchangeAdd", "System.Threading", "Interlocked"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd64, "ExchangeAdd", "System.Threading", "Interlocked"); // ambiguous match table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32, "Exchange", "System.Threading", "Interlocked"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg64, "Exchange", "System.Threading", "Interlocked"); // ambiguous match table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32, "CompareExchange", "System.Threading", "Interlocked"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg64, "CompareExchange", "System.Threading", "Interlocked"); // ambiguous match table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_MemoryBarrier, "MemoryBarrier", "System.Threading", "Interlocked"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetCurrentManagedThread, "GetCurrentThreadNative", "System", "Thread"); // not in .NET Core // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetManagedThreadId, "get_ManagedThreadId", "System", "Thread"); // not in .NET Core // If this assert fails, make sure to add the new intrinsics to the table above and update the expected count below. Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_Count == 45); return table; } static IntrinsicHashtable s_IntrinsicHashtable = InitializeIntrinsicHashtable(); private CorInfoIntrinsics getIntrinsicID(CORINFO_METHOD_STRUCT_* ftn, ref bool pMustExpand) { pMustExpand = false; var method = HandleToObject(ftn); Debug.Assert(method.IsIntrinsic); IntrinsicKey key = new IntrinsicKey(); key.MethodName = method.Name; var metadataType = method.OwningType as MetadataType; if (metadataType != null) { key.TypeNamespace = metadataType.Namespace; key.TypeName = metadataType.Name; } IntrinsicEntry entry; if (!s_IntrinsicHashtable.TryGetValue(key, out entry)) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; // Some intrinsics need further disambiguation CorInfoIntrinsics id = entry.Id; switch (id) { case CorInfoIntrinsics.CORINFO_INTRINSIC_Abs: { // RyuJIT handles floating point overloads only var returnTypeCategory = method.Signature.ReturnType.Category; if (returnTypeCategory != TypeFlags.Double && returnTypeCategory != TypeFlags.Single) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; } break; case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Get: case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Address: case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Set: if (!method.OwningType.IsArray) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; break; case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32: case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32: case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32: { // RyuJIT handles int32 and int64 overloads only var returnTypeCategory = method.Signature.ReturnType.Category; if (returnTypeCategory != TypeFlags.Int32 && returnTypeCategory != TypeFlags.Int64 && returnTypeCategory != TypeFlags.IntPtr) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; // int64 overloads have different ids if (returnTypeCategory == TypeFlags.Int64) { Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd64); Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg64); Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg64); id = (CorInfoIntrinsics)((int)id + 1); } } break; case CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal: case CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray: pMustExpand = true; break; default: break; } return id; } } }
// 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; using static System.Runtime.Intrinsics.X86.Sse; using static System.Runtime.Intrinsics.X86.Sse2; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertSingle192() { var test = new InsertVector128Test__InsertSingle192(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.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(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 InsertVector128Test__InsertSingle192 { private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(InsertVector128Test__InsertSingle192 testClass) { var result = Sse41.Insert(_fld1, _fld2, 192); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static InsertVector128Test__InsertSingle192() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public InsertVector128Test__InsertSingle192() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Insert( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), 192 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.Insert( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), LoadVector128((Single*)(_dataTable.inArray2Ptr)), 192 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Insert( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), 192 ); 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(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), (byte)192 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), LoadVector128((Single*)(_dataTable.inArray2Ptr)), (byte)192 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), (byte)192 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Insert( _clsVar1, _clsVar2, 192 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse41.Insert(left, right, 192); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.Insert(left, right, 192); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.Insert(left, right, 192); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertVector128Test__InsertSingle192(); var result = Sse41.Insert(test._fld1, test._fld2, 192); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Insert(_fld1, _fld2, 192); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Insert(test._fld1, test._fld2, 192); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(right[3])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.192): {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; } } } }
// <copyright file="LeaderboardManager.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.Native.PInvoke { using System; using System.Runtime.InteropServices; using GooglePlayGames.BasicApi; using GooglePlayGames.OurUtils; using C = GooglePlayGames.Native.Cwrapper.LeaderboardManager; using Types = GooglePlayGames.Native.Cwrapper.Types; using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus; using UnityEngine.SocialPlatforms; internal class LeaderboardManager { private readonly GameServices mServices; internal LeaderboardManager(GameServices services) { mServices = Misc.CheckNotNull(services); } internal int LeaderboardMaxResults { get { return 25; } } internal void SubmitScore(string leaderboardId, long score, string metadata) { Misc.CheckNotNull(leaderboardId, "leaderboardId"); Logger.d("Native Submitting score: " + score + " for lb " + leaderboardId + " with metadata: " + metadata); C.LeaderboardManager_SubmitScore(mServices.AsHandle(), leaderboardId, (ulong)score, metadata ?? ""); } internal void ShowAllUI(Action<Status.UIStatus> callback) { Misc.CheckNotNull(callback); C.LeaderboardManager_ShowAllUI(mServices.AsHandle(), Callbacks.InternalShowUICallback, Callbacks.ToIntPtr(callback)); } internal void ShowUI(string leaderboardId, LeaderboardTimeSpan span, Action<Status.UIStatus> callback) { Misc.CheckNotNull(callback); C.LeaderboardManager_ShowUI(mServices.AsHandle(), leaderboardId, (Types.LeaderboardTimeSpan)span, Callbacks.InternalShowUICallback, Callbacks.ToIntPtr(callback)); } /// <summary> /// Loads the leaderboard data. This is the "top level" call /// to load leaderboard data. A token for fetching scores is created /// based on the parameters. /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="start">Start of scores location</param> /// <param name="rowCount">Row count.</param> /// <param name="collection">Collection social or public</param> /// <param name="timeSpan">Time span of leaderboard</param> /// <param name="playerId">Player identifier.</param> /// <param name="callback">Callback.</param> public void LoadLeaderboardData(string leaderboardId, LeaderboardStart start, int rowCount, LeaderboardCollection collection, LeaderboardTimeSpan timeSpan, string playerId, Action<LeaderboardScoreData> callback) { //Create a token we'll use to load scores later. NativeScorePageToken nativeToken = new NativeScorePageToken( C.LeaderboardManager_ScorePageToken( mServices.AsHandle(), leaderboardId, (Types.LeaderboardStart)start, (Types.LeaderboardTimeSpan)timeSpan, (Types.LeaderboardCollection)collection)); ScorePageToken token = new ScorePageToken(nativeToken, leaderboardId, collection, timeSpan); // First fetch the leaderboard to get the title C.LeaderboardManager_Fetch(mServices.AsHandle(), Types.DataSource.CACHE_OR_NETWORK, leaderboardId, InternalFetchCallback, Callbacks.ToIntPtr<FetchResponse>((rsp) => HandleFetch(token, rsp, playerId, rowCount, callback), FetchResponse.FromPointer)); } [AOT.MonoPInvokeCallback(typeof(C.FetchCallback))] private static void InternalFetchCallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback("LeaderboardManager#InternalFetchCallback", Callbacks.Type.Temporary, response, data); } /// <summary> /// Handles the fetch of a specific leaderboard definition. This /// is called with the expectation that the leaderboard summary and /// scores are also needed. /// </summary> /// <param name="token">token for the current fetching request.</param> /// <param name="response">Response.</param> /// <param name="selfPlayerId">Self player identifier.</param> /// <param name="maxResults">Number of scores to return.</param> /// <param name="callback">Callback.</param> internal void HandleFetch(ScorePageToken token, FetchResponse response, string selfPlayerId, int maxResults, Action<LeaderboardScoreData> callback) { LeaderboardScoreData data = new LeaderboardScoreData( token.LeaderboardId, (ResponseStatus)response.GetStatus()); if (response.GetStatus() != Status.ResponseStatus.VALID && response.GetStatus() != Status.ResponseStatus.VALID_BUT_STALE) { Logger.w("Error returned from fetch: " + response.GetStatus()); callback(data); return; } data.Title = response.Leaderboard().Title(); data.Id = token.LeaderboardId; // now fetch the summary of the leaderboard. C.LeaderboardManager_FetchScoreSummary(mServices.AsHandle(), Types.DataSource.CACHE_OR_NETWORK, token.LeaderboardId, (Types.LeaderboardTimeSpan)token.TimeSpan, (Types.LeaderboardCollection)token.Collection, InternalFetchSummaryCallback, Callbacks.ToIntPtr<FetchScoreSummaryResponse>((rsp) => HandleFetchScoreSummary(data, rsp, selfPlayerId, maxResults, token, callback), FetchScoreSummaryResponse.FromPointer) ); } [AOT.MonoPInvokeCallback(typeof(C.FetchScoreSummaryCallback))] private static void InternalFetchSummaryCallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback("LeaderboardManager#InternalFetchSummaryCallback", Callbacks.Type.Temporary, response, data); } internal void HandleFetchScoreSummary(LeaderboardScoreData data, FetchScoreSummaryResponse response, string selfPlayerId, int maxResults, ScorePageToken token, Action<LeaderboardScoreData> callback) { if (response.GetStatus() != Status.ResponseStatus.VALID && response.GetStatus() != Status.ResponseStatus.VALID_BUT_STALE) { Logger.w("Error returned from fetchScoreSummary: " + response); data.Status = (ResponseStatus)response.GetStatus(); callback(data); return; } NativeScoreSummary summary = response.GetScoreSummary(); data.ApproximateCount = summary.ApproximateResults(); data.PlayerScore = summary.LocalUserScore().AsScore(data.Id, selfPlayerId); // if the maxResults is 0, no scores are needed, so we are done. if (maxResults <= 0) { callback(data); return; } LoadScorePage(data, maxResults, token, callback); } /// <summary> /// Loads the score page. This is used to page through the rows /// of leaderboard scores. /// </summary> /// <param name="data">Data - partially completed result data, can be null</param> /// <param name="maxResults">Max results to return</param> /// <param name="token">Token to use for getting the score page,</param> /// <param name="callback">Callback.</param> public void LoadScorePage(LeaderboardScoreData data, int maxResults, ScorePageToken token, Action<LeaderboardScoreData> callback) { if (data == null) { data = new LeaderboardScoreData(token.LeaderboardId); } NativeScorePageToken nativeToken = (NativeScorePageToken)token.InternalObject; C.LeaderboardManager_FetchScorePage(mServices.AsHandle(), Types.DataSource.CACHE_OR_NETWORK, nativeToken.AsPointer(), (uint)maxResults, InternalFetchScorePage, Callbacks.ToIntPtr<FetchScorePageResponse>((rsp) => { HandleFetchScorePage(data, token, rsp, callback); }, FetchScorePageResponse.FromPointer) ); } [AOT.MonoPInvokeCallback(typeof(C.FetchScorePageCallback))] private static void InternalFetchScorePage(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback("LeaderboardManager#InternalFetchScorePage", Callbacks.Type.Temporary, response, data); } internal void HandleFetchScorePage(LeaderboardScoreData data, ScorePageToken token, FetchScorePageResponse rsp, Action<LeaderboardScoreData> callback) { data.Status = (ResponseStatus)rsp.GetStatus(); // add the scores that match the criteria if (rsp.GetStatus() != Status.ResponseStatus.VALID && rsp.GetStatus() != Status.ResponseStatus.VALID_BUT_STALE) { callback(data); } NativeScorePage page = rsp.GetScorePage(); if (!page.Valid()) { callback(data); } if (page.HasNextScorePage()) { data.NextPageToken = new ScorePageToken( page.GetNextScorePageToken(), token.LeaderboardId, token.Collection, token.TimeSpan); } if (page.HasPrevScorePage()) { data.PrevPageToken = new ScorePageToken( page.GetPreviousScorePageToken(), token.LeaderboardId, token.Collection, token.TimeSpan); } foreach (NativeScoreEntry ent in page) { data.AddScore(ent.AsScore(data.Id)); } callback(data); } } internal class FetchScorePageResponse : BaseReferenceHolder { internal FetchScorePageResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void CallDispose(HandleRef selfPointer) { C.LeaderboardManager_FetchScorePageResponse_Dispose(SelfPtr()); } internal Status.ResponseStatus GetStatus() { return C.LeaderboardManager_FetchScorePageResponse_GetStatus(SelfPtr()); } internal NativeScorePage GetScorePage() { return NativeScorePage.FromPointer( C.LeaderboardManager_FetchScorePageResponse_GetData(SelfPtr())); } internal static FetchScorePageResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new FetchScorePageResponse(pointer); } } internal class FetchResponse : BaseReferenceHolder { internal FetchResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void CallDispose(HandleRef selfPointer) { C.LeaderboardManager_FetchResponse_Dispose(SelfPtr()); } internal NativeLeaderboard Leaderboard() { return NativeLeaderboard.FromPointer( C.LeaderboardManager_FetchResponse_GetData(SelfPtr())); } internal Status.ResponseStatus GetStatus() { return C.LeaderboardManager_FetchResponse_GetStatus(SelfPtr()); } internal static FetchResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new FetchResponse(pointer); } } internal class FetchScoreSummaryResponse : BaseReferenceHolder { internal FetchScoreSummaryResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void CallDispose(HandleRef selfPointer) { C.LeaderboardManager_FetchScoreSummaryResponse_Dispose(selfPointer); } internal Status.ResponseStatus GetStatus() { return C.LeaderboardManager_FetchScoreSummaryResponse_GetStatus(SelfPtr()); } internal NativeScoreSummary GetScoreSummary() { return NativeScoreSummary.FromPointer( C.LeaderboardManager_FetchScoreSummaryResponse_GetData(SelfPtr() )); } internal static FetchScoreSummaryResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new FetchScoreSummaryResponse(pointer); } } } #endif
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type OnenoteSectionPagesCollectionRequest. /// </summary> public partial class OnenoteSectionPagesCollectionRequest : BaseRequest, IOnenoteSectionPagesCollectionRequest { /// <summary> /// Constructs a new OnenoteSectionPagesCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public OnenoteSectionPagesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified OnenotePage to the collection via POST. /// </summary> /// <param name="onenotePage">The OnenotePage to add.</param> /// <returns>The created OnenotePage.</returns> public System.Threading.Tasks.Task<OnenotePage> AddAsync(OnenotePage onenotePage) { return this.AddAsync(onenotePage, CancellationToken.None); } /// <summary> /// Adds the specified OnenotePage to the collection via POST. /// </summary> /// <param name="onenotePage">The OnenotePage to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created OnenotePage.</returns> public System.Threading.Tasks.Task<OnenotePage> AddAsync(OnenotePage onenotePage, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<OnenotePage>(onenotePage, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IOnenoteSectionPagesCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IOnenoteSectionPagesCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<OnenoteSectionPagesCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IOnenoteSectionPagesCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IOnenoteSectionPagesCollectionRequest Expand(Expression<Func<OnenotePage, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IOnenoteSectionPagesCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IOnenoteSectionPagesCollectionRequest Select(Expression<Func<OnenotePage, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IOnenoteSectionPagesCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IOnenoteSectionPagesCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IOnenoteSectionPagesCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IOnenoteSectionPagesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // ReSharper disable UnusedMember.Global // ReSharper disable RedundantCast namespace System.Management.Automation { internal static class Boxed { internal static readonly object True = (object)true; internal static readonly object False = (object)false; } internal static class IntOps { internal static object Add(int lhs, int rhs) { long result = (long)lhs + (long)rhs; if (result <= int.MaxValue && result >= int.MinValue) { return (int)result; } return (double)result; } internal static object Sub(int lhs, int rhs) { long result = (long)lhs - (long)rhs; if (result <= int.MaxValue && result >= int.MinValue) { return (int)result; } return (double)result; } internal static object Multiply(int lhs, int rhs) { long result = (long)lhs * (long)rhs; if (result <= int.MaxValue && result >= int.MinValue) { return (int)result; } return (double)result; } internal static object Divide(int lhs, int rhs) { // TBD: is it better to cover the special cases explicitly, or // alternatively guard with try/catch? if (rhs == 0) { DivideByZeroException dbze = new DivideByZeroException(); throw new RuntimeException(dbze.Message, dbze); } if (lhs == int.MinValue && rhs == -1) { // The result of this operation can't fit in an int, so promote. return (double)lhs / (double)rhs; } // If the remainder is 0, stay with integer division, otherwise use doubles. if ((lhs % rhs) == 0) { return lhs / rhs; } return (double)lhs / (double)rhs; } internal static object Remainder(int lhs, int rhs) { // TBD: is it better to cover the special cases explicitly, or // alternatively guard with try/catch? if (rhs == 0) { DivideByZeroException dbze = new DivideByZeroException(); throw new RuntimeException(dbze.Message, dbze); } if (lhs == int.MinValue && rhs == -1) { // The CLR raises an overflow exception for these values. PowerShell typically // promotes whenever things overflow, so we just hard code the result value. return 0; } return lhs % rhs; } internal static object CompareEq(int lhs, int rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } internal static object CompareNe(int lhs, int rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } internal static object CompareLt(int lhs, int rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } internal static object CompareLe(int lhs, int rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } internal static object CompareGt(int lhs, int rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } internal static object CompareGe(int lhs, int rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } internal static object[] Range(int lower, int upper) { int absRange = Math.Abs(checked(upper - lower)); object[] ra = new object[absRange + 1]; if (lower > upper) { // 3 .. 1 => 3 2 1 for (int offset = 0; offset < ra.Length; offset++) ra[offset] = lower--; } else { // 1 .. 3 => 1 2 3 for (int offset = 0; offset < ra.Length; offset++) ra[offset] = lower++; } return ra; } } internal static class UIntOps { internal static object Add(uint lhs, uint rhs) { ulong result = (ulong)lhs + (ulong)rhs; if (result <= uint.MaxValue) { return (uint)result; } return (double)result; } internal static object Sub(uint lhs, uint rhs) { long result = (long)lhs - (long)rhs; if (result >= uint.MinValue) { return (uint)result; } return (double)result; } internal static object Multiply(uint lhs, uint rhs) { ulong result = (ulong)lhs * (ulong)rhs; if (result <= uint.MaxValue) { return (uint)result; } return (double)result; } internal static object Divide(uint lhs, uint rhs) { // TBD: is it better to cover the special cases explicitly, or // alternatively guard with try/catch? if (rhs == 0) { DivideByZeroException dbze = new DivideByZeroException(); throw new RuntimeException(dbze.Message, dbze); } // If the remainder is 0, stay with integer division, otherwise use doubles. if ((lhs % rhs) == 0) { return lhs / rhs; } return (double)lhs / (double)rhs; } internal static object Remainder(uint lhs, uint rhs) { // TBD: is it better to cover the special cases explicitly, or // alternatively guard with try/catch? if (rhs == 0) { DivideByZeroException dbze = new DivideByZeroException(); throw new RuntimeException(dbze.Message, dbze); } return lhs % rhs; } internal static object CompareEq(uint lhs, uint rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } internal static object CompareNe(uint lhs, uint rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } internal static object CompareLt(uint lhs, uint rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } internal static object CompareLe(uint lhs, uint rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } internal static object CompareGt(uint lhs, uint rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } internal static object CompareGe(uint lhs, uint rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } internal static class LongOps { internal static object Add(long lhs, long rhs) { decimal result = (decimal)lhs + (decimal)rhs; if (result <= long.MaxValue && result >= long.MinValue) { return (long)result; } return (double)result; } internal static object Sub(long lhs, long rhs) { decimal result = (decimal)lhs - (decimal)rhs; if (result <= long.MaxValue && result >= long.MinValue) { return (long)result; } return (double)result; } internal static object Multiply(long lhs, long rhs) { System.Numerics.BigInteger biLhs = lhs; System.Numerics.BigInteger biRhs = rhs; System.Numerics.BigInteger biResult = biLhs * biRhs; if (biResult <= long.MaxValue && biResult >= long.MinValue) { return (long)biResult; } return (double)biResult; } internal static object Divide(long lhs, long rhs) { // TBD: is it better to cover the special cases explicitly, or // alternatively guard with try/catch? if (rhs == 0) { DivideByZeroException dbze = new DivideByZeroException(); throw new RuntimeException(dbze.Message, dbze); } // Special case. // This changes the sign of the min value, causing an integer overflow. if (lhs == long.MinValue && rhs == -1) { return (double)lhs / (double)rhs; } // If the remainder is 0, stay with integer division, otherwise use doubles. if ((lhs % rhs) == 0) { return lhs / rhs; } return (double)lhs / (double)rhs; } internal static object Remainder(long lhs, long rhs) { // TBD: is it better to cover the special cases explicitly, or // alternatively guard with try/catch? if (rhs == 0) { DivideByZeroException dbze = new DivideByZeroException(); throw new RuntimeException(dbze.Message, dbze); } if (lhs == long.MinValue && rhs == -1) { // The CLR raises an overflow exception for these values. PowerShell typically // promotes whenever things overflow, so we just hard code the result value. return 0L; } return lhs % rhs; } internal static object CompareEq(long lhs, long rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } internal static object CompareNe(long lhs, long rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } internal static object CompareLt(long lhs, long rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } internal static object CompareLe(long lhs, long rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } internal static object CompareGt(long lhs, long rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } internal static object CompareGe(long lhs, long rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } internal static class ULongOps { internal static object Add(ulong lhs, ulong rhs) { decimal result = (decimal)lhs + (decimal)rhs; if (result <= ulong.MaxValue) { return (ulong)result; } return (double)result; } internal static object Sub(ulong lhs, ulong rhs) { decimal result = (decimal)lhs - (decimal)rhs; if (result >= ulong.MinValue) { return (ulong)result; } return (double)result; } internal static object Multiply(ulong lhs, ulong rhs) { System.Numerics.BigInteger biLhs = lhs; System.Numerics.BigInteger biRhs = rhs; System.Numerics.BigInteger biResult = biLhs * biRhs; if (biResult <= ulong.MaxValue) { return (ulong)biResult; } return (double)biResult; } internal static object Divide(ulong lhs, ulong rhs) { // TBD: is it better to cover the special cases explicitly, or // alternatively guard with try/catch? if (rhs == 0) { DivideByZeroException dbze = new DivideByZeroException(); throw new RuntimeException(dbze.Message, dbze); } // If the remainder is 0, stay with integer division, otherwise use doubles. if ((lhs % rhs) == 0) { return lhs / rhs; } return (double)lhs / (double)rhs; } internal static object Remainder(ulong lhs, ulong rhs) { // TBD: is it better to cover the special cases explicitly, or // alternatively guard with try/catch? if (rhs == 0) { DivideByZeroException dbze = new DivideByZeroException(); throw new RuntimeException(dbze.Message, dbze); } return lhs % rhs; } internal static object CompareEq(ulong lhs, ulong rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } internal static object CompareNe(ulong lhs, ulong rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } internal static object CompareLt(ulong lhs, ulong rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } internal static object CompareLe(ulong lhs, ulong rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } internal static object CompareGt(ulong lhs, ulong rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } internal static object CompareGe(ulong lhs, ulong rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } internal static class DecimalOps { internal static object Add(decimal lhs, decimal rhs) { try { return checked(lhs + rhs); } catch (OverflowException oe) { throw new RuntimeException(oe.Message, oe); } } internal static object Sub(decimal lhs, decimal rhs) { try { return checked(lhs - rhs); } catch (OverflowException oe) { throw new RuntimeException(oe.Message, oe); } } internal static object Multiply(decimal lhs, decimal rhs) { try { return checked(lhs * rhs); } catch (OverflowException oe) { throw new RuntimeException(oe.Message, oe); } } internal static object Divide(decimal lhs, decimal rhs) { try { return checked(lhs / rhs); } catch (OverflowException oe) { throw new RuntimeException(oe.Message, oe); } catch (DivideByZeroException dbze) { throw new RuntimeException(dbze.Message, dbze); } } internal static object Remainder(decimal lhs, decimal rhs) { try { return checked(lhs % rhs); } catch (OverflowException oe) { throw new RuntimeException(oe.Message, oe); } catch (DivideByZeroException dbze) { throw new RuntimeException(dbze.Message, dbze); } } internal static object BNot(decimal val) { if (val <= int.MaxValue && val >= int.MinValue) { return unchecked(~LanguagePrimitives.ConvertTo<int>(val)); } if (val <= uint.MaxValue && val >= uint.MinValue) { return unchecked(~LanguagePrimitives.ConvertTo<uint>(val)); } if (val <= long.MaxValue && val >= long.MinValue) { return unchecked(~LanguagePrimitives.ConvertTo<long>(val)); } if (val <= ulong.MaxValue && val >= ulong.MinValue) { return unchecked(~LanguagePrimitives.ConvertTo<ulong>(val)); } LanguagePrimitives.ThrowInvalidCastException(val, typeof(int)); Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException."); return null; } internal static object BOr(decimal lhs, decimal rhs) { ulong l = ConvertToUlong(lhs); ulong r = ConvertToUlong(rhs); // If either operand is signed, return signed result if (lhs < 0 || rhs < 0) { unchecked { return (long)(l | r); } } return l | r; } internal static object BXor(decimal lhs, decimal rhs) { ulong l = ConvertToUlong(lhs); ulong r = ConvertToUlong(rhs); // If either operand is signed, return signed result if (lhs < 0 || rhs < 0) { unchecked { return (long)(l ^ r); } } return l ^ r; } internal static object BAnd(decimal lhs, decimal rhs) { ulong l = ConvertToUlong(lhs); ulong r = ConvertToUlong(rhs); // If either operand is signed, return signed result if (lhs < 0 || rhs < 0) { unchecked { return (long)(l & r); } } return l & r; } // This had to be done because if we try to cast a negative decimal number to unsigned, we get an OverFlowException // We had to cast them to long (if they are negative) and then promote everything to ULong. // While returning the result, we can return either signed or unsigned depending on the input. private static ulong ConvertToUlong(decimal val) { if (val < 0) { long lValue = LanguagePrimitives.ConvertTo<long>(val); return unchecked((ulong)lValue); } return LanguagePrimitives.ConvertTo<ulong>(val); } internal static object LeftShift(decimal val, int count) { if (val <= int.MaxValue && val >= int.MinValue) { return unchecked(LanguagePrimitives.ConvertTo<int>(val) << count); } if (val <= uint.MaxValue && val >= uint.MinValue) { return unchecked(LanguagePrimitives.ConvertTo<uint>(val) << count); } if (val <= long.MaxValue && val >= long.MinValue) { return unchecked(LanguagePrimitives.ConvertTo<long>(val) << count); } if (val <= ulong.MaxValue && val >= ulong.MinValue) { return unchecked(LanguagePrimitives.ConvertTo<ulong>(val) << count); } LanguagePrimitives.ThrowInvalidCastException(val, typeof(int)); Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException."); return null; } internal static object RightShift(decimal val, int count) { if (val <= int.MaxValue && val >= int.MinValue) { return unchecked(LanguagePrimitives.ConvertTo<int>(val) >> count); } if (val <= uint.MaxValue && val >= uint.MinValue) { return unchecked(LanguagePrimitives.ConvertTo<uint>(val) >> count); } if (val <= long.MaxValue && val >= long.MinValue) { return unchecked(LanguagePrimitives.ConvertTo<long>(val) >> count); } if (val <= ulong.MaxValue && val >= ulong.MinValue) { return unchecked(LanguagePrimitives.ConvertTo<ulong>(val) >> count); } LanguagePrimitives.ThrowInvalidCastException(val, typeof(int)); Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException."); return null; } internal static object CompareEq(decimal lhs, decimal rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } internal static object CompareNe(decimal lhs, decimal rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } internal static object CompareLt(decimal lhs, decimal rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } internal static object CompareLe(decimal lhs, decimal rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } internal static object CompareGt(decimal lhs, decimal rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } internal static object CompareGe(decimal lhs, decimal rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } private static object CompareWithDouble(decimal left, double right, Func<double, double, object> doubleComparer, Func<decimal, decimal, object> decimalComparer) { decimal rightAsDecimal; try { rightAsDecimal = (decimal)right; } catch (OverflowException) { return doubleComparer((double)left, right); } return decimalComparer(left, rightAsDecimal); } private static object CompareWithDouble(double left, decimal right, Func<double, double, object> doubleComparer, Func<decimal, decimal, object> decimalComparer) { decimal leftAsDecimal; try { leftAsDecimal = (decimal)left; } catch (OverflowException) { return doubleComparer(left, (double)right); } return decimalComparer(leftAsDecimal, right); } internal static object CompareEq1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareEq, CompareEq); } internal static object CompareNe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareNe, CompareNe); } internal static object CompareLt1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLt, CompareLt); } internal static object CompareLe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLe, CompareLe); } internal static object CompareGt1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGt, CompareGt); } internal static object CompareGe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGe, CompareGe); } internal static object CompareEq2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareEq, CompareEq); } internal static object CompareNe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareNe, CompareNe); } internal static object CompareLt2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLt, CompareLt); } internal static object CompareLe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLe, CompareLe); } internal static object CompareGt2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGt, CompareGt); } internal static object CompareGe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGe, CompareGe); } } internal static class DoubleOps { internal static object Add(double lhs, double rhs) { return lhs + rhs; } internal static object Sub(double lhs, double rhs) { return lhs - rhs; } internal static object Multiply(double lhs, double rhs) { return lhs * rhs; } internal static object Divide(double lhs, double rhs) { return lhs / rhs; } internal static object Remainder(double lhs, double rhs) { return lhs % rhs; } internal static object BNot(double val) { try { checked { if (val <= int.MaxValue && val >= int.MinValue) { return ~LanguagePrimitives.ConvertTo<int>(val); } if (val <= uint.MaxValue && val >= uint.MinValue) { return ~LanguagePrimitives.ConvertTo<uint>(val); } if (val <= long.MaxValue && val >= long.MinValue) { return ~LanguagePrimitives.ConvertTo<long>(val); } if (val <= ulong.MaxValue && val >= ulong.MinValue) { return ~LanguagePrimitives.ConvertTo<ulong>(val); } } } catch (OverflowException) { } LanguagePrimitives.ThrowInvalidCastException(val, typeof(ulong)); Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException."); return null; } internal static object BOr(double lhs, double rhs) { ulong l = ConvertToUlong(lhs); ulong r = ConvertToUlong(rhs); // If either operand is signed, return signed result if (lhs < 0 || rhs < 0) { unchecked { return (long)(l | r); } } return l | r; } internal static object BXor(double lhs, double rhs) { ulong l = ConvertToUlong(lhs); ulong r = ConvertToUlong(rhs); // If either operand is signed, return signed result if (lhs < 0 || rhs < 0) { unchecked { return (long)(l ^ r); } } return l ^ r; } internal static object BAnd(double lhs, double rhs) { ulong l = ConvertToUlong(lhs); ulong r = ConvertToUlong(rhs); // If either operand is signed, return signed result if (lhs < 0 || rhs < 0) { unchecked { return (long)(l & r); } } return l & r; } // This had to be done because if we try to cast a negative double number to unsigned, we get an OverFlowException // We had to cast them to long (if they are negative) and then promote everything to ULong. // While returning the result, we can return either signed or unsigned depending on the input. private static ulong ConvertToUlong(double val) { if (val < 0) { long lValue = LanguagePrimitives.ConvertTo<long>(val); return unchecked((ulong)lValue); } return LanguagePrimitives.ConvertTo<ulong>(val); } internal static object LeftShift(double val, int count) { checked { if (val <= int.MaxValue && val >= int.MinValue) { return LanguagePrimitives.ConvertTo<int>(val) << count; } if (val <= uint.MaxValue && val >= uint.MinValue) { return LanguagePrimitives.ConvertTo<uint>(val) << count; } if (val <= long.MaxValue && val >= long.MinValue) { return LanguagePrimitives.ConvertTo<long>(val) << count; } if (val <= ulong.MaxValue && val >= ulong.MinValue) { return LanguagePrimitives.ConvertTo<ulong>(val) << count; } } LanguagePrimitives.ThrowInvalidCastException(val, typeof(ulong)); Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException."); return null; } internal static object RightShift(double val, int count) { checked { if (val <= int.MaxValue && val >= int.MinValue) { return LanguagePrimitives.ConvertTo<int>(val) >> count; } if (val <= uint.MaxValue && val >= uint.MinValue) { return LanguagePrimitives.ConvertTo<uint>(val) >> count; } if (val <= long.MaxValue && val >= long.MinValue) { return LanguagePrimitives.ConvertTo<long>(val) >> count; } if (val <= ulong.MaxValue && val >= ulong.MinValue) { return LanguagePrimitives.ConvertTo<ulong>(val) >> count; } } LanguagePrimitives.ThrowInvalidCastException(val, typeof(ulong)); Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException."); return null; } internal static object CompareEq(double lhs, double rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; } internal static object CompareNe(double lhs, double rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; } internal static object CompareLt(double lhs, double rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; } internal static object CompareLe(double lhs, double rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; } internal static object CompareGt(double lhs, double rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; } internal static object CompareGe(double lhs, double rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } internal static class CharOps { internal static object CompareStringIeq(char lhs, string rhs) { if (rhs.Length != 1) { return Boxed.False; } return CompareIeq(lhs, rhs[0]); } internal static object CompareStringIne(char lhs, string rhs) { if (rhs.Length != 1) { return Boxed.True; } return CompareIne(lhs, rhs[0]); } internal static object CompareIeq(char lhs, char rhs) { char firstAsUpper = char.ToUpperInvariant(lhs); char secondAsUpper = char.ToUpperInvariant(rhs); return firstAsUpper == secondAsUpper ? Boxed.True : Boxed.False; } internal static object CompareIne(char lhs, char rhs) { char firstAsUpper = char.ToUpperInvariant(lhs); char secondAsUpper = char.ToUpperInvariant(rhs); return firstAsUpper != secondAsUpper ? Boxed.True : Boxed.False; } internal static object[] Range(char start, char end) { int lower = (int)start; int upper = (int)end; int absRange = Math.Abs(checked(upper - lower)); object[] ra = new object[absRange + 1]; if (lower > upper) { // 3 .. 1 => 3 2 1 for (int offset = 0; offset < ra.Length; offset++) ra[offset] = (char)lower--; } else { // 1 .. 3 => 1 2 3 for (int offset = 0; offset < ra.Length; offset++) ra[offset] = (char)lower++; } return ra; } } }
// 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.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // internal class EncoderNLS : Encoder { // Need a place for the last left over character, most of our encodings use this internal char _charLeftOver; private Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _charsUsed; internal EncoderNLS(Encoding encoding) { _encoding = encoding; _fallback = _encoding.EncoderFallback; this.Reset(); } public override void Reset() { _charLeftOver = (char)0; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call the pointer version int result = -1; fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) { result = GetByteCount(pChars + index, count, flush); } return result; } public unsafe override int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); _mustFlush = flush; _throwOnOverflow = true; Debug.Assert(_encoding != null); return _encoding.GetByteCount(chars, count, this); } public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; // Just call pointer version fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) // Remember that charCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush); } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); _mustFlush = flush; _throwOnOverflow = true; Debug.Assert(_encoding != null); return _encoding.GetBytes(chars, charCount, bytes, byteCount, this); } // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) public override unsafe void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call the pointer version (can't do this for non-msft encoders) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) { fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) { Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes public override unsafe void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // We don't want to throw _mustFlush = flush; _throwOnOverflow = false; _charsUsed = 0; // Do conversion Debug.Assert(_encoding != null); bytesUsed = _encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = _charsUsed; // Per MSDN, "The completed output parameter indicates whether all the data in the input // buffer was converted and stored in the output buffer." That means we've successfully // consumed all the input _and_ there's no pending state or fallback data remaining to be output. completed = (charsUsed == charCount) && !this.HasState && (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0); // Our data thingys are now full, we can return } public Encoding Encoding { get { Debug.Assert(_encoding != null); return _encoding; } } public bool MustFlush { get { return _mustFlush; } } /// <summary> /// States whether a call to <see cref="Encoding.GetBytes(char*, int, byte*, int, EncoderNLS)"/> must first drain data on this <see cref="EncoderNLS"/> instance. /// </summary> internal bool HasLeftoverData => _charLeftOver != default || (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0); // Anything left in our encoder? internal virtual bool HasState { get { return (_charLeftOver != (char)0); } } // Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow) internal void ClearMustFlush() { _mustFlush = false; } internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan<char> chars, out int charsConsumed) { // Quick check: we _should not_ have leftover fallback data from a previous invocation, // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, Encoding.EncodingName, _fallbackBuffer.GetType())); } // If we have a leftover high surrogate from a previous operation, consume it now. // We won't clear the _charLeftOver field since GetByteCount is supposed to be // a non-mutating operation, and we need the field to retain its value for the // next call to Convert. charsConsumed = 0; // could be incorrect, will fix up later in the method if (_charLeftOver == default) { return 0; // no leftover high surrogate char - short-circuit and finish } else { char secondChar = default; if (chars.IsEmpty) { // If the input buffer is empty and we're not being asked to flush, no-op and return // success to our caller. If we're being asked to flush, the leftover high surrogate from // the previous operation will go through the fallback mechanism by itself. if (!MustFlush) { return 0; // no-op = success } } else { secondChar = chars[0]; } // If we have to fallback the chars we're reading immediately below, populate the // fallback buffer with the invalid data. We'll just fall through to the "consume // fallback buffer" logic at the end of the method. bool didFallback; if (Rune.TryCreate(_charLeftOver, secondChar, out Rune rune)) { charsConsumed = 1; // consumed the leftover high surrogate + the first char in the input buffer Debug.Assert(_encoding != null); if (_encoding.TryGetByteCount(rune, out int byteCount)) { Debug.Assert(byteCount >= 0, "Encoding shouldn't have returned a negative byte count."); return byteCount; } else { // The fallback mechanism relies on a negative index to convey "the start of the invalid // sequence was some number of chars back before the current buffer." In this block and // in the block immediately thereafter, we know we have a single leftover high surrogate // character from a previous operation, so we provide an index of -1 to convey that the // char immediately before the current buffer was the start of the invalid sequence. didFallback = FallbackBuffer.Fallback(_charLeftOver, secondChar, index: -1); } } else { didFallback = FallbackBuffer.Fallback(_charLeftOver, index: -1); } // Now tally the number of bytes that would've been emitted as part of fallback. Debug.Assert(_fallbackBuffer != null); return _fallbackBuffer.DrainRemainingDataForGetByteCount(); } } internal bool TryDrainLeftoverDataForGetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsConsumed, out int bytesWritten) { // We may have a leftover high surrogate data from a previous invocation, or we may have leftover // data in the fallback buffer, or we may have neither, but we will never have both. Check for these // conditions and handle them now. charsConsumed = 0; // could be incorrect, will fix up later in the method bytesWritten = 0; // could be incorrect, will fix up later in the method if (_charLeftOver != default) { char secondChar = default; if (chars.IsEmpty) { // If the input buffer is empty and we're not being asked to flush, no-op and return // success to our caller. If we're being asked to flush, the leftover high surrogate from // the previous operation will go through the fallback mechanism by itself. if (!MustFlush) { charsConsumed = 0; bytesWritten = 0; return true; // no-op = success } } else { secondChar = chars[0]; } // If we have to fallback the chars we're reading immediately below, populate the // fallback buffer with the invalid data. We'll just fall through to the "consume // fallback buffer" logic at the end of the method. if (Rune.TryCreate(_charLeftOver, secondChar, out Rune rune)) { charsConsumed = 1; // at the very least, we consumed 1 char from the input Debug.Assert(_encoding != null); switch (_encoding.EncodeRune(rune, bytes, out bytesWritten)) { case OperationStatus.Done: _charLeftOver = default; // we just consumed this char return true; // that's all - we've handled the leftover data case OperationStatus.DestinationTooSmall: _charLeftOver = default; // we just consumed this char _encoding.ThrowBytesOverflow(this, nothingEncoded: true); // will throw break; case OperationStatus.InvalidData: FallbackBuffer.Fallback(_charLeftOver, secondChar, index: -1); // see comment in DrainLeftoverDataForGetByteCount break; default: Debug.Fail("Unknown return value."); break; } } else { FallbackBuffer.Fallback(_charLeftOver, index: -1); // see comment in DrainLeftoverDataForGetByteCount } } // Now check the fallback buffer for any remaining data. if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) { return _fallbackBuffer.TryDrainRemainingDataForGetBytes(bytes, out bytesWritten); } // And we're done! return true; // success } } }
namespace android.database { [global::MonoJavaBridge.JavaClass(typeof(global::android.database.AbstractCursor_))] public abstract partial class AbstractCursor : java.lang.Object, CrossProcessCursor { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AbstractCursor() { InitJNI(); } protected AbstractCursor(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] protected partial class SelfContentObserver : android.database.ContentObserver { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static SelfContentObserver() { InitJNI(); } protected SelfContentObserver(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _deliverSelfNotifications2429; public override bool deliverSelfNotifications() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.SelfContentObserver._deliverSelfNotifications2429); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.SelfContentObserver.staticClass, global::android.database.AbstractCursor.SelfContentObserver._deliverSelfNotifications2429); } internal static global::MonoJavaBridge.MethodId _onChange2430; public override void onChange(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.SelfContentObserver._onChange2430, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.SelfContentObserver.staticClass, global::android.database.AbstractCursor.SelfContentObserver._onChange2430, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _SelfContentObserver2431; public SelfContentObserver(android.database.AbstractCursor arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.database.AbstractCursor.SelfContentObserver.staticClass, global::android.database.AbstractCursor.SelfContentObserver._SelfContentObserver2431, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.AbstractCursor.SelfContentObserver.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/AbstractCursor$SelfContentObserver")); global::android.database.AbstractCursor.SelfContentObserver._deliverSelfNotifications2429 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.SelfContentObserver.staticClass, "deliverSelfNotifications", "()Z"); global::android.database.AbstractCursor.SelfContentObserver._onChange2430 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.SelfContentObserver.staticClass, "onChange", "(Z)V"); global::android.database.AbstractCursor.SelfContentObserver._SelfContentObserver2431 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.SelfContentObserver.staticClass, "<init>", "(Landroid/database/AbstractCursor;)V"); } } internal static global::MonoJavaBridge.MethodId _finalize2432; protected override void finalize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._finalize2432); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._finalize2432); } internal static global::MonoJavaBridge.MethodId _getShort2433; public abstract short getShort(int arg0); internal static global::MonoJavaBridge.MethodId _getInt2434; public abstract int getInt(int arg0); internal static global::MonoJavaBridge.MethodId _getLong2435; public abstract long getLong(int arg0); internal static global::MonoJavaBridge.MethodId _getFloat2436; public abstract float getFloat(int arg0); internal static global::MonoJavaBridge.MethodId _getDouble2437; public abstract double getDouble(int arg0); internal static global::MonoJavaBridge.MethodId _close2438; public virtual void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._close2438); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._close2438); } internal static global::MonoJavaBridge.MethodId _getString2439; public abstract global::java.lang.String getString(int arg0); internal static global::MonoJavaBridge.MethodId _isFirst2440; public virtual bool isFirst() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._isFirst2440); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._isFirst2440); } internal static global::MonoJavaBridge.MethodId _isClosed2441; public virtual bool isClosed() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._isClosed2441); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._isClosed2441); } internal static global::MonoJavaBridge.MethodId _getPosition2442; public virtual int getPosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.AbstractCursor._getPosition2442); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getPosition2442); } internal static global::MonoJavaBridge.MethodId _getExtras2443; public virtual global::android.os.Bundle getExtras() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.AbstractCursor._getExtras2443)) as android.os.Bundle; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getExtras2443)) as android.os.Bundle; } internal static global::MonoJavaBridge.MethodId _registerContentObserver2444; public virtual void registerContentObserver(android.database.ContentObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._registerContentObserver2444, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._registerContentObserver2444, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterContentObserver2445; public virtual void unregisterContentObserver(android.database.ContentObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._unregisterContentObserver2445, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._unregisterContentObserver2445, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getWindow2446; public virtual global::android.database.CursorWindow getWindow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.AbstractCursor._getWindow2446)) as android.database.CursorWindow; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getWindow2446)) as android.database.CursorWindow; } internal static global::MonoJavaBridge.MethodId _getCount2447; public abstract int getCount(); internal static global::MonoJavaBridge.MethodId _move2448; public virtual bool move(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._move2448, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._move2448, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _moveToPosition2449; public virtual bool moveToPosition(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._moveToPosition2449, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._moveToPosition2449, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _moveToFirst2450; public virtual bool moveToFirst() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._moveToFirst2450); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._moveToFirst2450); } internal static global::MonoJavaBridge.MethodId _moveToLast2451; public virtual bool moveToLast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._moveToLast2451); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._moveToLast2451); } internal static global::MonoJavaBridge.MethodId _moveToNext2452; public virtual bool moveToNext() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._moveToNext2452); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._moveToNext2452); } internal static global::MonoJavaBridge.MethodId _moveToPrevious2453; public virtual bool moveToPrevious() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._moveToPrevious2453); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._moveToPrevious2453); } internal static global::MonoJavaBridge.MethodId _isLast2454; public virtual bool isLast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._isLast2454); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._isLast2454); } internal static global::MonoJavaBridge.MethodId _isBeforeFirst2455; public virtual bool isBeforeFirst() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._isBeforeFirst2455); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._isBeforeFirst2455); } internal static global::MonoJavaBridge.MethodId _isAfterLast2456; public virtual bool isAfterLast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._isAfterLast2456); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._isAfterLast2456); } internal static global::MonoJavaBridge.MethodId _getColumnIndex2457; public virtual int getColumnIndex(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.AbstractCursor._getColumnIndex2457, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getColumnIndex2457, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getColumnIndexOrThrow2458; public virtual int getColumnIndexOrThrow(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.AbstractCursor._getColumnIndexOrThrow2458, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getColumnIndexOrThrow2458, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getColumnName2459; public virtual global::java.lang.String getColumnName(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.AbstractCursor._getColumnName2459, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getColumnName2459, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getColumnNames2460; public abstract global::java.lang.String[] getColumnNames(); internal static global::MonoJavaBridge.MethodId _getColumnCount2461; public virtual int getColumnCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.AbstractCursor._getColumnCount2461); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getColumnCount2461); } internal static global::MonoJavaBridge.MethodId _getBlob2462; public virtual byte[] getBlob(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.AbstractCursor._getBlob2462, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getBlob2462, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; } internal static global::MonoJavaBridge.MethodId _copyStringToBuffer2463; public virtual void copyStringToBuffer(int arg0, android.database.CharArrayBuffer arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._copyStringToBuffer2463, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._copyStringToBuffer2463, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isNull2464; public abstract bool isNull(int arg0); internal static global::MonoJavaBridge.MethodId _deactivate2465; public virtual void deactivate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._deactivate2465); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._deactivate2465); } internal static global::MonoJavaBridge.MethodId _requery2466; public virtual bool requery() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._requery2466); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._requery2466); } internal static global::MonoJavaBridge.MethodId _registerDataSetObserver2467; public virtual void registerDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._registerDataSetObserver2467, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._registerDataSetObserver2467, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterDataSetObserver2468; public virtual void unregisterDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._unregisterDataSetObserver2468, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._unregisterDataSetObserver2468, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setNotificationUri2469; public virtual void setNotificationUri(android.content.ContentResolver arg0, android.net.Uri arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._setNotificationUri2469, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._setNotificationUri2469, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getWantsAllOnMoveCalls2470; public virtual bool getWantsAllOnMoveCalls() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._getWantsAllOnMoveCalls2470); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getWantsAllOnMoveCalls2470); } internal static global::MonoJavaBridge.MethodId _respond2471; public virtual global::android.os.Bundle respond(android.os.Bundle arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.AbstractCursor._respond2471, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Bundle; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._respond2471, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Bundle; } internal static global::MonoJavaBridge.MethodId _onChange2472; protected virtual void onChange(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._onChange2472, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._onChange2472, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onMove2473; public virtual bool onMove(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._onMove2473, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._onMove2473, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _fillWindow2474; public virtual void fillWindow(int arg0, android.database.CursorWindow arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._fillWindow2474, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._fillWindow2474, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isFieldUpdated2475; protected virtual bool isFieldUpdated(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor._isFieldUpdated2475, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._isFieldUpdated2475, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getUpdatedField2476; protected virtual global::java.lang.Object getUpdatedField(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.AbstractCursor._getUpdatedField2476, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._getUpdatedField2476, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _checkPosition2477; protected virtual void checkPosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.AbstractCursor._checkPosition2477); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._checkPosition2477); } internal static global::MonoJavaBridge.MethodId _AbstractCursor2478; public AbstractCursor() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.database.AbstractCursor.staticClass, global::android.database.AbstractCursor._AbstractCursor2478); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.AbstractCursor.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/AbstractCursor")); global::android.database.AbstractCursor._finalize2432 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "finalize", "()V"); global::android.database.AbstractCursor._getShort2433 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getShort", "(I)S"); global::android.database.AbstractCursor._getInt2434 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getInt", "(I)I"); global::android.database.AbstractCursor._getLong2435 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getLong", "(I)J"); global::android.database.AbstractCursor._getFloat2436 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getFloat", "(I)F"); global::android.database.AbstractCursor._getDouble2437 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getDouble", "(I)D"); global::android.database.AbstractCursor._close2438 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "close", "()V"); global::android.database.AbstractCursor._getString2439 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getString", "(I)Ljava/lang/String;"); global::android.database.AbstractCursor._isFirst2440 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "isFirst", "()Z"); global::android.database.AbstractCursor._isClosed2441 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "isClosed", "()Z"); global::android.database.AbstractCursor._getPosition2442 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getPosition", "()I"); global::android.database.AbstractCursor._getExtras2443 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getExtras", "()Landroid/os/Bundle;"); global::android.database.AbstractCursor._registerContentObserver2444 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "registerContentObserver", "(Landroid/database/ContentObserver;)V"); global::android.database.AbstractCursor._unregisterContentObserver2445 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "unregisterContentObserver", "(Landroid/database/ContentObserver;)V"); global::android.database.AbstractCursor._getWindow2446 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getWindow", "()Landroid/database/CursorWindow;"); global::android.database.AbstractCursor._getCount2447 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getCount", "()I"); global::android.database.AbstractCursor._move2448 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "move", "(I)Z"); global::android.database.AbstractCursor._moveToPosition2449 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "moveToPosition", "(I)Z"); global::android.database.AbstractCursor._moveToFirst2450 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "moveToFirst", "()Z"); global::android.database.AbstractCursor._moveToLast2451 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "moveToLast", "()Z"); global::android.database.AbstractCursor._moveToNext2452 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "moveToNext", "()Z"); global::android.database.AbstractCursor._moveToPrevious2453 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "moveToPrevious", "()Z"); global::android.database.AbstractCursor._isLast2454 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "isLast", "()Z"); global::android.database.AbstractCursor._isBeforeFirst2455 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "isBeforeFirst", "()Z"); global::android.database.AbstractCursor._isAfterLast2456 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "isAfterLast", "()Z"); global::android.database.AbstractCursor._getColumnIndex2457 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getColumnIndex", "(Ljava/lang/String;)I"); global::android.database.AbstractCursor._getColumnIndexOrThrow2458 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getColumnIndexOrThrow", "(Ljava/lang/String;)I"); global::android.database.AbstractCursor._getColumnName2459 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getColumnName", "(I)Ljava/lang/String;"); global::android.database.AbstractCursor._getColumnNames2460 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getColumnNames", "()[Ljava/lang/String;"); global::android.database.AbstractCursor._getColumnCount2461 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getColumnCount", "()I"); global::android.database.AbstractCursor._getBlob2462 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getBlob", "(I)[B"); global::android.database.AbstractCursor._copyStringToBuffer2463 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "copyStringToBuffer", "(ILandroid/database/CharArrayBuffer;)V"); global::android.database.AbstractCursor._isNull2464 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "isNull", "(I)Z"); global::android.database.AbstractCursor._deactivate2465 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "deactivate", "()V"); global::android.database.AbstractCursor._requery2466 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "requery", "()Z"); global::android.database.AbstractCursor._registerDataSetObserver2467 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "registerDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.database.AbstractCursor._unregisterDataSetObserver2468 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "unregisterDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.database.AbstractCursor._setNotificationUri2469 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "setNotificationUri", "(Landroid/content/ContentResolver;Landroid/net/Uri;)V"); global::android.database.AbstractCursor._getWantsAllOnMoveCalls2470 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getWantsAllOnMoveCalls", "()Z"); global::android.database.AbstractCursor._respond2471 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "respond", "(Landroid/os/Bundle;)Landroid/os/Bundle;"); global::android.database.AbstractCursor._onChange2472 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "onChange", "(Z)V"); global::android.database.AbstractCursor._onMove2473 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "onMove", "(II)Z"); global::android.database.AbstractCursor._fillWindow2474 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "fillWindow", "(ILandroid/database/CursorWindow;)V"); global::android.database.AbstractCursor._isFieldUpdated2475 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "isFieldUpdated", "(I)Z"); global::android.database.AbstractCursor._getUpdatedField2476 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "getUpdatedField", "(I)Ljava/lang/Object;"); global::android.database.AbstractCursor._checkPosition2477 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "checkPosition", "()V"); global::android.database.AbstractCursor._AbstractCursor2478 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.database.AbstractCursor))] public sealed partial class AbstractCursor_ : android.database.AbstractCursor { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AbstractCursor_() { InitJNI(); } internal AbstractCursor_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getShort2479; public override short getShort(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::android.database.AbstractCursor_._getShort2479, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._getShort2479, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getInt2480; public override int getInt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.AbstractCursor_._getInt2480, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._getInt2480, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getLong2481; public override long getLong(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.AbstractCursor_._getLong2481, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._getLong2481, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFloat2482; public override float getFloat(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.database.AbstractCursor_._getFloat2482, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._getFloat2482, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDouble2483; public override double getDouble(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::android.database.AbstractCursor_._getDouble2483, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._getDouble2483, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getString2484; public override global::java.lang.String getString(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.AbstractCursor_._getString2484, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._getString2484, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getCount2485; public override int getCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.AbstractCursor_._getCount2485); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._getCount2485); } internal static global::MonoJavaBridge.MethodId _getColumnNames2486; public override global::java.lang.String[] getColumnNames() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.AbstractCursor_._getColumnNames2486)) as java.lang.String[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._getColumnNames2486)) as java.lang.String[]; } internal static global::MonoJavaBridge.MethodId _isNull2487; public override bool isNull(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor_._isNull2487, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.AbstractCursor_.staticClass, global::android.database.AbstractCursor_._isNull2487, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.AbstractCursor_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/AbstractCursor")); global::android.database.AbstractCursor_._getShort2479 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "getShort", "(I)S"); global::android.database.AbstractCursor_._getInt2480 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "getInt", "(I)I"); global::android.database.AbstractCursor_._getLong2481 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "getLong", "(I)J"); global::android.database.AbstractCursor_._getFloat2482 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "getFloat", "(I)F"); global::android.database.AbstractCursor_._getDouble2483 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "getDouble", "(I)D"); global::android.database.AbstractCursor_._getString2484 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "getString", "(I)Ljava/lang/String;"); global::android.database.AbstractCursor_._getCount2485 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "getCount", "()I"); global::android.database.AbstractCursor_._getColumnNames2486 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "getColumnNames", "()[Ljava/lang/String;"); global::android.database.AbstractCursor_._isNull2487 = @__env.GetMethodIDNoThrow(global::android.database.AbstractCursor_.staticClass, "isNull", "(I)Z"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Controls.Primitives; using System.Windows.Media; using Xwt.Accessibility; using Xwt.Backends; namespace Xwt.WPFBackend { class AccessibleBackend : IAccessibleBackend { UIElement element; IAccessibleEventSink eventSink; ApplicationContext context; IList<object> nativeChildren = new List<object> (); public bool IsAccessible { get; set; } private string identifier; public string Identifier { get { return AutomationProperties.GetAutomationId (element); } set { identifier = value; AutomationProperties.SetAutomationId (element, value); } } private string label; public string Label { get { return AutomationProperties.GetName (element); } set { label = value; AutomationProperties.SetName (element, value); } } private string description; public string Description { get { return AutomationProperties.GetHelpText (element); } set { description = value; AutomationProperties.SetHelpText (element, value); } } private Widget labelWidget; public Widget LabelWidget { set { labelWidget = value; AutomationProperties.SetLabeledBy (element, (Toolkit.GetBackend (value) as WidgetBackend)?.Widget); } } /// <summary> /// In some cases (just Popovers currently) we need to wait to set the automation properties until the element /// that needs them comes into existence (a PopoverRoot in the case of a Popover, when it's shown). This is /// used for that delayed initialization. /// </summary> /// <param name="element">UIElement on which to set the properties</param> public void InitAutomationProperties (UIElement element) { if (identifier != null) AutomationProperties.SetAutomationId (element, identifier); if (label != null) AutomationProperties.SetName (element, label); if (description != null) AutomationProperties.SetHelpText (element, description); if (labelWidget != null) AutomationProperties.SetLabeledBy (element, (Toolkit.GetBackend (labelWidget) as WidgetBackend)?.Widget); } public string Title { get; set; } public string Value { get; set; } public Role Role { get; set; } = Role.Custom; public Uri Uri { get; set; } public Rectangle Bounds { get; set; } public string RoleDescription { get; set; } public void DisableEvent (object eventId) { } public void EnableEvent (object eventId) { } public void Initialize (IWidgetBackend parentWidget, IAccessibleEventSink eventSink) { Initialize (parentWidget.NativeWidget, eventSink); var wpfBackend = parentWidget as WidgetBackend; if (wpfBackend != null) wpfBackend.HasAccessibleObject = true; } public void Initialize (IPopoverBackend parentPopover, IAccessibleEventSink eventSink) { var popoverBackend = (PopoverBackend) parentPopover; Popup popup = popoverBackend.NativeWidget; Initialize (popup, eventSink); } public void Initialize(IMenuBackend parentMenu, IAccessibleEventSink eventSync) { var menuBackend = (MenuBackend)parentMenu; Initialize(menuBackend.NativeMenu, eventSink); } public void Initialize (IMenuItemBackend parentMenuItem, IAccessibleEventSink eventSink) { var menuItemBackend = (MenuItemBackend)parentMenuItem; Initialize (menuItemBackend.MenuItem, eventSink); } public void Initialize (object parentWidget, IAccessibleEventSink eventSink) { this.element = parentWidget as UIElement; if (element == null) throw new ArgumentException ("Widget is not a UIElement"); this.eventSink = eventSink; } public void InitializeBackend (object frontend, ApplicationContext context) { this.context = context; } internal void PerformInvoke () { context.InvokeUserCode (() => eventSink.OnPress ()); } // The following child methods are only supported for Canvas based widgets public void AddChild (object nativeChild) { if (element is CustomCanvas && nativeChild is AutomationPeer) ((CustomCanvas)element).AutomationPeer?.AddChild ((AutomationPeer)nativeChild); else nativeChildren.Add (nativeChild); } public void RemoveAllChildren () { if (element is CustomCanvas) ((CustomCanvas)element).AutomationPeer?.RemoveAllChildren (); else nativeChildren.Clear (); } public void RemoveChild (object nativeChild) { if (element is CustomCanvas && nativeChild is AutomationPeer) ((CustomCanvas)element).AutomationPeer?.RemoveChild ((AutomationPeer)nativeChild); else nativeChildren.Remove (nativeChild); } public IEnumerable<object> GetChildren () { if (element is CustomCanvas) return ((CustomCanvas)element).AutomationPeer.GetChildren (); else return nativeChildren; } public static AutomationControlType RoleToControlType (Role role) { switch (role) { case Role.Button: case Role.MenuButton: case Role.ToggleButton: return AutomationControlType.Button; case Role.CheckBox: return AutomationControlType.CheckBox; case Role.RadioButton: return AutomationControlType.RadioButton; case Role.RadioGroup: return AutomationControlType.Group; case Role.ComboBox: return AutomationControlType.ComboBox; case Role.List: return AutomationControlType.List; case Role.Popup: case Role.ToolTip: return AutomationControlType.ToolTip; case Role.ToolBar: return AutomationControlType.ToolBar; case Role.Label: return AutomationControlType.Text; case Role.Link: return AutomationControlType.Hyperlink; case Role.Image: return AutomationControlType.Image; case Role.Cell: return AutomationControlType.DataItem; case Role.Table: return AutomationControlType.DataGrid; case Role.Paned: return AutomationControlType.Pane; default: return AutomationControlType.Custom; } } } }
//------------------------------------------------------------------------------ // <copyright file="ValidateNames.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ using System; #if !SILVERLIGHT using System.Xml.XPath; #endif using System.Diagnostics; using System.Globalization; #if SILVERLIGHT_XPATH namespace System.Xml.XPath { #else namespace System.Xml { #endif /// <summary> /// Contains various static functions and methods for parsing and validating: /// NCName (not namespace-aware, no colons allowed) /// QName (prefix:local-name) /// </summary> internal static class ValidateNames { internal enum Flags { NCNames = 0x1, // Validate that each non-empty prefix and localName is a valid NCName CheckLocalName = 0x2, // Validate the local-name CheckPrefixMapping = 0x4, // Validate the prefix --> namespace mapping All = 0x7, AllExceptNCNames = 0x6, AllExceptPrefixMapping = 0x3, }; static XmlCharType xmlCharType = XmlCharType.Instance; #if !SILVERLIGHT //----------------------------------------------- // Nmtoken parsing //----------------------------------------------- /// <summary> /// Attempts to parse the input string as an Nmtoken (see the XML spec production [7] && XML Namespaces spec). /// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached. /// Returns the number of valid Nmtoken chars that were parsed. /// </summary> internal static unsafe int ParseNmtoken(string s, int offset) { Debug.Assert(s != null && offset <= s.Length); // Keep parsing until the end of string or an invalid NCName character is reached int i = offset; while (i < s.Length) { if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0) { // if (xmlCharType.IsNCNameSingleChar(s[i])) { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { break; } } return i - offset; } #endif //----------------------------------------------- // Nmtoken parsing (no XML namespaces support) //----------------------------------------------- /// <summary> /// Attempts to parse the input string as an Nmtoken (see the XML spec production [7]) without taking /// into account the XML Namespaces spec. What it means is that the ':' character is allowed at any /// position and any number of times in the token. /// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached. /// Returns the number of valid Nmtoken chars that were parsed. /// </summary> #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif internal static unsafe int ParseNmtokenNoNamespaces(string s, int offset) { Debug.Assert(s != null && offset <= s.Length); // Keep parsing until the end of string or an invalid Name character is reached int i = offset; while (i < s.Length) { if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0 || s[i] == ':') { // if (xmlCharType.IsNameSingleChar(s[i])) { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { break; } } return i - offset; } // helper methods internal static bool IsNmtokenNoNamespaces(string s) { int endPos = ParseNmtokenNoNamespaces(s, 0); return endPos > 0 && endPos == s.Length; } //----------------------------------------------- // Name parsing (no XML namespaces support) //----------------------------------------------- /// <summary> /// Attempts to parse the input string as a Name without taking into account the XML Namespaces spec. /// What it means is that the ':' character does not delimiter prefix and local name, but it is a regular /// name character, which is allowed to appear at any position and any number of times in the name. /// Quits parsing when an invalid Name char is reached or the end of string is reached. /// Returns the number of valid Name chars that were parsed. /// </summary> #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif internal static unsafe int ParseNameNoNamespaces(string s, int offset) { Debug.Assert(s != null && offset <= s.Length); // Quit if the first character is not a valid NCName starting character int i = offset; if (i < s.Length) { if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCStartNameSC) != 0 || s[i] == ':') { // xmlCharType.IsStartNCNameSingleChar(s[i])) { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { return 0; // no valid StartNCName char } // Keep parsing until the end of string or an invalid NCName character is reached while (i < s.Length) { if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0 || s[i] == ':') { // if (xmlCharType.IsNCNameSingleChar(s[i])) i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { break; } } } return i - offset; } // helper methods internal static bool IsNameNoNamespaces(string s) { int endPos = ParseNameNoNamespaces(s, 0); return endPos > 0 && endPos == s.Length; } //----------------------------------------------- // NCName parsing //----------------------------------------------- /// <summary> /// Attempts to parse the input string as an NCName (see the XML Namespace spec). /// Quits parsing when an invalid NCName char is reached or the end of string is reached. /// Returns the number of valid NCName chars that were parsed. /// </summary> #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif internal static unsafe int ParseNCName(string s, int offset) { Debug.Assert(s != null && offset <= s.Length); // Quit if the first character is not a valid NCName starting character int i = offset; if (i < s.Length) { if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCStartNameSC) != 0) { // xmlCharType.IsStartNCNameSingleChar(s[i])) { i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { return 0; // no valid StartNCName char } // Keep parsing until the end of string or an invalid NCName character is reached while (i < s.Length) { if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0) { // if (xmlCharType.IsNCNameSingleChar(s[i])) i++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(s, i)) { i += 2; } #endif else { break; } } } return i - offset; } internal static int ParseNCName(string s) { return ParseNCName(s, 0); } /// <summary> /// Calls parseName and throws exception if the resulting name is not a valid NCName. /// Returns the input string if there is no error. /// </summary> internal static string ParseNCNameThrow(string s) { // throwOnError = true ParseNCNameInternal(s, true); return s; } /// <summary> /// Calls parseName and returns false or throws exception if the resulting name is not /// a valid NCName. Returns the input string if there is no error. /// </summary> private static bool ParseNCNameInternal(string s, bool throwOnError) { int len = ParseNCName(s, 0); if (len == 0 || len != s.Length) { // If the string is not a valid NCName, then throw or return false if (throwOnError) ThrowInvalidName(s, 0, len); return false; } return true; } //----------------------------------------------- // QName parsing //----------------------------------------------- /// <summary> /// Attempts to parse the input string as a QName (see the XML Namespace spec). /// Quits parsing when an invalid QName char is reached or the end of string is reached. /// Returns the number of valid QName chars that were parsed. /// Sets colonOffset to the offset of a colon character if it exists, or 0 otherwise. /// </summary> internal static int ParseQName(string s, int offset, out int colonOffset) { int len, lenLocal; // Assume no colon colonOffset = 0; // Parse NCName (may be prefix, may be local name) len = ParseNCName(s, offset); if (len != 0) { // Non-empty NCName, so look for colon if there are any characters left offset += len; if (offset < s.Length && s[offset] == ':') { // First NCName was prefix, so look for local name part lenLocal = ParseNCName(s, offset + 1); if (lenLocal != 0) { // Local name part found, so increase total QName length (add 1 for colon) colonOffset = offset; len += lenLocal + 1; } } } return len; } /// <summary> /// Calls parseQName and throws exception if the resulting name is not a valid QName. /// Returns the prefix and local name parts. /// </summary> internal static void ParseQNameThrow(string s, out string prefix, out string localName) { int colonOffset; int len = ParseQName(s, 0, out colonOffset); if (len == 0 || len != s.Length) { // If the string is not a valid QName, then throw ThrowInvalidName(s, 0, len); } if (colonOffset != 0) { prefix = s.Substring(0, colonOffset); localName = s.Substring(colonOffset + 1); } else { prefix = ""; localName = s; } } #if !SILVERLIGHT /// <summary> /// Parses the input string as a NameTest (see the XPath spec), returning the prefix and /// local name parts. Throws an exception if the given string is not a valid NameTest. /// If the NameTest contains a star, null values for localName (case NCName':*'), or for /// both localName and prefix (case '*') are returned. /// </summary> internal static void ParseNameTestThrow(string s, out string prefix, out string localName) { int len, lenLocal, offset; if (s.Length != 0 && s[0] == '*') { // '*' as a NameTest prefix = localName = null; len = 1; } else { // Parse NCName (may be prefix, may be local name) len = ParseNCName(s, 0); if (len != 0) { // Non-empty NCName, so look for colon if there are any characters left localName = s.Substring(0, len); if (len < s.Length && s[len] == ':') { // First NCName was prefix, so look for local name part prefix = localName; offset = len + 1; if (offset < s.Length && s[offset] == '*') { // '*' as a local name part, add 2 to len for colon and star localName = null; len += 2; } else { lenLocal = ParseNCName(s, offset); if (lenLocal != 0) { // Local name part found, so increase total NameTest length localName = s.Substring(offset, lenLocal); len += lenLocal + 1; } } } else { prefix = string.Empty; } } else { // Make the compiler happy prefix = localName = null; } } if (len == 0 || len != s.Length) { // If the string is not a valid NameTest, then throw ThrowInvalidName(s, 0, len); } } #endif /// <summary> /// Throws an invalid name exception. /// </summary> /// <param name="s">String that was parsed.</param> /// <param name="offsetStartChar">Offset in string where parsing began.</param> /// <param name="offsetBadChar">Offset in string where parsing failed.</param> internal static void ThrowInvalidName(string s, int offsetStartChar, int offsetBadChar) { // If the name is empty, throw an exception if (offsetStartChar >= s.Length) #if !SILVERLIGHT_XPATH throw new XmlException(Res.Xml_EmptyName, string.Empty); #else throw new XmlException(Res.GetString(Res.Xml_EmptyName, string.Empty)); #endif Debug.Assert(offsetBadChar < s.Length); if (xmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !XmlCharType.Instance.IsStartNCNameSingleChar(s[offsetBadChar])) { // The error character is a valid name character, but is not a valid start name character #if !SILVERLIGHT_XPATH throw new XmlException(Res.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar)); #else throw new XmlException(Res.GetString(Res.Xml_BadStartNameChar, XmlExceptionHelper.BuildCharExceptionArgs(s, offsetBadChar))); #endif } else { // The error character is an invalid name character #if !SILVERLIGHT_XPATH throw new XmlException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar)); #else throw new XmlException(Res.GetString(Res.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(s, offsetBadChar))); #endif } } #if !SILVERLIGHT internal static Exception GetInvalidNameException(string s, int offsetStartChar, int offsetBadChar) { // If the name is empty, throw an exception if (offsetStartChar >= s.Length) return new XmlException(Res.Xml_EmptyName, string.Empty); Debug.Assert(offsetBadChar < s.Length); if (xmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !xmlCharType.IsStartNCNameSingleChar(s[offsetBadChar])) { // The error character is a valid name character, but is not a valid start name character return new XmlException(Res.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar)); } else { // The error character is an invalid name character return new XmlException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar)); } } /// <summary> /// Returns true if "prefix" starts with the characters 'x', 'm', 'l' (case-insensitive). /// </summary> internal static bool StartsWithXml(string s) { if (s.Length < 3) return false; if (s[0] != 'x' && s[0] != 'X') return false; if (s[1] != 'm' && s[1] != 'M') return false; if (s[2] != 'l' && s[2] != 'L') return false; return true; } /// <summary> /// Returns true if "s" is a namespace that is reserved by Xml 1.0 or Namespace 1.0. /// </summary> internal static bool IsReservedNamespace(string s) { return s.Equals(XmlReservedNs.NsXml) || s.Equals(XmlReservedNs.NsXmlNs); } /// <summary> /// Throw if the specified name parts are not valid according to the rules of "nodeKind". Check only rules that are /// specified by the Flags. /// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty. /// </summary> internal static void ValidateNameThrow(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags) { // throwOnError = true ValidateNameInternal(prefix, localName, ns, nodeKind, flags, true); } /// <summary> /// Return false if the specified name parts are not valid according to the rules of "nodeKind". Check only rules that are /// specified by the Flags. /// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty. /// </summary> internal static bool ValidateName(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags) { // throwOnError = false return ValidateNameInternal(prefix, localName, ns, nodeKind, flags, false); } /// <summary> /// Return false or throw if the specified name parts are not valid according to the rules of "nodeKind". Check only rules /// that are specified by the Flags. /// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty. /// </summary> private static bool ValidateNameInternal(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags, bool throwOnError) { Debug.Assert(prefix != null && localName != null && ns != null); if ((flags & Flags.NCNames) != 0) { // 1. Verify that each non-empty prefix and localName is a valid NCName if (prefix.Length != 0) if (!ParseNCNameInternal(prefix, throwOnError)) { return false; } if (localName.Length != 0) if (!ParseNCNameInternal(localName, throwOnError)) { return false; } } if ((flags & Flags.CheckLocalName) != 0) { // 2. Determine whether the local name is valid switch (nodeKind) { case XPathNodeType.Element: // Elements and attributes must have a non-empty local name if (localName.Length == 0) { if (throwOnError) throw new XmlException(Res.Xdom_Empty_LocalName, string.Empty); return false; } break; case XPathNodeType.Attribute: // Attribute local name cannot be "xmlns" if namespace is empty if (ns.Length == 0 && localName.Equals("xmlns")) { if (throwOnError) throw new XmlException(Res.XmlBadName, new string[] {nodeKind.ToString(), localName}); return false; } goto case XPathNodeType.Element; case XPathNodeType.ProcessingInstruction: // PI's local-name must be non-empty and cannot be 'xml' (case-insensitive) if (localName.Length == 0 || (localName.Length == 3 && StartsWithXml(localName))) { if (throwOnError) throw new XmlException(Res.Xml_InvalidPIName, localName); return false; } break; default: // All other node types must have empty local-name if (localName.Length != 0) { if (throwOnError) throw new XmlException(Res.XmlNoNameAllowed, nodeKind.ToString()); return false; } break; } } if ((flags & Flags.CheckPrefixMapping) != 0) { // 3. Determine whether the prefix is valid switch (nodeKind) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.Namespace: if (ns.Length == 0) { // If namespace is empty, then prefix must be empty if (prefix.Length != 0) { if (throwOnError) throw new XmlException(Res.Xml_PrefixForEmptyNs, string.Empty); return false; } } else { // Don't allow empty attribute prefix since namespace is non-empty if (prefix.Length == 0 && nodeKind == XPathNodeType.Attribute) { if (throwOnError) throw new XmlException(Res.XmlBadName, new string[] {nodeKind.ToString(), localName}); return false; } if (prefix.Equals("xml")) { // xml prefix must be mapped to the xml namespace if (!ns.Equals(XmlReservedNs.NsXml)) { if (throwOnError) throw new XmlException(Res.Xml_XmlPrefix, string.Empty); return false; } } else if (prefix.Equals("xmlns")) { // Prefix may never be 'xmlns' if (throwOnError) throw new XmlException(Res.Xml_XmlnsPrefix, string.Empty); return false; } else if (IsReservedNamespace(ns)) { // Don't allow non-reserved prefixes to map to xml or xmlns namespaces if (throwOnError) throw new XmlException(Res.Xml_NamespaceDeclXmlXmlns, string.Empty); return false; } } break; case XPathNodeType.ProcessingInstruction: // PI's prefix and namespace must be empty if (prefix.Length != 0 || ns.Length != 0) { if (throwOnError) throw new XmlException(Res.Xml_InvalidPIName, CreateName(prefix, localName)); return false; } break; default: // All other node types must have empty prefix and namespace if (prefix.Length != 0 || ns.Length != 0) { if (throwOnError) throw new XmlException(Res.XmlNoNameAllowed, nodeKind.ToString()); return false; } break; } } return true; } /// <summary> /// Creates a colon-delimited qname from prefix and local name parts. /// </summary> private static string CreateName(string prefix, string localName) { return (prefix.Length != 0) ? prefix + ":" + localName : localName; } #endif #if !SILVERLIGHT || SILVERLIGHT_XPATH /// <summary> /// Split a QualifiedName into prefix and localname, w/o any checking. /// (Used for XmlReader/XPathNavigator MoveTo(name) methods) /// </summary> internal static void SplitQName(string name, out string prefix, out string lname) { int colonPos = name.IndexOf(':'); if (-1 == colonPos) { prefix = string.Empty; lname = name; } else if (0 == colonPos || (name.Length-1) == colonPos) { #if !SILVERLIGHT_XPATH throw new ArgumentException(Res.GetString(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(':', '\0')), "name"); #else throw new ArgumentException(Res.GetString(Res.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(':', '\0')), "name"); #endif } else { prefix = name.Substring(0, colonPos); colonPos++; // move after colon lname = name.Substring(colonPos, name.Length - colonPos); } } #endif } #if SILVERLIGHT_XPATH internal class XmlExceptionHelper { internal static string[] BuildCharExceptionArgs(string data, int invCharIndex) { return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < data.Length ? data[invCharIndex + 1] : '\0'); } internal static string[] BuildCharExceptionArgs(char[] data, int invCharIndex) { return BuildCharExceptionArgs(data, data.Length, invCharIndex); } internal static string[] BuildCharExceptionArgs(char[] data, int length, int invCharIndex) { Debug.Assert(invCharIndex < data.Length); Debug.Assert(invCharIndex < length); Debug.Assert(length <= data.Length); return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < length ? data[invCharIndex + 1] : '\0'); } internal static string[] BuildCharExceptionArgs(char invChar, char nextChar) { string[] aStringList = new string[2]; // for surrogate characters include both high and low char in the message so that a full character is displayed if (XmlCharType.IsHighSurrogate(invChar) && nextChar != 0) { int combinedChar = XmlCharType.CombineSurrogateChar(nextChar, invChar); aStringList[0] = new string(new char[] { invChar, nextChar }); aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", combinedChar); } else { // don't include 0 character in the string - in means eof-of-string in native code, where this may bubble up to if ((int)invChar == 0) { aStringList[0] = "."; } else { aStringList[0] = invChar.ToString(CultureInfo.InvariantCulture); } aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", (int)invChar); } return aStringList; } } #endif }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Xml; using ASC.Core.Common.Settings; using ASC.Web.Studio.PublicResources; namespace ASC.Web.Studio.Core.Users { [Serializable] [DataContract] public class PeopleNamesSettings : BaseSettings<PeopleNamesSettings> { public override Guid ID { get { return new Guid("47F34957-6A70-4236-9681-C8281FB762FA"); } } [DataMember(Name = "Item")] public PeopleNamesItem Item { get; set; } [DataMember(Name = "ItemId")] public string ItemID { get; set; } public override ISettings GetDefault() { return new PeopleNamesSettings { ItemID = PeopleNamesItem.DefaultID }; } } [DataContract] public class PeopleNamesItem { private static readonly StringComparison cmp = StringComparison.InvariantCultureIgnoreCase; [DataMember(Name = "SchemaName")] private string schemaName; [DataMember(Name = "UserCaption")] private string userCaption; [DataMember(Name = "UsersCaption")] private string usersCaption; [DataMember(Name = "GroupCaption")] private string groupCaption; [DataMember(Name = "GroupsCaption")] private string groupsCaption; [DataMember(Name = "UserPostCaption")] private string userPostCaption; [DataMember(Name = "GroupHeadCaption")] private string groupHeadCaption; [DataMember(Name = "RegDateCaption")] private string regDateCaption; [DataMember(Name = "GuestCaption")] private string guestCaption; [DataMember(Name = "GuestsCaption")] private string guestsCaption; public static string DefaultID { get { return "common"; } } public static string CustomID { get { return "custom"; } } [DataMember(Name = "Id")] public string Id { get; set; } public string SchemaName { get { return Id.Equals(CustomID, cmp) ? schemaName ?? string.Empty : GetResourceValue(schemaName); } set { schemaName = value; } } public string UserCaption { get { return Id.Equals(CustomID, cmp) ? userCaption ?? string.Empty : GetResourceValue(userCaption); } set { userCaption = value; } } public string UsersCaption { get { return Id.Equals(CustomID, cmp) ? usersCaption ?? string.Empty : GetResourceValue(usersCaption); } set { usersCaption = value; } } public string GroupCaption { get { return Id.Equals(CustomID, cmp) ? groupCaption ?? string.Empty : GetResourceValue(groupCaption); } set { groupCaption = value; } } public string GroupsCaption { get { return Id.Equals(CustomID, cmp) ? groupsCaption ?? string.Empty : GetResourceValue(groupsCaption); } set { groupsCaption = value; } } public string UserPostCaption { get { return Id.Equals(CustomID, cmp) ? userPostCaption ?? string.Empty : GetResourceValue(userPostCaption); } set { userPostCaption = value; } } public string GroupHeadCaption { get { return Id.Equals(CustomID, cmp) ? groupHeadCaption ?? string.Empty : GetResourceValue(groupHeadCaption); } set { groupHeadCaption = value; } } public string RegDateCaption { get { return Id.Equals(CustomID, cmp) ? regDateCaption ?? string.Empty : GetResourceValue(regDateCaption); } set { regDateCaption = value; } } public string GuestCaption { get { return Id.Equals(CustomID, cmp) ? guestCaption ?? NamingPeopleResource.CommonGuest : GetResourceValue(guestCaption); } set { guestCaption = value; } } public string GuestsCaption { get { return Id.Equals(CustomID, cmp) ? guestsCaption ?? NamingPeopleResource.CommonGuests : GetResourceValue(guestsCaption); } set { guestsCaption = value; } } private static string GetResourceValue(string resourceKey) { if (string.IsNullOrEmpty(resourceKey)) { return string.Empty; } return (string)typeof(NamingPeopleResource).GetProperty(resourceKey, BindingFlags.Static | BindingFlags.Public).GetValue(null, null); } } public class CustomNamingPeople { private static bool loaded = false; private static readonly List<PeopleNamesItem> items = new List<PeopleNamesItem>(); public static PeopleNamesItem Current { get { var settings = PeopleNamesSettings.Load(); return PeopleNamesItem.CustomID.Equals(settings.ItemID, StringComparison.InvariantCultureIgnoreCase) && settings.Item != null ? settings.Item : GetPeopleNames(settings.ItemID); } } public static string Substitute<T>(string resourceKey) where T : class { var text = (string)typeof(T).GetProperty(resourceKey, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null, null); return Substitute(text); } public static string Substitute(string text) { return SubstituteGuest(SubstituteUserPost(SubstituteRegDate(SubstituteGroupHead(SubstitutePost(SubstituteGroup(SubstituteUser(text))))))); } public static Dictionary<string, string> GetSchemas() { Load(); var dict = items.ToDictionary(i => i.Id.ToLower(), i => i.SchemaName); dict.Add(PeopleNamesItem.CustomID, Resource.CustomNamingPeopleSchema); return dict; } public static PeopleNamesItem GetPeopleNames(string schemaId) { if (PeopleNamesItem.CustomID.Equals(schemaId, StringComparison.InvariantCultureIgnoreCase)) { var settings = PeopleNamesSettings.Load(); return settings.Item ?? new PeopleNamesItem { Id = PeopleNamesItem.CustomID, GroupCaption = string.Empty, GroupHeadCaption = string.Empty, GroupsCaption = string.Empty, RegDateCaption = string.Empty, UserCaption = string.Empty, UserPostCaption = string.Empty, UsersCaption = string.Empty, GuestCaption = string.Empty, GuestsCaption = string.Empty, SchemaName = Resource.CustomNamingPeopleSchema }; } Load(); return items.Find(i => i.Id.Equals(schemaId, StringComparison.InvariantCultureIgnoreCase)); } public static void SetPeopleNames(string schemaId) { var settings = PeopleNamesSettings.Load(); settings.ItemID = schemaId; settings.Save(); } public static void SetPeopleNames(PeopleNamesItem custom) { var settings = PeopleNamesSettings.Load(); custom.Id = PeopleNamesItem.CustomID; settings.ItemID = PeopleNamesItem.CustomID; settings.Item = custom; settings.Save(); } private static void Load() { if (loaded) { return; } loaded = true; var doc = new XmlDocument(); doc.LoadXml(NamingPeopleResource.PeopleNames); items.Clear(); foreach (XmlNode node in doc.SelectNodes("/root/item")) { var item = new PeopleNamesItem { Id = node.SelectSingleNode("id").InnerText, SchemaName = node.SelectSingleNode("names/schemaname").InnerText, GroupHeadCaption = node.SelectSingleNode("names/grouphead").InnerText, GroupCaption = node.SelectSingleNode("names/group").InnerText, GroupsCaption = node.SelectSingleNode("names/groups").InnerText, UserCaption = node.SelectSingleNode("names/user").InnerText, UsersCaption = node.SelectSingleNode("names/users").InnerText, UserPostCaption = node.SelectSingleNode("names/userpost").InnerText, RegDateCaption = node.SelectSingleNode("names/regdate").InnerText, GuestCaption = node.SelectSingleNode("names/guest").InnerText, GuestsCaption = node.SelectSingleNode("names/guests").InnerText, }; items.Add(item); } } private static string SubstituteUser(string text) { var item = Current; if (item != null) { return text .Replace("{!User}", item.UserCaption) .Replace("{!user}", item.UserCaption.ToLower()) .Replace("{!Users}", item.UsersCaption) .Replace("{!users}", item.UsersCaption.ToLower()); } return text; } private static string SubstituteGroup(string text) { var item = Current; if (item != null) { return text .Replace("{!Group}", item.GroupCaption) .Replace("{!group}", item.GroupCaption.ToLower()) .Replace("{!Groups}", item.GroupsCaption) .Replace("{!groups}", item.GroupsCaption.ToLower()); } return text; } private static string SubstituteGuest(string text) { var item = Current; if (item != null) { return text .Replace("{!Guest}", item.GuestCaption) .Replace("{!guest}", item.GuestCaption.ToLower()) .Replace("{!Guests}", item.GuestsCaption) .Replace("{!guests}", item.GuestsCaption.ToLower()); } return text; } private static string SubstitutePost(string text) { var item = Current; if (item != null) { return text .Replace("{!Post}", item.UserPostCaption) .Replace("{!post}", item.UserPostCaption.ToLower()); } return text; } private static string SubstituteGroupHead(string text) { var item = Current; if (item != null) { return text .Replace("{!Head}", item.GroupHeadCaption) .Replace("{!head}", item.GroupHeadCaption.ToLower()); } return text; } private static string SubstituteRegDate(string text) { var item = Current; if (item != null) { return text .Replace("{!Regdate}", item.RegDateCaption) .Replace("{!regdate}", item.RegDateCaption.ToLower()); } return text; } private static string SubstituteUserPost(string text) { var item = Current; if (item != null) { return text .Replace("{!Userpost}", item.UserPostCaption) .Replace("{!userpost}", item.UserPostCaption.ToLower()); } return text; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 Gallio.Icarus.ProjectProperties { partial class View { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(View)); this.propertiesTabControl = new Gallio.Icarus.Controls.PropertiesTabControl(); this.hintDirectoriesTabPage = new System.Windows.Forms.TabPage(); this.hintDirectoriesGroupBox = new System.Windows.Forms.GroupBox(); this.hintDirectoriesListBox = new System.Windows.Forms.ListBox(); this.newHintDirectoryTextBox = new System.Windows.Forms.TextBox(); this.addFolderButton = new System.Windows.Forms.Button(); this.removeHintDirectoryButton = new System.Windows.Forms.Button(); this.findHintDirectoryButton = new System.Windows.Forms.Button(); this.testPackageTabPage = new System.Windows.Forms.TabPage(); this.testPackageConfigGroupBox = new System.Windows.Forms.GroupBox(); this.shadowCopyCheckBox = new System.Windows.Forms.CheckBox(); this.applicationBaseDirectoryLabel = new System.Windows.Forms.Label(); this.findWorkingDirectoryButton = new System.Windows.Forms.Button(); this.workingDirectoryTextBox = new System.Windows.Forms.TextBox(); this.applicationBaseDirectoryTextBox = new System.Windows.Forms.TextBox(); this.workingDirectoryLabel = new System.Windows.Forms.Label(); this.findApplicationBaseDirectoryButton = new System.Windows.Forms.Button(); this.runnerExtensionsTabPage = new System.Windows.Forms.TabPage(); this.testRunnerExtensionsGroupBox = new System.Windows.Forms.GroupBox(); this.newExtensionTextBox = new System.Windows.Forms.TextBox(); this.removeExtensionButton = new System.Windows.Forms.Button(); this.testRunnerExtensionsListBox = new System.Windows.Forms.ListBox(); this.addTestRunnerExtensionButton = new System.Windows.Forms.Button(); this.reportsTabPage = new System.Windows.Forms.TabPage(); this.reportsGroupBox = new System.Windows.Forms.GroupBox(); this.reportNameFormatTextBox = new System.Windows.Forms.TextBox(); this.reportDirectoryTextBox = new System.Windows.Forms.TextBox(); this.reportNameFormatLabel = new System.Windows.Forms.Label(); this.reportDirectoryLabel = new System.Windows.Forms.Label(); this.propertiesTabControl.SuspendLayout(); this.hintDirectoriesTabPage.SuspendLayout(); this.hintDirectoriesGroupBox.SuspendLayout(); this.testPackageTabPage.SuspendLayout(); this.testPackageConfigGroupBox.SuspendLayout(); this.runnerExtensionsTabPage.SuspendLayout(); this.testRunnerExtensionsGroupBox.SuspendLayout(); this.reportsTabPage.SuspendLayout(); this.reportsGroupBox.SuspendLayout(); this.SuspendLayout(); // // propertiesTabControl // this.propertiesTabControl.Alignment = System.Windows.Forms.TabAlignment.Left; this.propertiesTabControl.Controls.Add(this.hintDirectoriesTabPage); this.propertiesTabControl.Controls.Add(this.testPackageTabPage); this.propertiesTabControl.Controls.Add(this.runnerExtensionsTabPage); this.propertiesTabControl.Controls.Add(this.reportsTabPage); this.propertiesTabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.propertiesTabControl.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed; this.propertiesTabControl.ItemSize = new System.Drawing.Size(35, 125); this.propertiesTabControl.Location = new System.Drawing.Point(0, 0); this.propertiesTabControl.Multiline = true; this.propertiesTabControl.Name = "propertiesTabControl"; this.propertiesTabControl.SelectedIndex = 0; this.propertiesTabControl.Size = new System.Drawing.Size(739, 604); this.propertiesTabControl.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; this.propertiesTabControl.TabIndex = 0; // // hintDirectoriesTabPage // this.hintDirectoriesTabPage.Controls.Add(this.hintDirectoriesGroupBox); this.hintDirectoriesTabPage.Location = new System.Drawing.Point(129, 4); this.hintDirectoriesTabPage.Name = "hintDirectoriesTabPage"; this.hintDirectoriesTabPage.Padding = new System.Windows.Forms.Padding(3); this.hintDirectoriesTabPage.Size = new System.Drawing.Size(606, 596); this.hintDirectoriesTabPage.TabIndex = 0; this.hintDirectoriesTabPage.Text = "Hint Directories"; this.hintDirectoriesTabPage.UseVisualStyleBackColor = true; // // hintDirectoriesGroupBox // this.hintDirectoriesGroupBox.Controls.Add(this.hintDirectoriesListBox); this.hintDirectoriesGroupBox.Controls.Add(this.newHintDirectoryTextBox); this.hintDirectoriesGroupBox.Controls.Add(this.addFolderButton); this.hintDirectoriesGroupBox.Controls.Add(this.removeHintDirectoryButton); this.hintDirectoriesGroupBox.Controls.Add(this.findHintDirectoryButton); this.hintDirectoriesGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.hintDirectoriesGroupBox.Location = new System.Drawing.Point(3, 3); this.hintDirectoriesGroupBox.Name = "hintDirectoriesGroupBox"; this.hintDirectoriesGroupBox.Size = new System.Drawing.Size(600, 590); this.hintDirectoriesGroupBox.TabIndex = 15; this.hintDirectoriesGroupBox.TabStop = false; this.hintDirectoriesGroupBox.Text = "Hint Directories"; // // hintDirectoriesListBox // this.hintDirectoriesListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.hintDirectoriesListBox.FormattingEnabled = true; this.hintDirectoriesListBox.Location = new System.Drawing.Point(17, 89); this.hintDirectoriesListBox.Name = "hintDirectoriesListBox"; this.hintDirectoriesListBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; this.hintDirectoriesListBox.Size = new System.Drawing.Size(528, 238); this.hintDirectoriesListBox.TabIndex = 3; this.hintDirectoriesListBox.SelectedIndexChanged += new System.EventHandler(this.hintDirectoriesListBox_SelectedIndexChanged); // // newHintDirectoryTextBox // this.newHintDirectoryTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.newHintDirectoryTextBox.Location = new System.Drawing.Point(17, 29); this.newHintDirectoryTextBox.Name = "newHintDirectoryTextBox"; this.newHintDirectoryTextBox.Size = new System.Drawing.Size(528, 20); this.newHintDirectoryTextBox.TabIndex = 1; // // addFolderButton // this.addFolderButton.Location = new System.Drawing.Point(17, 55); this.addFolderButton.Name = "addFolderButton"; this.addFolderButton.Size = new System.Drawing.Size(66, 23); this.addFolderButton.TabIndex = 4; this.addFolderButton.Text = "Add Folder"; this.addFolderButton.UseVisualStyleBackColor = true; this.addFolderButton.Click += new System.EventHandler(this.addFolderButton_Click); // // removeHintDirectoryButton // this.removeHintDirectoryButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.removeHintDirectoryButton.Enabled = false; this.removeHintDirectoryButton.Image = ((System.Drawing.Image)(resources.GetObject("removeHintDirectoryButton.Image"))); this.removeHintDirectoryButton.Location = new System.Drawing.Point(551, 89); this.removeHintDirectoryButton.Name = "removeHintDirectoryButton"; this.removeHintDirectoryButton.Size = new System.Drawing.Size(33, 28); this.removeHintDirectoryButton.TabIndex = 5; this.removeHintDirectoryButton.UseVisualStyleBackColor = true; this.removeHintDirectoryButton.Click += new System.EventHandler(this.removeHintDirectoryButton_Click); // // findHintDirectoryButton // this.findHintDirectoryButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.findHintDirectoryButton.Location = new System.Drawing.Point(551, 29); this.findHintDirectoryButton.Name = "findHintDirectoryButton"; this.findHintDirectoryButton.Size = new System.Drawing.Size(33, 23); this.findHintDirectoryButton.TabIndex = 2; this.findHintDirectoryButton.Text = "..."; this.findHintDirectoryButton.UseVisualStyleBackColor = true; this.findHintDirectoryButton.Click += new System.EventHandler(this.findHintDirectoryButton_Click); // // testPackageTabPage // this.testPackageTabPage.Controls.Add(this.testPackageConfigGroupBox); this.testPackageTabPage.Location = new System.Drawing.Point(129, 4); this.testPackageTabPage.Name = "testPackageTabPage"; this.testPackageTabPage.Padding = new System.Windows.Forms.Padding(3); this.testPackageTabPage.Size = new System.Drawing.Size(606, 596); this.testPackageTabPage.TabIndex = 1; this.testPackageTabPage.Text = "Test Package"; this.testPackageTabPage.UseVisualStyleBackColor = true; // // testPackageConfigGroupBox // this.testPackageConfigGroupBox.Controls.Add(this.shadowCopyCheckBox); this.testPackageConfigGroupBox.Controls.Add(this.applicationBaseDirectoryLabel); this.testPackageConfigGroupBox.Controls.Add(this.findWorkingDirectoryButton); this.testPackageConfigGroupBox.Controls.Add(this.workingDirectoryTextBox); this.testPackageConfigGroupBox.Controls.Add(this.applicationBaseDirectoryTextBox); this.testPackageConfigGroupBox.Controls.Add(this.workingDirectoryLabel); this.testPackageConfigGroupBox.Controls.Add(this.findApplicationBaseDirectoryButton); this.testPackageConfigGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.testPackageConfigGroupBox.Location = new System.Drawing.Point(3, 3); this.testPackageConfigGroupBox.Name = "testPackageConfigGroupBox"; this.testPackageConfigGroupBox.Size = new System.Drawing.Size(600, 590); this.testPackageConfigGroupBox.TabIndex = 16; this.testPackageConfigGroupBox.TabStop = false; this.testPackageConfigGroupBox.Text = "Test Package Config"; // // shadowCopyCheckBox // this.shadowCopyCheckBox.AutoSize = true; this.shadowCopyCheckBox.Location = new System.Drawing.Point(19, 128); this.shadowCopyCheckBox.Name = "shadowCopyCheckBox"; this.shadowCopyCheckBox.Size = new System.Drawing.Size(91, 17); this.shadowCopyCheckBox.TabIndex = 12; this.shadowCopyCheckBox.Text = "Shadow copy"; this.shadowCopyCheckBox.UseVisualStyleBackColor = true; this.shadowCopyCheckBox.CheckedChanged += new System.EventHandler(this.shadowCopyCheckBox_CheckedChanged); // // applicationBaseDirectoryLabel // this.applicationBaseDirectoryLabel.AutoSize = true; this.applicationBaseDirectoryLabel.Location = new System.Drawing.Point(15, 25); this.applicationBaseDirectoryLabel.Name = "applicationBaseDirectoryLabel"; this.applicationBaseDirectoryLabel.Size = new System.Drawing.Size(131, 13); this.applicationBaseDirectoryLabel.TabIndex = 6; this.applicationBaseDirectoryLabel.Text = "Application base directory:"; // // findWorkingDirectoryButton // this.findWorkingDirectoryButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.findWorkingDirectoryButton.Location = new System.Drawing.Point(553, 86); this.findWorkingDirectoryButton.Name = "findWorkingDirectoryButton"; this.findWorkingDirectoryButton.Size = new System.Drawing.Size(33, 23); this.findWorkingDirectoryButton.TabIndex = 11; this.findWorkingDirectoryButton.Text = "..."; this.findWorkingDirectoryButton.UseVisualStyleBackColor = true; this.findWorkingDirectoryButton.Click += new System.EventHandler(this.findWorkingDirectoryButton_Click); // // workingDirectoryTextBox // this.workingDirectoryTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.workingDirectoryTextBox.Location = new System.Drawing.Point(19, 89); this.workingDirectoryTextBox.Name = "workingDirectoryTextBox"; this.workingDirectoryTextBox.Size = new System.Drawing.Size(517, 20); this.workingDirectoryTextBox.TabIndex = 10; this.workingDirectoryTextBox.Leave += new System.EventHandler(this.workingDirectoryTextBox_Leave); // // applicationBaseDirectoryTextBox // this.applicationBaseDirectoryTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.applicationBaseDirectoryTextBox.Location = new System.Drawing.Point(18, 41); this.applicationBaseDirectoryTextBox.Name = "applicationBaseDirectoryTextBox"; this.applicationBaseDirectoryTextBox.Size = new System.Drawing.Size(517, 20); this.applicationBaseDirectoryTextBox.TabIndex = 7; this.applicationBaseDirectoryTextBox.Leave += new System.EventHandler(this.applicationBaseDirectoryTextBox_Leave); // // workingDirectoryLabel // this.workingDirectoryLabel.AutoSize = true; this.workingDirectoryLabel.Location = new System.Drawing.Point(15, 73); this.workingDirectoryLabel.Name = "workingDirectoryLabel"; this.workingDirectoryLabel.Size = new System.Drawing.Size(93, 13); this.workingDirectoryLabel.TabIndex = 9; this.workingDirectoryLabel.Text = "Working directory:"; // // findApplicationBaseDirectoryButton // this.findApplicationBaseDirectoryButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.findApplicationBaseDirectoryButton.Location = new System.Drawing.Point(552, 38); this.findApplicationBaseDirectoryButton.Name = "findApplicationBaseDirectoryButton"; this.findApplicationBaseDirectoryButton.Size = new System.Drawing.Size(33, 23); this.findApplicationBaseDirectoryButton.TabIndex = 8; this.findApplicationBaseDirectoryButton.Text = "..."; this.findApplicationBaseDirectoryButton.UseVisualStyleBackColor = true; this.findApplicationBaseDirectoryButton.Click += new System.EventHandler(this.findApplicationBaseDirectoryButton_Click); // // runnerExtensionsTabPage // this.runnerExtensionsTabPage.Controls.Add(this.testRunnerExtensionsGroupBox); this.runnerExtensionsTabPage.Location = new System.Drawing.Point(129, 4); this.runnerExtensionsTabPage.Name = "runnerExtensionsTabPage"; this.runnerExtensionsTabPage.Size = new System.Drawing.Size(606, 596); this.runnerExtensionsTabPage.TabIndex = 2; this.runnerExtensionsTabPage.Text = "Runner Extensions"; this.runnerExtensionsTabPage.UseVisualStyleBackColor = true; // // testRunnerExtensionsGroupBox // this.testRunnerExtensionsGroupBox.Controls.Add(this.newExtensionTextBox); this.testRunnerExtensionsGroupBox.Controls.Add(this.removeExtensionButton); this.testRunnerExtensionsGroupBox.Controls.Add(this.testRunnerExtensionsListBox); this.testRunnerExtensionsGroupBox.Controls.Add(this.addTestRunnerExtensionButton); this.testRunnerExtensionsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.testRunnerExtensionsGroupBox.Location = new System.Drawing.Point(0, 0); this.testRunnerExtensionsGroupBox.Name = "testRunnerExtensionsGroupBox"; this.testRunnerExtensionsGroupBox.Size = new System.Drawing.Size(606, 596); this.testRunnerExtensionsGroupBox.TabIndex = 14; this.testRunnerExtensionsGroupBox.TabStop = false; this.testRunnerExtensionsGroupBox.Text = "Test Runner Extensions"; // // newExtensionTextBox // this.newExtensionTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.newExtensionTextBox.Location = new System.Drawing.Point(18, 29); this.newExtensionTextBox.Name = "newExtensionTextBox"; this.newExtensionTextBox.Size = new System.Drawing.Size(523, 20); this.newExtensionTextBox.TabIndex = 7; // // removeExtensionButton // this.removeExtensionButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.removeExtensionButton.Enabled = false; this.removeExtensionButton.Image = global::Gallio.Icarus.Properties.Resources.cross; this.removeExtensionButton.Location = new System.Drawing.Point(560, 98); this.removeExtensionButton.Name = "removeExtensionButton"; this.removeExtensionButton.Size = new System.Drawing.Size(30, 28); this.removeExtensionButton.TabIndex = 11; this.removeExtensionButton.UseVisualStyleBackColor = true; this.removeExtensionButton.Click += new System.EventHandler(this.removeExtensionButton_Click); // // testRunnerExtensionsListBox // this.testRunnerExtensionsListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.testRunnerExtensionsListBox.FormattingEnabled = true; this.testRunnerExtensionsListBox.Location = new System.Drawing.Point(20, 98); this.testRunnerExtensionsListBox.Name = "testRunnerExtensionsListBox"; this.testRunnerExtensionsListBox.Size = new System.Drawing.Size(523, 251); this.testRunnerExtensionsListBox.TabIndex = 9; this.testRunnerExtensionsListBox.SelectedIndexChanged += new System.EventHandler(this.testRunnerExtensionsListBox_SelectedIndexChanged); // // addTestRunnerExtensionButton // this.addTestRunnerExtensionButton.AutoSize = true; this.addTestRunnerExtensionButton.Location = new System.Drawing.Point(18, 55); this.addTestRunnerExtensionButton.Name = "addTestRunnerExtensionButton"; this.addTestRunnerExtensionButton.Size = new System.Drawing.Size(85, 23); this.addTestRunnerExtensionButton.TabIndex = 10; this.addTestRunnerExtensionButton.Text = "Add Extension"; this.addTestRunnerExtensionButton.UseVisualStyleBackColor = true; this.addTestRunnerExtensionButton.Click += new System.EventHandler(this.addExtensionButton_Click); // // reportsTabPage // this.reportsTabPage.Controls.Add(this.reportsGroupBox); this.reportsTabPage.Location = new System.Drawing.Point(129, 4); this.reportsTabPage.Name = "reportsTabPage"; this.reportsTabPage.Size = new System.Drawing.Size(606, 596); this.reportsTabPage.TabIndex = 3; this.reportsTabPage.Text = "Reports"; this.reportsTabPage.UseVisualStyleBackColor = true; // // reportsGroupBox // this.reportsGroupBox.Controls.Add(this.reportNameFormatTextBox); this.reportsGroupBox.Controls.Add(this.reportDirectoryTextBox); this.reportsGroupBox.Controls.Add(this.reportNameFormatLabel); this.reportsGroupBox.Controls.Add(this.reportDirectoryLabel); this.reportsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.reportsGroupBox.Location = new System.Drawing.Point(0, 0); this.reportsGroupBox.Name = "reportsGroupBox"; this.reportsGroupBox.Size = new System.Drawing.Size(606, 596); this.reportsGroupBox.TabIndex = 0; this.reportsGroupBox.TabStop = false; this.reportsGroupBox.Text = "Reports"; // // reportNameFormatTextBox // this.reportNameFormatTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.reportNameFormatTextBox.Location = new System.Drawing.Point(21, 124); this.reportNameFormatTextBox.Name = "reportNameFormatTextBox"; this.reportNameFormatTextBox.Size = new System.Drawing.Size(563, 20); this.reportNameFormatTextBox.TabIndex = 3; this.reportNameFormatTextBox.Leave += new System.EventHandler(this.reportNameFormatTextBox_Leave); // // reportDirectoryTextBox // this.reportDirectoryTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.reportDirectoryTextBox.Location = new System.Drawing.Point(21, 52); this.reportDirectoryTextBox.Name = "reportDirectoryTextBox"; this.reportDirectoryTextBox.ReadOnly = true; this.reportDirectoryTextBox.Size = new System.Drawing.Size(563, 20); this.reportDirectoryTextBox.TabIndex = 2; // // reportNameFormatLabel // this.reportNameFormatLabel.AutoSize = true; this.reportNameFormatLabel.Location = new System.Drawing.Point(18, 99); this.reportNameFormatLabel.Name = "reportNameFormatLabel"; this.reportNameFormatLabel.Size = new System.Drawing.Size(111, 13); this.reportNameFormatLabel.TabIndex = 1; this.reportNameFormatLabel.Text = "Report Name Format: "; // // reportDirectoryLabel // this.reportDirectoryLabel.AutoSize = true; this.reportDirectoryLabel.Location = new System.Drawing.Point(18, 26); this.reportDirectoryLabel.Name = "reportDirectoryLabel"; this.reportDirectoryLabel.Size = new System.Drawing.Size(90, 13); this.reportDirectoryLabel.TabIndex = 0; this.reportDirectoryLabel.Text = "Report Directory: "; // // View // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.propertiesTabControl); this.Name = "View"; this.Size = new System.Drawing.Size(739, 604); this.propertiesTabControl.ResumeLayout(false); this.hintDirectoriesTabPage.ResumeLayout(false); this.hintDirectoriesGroupBox.ResumeLayout(false); this.hintDirectoriesGroupBox.PerformLayout(); this.testPackageTabPage.ResumeLayout(false); this.testPackageConfigGroupBox.ResumeLayout(false); this.testPackageConfigGroupBox.PerformLayout(); this.runnerExtensionsTabPage.ResumeLayout(false); this.testRunnerExtensionsGroupBox.ResumeLayout(false); this.testRunnerExtensionsGroupBox.PerformLayout(); this.reportsTabPage.ResumeLayout(false); this.reportsGroupBox.ResumeLayout(false); this.reportsGroupBox.PerformLayout(); this.ResumeLayout(false); } #endregion private Gallio.Icarus.Controls.PropertiesTabControl propertiesTabControl; private System.Windows.Forms.TabPage hintDirectoriesTabPage; private System.Windows.Forms.TabPage testPackageTabPage; private System.Windows.Forms.TabPage runnerExtensionsTabPage; private System.Windows.Forms.TabPage reportsTabPage; private System.Windows.Forms.GroupBox hintDirectoriesGroupBox; private System.Windows.Forms.ListBox hintDirectoriesListBox; private System.Windows.Forms.TextBox newHintDirectoryTextBox; private System.Windows.Forms.Button addFolderButton; private System.Windows.Forms.Button removeHintDirectoryButton; private System.Windows.Forms.Button findHintDirectoryButton; private System.Windows.Forms.GroupBox testPackageConfigGroupBox; private System.Windows.Forms.CheckBox shadowCopyCheckBox; private System.Windows.Forms.Label applicationBaseDirectoryLabel; private System.Windows.Forms.Button findWorkingDirectoryButton; private System.Windows.Forms.TextBox workingDirectoryTextBox; private System.Windows.Forms.TextBox applicationBaseDirectoryTextBox; private System.Windows.Forms.Label workingDirectoryLabel; private System.Windows.Forms.Button findApplicationBaseDirectoryButton; private System.Windows.Forms.GroupBox testRunnerExtensionsGroupBox; private System.Windows.Forms.TextBox newExtensionTextBox; private System.Windows.Forms.Button removeExtensionButton; private System.Windows.Forms.ListBox testRunnerExtensionsListBox; private System.Windows.Forms.Button addTestRunnerExtensionButton; private System.Windows.Forms.GroupBox reportsGroupBox; private System.Windows.Forms.Label reportDirectoryLabel; private System.Windows.Forms.TextBox reportNameFormatTextBox; private System.Windows.Forms.TextBox reportDirectoryTextBox; private System.Windows.Forms.Label reportNameFormatLabel; } }
// 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.Runtime.CompilerServices; using Xunit; namespace System.Linq.Expressions.Tests { public class RuntimeVariablesTests { [Theory] [ClassData(typeof(CompilationTypes))] public void ReadAndReturnVars(bool useInterpreter) { ParameterExpression x = Expression.Variable(typeof(int)); ParameterExpression y = Expression.Variable(typeof(decimal)); ParameterExpression z = Expression.Variable(typeof(string)); IRuntimeVariables vars = Expression.Lambda<Func<IRuntimeVariables>>( Expression.Block( new[] { x, y, z }, Expression.Assign(x, Expression.Constant(12)), Expression.Assign(y, Expression.Constant(34m)), Expression.Assign(z, Expression.Constant("hello")), Expression.RuntimeVariables(x, y, z) ) ).Compile(useInterpreter)(); Assert.Equal(3, vars.Count); Assert.Equal(12, vars[0]); Assert.Equal(34m, vars[1]); Assert.Equal("hello", vars[2]); } [Theory] [ClassData(typeof(CompilationTypes))] public void IRuntimeVariablesListChecksBounds(bool useInterpreter) { ParameterExpression x = Expression.Variable(typeof(int)); ParameterExpression y = Expression.Variable(typeof(int)); IRuntimeVariables vars = Expression.Lambda<Func<IRuntimeVariables>>( Expression.Block( new[] { x, y }, Expression.RuntimeVariables(x, y) ) ).Compile(useInterpreter)(); Assert.Equal(2, vars.Count); Assert.Throws<IndexOutOfRangeException>(() => vars[-1]); Assert.Throws<IndexOutOfRangeException>(() => vars[-1] = null); Assert.Throws<IndexOutOfRangeException>(() => vars[2]); Assert.Throws<IndexOutOfRangeException>(() => vars[2] = null); } [Theory] [ClassData(typeof(CompilationTypes))] public void ReadAndWriteVars(bool useInterpreter) { ParameterExpression x = Expression.Variable(typeof(int)); ParameterExpression y = Expression.Variable(typeof(decimal)); ParameterExpression z = Expression.Variable(typeof(string)); ParameterExpression r = Expression.Variable(typeof(IRuntimeVariables)); ParameterExpression b = Expression.Variable(typeof(bool)); Assert.True(Expression.Lambda<Func<bool>>( Expression.Block( new[] { x, y, z, r, b }, Expression.Assign(x, Expression.Constant(45)), Expression.Assign(y, Expression.Constant(98.01m)), Expression.Assign(z, Expression.Constant("In fair Verona, where we lay our scene,")), Expression.Assign(r, Expression.RuntimeVariables(x, y, z)), Expression.Assign(b, Expression.Equal(Expression.Constant(45), Expression.Convert(Expression.Property(r, "Item", Expression.Constant(0)), typeof(int)))), Expression.AndAssign(b, Expression.Equal(Expression.Constant(98.01m), Expression.Convert(Expression.Property(r, "Item", Expression.Constant(1)), typeof(decimal)))), Expression.AndAssign(b, Expression.Equal(Expression.Constant("In fair Verona, where we lay our scene,"), Expression.Convert(Expression.Property(r, "Item", Expression.Constant(2)), typeof(string)))), Expression.Assign(Expression.Property(r, "Item", Expression.Constant(0)), Expression.Constant(988, typeof(object))), Expression.Assign(Expression.Property(r, "Item", Expression.Constant(1)), Expression.Constant(0.01m, typeof(object))), Expression.Assign(Expression.Property(r, "Item", Expression.Constant(2)), Expression.Constant("Where civil blood makes civil hands unclean.", typeof(object))), Expression.AndAssign(b, Expression.Equal(Expression.Convert(x, typeof(int)), Expression.Constant(988))), Expression.AndAssign(b, Expression.Equal(Expression.Convert(y, typeof(decimal)), Expression.Constant(0.01m))), Expression.AndAssign(b, Expression.Equal(Expression.Convert(z, typeof(string)), Expression.Constant("Where civil blood makes civil hands unclean."))), b ) ).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void AliasingAllowed(bool useInterpreter) { ParameterExpression x = Expression.Variable(typeof(int)); ParameterExpression r = Expression.Variable(typeof(IRuntimeVariables)); Assert.Equal(15, Expression.Lambda<Func<int>>( Expression.Block( new[] { x, r }, Expression.Assign(x, Expression.Constant(8)), Expression.Assign(r, Expression.RuntimeVariables(x, x)), Expression.Assign( Expression.Property(r, "Item", Expression.Constant(1)), Expression.Convert( Expression.Add( Expression.Constant(7), Expression.Convert(Expression.Property(r, "Item", Expression.Constant(0)), typeof(int)) ), typeof(object)) ), x ) ).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void MixedScope(bool useInterpreter) { ParameterExpression x = Expression.Variable(typeof(int)); ParameterExpression y = Expression.Variable(typeof(int)); IRuntimeVariables vars = Expression.Lambda<Func<IRuntimeVariables>>( Expression.Block( new[] { x }, Expression.Assign(x, Expression.Constant(3)), Expression.Block( new[] { y }, Expression.Assign(y, Expression.Constant(19)), Expression.RuntimeVariables(x, y) ) ) ).Compile(useInterpreter)(); Assert.Equal(3, vars[0]); Assert.Equal(19, vars[1]); } [Fact] public void NullVariableList() { Assert.Throws<ArgumentNullException>("variables", () => Expression.RuntimeVariables(default(ParameterExpression[]))); Assert.Throws<ArgumentNullException>("variables", () => Expression.RuntimeVariables(default(IEnumerable<ParameterExpression>))); } [Fact] public void NullVariableInList() { Assert.Throws<ArgumentNullException>("variables[1]", () => Expression.RuntimeVariables(Expression.Variable(typeof(int)), null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void ZeroVariables(bool useInterpreter) { IRuntimeVariables vars = Expression.Lambda<Func<IRuntimeVariables>>(Expression.RuntimeVariables()).Compile(useInterpreter)(); Assert.Equal(0, vars.Count); Assert.Throws<IndexOutOfRangeException>(() => vars[0]); Assert.Throws<IndexOutOfRangeException>(() => vars[0] = null); } [Fact] public void CannotReduce() { RuntimeVariablesExpression vars = Expression.RuntimeVariables(Expression.Variable(typeof(int))); Assert.False(vars.CanReduce); Assert.Same(vars, vars.Reduce()); Assert.Throws<ArgumentException>(null, () => vars.ReduceAndCheck()); } [Fact] public void UpdateSameCollectionSameNode() { ParameterExpression[] variables = {Expression.Variable(typeof(RuntimeVariablesTests))}; RuntimeVariablesExpression varExp = Expression.RuntimeVariables(variables); Assert.Same(varExp, varExp.Update(variables)); Assert.Same(varExp, varExp.Update(varExp.Variables)); Assert.Same(varExp, NoOpVisitor.Instance.Visit(varExp)); } [Fact] public void UpdateDiffVarsDiffNode() { RuntimeVariablesExpression varExp = Expression.RuntimeVariables(Enumerable.Repeat(Expression.Variable(typeof(RuntimeVariablesTests)), 1)); Assert.NotSame(varExp, varExp.Update(new[] { Expression.Variable(typeof(RuntimeVariablesTests)) })); } [Fact] public void UpdateDoesntRepeatEnumeration() { RuntimeVariablesExpression varExp = Expression.RuntimeVariables(Enumerable.Repeat(Expression.Variable(typeof(RuntimeVariablesTests)), 1)); Assert.NotSame(varExp, varExp.Update(new RunOnceEnumerable<ParameterExpression>(new[] { Expression.Variable(typeof(RuntimeVariablesTests)) }))); } [Fact] public void UpdateNullThrows() { RuntimeVariablesExpression varExp = Expression.RuntimeVariables(Enumerable.Repeat(Expression.Variable(typeof(RuntimeVariablesTests)), 0)); Assert.Throws<ArgumentNullException>("variables", () => varExp.Update(null)); } [Fact] public void ToStringTest() { RuntimeVariablesExpression e1 = Expression.RuntimeVariables(); Assert.Equal("()", e1.ToString()); RuntimeVariablesExpression e2 = Expression.RuntimeVariables(Expression.Parameter(typeof(int), "x")); Assert.Equal("(x)", e2.ToString()); RuntimeVariablesExpression e3 = Expression.RuntimeVariables(Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y")); Assert.Equal("(x, y)", e3.ToString()); } } }
using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Reflection; using bv.common.Core; using System.IO; using System.Linq; #if !MONO using bv.common.Configuration; using System.Windows.Forms; #endif namespace bv.common.Diagnostics { public class Dbg { //private static Regex s_DebugMethodFilterRegexp; //private static bool s_DebugMethodFilterRegexpDefined; private static int m_DefaultDetailLevel; private Dbg() { // NOOP } private static readonly StandardOutput m_StandardOutput = new StandardOutput(); private static IDebugOutput CreateDefaultOutputMethod() { #if !MONO // TODO: allow configurable output to log file m_DefaultDetailLevel = BaseSettings.DebugDetailLevel; if (!BaseSettings.DebugOutput) { return null; } if (!Utils.IsEmpty(BaseSettings.DebugLogFile)) { string logfile = null; DirectoryInfo dir = Directory.GetParent(Application.CommonAppDataPath); logfile = dir.FullName + "\\" + BaseSettings.DebugLogFile; if (IsValidOutputFile(logfile)) return new DebugFileOutput(logfile, false); logfile = Utils.GetExecutingPath() + BaseSettings.DebugLogFile; if (IsValidOutputFile(logfile)) return new DebugFileOutput(logfile, false); } #endif return m_StandardOutput; } private static bool IsValidOutputFile(string fileName) { try { if (System.IO.File.Exists(fileName)) { FileAttributes attr = System.IO.File.GetAttributes(fileName); if ((attr & FileAttributes.ReadOnly)!=0) { attr = attr & (~FileAttributes.ReadOnly); System.IO.File.SetAttributes(fileName, attr); } System.IO.FileStream fs = System.IO.File.OpenWrite(fileName); fs.Close(); } else { System.IO.FileStream fs = System.IO.File.Create(fileName); fs.Close(); } return true; } catch (Exception) { return false; } } private static string FormatDataRow(DataRow row) { var @out = (from DataColumn col in row.Table.Columns select string.Format(":{0} <{1}>", col.ColumnName, FormatValue(row[col]))).ToList(); return string.Format("#<DataRow {0}>", Utils.Join(" ", @out)); } public static string FormatValue(object value) { if (value == null) { return "*Nothing*"; } if (value == DBNull.Value) { return "*DBNull*"; } if (value is DataRow) { return FormatDataRow((DataRow)value); } if (value is DataRowView) { return FormatDataRow(((DataRowView)value).Row); } return value.ToString(); } private static IDebugOutput m_OutputMethod; public static IDebugOutput OutputMethod { get { #if !MONO if (!Config.IsInitialized) return m_StandardOutput; #endif if (m_OutputMethod == null) m_OutputMethod = CreateDefaultOutputMethod(); return m_OutputMethod; //Dim result As IDebugOutput = Nothing //If InitSlot() Then // result = CType(Thread.GetData(s_OutputMethodSlot), IDebugOutput) //Else // result = CreateDefaultOutputMethod() // Thread.SetData(s_OutputMethodSlot, result) //End If //Return result } set { m_OutputMethod = value; //InitSlot() //Thread.SetData(s_OutputMethodSlot, value) } } private static void DoDbg(int detailLevel, string fmt, params object[] args) { if (OutputMethod != null) { var trace = new StackTrace(2, true); MethodBase method = trace.GetFrame(0).GetMethod(); if (ShouldIgnore(detailLevel, method)) { return; } if (args == null || args.Length == 0) { OutputMethod.WriteLine(string.Format("{0} {1}.{2}(): {3}", DateTime.Now, method.DeclaringType.Name, method.Name, fmt)); return; } var newArgs = new string[args.Length]; for (int i = 0; i <= args.Length - 1; i++) { newArgs[i] = FormatValue(args[i]); } OutputMethod.WriteLine(string.Format("{0} {1}.{2}(): {3}", DateTime.Now, method.DeclaringType.Name, method.Name, string.Format(fmt, newArgs))); } } public static void WriteLine(string fmt, params object[] args) { if (OutputMethod != null) { var newArgs = new string[args.Length]; for (int i = 0; i <= args.Length - 1; i++) newArgs[i] = FormatValue(args[i]); OutputMethod.WriteLine(args.Length == 0 ? fmt : string.Format(fmt, newArgs)); } } public static void Debug(string fmt, params object[] args) { DoDbg(0, fmt, args); } public static void ConditionalDebug(int detailLevel, string fmt, params object[] args) { DoDbg(detailLevel, fmt, args); } public static void ConditionalDebug(DebugDetalizationLevel detailLevel, string fmt, params object[] args) { DoDbg((int)detailLevel, fmt, args); } public static void Fail(string fmt, params object[] args) { string message = "Assertion failed: " + string.Format(fmt, args); DoDbg(0, "{0}", message); // TODO: always print failure messages if (Debugger.IsAttached) { Debugger.Break(); } throw (new InternalErrorException(message)); } public static void Assert(bool value, string fmt, params object[] args) { if (!value) { // we duplicate Fail here to make DoDbg work correctly string message = "Assertion failed: " + string.Format(fmt, args); DoDbg(0, "{0}", message); if (Debugger.IsAttached) { Debugger.Break(); } throw (new InternalErrorException(message)); } } public static void DbgAssert(bool value, string fmt, params object[] args) { if (!value) { // we duplicate Fail here to make DoDbg work correctly string message = "Assertion failed: " + string.Format(fmt, args); DoDbg(0, "{0}", message); } } public static void DbgAssert(int detailLevel, bool value, string fmt, params object[] args) { if (!value) { // we duplicate Fail here to make DoDbg work correctly string message = "Assertion failed: " + string.Format(fmt, args); DoDbg(detailLevel, "{0}", message); } } // TODO: probably System.Diagnostics.SymbolStore.* can be used to display extended error information public static void Require(params object[] values) { for (int i = 0; i <= values.Length - 1; i++) { if (values[i] == null) { // we duplicate Fail here to make DoDbg work correctly string message = string.Format("Require: value #{0} (starting from 1) is Nothing", i + 1); DoDbg(0, "{0}", message); if (Debugger.IsAttached) { Debugger.Break(); } throw (new InternalErrorException(message)); } } } private static bool ShouldIgnore(int detailLevel, MethodBase method) { if (detailLevel <= m_DefaultDetailLevel) { return false; } return true; //TODO: should be implemented to skip some output } public static void Trace(params object[] argValues) { #if TRACE if (OutputMethod == null) { return; } var trace = new StackTrace(1, true); MethodBase method = trace.GetFrame(0).GetMethod(); var argStrings = new List<string>(); if (argValues != null && argValues.Length != 0) { ParameterInfo[] @params = method.GetParameters(); int numArgs = Math.Min(@params.Length, argValues.Length); for (int i = 0; i <= numArgs - 1; i++) { string valString = FormatValue(argValues[i]); argStrings.Add(string.Format("{0} = <{1}>", @params[i].Name, valString)); } } OutputMethod.WriteLine(string.Format("--> {0}.{1}({2})", method.DeclaringType.Name, method.Name, Utils.Join(", ", argStrings))); #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Linq.Expressions; using System.Numerics; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Dynamic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Operations; using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; namespace IronPython.Runtime.Types { [PythonType("instance")] [Serializable] [DebuggerTypeProxy(typeof(OldInstance.OldInstanceDebugView)), DebuggerDisplay("old-style instance of {ClassName}")] public sealed partial class OldInstance : ICodeFormattable, #if FEATURE_CUSTOM_TYPE_DESCRIPTOR ICustomTypeDescriptor, #endif ISerializable, IWeakReferenceable, IDynamicMetaObjectProvider, IPythonMembersList, Binding.IFastGettable { private PythonDictionary _dict; internal OldClass _class; private WeakRefTracker _weakRef; // initialized if user defines finalizer on class or instance private static PythonDictionary MakeDictionary(OldClass oldClass) { return new PythonDictionary(new CustomInstanceDictionaryStorage(oldClass.OptimizedInstanceNames, oldClass.OptimizedInstanceNamesVersion)); } public OldInstance(CodeContext/*!*/ context, OldClass @class) { _class = @class; _dict = MakeDictionary(@class); if (_class.HasFinalizer) { // class defines finalizer, we get it automatically. AddFinalizer(context); } } public OldInstance(CodeContext/*!*/ context, OldClass @class, PythonDictionary dict) { _class = @class; _dict = dict ?? PythonDictionary.MakeSymbolDictionary(); if (_class.HasFinalizer) { // class defines finalizer, we get it automatically. AddFinalizer(context); } } #if FEATURE_SERIALIZATION private OldInstance(SerializationInfo info, StreamingContext context) { _class = (OldClass)info.GetValue("__class__", typeof(OldClass)); _dict = MakeDictionary(_class); List<object> keys = (List<object>)info.GetValue("keys", typeof(List<object>)); List<object> values = (List<object>)info.GetValue("values", typeof(List<object>)); for (int i = 0; i < keys.Count; i++) { _dict[keys[i]] = values[i]; } } #pragma warning disable 169 // unused method - called via reflection from serialization [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] private void GetObjectData(SerializationInfo info, StreamingContext context) { ContractUtils.RequiresNotNull(info, "info"); info.AddValue("__class__", _class); List<object> keys = new List<object>(); List<object> values = new List<object>(); foreach (object o in _dict.keys()) { keys.Add(o); object value; bool res = _dict.TryGetValue(o, out value); Debug.Assert(res); values.Add(value); } info.AddValue("keys", keys); info.AddValue("values", values); } #pragma warning restore 169 #endif /// <summary> /// Returns the dictionary used to store state for this object /// </summary> internal PythonDictionary Dictionary { get { return _dict; } } internal string ClassName { get { return _class.Name; } } public static bool operator true(OldInstance self) { return (bool)self.__nonzero__(DefaultContext.Default); } public static bool operator false(OldInstance self) { return !(bool)self.__nonzero__(DefaultContext.Default); } #region Object overrides public override string ToString() { object ret = InvokeOne(this, "__str__"); if (ret != NotImplementedType.Value) { string strRet; if (Converter.TryConvertToString(ret, out strRet) && strRet != null) { return strRet; } throw PythonOps.TypeError("__str__ returned non-string type ({0})", PythonTypeOps.GetName(ret)); } return __repr__(DefaultContext.Default); } #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { object ret = InvokeOne(this, "__repr__"); if(ret != NotImplementedType.Value) { string strRet; if (Converter.TryConvertToString(ret, out strRet) && strRet != null) { return strRet; } throw PythonOps.TypeError("__repr__ returned non-string type ({0})", PythonTypeOps.GetName(ret)); } return string.Format("<{0} instance at {1}>", _class.FullName, PythonOps.HexId(this)); } #endregion [return: MaybeNotImplemented] public object __divmod__(CodeContext context, object divmod) { object value; if (TryGetBoundCustomMember(context, "__divmod__", out value)) { return PythonCalls.Call(context, value, divmod); } return NotImplementedType.Value; } [return: MaybeNotImplemented] public static object __rdivmod__(CodeContext context, object divmod, [NotNull]OldInstance self) { object value; if (self.TryGetBoundCustomMember(context, "__rdivmod__", out value)) { return PythonCalls.Call(context, value, divmod); } return NotImplementedType.Value; } public object __coerce__(CodeContext context, object other) { object value; if (TryGetBoundCustomMember(context, "__coerce__", out value)) { return PythonCalls.Call(context, value, other); } return NotImplementedType.Value; } public object __len__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__len__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__len__"); } public object __pos__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__pos__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__pos__"); } [SpecialName] public object GetItem(CodeContext context, object item) { return PythonOps.Invoke(context, this, "__getitem__", item); } [SpecialName] public void SetItem(CodeContext context, object item, object value) { PythonOps.Invoke(context, this, "__setitem__", item, value); } [SpecialName] public object DeleteItem(CodeContext context, object item) { object value; if (TryGetBoundCustomMember(context, "__delitem__", out value)) { return PythonCalls.Call(context, value, item); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__delitem__"); } [Python3Warning("in 3.x, __getslice__ has been removed; use __getitem__")] public object __getslice__(CodeContext context, int i, int j) { object callable; if (TryRawGetAttr(context, "__getslice__", out callable)) { return PythonCalls.Call(context, callable, i, j); } else if (TryRawGetAttr(context, "__getitem__", out callable)) { return PythonCalls.Call(context, callable, new Slice(i, j)); } throw PythonOps.TypeError("instance {0} does not have __getslice__ or __getitem__", _class.Name); } [Python3Warning("in 3.x, __setslice__ has been removed; use __setitem__")] public void __setslice__(CodeContext context, int i, int j, object value) { object callable; if (TryRawGetAttr(context, "__setslice__", out callable)) { PythonCalls.Call(context, callable, i, j, value); return; } else if (TryRawGetAttr(context, "__setitem__", out callable)) { PythonCalls.Call(context, callable, new Slice(i, j), value); return; } throw PythonOps.TypeError("instance {0} does not have __setslice__ or __setitem__", _class.Name); } [Python3Warning("in 3.x, __delslice__ has been removed; use __delitem__")] public object __delslice__(CodeContext context, int i, int j) { object callable; if (TryRawGetAttr(context, "__delslice__", out callable)) { return PythonCalls.Call(context, callable, i, j); } else if (TryRawGetAttr(context, "__delitem__", out callable)) { return PythonCalls.Call(context, callable, new Slice(i, j)); } throw PythonOps.TypeError("instance {0} does not have __delslice__ or __delitem__", _class.Name); } public object __index__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__int__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.TypeError("object cannot be converted to an index"); } public object __neg__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__neg__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__neg__"); } public object __abs__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__abs__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__abs__"); } public object __invert__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__invert__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__invert__"); } public object __contains__(CodeContext context, object index) { object value; if (TryGetBoundCustomMember(context, "__contains__", out value)) { return PythonCalls.Call(context, value, index); } IEnumerator ie = PythonOps.GetEnumerator(this); while (ie.MoveNext()) { if (PythonOps.EqualRetBool(context, ie.Current, index)) return ScriptingRuntimeHelpers.True; } return ScriptingRuntimeHelpers.False; } [SpecialName] public object Call(CodeContext context) { return Call(context, ArrayUtils.EmptyObjects); } [SpecialName] public object Call(CodeContext context, object args) { try { PythonOps.FunctionPushFrame(context.LanguageContext); object value; if (TryGetBoundCustomMember(context, "__call__", out value)) { return PythonOps.CallWithContext(context, value, args); } } finally { PythonOps.FunctionPopFrame(); } throw PythonOps.AttributeError("{0} instance has no __call__ method", _class.Name); } [SpecialName] public object Call(CodeContext context, params object[] args) { try { PythonOps.FunctionPushFrame(context.LanguageContext); object value; if (TryGetBoundCustomMember(context, "__call__", out value)) { return PythonOps.CallWithContext(context, value, args); } } finally { PythonOps.FunctionPopFrame(); } throw PythonOps.AttributeError("{0} instance has no __call__ method", _class.Name); } [SpecialName] public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) { try { PythonOps.FunctionPushFrame(context.LanguageContext); object value; if (TryGetBoundCustomMember(context, "__call__", out value)) { return context.LanguageContext.CallWithKeywords(value, args, dict); } } finally { PythonOps.FunctionPopFrame(); } throw PythonOps.AttributeError("{0} instance has no __call__ method", _class.Name); } public object __nonzero__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__nonzero__", out value)) { return PythonOps.CallWithContext(context, value); } if (TryGetBoundCustomMember(context, "__len__", out value)) { value = PythonOps.CallWithContext(context, value); // Convert resulting object to the desired type if (value is Int32 || value is BigInteger) { return ScriptingRuntimeHelpers.BooleanToObject(Converter.ConvertToBoolean(value)); } throw PythonOps.TypeError("an integer is required, got {0}", PythonTypeOps.GetName(value)); } return ScriptingRuntimeHelpers.True; } public object __hex__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__hex__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__hex__"); } public object __oct__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__oct__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__oct__"); } public object __int__(CodeContext context) { object value; if (PythonOps.TryGetBoundAttr(context, this, "__int__", out value)) { return PythonOps.CallWithContext(context, value); } return NotImplementedType.Value; } public object __long__(CodeContext context) { object value; if (PythonOps.TryGetBoundAttr(context, this, "__long__", out value)) { return PythonOps.CallWithContext(context, value); } return NotImplementedType.Value; } public object __float__(CodeContext context) { object value; if (PythonOps.TryGetBoundAttr(context, this, "__float__", out value)) { return PythonOps.CallWithContext(context, value); } return NotImplementedType.Value; } public object __complex__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__complex__", out value)) { return PythonOps.CallWithContext(context, value); } return NotImplementedType.Value; } public object __getattribute__(CodeContext context, string name) { object res; if (TryGetBoundCustomMember(context, name, out res)) { return res; } throw PythonOps.AttributeError("{0} instance has no attribute '{1}'", _class._name, name); } internal object GetBoundMember(CodeContext context, string name) { object ret; if (TryGetBoundCustomMember(context, name, out ret)) { return ret; } throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'", PythonTypeOps.GetName(this), name); } #region ICustomMembers Members internal bool TryGetBoundCustomMember(CodeContext context, string name, out object value) { if (name == "__dict__") { //!!! user code can modify __del__ property of __dict__ behind our back value = _dict; return true; } else if (name == "__class__") { value = _class; return true; } if (TryRawGetAttr(context, name, out value)) return true; if (name != "__getattr__") { object getattr; if (TryRawGetAttr(context, "__getattr__", out getattr)) { try { value = PythonCalls.Call(context, getattr, name); return true; } catch (MissingMemberException) { // __getattr__ raised AttributeError, return false. } } } return false; } internal void SetCustomMember(CodeContext context, string name, object value) { object setFunc; if (name == "__class__") { SetClass(value); } else if (name == "__dict__") { SetDict(context, value); } else if (_class.HasSetAttr && _class.TryLookupSlot("__setattr__", out setFunc)) { PythonCalls.Call(context, _class.GetOldStyleDescriptor(context, setFunc, this, _class), name.ToString(), value); } else if (name == "__del__") { SetFinalizer(context, name, value); } else { _dict[name] = value; } } private void SetFinalizer(CodeContext/*!*/ context, string name, object value) { if (!HasFinalizer()) { // user is defining __del__ late bound for the 1st time AddFinalizer(context); } _dict[name] = value; } private void SetDict(CodeContext/*!*/ context, object value) { if (!(value is PythonDictionary dict)) { throw PythonOps.TypeError("__dict__ must be set to a dictionary"); } if (HasFinalizer() && !_class.HasFinalizer) { if (!dict.ContainsKey("__del__")) { ClearFinalizer(); } } else if (dict.ContainsKey("__del__")) { AddFinalizer(context); } _dict = dict; } private void SetClass(object value) { if (!(value is OldClass oc)) { throw PythonOps.TypeError("__class__ must be set to class"); } _class = oc; } internal bool DeleteCustomMember(CodeContext context, string name) { if (name == "__class__") throw PythonOps.TypeError("__class__ must be set to class"); if (name == "__dict__") throw PythonOps.TypeError("__dict__ must be set to a dictionary"); object delFunc; if (_class.HasDelAttr && _class.TryLookupSlot("__delattr__", out delFunc)) { PythonCalls.Call(context, _class.GetOldStyleDescriptor(context, delFunc, this, _class), name.ToString()); return true; } if (name == "__del__") { // removing finalizer if (HasFinalizer() && !_class.HasFinalizer) { ClearFinalizer(); } } if (!_dict.Remove(name)) { throw PythonOps.AttributeError("{0} is not a valid attribute", name); } return true; } #endregion #region IMembersList Members IList<string> IMembersList.GetMemberNames() { return PythonOps.GetStringMemberList(this); } IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { PythonDictionary attrs = new PythonDictionary(_dict); OldClass.RecurseAttrHierarchy(this._class, attrs); return PythonOps.MakeListFromSequence(attrs); } #endregion [return: MaybeNotImplemented] public object __cmp__(CodeContext context, object other) { OldInstance oiOther = other as OldInstance; // CPython raises this if called directly, but not via cmp(os,ns) which still calls the user __cmp__ //if(!(oiOther is OldInstance)) // throw Ops.TypeError("instance.cmp(x,y) -> y must be an instance, got {0}", Ops.StringRepr(DynamicHelpers.GetPythonType(other))); object res = InternalCompare("__cmp__", other); if (res != NotImplementedType.Value) return res; if (oiOther != null) { res = oiOther.InternalCompare("__cmp__", this); if (res != NotImplementedType.Value) return ((int)res) * -1; } return NotImplementedType.Value; } private object CompareForwardReverse(object other, string forward, string reverse) { object res = InternalCompare(forward, other); if (res != NotImplementedType.Value) return res; if (other is OldInstance oi) { // comparison operators are reflexive return oi.InternalCompare(reverse, this); } return NotImplementedType.Value; } [return: MaybeNotImplemented] public static object operator >([NotNull]OldInstance self, object other) { return self.CompareForwardReverse(other, "__gt__", "__lt__"); } [return: MaybeNotImplemented] public static object operator <([NotNull]OldInstance self, object other) { return self.CompareForwardReverse(other, "__lt__", "__gt__"); } [return: MaybeNotImplemented] public static object operator >=([NotNull]OldInstance self, object other) { return self.CompareForwardReverse(other, "__ge__", "__le__"); } [return: MaybeNotImplemented] public static object operator <=([NotNull]OldInstance self, object other) { return self.CompareForwardReverse(other, "__le__", "__ge__"); } private object InternalCompare(string cmp, object other) { return InvokeOne(this, other, cmp); } #region ICustomTypeDescriptor Members #if FEATURE_CUSTOM_TYPE_DESCRIPTOR AttributeCollection ICustomTypeDescriptor.GetAttributes() { return CustomTypeDescHelpers.GetAttributes(this); } string ICustomTypeDescriptor.GetClassName() { return CustomTypeDescHelpers.GetClassName(this); } string ICustomTypeDescriptor.GetComponentName() { return CustomTypeDescHelpers.GetComponentName(this); } TypeConverter ICustomTypeDescriptor.GetConverter() { return CustomTypeDescHelpers.GetConverter(this); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return CustomTypeDescHelpers.GetDefaultEvent(this); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return CustomTypeDescHelpers.GetDefaultProperty(this); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return CustomTypeDescHelpers.GetEditor(this, editorBaseType); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return CustomTypeDescHelpers.GetEvents(this, attributes); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return CustomTypeDescHelpers.GetEvents(this); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { return CustomTypeDescHelpers.GetProperties(this, attributes); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return CustomTypeDescHelpers.GetProperties(this); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return CustomTypeDescHelpers.GetPropertyOwner(this, pd); } #endif #endregion #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { return _weakRef; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { _weakRef = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { ((IWeakReferenceable)this).SetWeakRef(value); } #endregion #region Rich Equality // Specific rich equality support for when the user calls directly from oldinstance type. public int __hash__(CodeContext/*!*/ context) { object func; object ret = InvokeOne(this, "__hash__"); if (ret != NotImplementedType.Value) { if (ret is BigInteger) { return BigIntegerOps.__hash__((BigInteger)ret); } else if (!(ret is int)) throw PythonOps.TypeError("expected int from __hash__, got {0}", PythonTypeOps.GetName(ret)); return (int)ret; } if (TryGetBoundCustomMember(context, "__cmp__", out func) || TryGetBoundCustomMember(context, "__eq__", out func)) { throw PythonOps.TypeError("unhashable instance"); } return base.GetHashCode(); } public override int GetHashCode() { object ret; try { ret = InvokeOne(this, "__hash__"); } catch { return base.GetHashCode(); } if (ret != NotImplementedType.Value) { if (ret is int) { return (int)ret; } if (ret is BigInteger) { return BigIntegerOps.__hash__((BigInteger)ret); } } return base.GetHashCode(); } [return: MaybeNotImplemented] public object __eq__(object other) { object res = InvokeBoth(other, "__eq__"); if (res != NotImplementedType.Value) { return res; } return NotImplementedType.Value; } private object InvokeBoth(object other, string si) { object res = InvokeOne(this, other, si); if (res != NotImplementedType.Value) { return res; } if (other is OldInstance oi) { res = InvokeOne(oi, this, si); if (res != NotImplementedType.Value) { return res; } } return NotImplementedType.Value; } private static object InvokeOne(OldInstance self, object other, string si) { object func; try { if (!self.TryGetBoundCustomMember(DefaultContext.Default, si, out func)) { return NotImplementedType.Value; } } catch (MissingMemberException) { return NotImplementedType.Value; } return PythonOps.CallWithContext(DefaultContext.Default, func, other); } private static object InvokeOne(OldInstance self, object other, object other2, string si) { object func; try { if (!self.TryGetBoundCustomMember(DefaultContext.Default, si, out func)) { return NotImplementedType.Value; } } catch (MissingMemberException) { return NotImplementedType.Value; } return PythonOps.CallWithContext(DefaultContext.Default, func, other, other2); } private static object InvokeOne(OldInstance self, string si) { object func; try { if (!self.TryGetBoundCustomMember(DefaultContext.Default, si, out func)) { return NotImplementedType.Value; } } catch (MissingMemberException) { return NotImplementedType.Value; } return PythonOps.CallWithContext(DefaultContext.Default, func); } [return: MaybeNotImplemented] public object __ne__(object other) { object res = InvokeBoth(other, "__ne__"); if (res != NotImplementedType.Value) { return res; } return NotImplementedType.Value; } [return: MaybeNotImplemented] [SpecialName] public static object Power([NotNull]OldInstance self, object other, object mod) { object res = InvokeOne(self, other, mod, "__pow__"); if (res != NotImplementedType.Value) return res; return NotImplementedType.Value; } #endregion #region ISerializable Members #if FEATURE_SERIALIZATION void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("__class__", _class); info.AddValue("__dict__", _dict); } #endif #endregion #region Private Implementation Details private void RecurseAttrHierarchyInt(OldClass oc, IDictionary<string, object> attrs) { foreach (KeyValuePair<object, object> kvp in oc._dict._storage.GetItems()) { if (kvp.Key is string strKey) { if (!attrs.ContainsKey(strKey)) { attrs.Add(strKey, strKey); } } } // recursively get attrs in parent hierarchy if (oc.BaseClasses.Count != 0) { foreach (OldClass parent in oc.BaseClasses) { RecurseAttrHierarchyInt(parent, attrs); } } } private void AddFinalizer(CodeContext/*!*/ context) { InstanceFinalizer oif = new InstanceFinalizer(context, this); _weakRef = new WeakRefTracker(this, oif, oif); } private void ClearFinalizer() { if (_weakRef == null) return; WeakRefTracker wrt = _weakRef; if (wrt != null) { // find our handler and remove it (other users could have created weak refs to us) for (int i = 0; i < wrt.HandlerCount; i++) { if (wrt.GetHandlerCallback(i) is InstanceFinalizer) { wrt.RemoveHandlerAt(i); break; } } // we removed the last handler if (wrt.HandlerCount == 0) { GC.SuppressFinalize(wrt); _weakRef = null; } } } private bool HasFinalizer() { if (_weakRef != null) { WeakRefTracker wrt = _weakRef; if (wrt != null) { for (int i = 0; i < wrt.HandlerCount; i++) { if (wrt.GetHandlerCallback(i) is InstanceFinalizer) { return true; } } } } return false; } private bool TryRawGetAttr(CodeContext context, string name, out object ret) { if (_dict._storage.TryGetValue(name, out ret)) { return true; } if (_class.TryLookupSlot(name, out ret)) { ret = _class.GetOldStyleDescriptor(context, ret, this, _class); return true; } return false; } #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Expression/*!*/ parameter) { return new Binding.MetaOldInstance(parameter, BindingRestrictions.Empty, this); } #endregion internal class OldInstanceDebugView { private readonly OldInstance _userObject; public OldInstanceDebugView(OldInstance userObject) { _userObject = userObject; } public OldClass __class__ { get { return _userObject._class; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal List<ObjectDebugView> Members { get { var res = new List<ObjectDebugView>(); if (_userObject._dict != null) { foreach (var v in _userObject._dict) { res.Add(new ObjectDebugView(v.Key, v.Value)); } } return res; } } } class FastOldInstanceGet { private readonly string _name; public FastOldInstanceGet(string name) { _name = name; } public object Target(CallSite site, object instance, CodeContext context) { if (instance is OldInstance oi) { object res; if (oi.TryGetBoundCustomMember(context, _name, out res)) { return res; } throw PythonOps.AttributeError("{0} instance has no attribute '{1}'", oi._class.Name, _name); } return ((CallSite<Func<CallSite, object, CodeContext, object>>)site).Update(site, instance, context); } public object LightThrowTarget(CallSite site, object instance, CodeContext context) { if (instance is OldInstance oi) { object res; if (oi.TryGetBoundCustomMember(context, _name, out res)) { return res; } return LightExceptions.Throw(PythonOps.AttributeError("{0} instance has no attribute '{1}'", oi._class.Name, _name)); } return ((CallSite<Func<CallSite, object, CodeContext, object>>)site).Update(site, instance, context); } public object NoThrowTarget(CallSite site, object instance, CodeContext context) { if (instance is OldInstance oi) { object res; if (oi.TryGetBoundCustomMember(context, _name, out res)) { return res; } return OperationFailed.Value; } return ((CallSite<Func<CallSite, object, CodeContext, object>>)site).Update(site, instance, context); } } #region IFastGettable Members T Binding.IFastGettable.MakeGetBinding<T>(System.Runtime.CompilerServices.CallSite<T> site, Binding.PythonGetMemberBinder binder, CodeContext state, string name) { if (binder.IsNoThrow) { return (T)(object)new Func<CallSite, object, CodeContext, object>(new FastOldInstanceGet(name).NoThrowTarget); } else if (binder.SupportsLightThrow) { return (T)(object)new Func<CallSite, object, CodeContext, object>(new FastOldInstanceGet(name).LightThrowTarget); } else { return (T)(object)new Func<CallSite, object, CodeContext, object>(new FastOldInstanceGet(name).Target); } } #endregion } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green (sharpneat@gmail.com) * * SharpNEAT is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Diagnostics; using SharpNeat.Core; namespace SharpNeat.SpeciationStrategies { // ENHANCEMENT: k-means++ seeks to choose better starting clusters. (http://en.wikipedia.org/wiki/K-means_clustering) // ENHANCEMENT: The filtering algorithm uses kd-trees to speed up each k-means step[9]. (http://en.wikipedia.org/wiki/K-means_clustering) // ENHANCEMENT: Euclidean squared distance metric is equivalent for k-means and faster than euclidean (http://www.improvedoutcomes.com/docs/WebSiteDocs/Clustering/Clustering_Parameters/Euclidean_and_Euclidean_Squared_Distance_Metrics.htm) /// <summary> /// An ISpeciationStrategy that speciates genomes using the k-means clustering method. /// k-means requires a distance metric and as such this class requires am IDistanceMetric to be provided at /// construction time. Different distance metrics can be used including NeatDistanceMetric which is /// equivalent to the metric used in the standard NEAT method albeit with a different clustering/speciation /// algorithm (Standard NEAT does not use k-means). /// </summary> /// <typeparam name="TGenome">The genome type to apply clustering to.</typeparam> public class KMeansClusteringStrategy<TGenome> : ISpeciationStrategy<TGenome> where TGenome : class, IGenome<TGenome> { const int __MAX_KMEANS_LOOPS = 5; readonly IDistanceMetric _distanceMetric; #region Constructor /// <summary> /// Constructor that accepts an IDistanceMetric to be used for the k-means method. /// </summary> public KMeansClusteringStrategy(IDistanceMetric distanceMetric) { _distanceMetric = distanceMetric; } #endregion #region ISpeciationStrategy<TGenome> Members /// <summary> /// Speciates the genomes in genomeList into the number of species specified by specieCount /// and returns a newly constructed list of Specie objects containing the speciated genomes. /// </summary> public IList<Specie<TGenome>> InitializeSpeciation(IList<TGenome> genomeList, int specieCount) { // Create empty specieList. // Use an initial specieList capacity that will limit the need for memory reallocation but that isn't // too wasteful of memory. int initSpeciesCapacity = (genomeList.Count * 2) / specieCount; List<Specie<TGenome>> specieList = new List<Specie<TGenome>>(specieCount); for(int i=0; i<specieCount; i++) { specieList.Add(new Specie<TGenome>((uint)i, i, initSpeciesCapacity)); } // Speciate genomes into the empty species. SpeciateGenomes(genomeList, specieList); return specieList; } /// <summary> /// Speciates the genomes in genomeList into the provided specieList. It is assumed that /// the genomeList represents all of the required genomes and that the species are currently empty. /// /// This method can be used for initialization or completely respeciating an existing genome population. /// </summary> public void SpeciateGenomes(IList<TGenome> genomeList, IList<Specie<TGenome>> specieList) { Debug.Assert(SpeciationUtils.TestEmptySpecies(specieList), "SpeciateGenomes(IList<TGenome>,IList<Species<TGenome>>) called with non-empty species"); Debug.Assert(genomeList.Count >= specieList.Count, string.Format("SpeciateGenomes(IList<TGenome>,IList<Species<TGenome>>). Species count [{0}] is greater than genome count [{1}].", specieList.Count, genomeList.Count)); // Randomly allocate the first k genomes to their own specie. Because there is only one genome in these // species each genome effectively represents a specie centroid. This is necessary to ensure we get k specieList. // If we randomly assign all genomes to species from the outset and then calculate centroids then typically some // of the species become empty. // This approach ensures that each species will have at least one genome - because that genome is the specie // centroid and therefore has distance of zero from the centroid (itself). int specieCount = specieList.Count; for(int i=0; i<specieCount; i++) { Specie<TGenome> specie = specieList[i]; genomeList[i].SpecieIdx = specie.Idx; specie.GenomeList.Add(genomeList[i]); // Just set the specie centroid directly. specie.Centroid = genomeList[i].Position; } // Now allocate the remaining genomes based on their distance from the centroids. int genomeCount = genomeList.Count; for(int i=specieCount; i<genomeCount; i++) { TGenome genome = genomeList[i]; Specie<TGenome> closestSpecie = FindClosestSpecie(genome, specieList); genome.SpecieIdx = closestSpecie.Idx; closestSpecie.GenomeList.Add(genome); } // Recalculate each specie's centroid. foreach(Specie<TGenome> specie in specieList) { specie.Centroid = CalculateSpecieCentroid(specie); } // Perform the main k-means loop until convergence. SpeciateUntilConvergence(genomeList, specieList); Debug.Assert(SpeciationUtils.PerformIntegrityCheck(specieList)); } /// <summary> /// Speciates the offspring genomes in offspringList into the provided specieList. In contrast to /// SpeciateGenomes() offspringList is taken to be a list of new genomes (offspring) that should be /// added to existing species. That is, the species contain genomes that are not in offspringList /// that we wish to keep; typically these would be elite genomes that are the parents of the /// offspring. /// </summary> public void SpeciateOffspring(IList<TGenome> offspringList, IList<Specie<TGenome>> specieList) { // Each specie should contain at least one genome. We need at least one existing genome per specie to act // as a specie centroid in order to define where the specie is within the encoding space. Debug.Assert(SpeciationUtils.TestPopulatedSpecies(specieList), "SpeciateOffspring(IList<TGenome>,IList<Species<TGenome>>) called with an empty specie."); // Update the centroid of each specie. If we're adding offspring this means that old genomes // have been removed from the population and therefore the centroids are out-of-date. foreach(Specie<TGenome> specie in specieList) { specie.Centroid = CalculateSpecieCentroid(specie); } // Allocate each offspring genome to the specie it is closest to. foreach(TGenome genome in offspringList) { Specie<TGenome> closestSpecie = FindClosestSpecie(genome, specieList); closestSpecie.GenomeList.Add(genome); genome.SpecieIdx = closestSpecie.Idx; } // Recalculate each specie's centroid now that we have additional genomes in the specieList. foreach(Specie<TGenome> specie in specieList) { specie.Centroid = CalculateSpecieCentroid(specie); } // Accumulate *all* genomes into a flat genome list. int genomeCount = 0; foreach(Specie<TGenome> specie in specieList) { genomeCount += specie.GenomeList.Count; } List<TGenome> genomeList = new List<TGenome>(genomeCount); foreach(Specie<TGenome> specie in specieList) { genomeList.AddRange(specie.GenomeList); } // Perform the main k-means loop until convergence. SpeciateUntilConvergence(genomeList, specieList); Debug.Assert(SpeciationUtils.PerformIntegrityCheck(specieList)); } #endregion #region Private Methods [k-means] /// <summary> /// Perform the main k-means loop until no genome reallocations occur or some maximum number of loops /// has been performed. Theoretically a small number of reallocations may occur for a great many loops /// therefore we require the additional max loops threshold exit strategy - the clusters should be pretty /// stable and well defined after a few loops even if the the algorithm hasn't converged completely. /// </summary> private void SpeciateUntilConvergence(IList<TGenome> genomeList, IList<Specie<TGenome>> specieList) { List<Specie<TGenome>> emptySpecieList = new List<Specie<TGenome>>(); int specieCount = specieList.Count; // Array of flags that indicate if a specie was modified (had genomes allocated to and/or from it). bool[] specieModArr = new bool[specieCount]; // Main k-means loop. for(int loops=0; loops<__MAX_KMEANS_LOOPS; loops++) { // Track number of reallocations made on each loop. int reallocations = 0; // Loop over genomes. For each one find the specie it is closest to; if it is not the specie // it is currently in then reallocate it. foreach(TGenome genome in genomeList) { Specie<TGenome> closestSpecie = FindClosestSpecie(genome, specieList); if(genome.SpecieIdx != closestSpecie.Idx) { // Track which species have been modified. specieModArr[genome.SpecieIdx] = true; specieModArr[closestSpecie.Idx] = true; // Add the genome to its new specie and set its speciesIdx accordingly. // For now we leave the genome in its original species; It's more efficient to determine // all reallocations and then remove reallocated genomes from their origin specie all together; // This is because we can shuffle down the remaining genomes in a specie to fill the gaps made by // the removed genomes - and do so in one round of shuffling instead of shuffling to fill a gap on // each remove. closestSpecie.GenomeList.Add(genome); genome.SpecieIdx = closestSpecie.Idx; reallocations++; } } // Complete the reallocations. for(int i=0; i<specieCount; i++) { if(!specieModArr[i]) { // Specie not changed. Skip. continue; } // Reset flag. specieModArr[i] = false; // Remove the genomes that have been allocated to other other species. We fill the resulting // gaps by shuffling down the remaining genomes. Specie<TGenome> specie = specieList[i]; specie.GenomeList.RemoveAll(delegate(TGenome genome) { return genome.SpecieIdx != specie.Idx; }); // Track empty species. We will allocate genomes to them after this loop. // This is necessary as some distance metrics can result in empty species occuring. if(0 == specie.GenomeList.Count) { emptySpecieList.Add(specie); } else { // Recalc the specie centroid now that it contains a different set of genomes. specie.Centroid = CalculateSpecieCentroid(specie); } } // Check for empty species. We need to reallocate some genomes into the empty specieList to maintain the // required number of species. if(0 != emptySpecieList.Count) { // We find the genomes in the population as a whole that are furthest from their containing specie's // centroid genome - we call these outlier genomes. We then move these genomes into the empty species to // act as the sole member and centroid of those speciea; These act as specie seeds for the next k-means loop. TGenome[] genomeByDistanceArr = GetGenomesByDistanceFromSpecie(genomeList, specieList); // Reallocate each of the outlier genomes from their current specie to an empty specie. int emptySpecieCount = emptySpecieList.Count; int outlierIdx = 0; for(int i=0; i<emptySpecieCount; i++) { // Find the next outlier genome that can be re-allocated. Skip genomes that are the // only member of a specie - that would just create another empty specie. TGenome genome; Specie<TGenome> sourceSpecie; do { genome = genomeByDistanceArr[outlierIdx++]; sourceSpecie = specieList[genome.SpecieIdx]; } while(sourceSpecie.GenomeList.Count == 1 && outlierIdx < genomeByDistanceArr.Length); if(outlierIdx == genomeByDistanceArr.Length) { // Theoretically impossible. We do the test so that we get an easy to trace error message if it does happen. throw new SharpNeatException("Error finding outlier genome. No outliers could be found in any specie with more than 1 genome."); } // Get ref to the empty specie and register both source and target specie with specieModArr. Specie<TGenome> emptySpecie = emptySpecieList[i]; specieModArr[emptySpecie.Idx] = true; specieModArr[sourceSpecie.Idx] = true; // Reallocate the genome. Here we do the remove operation right away; We aren't expecting to deal with many empty // species, usually it will be one or two at most; Any more and there's probably something wrong with the distance // metric, e.g. maybe it doesn't satisfy the triangle inequality (see wikipedia). // Another reason to remove right is to eliminate the possibility of removing multiple outlier genomes from the // same specie and potentially leaving it empty; The test in the do-while loop above only takes genomes from // currently non-empty species. sourceSpecie.GenomeList.Remove(genome); emptySpecie.GenomeList.Add(genome); genome.SpecieIdx = emptySpecie.Idx; reallocations++; } // Recalculate centroid for all affected species. for(int i=0; i<specieCount; i++) { if(specieModArr[i]) { // Reset flag while we're here. Do this first to help maintain CPU cache coherency (we just tested it). specieModArr[i] = false; specieList[i].Centroid = CalculateSpecieCentroid(specieList[i]); } } // Clear emptySpecieList after using it. Otherwise we are holding old references and thus creating // work for the garbage collector. emptySpecieList.Clear(); } // Exit the loop if no genome reallocations have occured. The species are stable, speciation is completed. if(0==reallocations) { break; } } } /// <summary> /// Recalculate the specie centroid based on the genomes currently in the specie. /// </summary> private CoordinateVector CalculateSpecieCentroid(Specie<TGenome> specie) { // Special case - 1 genome in specie (its position *is* the specie centroid). if(1 == specie.GenomeList.Count) { return new CoordinateVector(specie.GenomeList[0].Position.CoordArray); } // Create a temp list containing all of the genome positions. List<TGenome> genomeList = specie.GenomeList; int count = genomeList.Count; List<CoordinateVector> coordList = new List<CoordinateVector>(count); for(int i=0; i<count; i++) { coordList.Add(genomeList[i].Position); } // The centroid calculation is a function of the distance metric. return _distanceMetric.CalculateCentroid(coordList); } // ENHANCEMENT: Optimization candidate. /// <summary> /// Gets an array of all genomes ordered by their distance from their current specie. /// </summary> private TGenome[] GetGenomesByDistanceFromSpecie(IList<TGenome> genomeList, IList<Specie<TGenome>> specieList) { // Build a list of all genomes paired with their distance from their centriod. int genomeCount = genomeList.Count; GenomeDistancePair<TGenome>[] genomeDistanceArr = new GenomeDistancePair<TGenome>[genomeCount]; for(int i=0; i<genomeCount; i++) { TGenome genome = genomeList[i]; double distance = _distanceMetric.MeasureDistance(genome.Position, specieList[genome.SpecieIdx].Centroid); genomeDistanceArr[i] = new GenomeDistancePair<TGenome>(distance, genome); } // Sort list. Longest distance first. Array.Sort(genomeDistanceArr); // Put the sorted genomes in an array and return it. TGenome[] genomeArr = new TGenome[genomeCount]; for(int i=0; i<genomeCount; i++) { genomeArr[i] = genomeDistanceArr[i]._genome; } return genomeArr; } /// <summary> /// Find the specie that a genome is closest to as determined by the distance metric. /// </summary> private Specie<TGenome> FindClosestSpecie(TGenome genome, IList<Specie<TGenome>> specieList) { // Measure distance to first specie's centroid. Specie<TGenome> closestSpecie = specieList[0]; double closestDistance = _distanceMetric.MeasureDistance(genome.Position, closestSpecie.Centroid); // Measure distance to all remaining species. int speciesCount = specieList.Count; for(int i=1; i<speciesCount; i++) { double distance = _distanceMetric.MeasureDistance(genome.Position, specieList[i].Centroid); if(distance < closestDistance) { closestDistance = distance; closestSpecie = specieList[i]; } } return closestSpecie; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Timers; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.CoreModules.Framework.EventQueue; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps = OpenSim.Framework.Capabilities.Caps; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class GroupsModule : ISharedRegionModule, IGroupsModule { /// <summary> /// ; To use this module, you must specify the following in your OpenSim.ini /// [GROUPS] /// Enabled = true /// /// Module = GroupsModule /// NoticesEnabled = true /// DebugEnabled = true /// /// GroupsServicesConnectorModule = XmlRpcGroupsServicesConnector /// XmlRpcServiceURL = http://osflotsam.org/xmlrpc.php /// XmlRpcServiceReadKey = 1234 /// XmlRpcServiceWriteKey = 1234 /// /// MessagingModule = GroupsMessagingModule /// MessagingEnabled = true /// /// ; Disables HTTP Keep-Alive for Groups Module HTTP Requests, work around for /// ; a problem discovered on some Windows based region servers. Only disable /// ; if you see a large number (dozens) of the following Exceptions: /// ; System.Net.WebException: The request was aborted: The request was canceled. /// /// XmlRpcDisableKeepAlive = false /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IMessageTransferModule m_msgTransferModule = null; private IGroupsServicesConnector m_groupData = null; class GroupRequestIDInfo { public GroupRequestID RequestID = new GroupRequestID(); public DateTime LastUsedTMStamp = DateTime.MinValue; } private Dictionary<UUID, GroupRequestIDInfo> m_clientRequestIDInfo = new Dictionary<UUID, GroupRequestIDInfo>(); private const int m_clientRequestIDFlushTimeOut = 300000; // Every 5 minutes private Timer m_clientRequestIDFlushTimer; // Configuration settings private bool m_groupsEnabled = false; private bool m_groupNoticesEnabled = true; private bool m_debugEnabled = true; #region IRegionModuleBase Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false); if (!m_groupsEnabled) { return; } if (groupsConfig.GetString("Module", "Default") != Name) { m_groupsEnabled = false; return; } m_log.InfoFormat("[GROUPS]: Initializing {0}", this.Name); m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true); m_clientRequestIDFlushTimer = new Timer(); m_clientRequestIDFlushTimer.Interval = m_clientRequestIDFlushTimeOut; m_clientRequestIDFlushTimer.Elapsed += FlushClientRequestIDInfoCache; m_clientRequestIDFlushTimer.AutoReset = true; m_clientRequestIDFlushTimer.Start(); } } void FlushClientRequestIDInfoCache(object sender, ElapsedEventArgs e) { lock (m_clientRequestIDInfo) { TimeSpan cacheTimeout = new TimeSpan(0,0, m_clientRequestIDFlushTimeOut / 1000); UUID[] CurrentKeys = new UUID[m_clientRequestIDInfo.Count]; foreach (UUID key in CurrentKeys) { if (m_clientRequestIDInfo.ContainsKey(key)) { if (DateTime.Now - m_clientRequestIDInfo[key].LastUsedTMStamp > cacheTimeout) { m_clientRequestIDInfo.Remove(key); } } } } } public void AddRegion(Scene scene) { if (m_groupsEnabled) scene.RegisterModuleInterface<IGroupsModule>(this); } public void RegionLoaded(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_groupData == null) { m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>(); // No Groups Service Connector, then nothing works... if (m_groupData == null) { m_groupsEnabled = false; m_log.Error("[GROUPS]: Could not get IGroupsServicesConnector"); Close(); return; } } if (m_msgTransferModule == null) { m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_msgTransferModule == null) { m_groupsEnabled = false; m_log.Error("[GROUPS]: Could not get MessageTransferModule"); Close(); return; } } lock (m_sceneList) { m_sceneList.Add(scene); } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; // The InstantMessageModule itself doesn't do this, // so lets see if things explode if we don't do it // scene.EventManager.OnClientClosed += OnClientClosed; } public void RemoveRegion(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_sceneList) { m_sceneList.Remove(scene); } } public void Close() { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module."); m_clientRequestIDFlushTimer.Stop(); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "GroupsModule"; } } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region EventHandlers private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnDirFindQuery += OnDirFindQuery; client.OnRequestAvatarProperties += OnRequestAvatarProperties; // Used for Notices and Group Invites/Accept/Reject client.OnInstantMessage += OnInstantMessage; lock (m_clientRequestIDInfo) { if (m_clientRequestIDInfo.ContainsKey(client.AgentId)) { // flush any old RequestID information m_clientRequestIDInfo.Remove(client.AgentId); } } SendAgentGroupDataUpdate(client, client.AgentId); } private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); //GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetClientGroupRequestID(remoteClient), avatarID).ToArray(); GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); } /* * This becomes very problematic in a shared module. In a shared module you may have more then one * reference to IClientAPI's, one for 0 or 1 root connections, and 0 or more child connections. * The OnClientClosed event does not provide anything to indicate which one of those should be closed * nor does it provide what scene it was from so that the specific reference can be looked up. * The InstantMessageModule.cs does not currently worry about unregistering the handles, * and it should be an issue, since it's the client that references us not the other way around * , so as long as we don't keep a reference to the client laying around, the client can still be GC'ed private void OnClientClosed(UUID AgentId) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_ActiveClients) { if (m_ActiveClients.ContainsKey(AgentId)) { IClientAPI client = m_ActiveClients[AgentId]; client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnDirFindQuery -= OnDirFindQuery; client.OnInstantMessage -= OnInstantMessage; m_ActiveClients.Remove(AgentId); } else { if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Client closed that wasn't registered here."); } } } */ void OnDirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { if (((DirFindFlags)queryFlags & DirFindFlags.Groups) == DirFindFlags.Groups) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called with queryText({1}) queryFlags({2}) queryStart({3})", System.Reflection.MethodBase.GetCurrentMethod().Name, queryText, (DirFindFlags)queryFlags, queryStart); // TODO: This currently ignores pretty much all the query flags including Mature and sort order remoteClient.SendDirGroupsReply(queryID, m_groupData.FindGroups(GetClientGroupRequestID(remoteClient), queryText).ToArray()); } } private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID activeGroupID = UUID.Zero; string activeGroupTitle = string.Empty; string activeGroupName = string.Empty; ulong activeGroupPowers = (ulong)GroupPowers.None; GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetClientGroupRequestID(remoteClient), dataForAgentID); if (membership != null) { activeGroupID = membership.GroupID; activeGroupTitle = membership.GroupTitle; activeGroupPowers = membership.GroupPowers; } SendAgentDataUpdate(remoteClient, dataForAgentID, activeGroupID, activeGroupName, activeGroupPowers, activeGroupTitle); SendScenePresenceUpdate(dataForAgentID, activeGroupTitle); } private void HandleUUIDGroupNameRequest(UUID GroupID,IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string GroupName; GroupRecord group = m_groupData.GetGroupRecord(GetClientGroupRequestID(remoteClient), GroupID, null); if (group != null) { GroupName = group.GroupName; } else { GroupName = "Unknown"; } remoteClient.SendGroupNameReply(GroupID, GroupName); } private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Group invitations if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)) { UUID inviteID = new UUID(im.imSessionID); GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetClientGroupRequestID(remoteClient), inviteID); if (inviteInfo == null) { if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Received an Invite IM for an invite that does not exist {0}.", inviteID); return; } if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID); UUID fromAgentID = new UUID(im.fromAgentID); if ((inviteInfo != null) && (fromAgentID == inviteInfo.AgentID)) { // Accept if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received an accept invite notice."); // and the sessionid is the role m_groupData.AddAgentToGroup(GetClientGroupRequestID(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID, inviteInfo.RoleID); GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = UUID.Zero.Guid; msg.toAgentID = inviteInfo.AgentID.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = "Groups"; msg.message = string.Format("You have been added to the group."); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, inviteInfo.AgentID); UpdateAllClientsWithGroupInfo(inviteInfo.AgentID); // TODO: If the inviter is still online, they need an agent dataupdate // and maybe group membership updates for the invitee m_groupData.RemoveAgentToGroupInvite(GetClientGroupRequestID(remoteClient), inviteID); } // Reject if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received a reject invite notice."); m_groupData.RemoveAgentToGroupInvite(GetClientGroupRequestID(remoteClient), inviteID); } } } // Group notices if ((im.dialog == (byte)InstantMessageDialog.GroupNotice)) { if (!m_groupNoticesEnabled) { return; } UUID GroupID = new UUID(im.toAgentID); if (m_groupData.GetGroupRecord(GetClientGroupRequestID(remoteClient), GroupID, null) != null) { UUID NoticeID = UUID.Random(); string Subject = im.message.Substring(0, im.message.IndexOf('|')); string Message = im.message.Substring(Subject.Length + 1); byte[] bucket; if ((im.binaryBucket.Length == 1) && (im.binaryBucket[0] == 0)) { bucket = new byte[19]; bucket[0] = 0; //dunno bucket[1] = 0; //dunno GroupID.ToBytes(bucket, 2); bucket[18] = 0; //dunno } else { string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket); binBucket = binBucket.Remove(0, 14).Trim(); if (m_debugEnabled) { m_log.WarnFormat("I don't understand a group notice binary bucket of: {0}", binBucket); OSDMap binBucketOSD = (OSDMap)OSDParser.DeserializeLLSDXml(binBucket); foreach (string key in binBucketOSD.Keys) { if (binBucketOSD.ContainsKey(key)) { m_log.WarnFormat("{0}: {1}", key, binBucketOSD[key].ToString()); } } } // treat as if no attachment bucket = new byte[19]; bucket[0] = 0; //dunno bucket[1] = 0; //dunno GroupID.ToBytes(bucket, 2); bucket[18] = 0; //dunno } m_groupData.AddGroupNotice(GetClientGroupRequestID(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, bucket); if (OnNewGroupNotice != null) { OnNewGroupNotice(GroupID, NoticeID); } // Send notice out to everyone that wants notices foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetClientGroupRequestID(remoteClient), GroupID)) { if (m_debugEnabled) { UserProfileData targetUserProfile = m_sceneList[0].CommsManager.UserService.GetUserProfile(member.AgentID); if (targetUserProfile != null) { m_log.DebugFormat("[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, targetUserProfile.Name, member.AcceptNotices); } else { m_log.DebugFormat("[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, member.AgentID, member.AcceptNotices); } } if (member.AcceptNotices) { // Build notice IIM GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice); msg.toAgentID = member.AgentID.Guid; OutgoingInstantMessage(msg, member.AgentID); } } } } // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presense server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue if ((im.dialog == 210)) { // This is sent from the region that the ejectee was ejected from // if it's being delivered here, then the ejectee is here // so we need to send local updates to the agent. UUID ejecteeID = new UUID(im.toAgentID); im.dialog = (byte)InstantMessageDialog.MessageFromAgent; OutgoingInstantMessage(im, ejecteeID); IClientAPI ejectee = GetActiveClient(ejecteeID); if (ejectee != null) { UUID groupID = new UUID(im.fromAgentID); ejectee.SendAgentDropGroup(groupID); } } } private void OnGridInstantMessage(GridInstantMessage msg) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Trigger the above event handler OnInstantMessage(null, msg); // If a message from a group arrives here, it may need to be forwarded to a local client if (msg.fromGroup == true) { switch (msg.dialog) { case (byte)InstantMessageDialog.GroupInvitation: case (byte)InstantMessageDialog.GroupNotice: UUID toAgentID = new UUID(msg.toAgentID); IClientAPI localClient = GetActiveClient(toAgentID); if (localClient != null) { localClient.SendInstantMessage(msg); } break; } } } #endregion #region IGroupsModule Members public event NewGroupNotice OnNewGroupNotice; public GroupRecord GetGroupRecord(UUID GroupID) { return m_groupData.GetGroupRecord(null, GroupID, null); } public void ActivateGroup(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroup(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID); // Changing active group changes title, active powers, all kinds of things // anyone who is in any region that can see this client, should probably be // updated with new group info. At a minimum, they should get ScenePresence // updated with new title. UpdateAllClientsWithGroupInfo(remoteClient.AgentId); } /// <summary> /// Get the Role Titles for an Agent, for a specific group /// </summary> public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupRequestID grID = GetClientGroupRequestID(remoteClient); List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(grID, remoteClient.AgentId, groupID); GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(grID, remoteClient.AgentId, groupID); List<GroupTitlesData> titles = new List<GroupTitlesData>(); foreach (GroupRolesData role in agentRoles) { GroupTitlesData title = new GroupTitlesData(); title.Name = role.Name; if (agentMembership != null) { title.Selected = agentMembership.ActiveRole == role.RoleID; } title.UUID = role.RoleID; titles.Add(title); } return titles; } public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupMembersData> data = m_groupData.GetGroupMembers(GetClientGroupRequestID(remoteClient), groupID); return data; } public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> data = m_groupData.GetGroupRoles(GetClientGroupRequestID(remoteClient), groupID); return data; } public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetClientGroupRequestID(remoteClient), groupID); return data; } public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupProfileData profile = new GroupProfileData(); GroupRequestID grID = GetClientGroupRequestID(remoteClient); GroupRecord groupInfo = m_groupData.GetGroupRecord(GetClientGroupRequestID(remoteClient), groupID, null); if (groupInfo != null) { profile.AllowPublish = groupInfo.AllowPublish; profile.Charter = groupInfo.Charter; profile.FounderID = groupInfo.FounderID; profile.GroupID = groupID; profile.GroupMembershipCount = m_groupData.GetGroupMembers(grID, groupID).Count; profile.GroupRolesCount = m_groupData.GetGroupRoles(grID, groupID).Count; profile.InsigniaID = groupInfo.GroupPicture; profile.MaturePublish = groupInfo.MaturePublish; profile.MembershipFee = groupInfo.MembershipFee; profile.Money = 0; // TODO: Get this from the currency server? profile.Name = groupInfo.GroupName; profile.OpenEnrollment = groupInfo.OpenEnrollment; profile.OwnerRole = groupInfo.OwnerRoleID; profile.ShowInList = groupInfo.ShowInList; } GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(grID, remoteClient.AgentId, groupID); if (memberInfo != null) { profile.MemberTitle = memberInfo.GroupTitle; profile.PowersMask = memberInfo.GroupPowers; } return profile; } public GroupMembershipData[] GetMembershipData(UUID agentID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); return m_groupData.GetAgentGroupMemberships(null, agentID).ToArray(); } public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); return m_groupData.GetAgentGroupMembership(null, agentID, groupID); } public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Security Check? m_groupData.UpdateGroup(GetClientGroupRequestID(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish); } public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile) { // TODO: Security Check? if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentGroupInfo(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID, acceptNotices, listInProfile); } public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupRequestID grID = GetClientGroupRequestID(remoteClient); if (m_groupData.GetGroupRecord(grID, UUID.Zero, name) != null) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); return UUID.Zero; } // is there is a money module present ? IMoneyModule money=remoteClient.Scene.RequestModuleInterface<IMoneyModule>(); if (money != null) { // do the transaction, that is if the agent has got sufficient funds if (!money.GroupCreationCovered(remoteClient)) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got issuficient funds to create a group."); return UUID.Zero; } money.ApplyGroupCreationCharge(remoteClient.AgentId); } UUID groupID = m_groupData.CreateGroup(grID, name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, remoteClient.AgentId); remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly"); // Update the founder with new group information. SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); return groupID; } public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // ToDo: check if agent is a member of group and is allowed to see notices? return m_groupData.GetGroupNotices(GetClientGroupRequestID(remoteClient), groupID).ToArray(); } /// <summary> /// Get the title of the agent's current role. /// </summary> public string GetGroupTitle(UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData membership = m_groupData.GetAgentActiveMembership(null, avatarID); if (membership != null) { return membership.GroupTitle; } return string.Empty; } /// <summary> /// Change the current Active Group Role for Agent /// </summary> public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroupRole(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID, titleRoleID); // TODO: Not sure what all is needed here, but if the active group role change is for the group // the client currently has set active, then we need to do a scene presence update too // if (m_groupData.GetAgentActiveMembership(remoteClient.AgentId).GroupID == GroupID) UpdateAllClientsWithGroupInfo(remoteClient.AgentId); } public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Security Checks are handled in the Groups Service. GroupRequestID grID = GetClientGroupRequestID(remoteClient); switch ((OpenMetaverse.GroupRoleUpdate)updateType) { case OpenMetaverse.GroupRoleUpdate.Create: m_groupData.AddGroupRole(grID, groupID, UUID.Random(), name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.Delete: m_groupData.RemoveGroupRole(grID, groupID, roleID); break; case OpenMetaverse.GroupRoleUpdate.UpdateAll: case OpenMetaverse.GroupRoleUpdate.UpdateData: case OpenMetaverse.GroupRoleUpdate.UpdatePowers: if (m_debugEnabled) { GroupPowers gp = (GroupPowers)powers; m_log.DebugFormat("[GROUPS]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString()); } m_groupData.UpdateGroupRole(grID, groupID, roleID, name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.NoUpdate: default: // No Op break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); } public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check GroupRequestID grID = GetClientGroupRequestID(remoteClient); switch (changes) { case 0: // Add m_groupData.AddAgentToGroupRole(grID, memberID, groupID, roleID); break; case 1: // Remove m_groupData.RemoveAgentFromGroupRole(grID, memberID, groupID, roleID); break; default: m_log.ErrorFormat("[GROUPS]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes); break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); } public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupRequestID grID = GetClientGroupRequestID(remoteClient); GroupNoticeInfo data = m_groupData.GetGroupNotice(grID, groupNoticeID); if (data != null) { GroupRecord groupInfo = m_groupData.GetGroupRecord(grID, data.GroupID, null); GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = data.GroupID.Guid; msg.toAgentID = remoteClient.AgentId.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = "Group Notice : " + groupInfo == null ? "Unknown" : groupInfo.GroupName; msg.message = data.noticeData.Subject + "|" + data.Message; msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupNoticeRequested; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; msg.binaryBucket = data.BinaryBucket; OutgoingInstantMessage(msg, remoteClient.AgentId); } } public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.toAgentID = agentID.Guid; msg.dialog = dialog; // msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupNotice; msg.fromGroup = true; msg.offline = (byte)1; // Allow this message to be stored for offline use msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; GroupNoticeInfo info = m_groupData.GetGroupNotice(null, groupNoticeID); if (info != null) { msg.fromAgentID = info.GroupID.Guid; msg.timestamp = info.noticeData.Timestamp; msg.fromAgentName = info.noticeData.FromName; msg.message = info.noticeData.Subject + "|" + info.Message; msg.binaryBucket = info.BinaryBucket; } else { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Group Notice {0} not found, composing empty message.", groupNoticeID); msg.fromAgentID = UUID.Zero.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); ; msg.fromAgentName = string.Empty; msg.message = string.Empty; msg.binaryBucket = new byte[0]; } return msg; } public void SendAgentGroupDataUpdate(IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Send agent information about his groups SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); } public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Should check to see if OpenEnrollment, or if there's an outstanding invitation m_groupData.AddAgentToGroup(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID, UUID.Zero); remoteClient.SendJoinGroupReply(groupID, true); // Should this send updates to everyone in the group? SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); } public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.RemoveAgentFromGroup(GetClientGroupRequestID(remoteClient), remoteClient.AgentId, groupID); remoteClient.SendLeaveGroupReply(groupID, true); remoteClient.SendAgentDropGroup(groupID); // SL sends out notifcations to the group messaging session that the person has left // Should this also update everyone who is in the group? SendAgentGroupDataUpdate(remoteClient, remoteClient.AgentId); } public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupRequestID grID = GetClientGroupRequestID(remoteClient); // Todo: Security check? m_groupData.RemoveAgentFromGroup(grID, ejecteeID, groupID); remoteClient.SendEjectGroupMemberReply(remoteClient.AgentId, groupID, true); GroupRecord groupInfo = m_groupData.GetGroupRecord(grID, groupID, null); UserProfileData userProfile = m_sceneList[0].CommsManager.UserService.GetUserProfile(ejecteeID); if ((groupInfo == null) || (userProfile == null)) { return; } // Send Message to Ejectee GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = remoteClient.AgentId.Guid; // msg.fromAgentID = info.GroupID; msg.toAgentID = ejecteeID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = remoteClient.Name; msg.message = string.Format("You have been ejected from '{1}' by {0}.", remoteClient.Name, groupInfo.GroupName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = remoteClient.Scene.RegionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, ejecteeID); // Message to ejector // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presense server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = remoteClient.AgentId.Guid; msg.toAgentID = remoteClient.AgentId.Guid; msg.timestamp = 0; msg.fromAgentName = remoteClient.Name; if (userProfile != null) { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", remoteClient.Name, groupInfo.GroupName, userProfile.Name); } else { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", remoteClient.Name, groupInfo.GroupName, "Unknown member"); } msg.dialog = (byte)210; //interop msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = remoteClient.Scene.RegionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, remoteClient.AgentId); // SL sends out messages to everyone in the group // Who all should receive updates and what should they be updated with? UpdateAllClientsWithGroupInfo(ejecteeID); } public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check, probably also want to send some kind of notification UUID InviteID = UUID.Random(); GroupRequestID grid = GetClientGroupRequestID(remoteClient); m_groupData.AddAgentToGroupInvite(grid, InviteID, groupID, roleID, invitedAgentID); // Check to see if the invite went through, if it did not then it's possible // the remoteClient did not validate or did not have permission to invite. GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(grid, InviteID); if (inviteInfo != null) { if (m_msgTransferModule != null) { Guid inviteUUID = InviteID.Guid; GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = inviteUUID; // msg.fromAgentID = remoteClient.AgentId.Guid; msg.fromAgentID = groupID.Guid; msg.toAgentID = invitedAgentID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = remoteClient.Name; msg.message = string.Format("{0} has invited you to join a group. There is no cost to join this group.", remoteClient.Name); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = remoteClient.Scene.RegionInfo.RegionID.Guid; msg.binaryBucket = new byte[20]; OutgoingInstantMessage(msg, invitedAgentID); } } } #endregion #region Client/Update Tools /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { IClientAPI child = null; // Try root avatar first foreach (Scene scene in m_sceneList) { if (scene.Entities.ContainsKey(agentID) && scene.Entities[agentID] is ScenePresence) { ScenePresence user = (ScenePresence)scene.Entities[agentID]; if (!user.IsChildAgent) { return user.ControllingClient; } else { child = user.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none return child; } private GroupRequestID GetClientGroupRequestID(IClientAPI client) { if (client == null) { return new GroupRequestID(); } lock (m_clientRequestIDInfo) { if (!m_clientRequestIDInfo.ContainsKey(client.AgentId)) { GroupRequestIDInfo info = new GroupRequestIDInfo(); info.RequestID.AgentID = client.AgentId; info.RequestID.SessionID = client.SessionId; UserProfileData userProfile = m_sceneList[0].CommsManager.UserService.GetUserProfile(client.AgentId); if (userProfile == null) { // This should be impossible. If I've been passed a reference to a client // that client should be registered with the UserService. So something // is horribly wrong somewhere. m_log.WarnFormat("[GROUPS]: Could not find a user profile for {0} / {1}", client.Name, client.AgentId); // Default to local user service and hope for the best? info.RequestID.UserServiceURL = m_sceneList[0].CommsManager.NetworkServersInfo.UserURL; } else if (userProfile is ForeignUserProfileData) { // They aren't from around here ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile; info.RequestID.UserServiceURL = fupd.UserServerURI; } else { // They're a local user, use this: info.RequestID.UserServiceURL = m_sceneList[0].CommsManager.NetworkServersInfo.UserURL; } m_clientRequestIDInfo.Add(client.AgentId, info); } m_clientRequestIDInfo[client.AgentId].LastUsedTMStamp = DateTime.Now; return m_clientRequestIDInfo[client.AgentId].RequestID; } // Unreachable code! // return new GroupRequestID(); } /// <summary> /// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'. /// </summary> private void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, UUID dataForAgentID, GroupMembershipData[] data) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDArray AgentData = new OSDArray(1); OSDMap AgentDataMap = new OSDMap(1); AgentDataMap.Add("AgentID", OSD.FromUUID(dataForAgentID)); AgentData.Add(AgentDataMap); OSDArray GroupData = new OSDArray(data.Length); OSDArray NewGroupData = new OSDArray(data.Length); foreach (GroupMembershipData membership in data) { if (remoteClient.AgentId != dataForAgentID) { if (!membership.ListInProfile) { // If we're sending group info to remoteclient about another agent, // filter out groups the other agent doesn't want to share. continue; } } OSDMap GroupDataMap = new OSDMap(6); OSDMap NewGroupDataMap = new OSDMap(1); GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID)); GroupDataMap.Add("GroupPowers", OSD.FromBinary(membership.GroupPowers)); GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices)); GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture)); GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution)); GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName)); NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile)); GroupData.Add(GroupDataMap); NewGroupData.Add(NewGroupDataMap); } OSDMap llDataStruct = new OSDMap(3); llDataStruct.Add("AgentData", AgentData); llDataStruct.Add("GroupData", GroupData); llDataStruct.Add("NewGroupData", NewGroupData); IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); if (queue != null) { queue.Enqueue(EventQueueHelper.buildEvent("AgentGroupDataUpdate", llDataStruct), remoteClient.AgentId); } } private void SendScenePresenceUpdate(UUID AgentID, string Title) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Updating scene title for {0} with title: {1}", AgentID, Title); ScenePresence presence = null; foreach (Scene scene in m_sceneList) { presence = scene.GetScenePresence(AgentID); if (presence != null) { presence.Grouptitle = Title; // FixMe: Ter suggests a "Schedule" method that I can't find. presence.SendFullUpdateToAllClients(); } } } /// <summary> /// Send updates to all clients who might be interested in groups data for dataForClientID /// </summary> private void UpdateAllClientsWithGroupInfo(UUID dataForClientID) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Probably isn't nessesary to update every client in every scene. // Need to examine client updates and do only what's nessesary. lock (m_sceneList) { foreach (Scene scene in m_sceneList) { scene.ForEachClient(delegate(IClientAPI client) { SendAgentGroupDataUpdate(client, dataForClientID); }); } } } /// <summary> /// Update remoteClient with group information about dataForAgentID /// </summary> private void SendAgentGroupDataUpdate(IClientAPI remoteClient, UUID dataForAgentID) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name); // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff OnAgentDataUpdateRequest(remoteClient, dataForAgentID, UUID.Zero); // Need to send a group membership update to the client // UDP version doesn't seem to behave nicely. But we're going to send it out here // with an empty group membership to hopefully remove groups being displayed due // to the core Groups Stub remoteClient.SendGroupMembership(new GroupMembershipData[0]); GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, dataForAgentID); SendGroupMembershipInfoViaCaps(remoteClient, dataForAgentID, membershipArray); remoteClient.SendAvatarGroupsReply(dataForAgentID, membershipArray); } /// <summary> /// Get a list of groups memberships for the agent that are marked "ListInProfile" /// </summary> /// <param name="dataForAgentID"></param> /// <returns></returns> private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID) { List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(GetClientGroupRequestID(requestingClient), dataForAgentID); GroupMembershipData[] membershipArray; if (requestingClient.AgentId != dataForAgentID) { Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership) { return membership.ListInProfile; }; membershipArray = membershipData.FindAll(showInProfile).ToArray(); } else { membershipArray = membershipData.ToArray(); } if (m_debugEnabled) { m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId); foreach (GroupMembershipData membership in membershipArray) { m_log.InfoFormat("[GROUPS]: {0} :: {1} - {2}", dataForAgentID, membership.GroupName, membership.GroupTitle); } } return membershipArray; } private void SendAgentDataUpdate(IClientAPI remoteClient, UUID dataForAgentID, UUID activeGroupID, string activeGroupName, ulong activeGroupPowers, string activeGroupTitle) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff UserProfileData userProfile = m_sceneList[0].CommsManager.UserService.GetUserProfile(dataForAgentID); string firstname, lastname; if (userProfile != null) { firstname = userProfile.FirstName; lastname = userProfile.SurName; } else { firstname = "Unknown"; lastname = "Unknown"; } remoteClient.SendAgentDataUpdate(dataForAgentID, activeGroupID, firstname, lastname, activeGroupPowers, activeGroupName, activeGroupTitle); } #endregion #region IM Backed Processes private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); IClientAPI localClient = GetActiveClient(msgTo); if (localClient != null) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is local, delivering directly", localClient.Name); localClient.SendInstantMessage(msg); } else { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo); m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Message Sent: {0}", success?"Succeeded":"Failed"); }); } } public void NotifyChange(UUID groupID) { // Notify all group members of a chnge in group roles and/or // permissions // } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; #pragma warning disable 0414 namespace System.Reflection.Tests { public class PropertyInfoGetValueTests { [Theory] [InlineData(typeof(ClassWithObjectArrayProperties), "PropertyA", null, new string[] { "hello" })] [InlineData(typeof(ClassWithObjectArrayProperties), "PropertyB", null, null)] [InlineData(typeof(ClassWithObjectArrayProperties), "PropertyC", new object[] { 1, "2" }, null)] [InlineData(typeof(ClassWithPrivateMethod), "Property2", null, 100)] [InlineData(typeof(InterfacePropertyClassImplementation), "Name", (object[])null, null)] public static void GetValue(Type type, string propertyName, object[] index, object expectedValue) { PropertyInfo propertyInfo = type.GetTypeInfo().GetProperty(propertyName); object instance = Activator.CreateInstance(type); if (index == null) { Assert.Equal(expectedValue, propertyInfo.GetValue(instance)); } Assert.Equal(expectedValue, propertyInfo.GetValue(instance, index)); } [Theory] [InlineData(typeof(ClassWithObjectArrayProperties), "PropertyA", new string[] { "hello" }, null)] [InlineData(typeof(ClassWithObjectArrayProperties), "PropertyB", new string[] { "hello" }, null)] [InlineData(typeof(InterfacePropertyClassImplementation), "Name", "hello", null)] public static void SetValue(Type type, string propertyName, object setValue, object[] index) { PropertyInfo propertyInfo = type.GetTypeInfo().GetProperty(propertyName); object instance = Activator.CreateInstance(type); if (index == null) { propertyInfo.SetValue(instance, setValue); } propertyInfo.SetValue(instance, setValue, index); Assert.Equal(setValue, propertyInfo.GetValue(instance)); } [Fact] public static void SetValue_Item() { string propertyName = "Item"; TypeWithProperties obj = new TypeWithProperties(); PropertyInfo pi = typeof(TypeWithProperties).GetTypeInfo().GetProperty(propertyName); string[] h = { "hello" }; Assert.Equal(pi.Name, propertyName); pi.SetValue(obj, "someotherstring", new object[] { 99, 2, h, "f" }); Assert.Equal("992f1someotherstring", obj.setValue); pi.SetValue(obj, "pw", new object[] { 99, 2, h, "SOME string" }); Assert.Equal("992SOME string1pw", obj.setValue); } // // Negative Tests for PropertyInfo // [Theory] [InlineData("PropertyC", typeof(ClassWithObjectArrayProperties), new object[] { 1, "2", 3 })] [InlineData("PropertyC", typeof(ClassWithObjectArrayProperties), null)] public static void GetValue_ThrowsTargetParameterCountException(string propertyName, Type type, object[]testObj) { object obj = Activator.CreateInstance(type); PropertyInfo pi = type.GetTypeInfo().GetProperty(propertyName); Assert.Equal(propertyName, pi.Name); Assert.Throws<TargetParameterCountException>(() => pi.GetValue(obj, testObj)); } [Fact] public static void GetValue_ThrowsException() { string propertyName = "PropertyC"; object obj = Activator.CreateInstance(typeof(ClassWithObjectArrayProperties)); PropertyInfo pi = typeof(ClassWithObjectArrayProperties).GetTypeInfo().GetProperty(propertyName); Assert.Equal(propertyName, pi.Name); Assert.Throws<TargetException>(() => pi.GetValue(null, new object[] { "1", "2" })); } [Theory] [InlineData("Property1", typeof(ClassWithPrivateMethod), null)] [InlineData("PropertyC", typeof(ClassWithObjectArrayProperties), new object[] { "1", "2" })] public static void GetValue_ThrowsArgumentException(string propertyName, Type type, object[] testObj) { object obj = Activator.CreateInstance(type); PropertyInfo pi = type.GetTypeInfo().GetProperty(propertyName); Assert.Equal(propertyName, pi.Name); Assert.Throws<ArgumentException>(() => pi.GetValue(obj, testObj)); } [Fact] public static void SetValue_IndexerProperty_IncorrectNumberOfParameters_ThrowsTargetParameterCountException() { string propertyName = "Item"; TypeWithProperties obj = new TypeWithProperties(); PropertyInfo pi = typeof(TypeWithProperties).GetTypeInfo().GetProperty(propertyName); Assert.Equal(propertyName, pi.Name); Assert.Throws<TargetParameterCountException>(() => pi.SetValue(obj, "pw", new object[] { 99, 2, new string[] { "SOME string" } })); } //Try to set instance Property with null object [Theory] [InlineData("HasSetterProp", null, null)] [InlineData("Item", "pw", new object[] { 99, 2, "SOME string" })] public static void SetValueNull_ThrowsException(string propertyName, object setValue, object[] index) { PropertyInfo pi = typeof(TypeWithProperties).GetTypeInfo().GetProperty(propertyName); Assert.Equal(propertyName, pi.Name); Assert.Throws<TargetException>(() => pi.SetValue(null, setValue, index)); } [Theory] [InlineData("NoSetterProp", 100, null)] [InlineData("Item", "pw", new object[] { 99, 2, "hello", "SOME string" })] [InlineData("Item", 100, new object[] { 99, 2, new string[] { "hello" }, "SOME string" })] [InlineData("HasSetterProp", "foo", null)] public static void SetValue_ThrowsArgumentException(string propertyName, object setValue, object[] index) { TypeWithProperties obj = new TypeWithProperties(); PropertyInfo pi = typeof(TypeWithProperties).GetTypeInfo().GetProperty(propertyName); Assert.Equal(propertyName, pi.Name); Assert.Throws<ArgumentException>(() => pi.SetValue(obj, setValue, index)); } } //Reflection Metadata public class ClassWithObjectArrayProperties { public static object[] objArr = new object[1]; public object[] objArr2; public static object[] PropertyA { get { return objArr; } set { objArr = value; } } public object[] PropertyB { get { return objArr2; } set { objArr2 = value; } } [System.Runtime.CompilerServices.IndexerNameAttribute("PropertyC")] // will make the property name be MyPropAA instead of default Item public object[] this[int index, string s] { get { return objArr2; } set { objArr2 = value; } } } public class TypeWithProperties { public int NoSetterProp { get { return 0; } } public int HasSetterProp { set { } } public string this[int index, int index2, string[] h, string myStr] { get { string strHashLength = "null"; if (h != null) { strHashLength = h.Length.ToString(); } return index.ToString() + index2.ToString() + myStr + strHashLength; } set { string strHashLength = "null"; if (h != null) { strHashLength = h.Length.ToString(); } setValue = setValue = index.ToString() + index2.ToString() + myStr + strHashLength + value; } } public string setValue = null; } public interface InterfaceProperty { string Name { get; set; } } public class InterfacePropertyClassImplementation : InterfaceProperty { private string _name = null; public string Name { get { return _name; } set { _name = value; } } } public class ClassWithPrivateMethod { public int Property1 { set { } } public int Property2 { private get { return 100; } set { } } } }
// // Copyright (C) 2012-2014 DataStax 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.Linq; namespace Cassandra { /// <summary> /// Represents a prepared statement, a query with bound variables that has been /// prepared (pre-parsed) by the database. <p> A prepared statement can be /// executed once concrete values has been provided for the bound variables. The /// pair of a prepared statement and values for its bound variables is a /// BoundStatement and can be executed (by <link>Session#Execute</link>).</p> /// </summary> public class PreparedStatement { internal readonly RowSetMetadata Metadata; private readonly int _protocolVersion; private volatile RoutingKey _routingKey; private string[] _routingNames; /// <summary> /// The cql query /// </summary> internal string Cql { get; private set; } /// <summary> /// The prepared statement identifier /// </summary> internal byte[] Id { get; private set; } /// <summary> /// The keyspace were the prepared statement was first executed /// </summary> internal string Keyspace { get; private set; } /// <summary> /// Gets the the incoming payload, that is, the payload that the server /// sent back with its prepared response, or null if the server did not include any custom payload. /// </summary> public IDictionary<string, byte[]> IncomingPayload { get; internal set; } /// <summary> /// Gets custom payload for that will be included when executing an Statement. /// </summary> public IDictionary<string, byte[]> OutgoingPayload { get; private set; } /// <summary> /// Gets metadata on the bounded variables of this prepared statement. /// </summary> public RowSetMetadata Variables { get { return Metadata; } } /// <summary> /// Gets the routing key for the prepared statement. /// </summary> public RoutingKey RoutingKey { get { return _routingKey; } } /// <summary> /// Gets or sets the parameter indexes that are part of the partition key /// </summary> public int[] RoutingIndexes { get; internal set; } /// <summary> /// Gets the default consistency level for all executions using this instance /// </summary> public ConsistencyLevel? ConsistencyLevel { get; private set; } /// <summary> /// Determines if the query is idempotent, i.e. whether it can be applied multiple times without /// changing the result beyond the initial application. /// <para> /// Idempotence of the prepared statement plays a role in <see cref="ISpeculativeExecutionPolicy"/>. /// If a query is <em>not idempotent</em>, the driver will not schedule speculative executions for it. /// </para> /// When the property is null, the driver will use the default value from the <see cref="QueryOptions.GetDefaultIdempotence()"/>. /// </summary> public bool? IsIdempotent { get; private set; } internal PreparedStatement(RowSetMetadata metadata, byte[] id, string cql, string keyspace, int protocolVersion) { Metadata = metadata; Id = id; Cql = cql; Keyspace = keyspace; _protocolVersion = protocolVersion; } /// <summary> /// Creates a new BoundStatement object and bind its variables to the provided /// values. /// <para> /// Specify the parameter values by the position of the markers in the query or by name, /// using a single instance of an anonymous type, with property names as parameter names. /// </para> /// <para> /// Note that while no more <c>values</c> than bound variables can be provided, it is allowed to /// provide less <c>values</c> that there is variables. /// </para> /// </summary> /// <param name="values"> the values to bind to the variables of the newly /// created BoundStatement. </param> /// <returns>the newly created <c>BoundStatement</c> with its variables /// bound to <c>values</c>. </returns> public BoundStatement Bind(params object[] values) { var bs = new BoundStatement(this) { ProtocolVersion = _protocolVersion }; bs.SetRoutingKey(_routingKey); if (values == null) { return bs; } var valuesByPosition = values; var useNamedParameters = values.Length == 1 && Utils.IsAnonymousType(values[0]); if (useNamedParameters) { //Using named parameters //Reorder the params according the position in the query valuesByPosition = Utils.GetValues(Metadata.Columns.Select(c => c.Name), values[0]).ToArray(); } bs.SetValues(valuesByPosition); bs.CalculateRoutingKey(useNamedParameters, RoutingIndexes, _routingNames, valuesByPosition, values); return bs; } /// <summary> /// Sets a default consistency level for all <c>BoundStatement</c> created /// from this object. <p> If no consistency level is set through this method, the /// BoundStatement created from this object will use the default consistency /// level (One). </p><p> Changing the default consistency level is not retroactive, /// it only applies to BoundStatement created after the change.</p> /// </summary> /// <param name="consistency"> the default consistency level to set. </param> /// <returns>this <c>PreparedStatement</c> object.</returns> public PreparedStatement SetConsistencyLevel(ConsistencyLevel consistency) { ConsistencyLevel = consistency; return this; } /// <summary> /// Sets the partition keys of the query /// </summary> /// <returns>True if it was possible to set the routing indexes for this query</returns> internal bool SetPartitionKeys(TableColumn[] keys) { var queryParameters = Metadata.Columns; var routingIndexes = new List<int>(); foreach (var key in keys) { //find the position of the key in the parameters for (var i = 0; i < queryParameters.Length; i++) { if (queryParameters[i].Name != key.Name) { continue; } routingIndexes.Add(i); break; } } if (routingIndexes.Count != keys.Length) { //The parameter names don't match the partition keys return false; } RoutingIndexes = routingIndexes.ToArray(); return true; } /// <summary> /// Set the routing key for this query. /// <para> /// The routing key is a hint for token aware load balancing policies but is never mandatory. /// This method allows you to manually provide a routing key for this query. /// </para> /// <para> /// Use this method ONLY if the partition keys are the same for all query executions (hard-coded parameters). /// </para> /// <para> /// If the partition key is composite, you should provide multiple routing key components. /// </para> /// </summary> /// <param name="routingKeyComponents"> the raw (binary) values to compose to /// obtain the routing key. </param> /// <returns>this <c>PreparedStatement</c> object.</returns> public PreparedStatement SetRoutingKey(params RoutingKey[] routingKeyComponents) { _routingKey = RoutingKey.Compose(routingKeyComponents); return this; } /// <summary> /// For named query markers, it sets the parameter names that are part of the routing key. /// <para> /// Use this method ONLY if the parameter names are different from the partition key names. /// </para> /// </summary> /// <returns>this <c>PreparedStatement</c> object.</returns> public PreparedStatement SetRoutingNames(params string[] names) { if (names == null) { return this; } _routingNames = names; return this; } /// <summary> /// Sets whether the prepared statement is idempotent. /// <para> /// Idempotence of the query plays a role in <see cref="ISpeculativeExecutionPolicy"/>. /// If a query is <em>not idempotent</em>, the driver will not schedule speculative executions for it. /// </para> /// </summary> public PreparedStatement SetIdempotence(bool value) { IsIdempotent = value; return this; } /// <summary> /// Sets a custom outgoing payload for this statement. /// Each time an statement generated using this prepared statement is executed, this payload will be included in the request. /// Once it is set using this method, the payload should not be modified. /// </summary> public PreparedStatement SetOutgoingPayload(IDictionary<string, byte[]> payload) { OutgoingPayload = payload; return this; } } }
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay // //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. /** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Text; using Thrift.Protocol; namespace Netfox.SnooperMessenger.Protocol { #if !SILVERLIGHT [Serializable] #endif public partial class LocationAttachement : TBase { private Coordinates _Coordinates; private bool _IsCurrentLocation; private long _PlaceID; public Coordinates Coordinates { get { return _Coordinates; } set { __isset.Coordinates = true; this._Coordinates = value; } } public bool IsCurrentLocation { get { return _IsCurrentLocation; } set { __isset.IsCurrentLocation = true; this._IsCurrentLocation = value; } } public long PlaceID { get { return _PlaceID; } set { __isset.PlaceID = true; this._PlaceID = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool Coordinates; public bool IsCurrentLocation; public bool PlaceID; } public LocationAttachement() { } public void Read (TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.Struct) { Coordinates = new Coordinates(); Coordinates.Read(iprot); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.Bool) { IsCurrentLocation = iprot.ReadBool(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.I64) { PlaceID = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } } public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("LocationAttachement"); oprot.WriteStructBegin(struc); TField field = new TField(); if (Coordinates != null && __isset.Coordinates) { field.Name = "Coordinates"; field.Type = TType.Struct; field.ID = 1; oprot.WriteFieldBegin(field); Coordinates.Write(oprot); oprot.WriteFieldEnd(); } if (__isset.IsCurrentLocation) { field.Name = "IsCurrentLocation"; field.Type = TType.Bool; field.ID = 2; oprot.WriteFieldBegin(field); oprot.WriteBool(IsCurrentLocation); oprot.WriteFieldEnd(); } if (__isset.PlaceID) { field.Name = "PlaceID"; field.Type = TType.I64; field.ID = 3; oprot.WriteFieldBegin(field); oprot.WriteI64(PlaceID); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { StringBuilder __sb = new StringBuilder("LocationAttachement("); bool __first = true; if (Coordinates != null && __isset.Coordinates) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Coordinates: "); __sb.Append(Coordinates== null ? "<null>" : Coordinates.ToString()); } if (__isset.IsCurrentLocation) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("IsCurrentLocation: "); __sb.Append(IsCurrentLocation); } if (__isset.PlaceID) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("PlaceID: "); __sb.Append(PlaceID); } __sb.Append(")"); return __sb.ToString(); } } }
//----------------------------------------------------------------------- // <copyright file="AuthTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.IO.IsolatedStorage; using System.Reflection; using System.Text; using Csla; using Csla.Serialization; using Csla.Rules; using Csla.Test.Security; using UnitDriven; using System.Diagnostics; #if NUNIT using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #elif MSTEST using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace Csla.Test.Authorization { #if TESTING [DebuggerNonUserCode] [DebuggerStepThrough] #endif [TestClass()] public class AuthTests { private DataPortal.DpRoot root = DataPortal.DpRoot.NewRoot(); [TestCleanup] public void Cleanup() { ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; } [TestMethod()] public void TestAuthCloneRules() { ApplicationContext.GlobalContext.Clear(); Security.TestPrincipal.SimulateLogin(); Assert.AreEqual(true, Csla.ApplicationContext.User.IsInRole("Admin")); #region "Pre Cloning Tests" //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", root.DenyReadOnProperty, "Read should have been denied 1"); //Is it denying write properly? root.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied 2"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", root.DenyReadWriteOnProperty, "Read should have been denied 3"); root.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied 4"); //Is it allowing both read and write properly? Assert.AreEqual(root.AllowReadWriteOnProperty, root.Auth, "Read should have been allowed 5"); root.AllowReadWriteOnProperty = "No value"; Assert.AreEqual("No value", root.Auth, "Write should have been allowed 6"); #endregion #region "After Cloning Tests" //Do they work under cloning as well? DataPortal.DpRoot NewRoot = root.Clone(); ApplicationContext.GlobalContext.Clear(); //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", NewRoot.DenyReadOnProperty, "Read should have been denied 7"); //Is it denying write properly? NewRoot.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", NewRoot.Auth, "Write should have been denied 8"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", NewRoot.DenyReadWriteOnProperty, "Read should have been denied 9"); NewRoot.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", NewRoot.Auth, "Write should have been denied 10"); //Is it allowing both read and write properly? Assert.AreEqual(NewRoot.AllowReadWriteOnProperty, NewRoot.Auth, "Read should have been allowed 11"); NewRoot.AllowReadWriteOnProperty = "AllowReadWriteOnProperty"; Assert.AreEqual("AllowReadWriteOnProperty", NewRoot.Auth, "Write should have been allowed 12"); #endregion Security.TestPrincipal.SimulateLogout(); } [TestMethod()] public void TestAuthBeginEditRules() { ApplicationContext.GlobalContext.Clear(); Security.TestPrincipal.SimulateLogin(); #if SILVERLIGHT Assert.AreEqual(true, Csla.ApplicationContext.User.IsInRole("Admin")); #else Assert.AreEqual(true, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); #endif root.Data = "Something new"; root.BeginEdit(); #region "Pre-Testing" root.Data = "Something new 1"; //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", root.DenyReadOnProperty, "Read should have been denied"); //Is it denying write properly? root.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", root.DenyReadWriteOnProperty, "Read should have been denied"); root.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it allowing both read and write properly? Assert.AreEqual(root.AllowReadWriteOnProperty, root.Auth, "Read should have been allowed"); root.AllowReadWriteOnProperty = "No value"; Assert.AreEqual("No value", root.Auth, "Write should have been allowed"); #endregion #region "Cancel Edit" //Cancel the edit and see if the authorization rules still work root.CancelEdit(); //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", root.DenyReadOnProperty, "Read should have been denied"); //Is it denying write properly? root.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", root.DenyReadWriteOnProperty, "Read should have been denied"); root.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it allowing both read and write properly? Assert.AreEqual(root.AllowReadWriteOnProperty, root.Auth, "Read should have been allowed"); root.AllowReadWriteOnProperty = "No value"; Assert.AreEqual("No value", root.Auth, "Write should have been allowed"); #endregion #region "Apply Edit" //Apply this edit and see if the authorization rules still work //Is it denying read properly? Assert.AreEqual("[DenyReadOnProperty] Can't read property", root.DenyReadOnProperty, "Read should have been denied"); //Is it denying write properly? root.DenyWriteOnProperty = "DenyWriteOnProperty"; Assert.AreEqual("[DenyWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it denying both read and write properly? Assert.AreEqual("[DenyReadWriteOnProperty] Can't read property", root.DenyReadWriteOnProperty, "Read should have been denied"); root.DenyReadWriteOnProperty = "DenyReadWriteONproperty"; Assert.AreEqual("[DenyReadWriteOnProperty] Can't write variable", root.Auth, "Write should have been denied"); //Is it allowing both read and write properly? Assert.AreEqual(root.AllowReadWriteOnProperty, root.Auth, "Read should have been allowed"); root.AllowReadWriteOnProperty = "No value"; Assert.AreEqual("No value", root.Auth, "Write should have been allowed"); #endregion Security.TestPrincipal.SimulateLogout(); } [TestMethod()] public void TestAuthorizationAfterEditCycle() { Csla.ApplicationContext.GlobalContext.Clear(); Csla.Test.Security.PermissionsRoot pr = Csla.Test.Security.PermissionsRoot.NewPermissionsRoot(); Csla.Test.Security.TestPrincipal.SimulateLogin(); pr.FirstName = "something"; pr.BeginEdit(); pr.FirstName = "ba"; pr.CancelEdit(); Csla.Test.Security.TestPrincipal.SimulateLogout(); Csla.Test.Security.PermissionsRoot prClone = pr.Clone(); Csla.Test.Security.TestPrincipal.SimulateLogin(); prClone.FirstName = "somethiansdfasdf"; Csla.Test.Security.TestPrincipal.SimulateLogout(); } [ExpectedException(typeof(Csla.Security.SecurityException))] [TestMethod] public void TestUnauthorizedAccessToGet() { Csla.ApplicationContext.GlobalContext.Clear(); PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //this should throw an exception, since only admins have access to this property string something = pr.FirstName; } [ExpectedException(typeof(Csla.Security.SecurityException))] [TestMethod] public void TestUnauthorizedAccessToSet() { PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //will cause an exception, because only admins can write to property pr.FirstName = "test"; } [TestMethod] public void TestAuthorizedAccess() { Csla.ApplicationContext.GlobalContext.Clear(); Csla.Test.Security.TestPrincipal.SimulateLogin(); PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //should work, because we are now logged in as an admin pr.FirstName = "something"; string something = pr.FirstName; #if SILVERLIGHT Assert.AreEqual(true, Csla.ApplicationContext.User.IsInRole("Admin")); #else Assert.AreEqual(true, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); #endif //set to null so the other testmethods continue to throw exceptions Csla.Test.Security.TestPrincipal.SimulateLogout(); #if SILVERLIGHT Assert.AreEqual(false, Csla.ApplicationContext.User.IsInRole("Admin")); #else Assert.AreEqual(false, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); #endif } [TestMethod] public void TestAuthExecute() { Csla.ApplicationContext.GlobalContext.Clear(); Csla.Test.Security.TestPrincipal.SimulateLogin(); PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //should work, because we are now logged in as an admin pr.DoWork(); #if SILVERLIGHT Assert.AreEqual(true, Csla.ApplicationContext.User.IsInRole("Admin")); #else Assert.AreEqual(true, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); #endif //set to null so the other testmethods continue to throw exceptions Csla.Test.Security.TestPrincipal.SimulateLogout(); #if SILVERLIGHT Assert.AreEqual(false, Csla.ApplicationContext.User.IsInRole("Admin")); #else Assert.AreEqual(false, System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); #endif } [TestMethod] [ExpectedException(typeof(Csla.Security.SecurityException))] public void TestUnAuthExecute() { Csla.ApplicationContext.GlobalContext.Clear(); Assert.AreEqual(false, Csla.ApplicationContext.User.IsInRole("Admin")); PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); //should fail, because we're not an admin pr.DoWork(); } //[TestMethod()] //public void TestAuthorizationAfterClone() //{ // Csla.ApplicationContext.GlobalContext.Clear(); // Csla.Test.Security.TestPrincipal.SimulateLogin(); // PermissionsRoot pr = PermissionsRoot.NewPermissionsRoot(); // //should work because we are now logged in as an admin // pr.FirstName = "something"; // string something = pr.FirstName; // //The permissions should persist across a cloning // PermissionsRoot prClone = pr.Clone(); // pr.FirstName = "something"; // something = pr.FirstName; //} [TestMethod] public void TestAuthRuleSetsOnStaticHasPermissionMethodsWhenAddingAuthzRuleSetExplicitly() { var root = PermissionsRoot.NewPermissionsRoot(); Csla.Test.Security.TestPrincipal.SimulateLogin(); #if SILVERLIGHT Assert.IsTrue(Csla.ApplicationContext.User.IsInRole("Admin")); Assert.IsFalse(Csla.ApplicationContext.User.IsInRole("User")); #else Assert.IsTrue(System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); Assert.IsFalse(System.Threading.Thread.CurrentPrincipal.IsInRole("User")); #endif //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "User"), ApplicationContext.DefaultRuleSet); //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "Admin"), "custom1"); //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "User", "Admin"), "custom2"); // implicit usage of ApplicationContext.RuleSet ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot))); ApplicationContext.RuleSet = "custom1"; Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot))); ApplicationContext.RuleSet = "custom2"; Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot))); ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; // directly specifying which ruleset to use Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot), ApplicationContext.DefaultRuleSet)); Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot), "custom1")); Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot), "custom2")); Csla.Test.Security.TestPrincipal.SimulateLogout(); } [TestMethod] public void TestAuthRuleSetsOnStaticHasPermissionMethodsWhenAddingAuthzRuleSetUsingApplicationContextRuleSet() { var root = PermissionsRoot2.NewPermissionsRoot(); Csla.Test.Security.TestPrincipal.SimulateLogin(); #if SILVERLIGHT Assert.IsTrue(Csla.ApplicationContext.User.IsInRole("Admin")); Assert.IsFalse(Csla.ApplicationContext.User.IsInRole("User")); #else Assert.IsTrue(System.Threading.Thread.CurrentPrincipal.IsInRole("Admin")); Assert.IsFalse(System.Threading.Thread.CurrentPrincipal.IsInRole("User")); #endif //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "User"), ApplicationContext.DefaultRuleSet); //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "Admin"), "custom1"); //BusinessRules.AddRule(typeof(PermissionsRoot), new IsInRole(AuthorizationActions.DeleteObject, "User", "Admin"), "custom2"); // implicit usage of ApplicationContext.RuleSet ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2))); ApplicationContext.RuleSet = "custom1"; Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2))); ApplicationContext.RuleSet = "custom2"; Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2))); ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; // directly specifying which ruleset to use Assert.IsFalse(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2), ApplicationContext.DefaultRuleSet)); Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2), "custom1")); Assert.IsTrue(BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(PermissionsRoot2), "custom2")); Csla.Test.Security.TestPrincipal.SimulateLogout(); } [TestMethod] public void TestAuthRulesCleanupAndAddAgainWhenExceptionIsThrownInAddObjectBusinessRules() { RootException.Counter = 0; ApplicationContext.RuleSet = ApplicationContext.DefaultRuleSet; // AddObjectAuthorizations should throw exception try { BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(RootException)); } catch (Exception ex) { #if !SILVERLIGHT Assert.IsInstanceOfType(ex, typeof(TargetInvocationException)); Assert.IsInstanceOfType(ex.InnerException, typeof(ArgumentException)); #else using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("sl_testauth.txt", FileMode.OpenOrCreate, isf)) { using (StreamWriter sw = new StreamWriter(isfs)) { sw.Write(ex.ToString()); sw.Close(); } } } Assert.IsInstanceOfType(typeof(TargetInvocationException), ex); Assert.IsInstanceOfType(typeof(ArgumentException), ex.InnerException); #endif } // AddObjectAuthorizations should be called again and // should throw exception again try { BusinessRules.HasPermission(AuthorizationActions.DeleteObject, typeof(RootException)); } catch (Exception ex) { #if !SILVERLIGHT Assert.IsInstanceOfType(ex, typeof(TargetInvocationException)); Assert.IsInstanceOfType(ex.InnerException, typeof(ArgumentException)); #else Assert.IsInstanceOfType(typeof(TargetInvocationException), ex); Assert.IsInstanceOfType(typeof(ArgumentException), ex.InnerException); #endif } Assert.IsTrue(RootException.Counter == 2); } [TestMethod] public void AuthorizeRemoveFromList() { var root = new RootList(); root.RemoveAt(0); } } [Serializable] public class RootList : BusinessListBase<RootList, ChildItem> { public RootList() { using (SuppressListChangedEvents) { Add(Csla.DataPortal.CreateChild<ChildItem>()); } } } [Serializable] public class ChildItem : BusinessBase<ChildItem> { protected override void AddBusinessRules() { base.AddBusinessRules(); BusinessRules.AddRule(new NoAuth(AuthorizationActions.DeleteObject)); } private class NoAuth : Csla.Rules.AuthorizationRule { public NoAuth(AuthorizationActions action) : base(action) {} protected override void Execute(AuthorizationContext context) { context.HasPermission = false; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Attachments { /// <summary> /// A module that just holds commands for inspecting avatar appearance. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SceneCommandsModule")] public class SceneCommandsModule : ISceneCommandsModule, INonSharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; public string Name { get { return "Scene Commands Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: INITIALIZED MODULE"); } public void PostInitialise() { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: POST INITIALIZED MODULE"); } public void Close() { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: CLOSED MODULE"); } public void AddRegion(Scene scene) { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); m_scene = scene; m_scene.RegisterModuleInterface<ISceneCommandsModule>(this); } public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[SCENE COMMANDS MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); } public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); scene.AddCommand( "Debug", this, "debug scene get", "debug scene get", "List current scene options.", "active - if false then main scene update and maintenance loops are suspended.\n" + "animations - if true then extra animations debug information is logged.\n" + "appear-refresh - if true then appearance is resent to other avatars every 60 seconds.\n" + "client-pos-upd - the tolerance before clients are updated with new rotation information for an avatar.\n" + "client-rot-upd - the tolerance before clients are updated with new rotation information for an avatar.\n" + "client-vel-upd - the tolerance before clients are updated with new velocity information for an avatar.\n" + "root-upd-per - if greater than 1, terse updates are only sent to root agents other than the originator on every n updates.\n" + "child-upd-per - if greater than 1, terse updates are only sent to child agents on every n updates.\n" + "collisions - if false then collisions with other objects are turned off.\n" + "pbackup - if false then periodic scene backup is turned off.\n" + "physics - if false then all physics objects are non-physical.\n" + "scripting - if false then no scripting operations happen.\n" + "teleport - if true then some extra teleport debug information is logged.\n" + "update-on-timer - If true then the scene is updated via a timer. If false then a thread with sleep is used.\n" + "updates - if true then any frame which exceeds double the maximum desired frame time is logged.", HandleDebugSceneGetCommand); scene.AddCommand( "Debug", this, "debug scene set", "debug scene set <param> <value>", "Turn on scene debugging options.", "active - if false then main scene update and maintenance loops are suspended.\n" + "animations - if true then extra animations debug information is logged.\n" + "appear-refresh - if true then appearance is resent to other avatars every 60 seconds.\n" + "client-pos-upd - the tolerance before clients are updated with new rotation information for an avatar.\n" + "client-rot-upd - the tolerance before clients are updated with new rotation information for an avatar.\n" + "client-vel-upd - the tolerance before clients are updated with new velocity information for an avatar.\n" + "root-upd-per - if greater than 1, terse updates are only sent to root agents other than the originator on every n updates.\n" + "child-upd-per - if greater than 1, terse updates are only sent to child agents on every n updates.\n" + "collisions - if false then collisions with other objects are turned off.\n" + "pbackup - if false then periodic scene backup is turned off.\n" + "physics - if false then all physics objects are non-physical.\n" + "scripting - if false then no scripting operations happen.\n" + "teleport - if true then some extra teleport debug information is logged.\n" + "update-on-timer - If true then the scene is updated via a timer. If false then a thread with sleep is used.\n" + "updates - if true then any frame which exceeds double the maximum desired frame time is logged.", HandleDebugSceneSetCommand); } private void HandleDebugSceneGetCommand(string module, string[] args) { if (args.Length == 3) { if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null) return; OutputSceneDebugOptions(); } else { MainConsole.Instance.Output("Usage: debug scene get"); } } private void OutputSceneDebugOptions() { ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("active", m_scene.Active); cdl.AddRow("animations", m_scene.DebugAnimations); cdl.AddRow("appear-refresh", m_scene.SendPeriodicAppearanceUpdates); cdl.AddRow("client-pos-upd", m_scene.RootPositionUpdateTolerance); cdl.AddRow("client-rot-upd", m_scene.RootRotationUpdateTolerance); cdl.AddRow("client-vel-upd", m_scene.RootVelocityUpdateTolerance); cdl.AddRow("root-upd-per", m_scene.RootTerseUpdatePeriod); cdl.AddRow("child-upd-per", m_scene.ChildTerseUpdatePeriod); cdl.AddRow("pbackup", m_scene.PeriodicBackup); cdl.AddRow("physics", m_scene.PhysicsEnabled); cdl.AddRow("scripting", m_scene.ScriptsEnabled); cdl.AddRow("teleport", m_scene.DebugTeleporting); // cdl.AddRow("update-on-timer", m_scene.UpdateOnTimer); cdl.AddRow("updates", m_scene.DebugUpdates); MainConsole.Instance.OutputFormat("Scene {0} options:", m_scene.Name); MainConsole.Instance.Output(cdl.ToString()); } private void HandleDebugSceneSetCommand(string module, string[] args) { if (args.Length == 5) { if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null) return; string key = args[3]; string value = args[4]; SetSceneDebugOptions(new Dictionary<string, string>() { { key, value } }); MainConsole.Instance.OutputFormat("Set {0} debug scene {1} = {2}", m_scene.Name, key, value); } else { MainConsole.Instance.Output("Usage: debug scene set <param> <value>"); } } public void SetSceneDebugOptions(Dictionary<string, string> options) { if (options.ContainsKey("active")) { bool active; if (bool.TryParse(options["active"], out active)) m_scene.Active = active; } if (options.ContainsKey("animations")) { bool active; if (bool.TryParse(options["animations"], out active)) m_scene.DebugAnimations = active; } if (options.ContainsKey("appear-refresh")) { bool newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, options["appear-refresh"], out newValue)) m_scene.SendPeriodicAppearanceUpdates = newValue; } if (options.ContainsKey("client-pos-upd")) { float newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-pos-upd"], out newValue)) m_scene.RootPositionUpdateTolerance = newValue; } if (options.ContainsKey("client-rot-upd")) { float newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-rot-upd"], out newValue)) m_scene.RootRotationUpdateTolerance = newValue; } if (options.ContainsKey("client-vel-upd")) { float newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-vel-upd"], out newValue)) m_scene.RootVelocityUpdateTolerance = newValue; } if (options.ContainsKey("root-upd-per")) { int newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, options["root-upd-per"], out newValue)) m_scene.RootTerseUpdatePeriod = newValue; } if (options.ContainsKey("child-upd-per")) { int newValue; // FIXME: This can only come from the console at the moment but might not always be true. if (ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, options["child-upd-per"], out newValue)) m_scene.ChildTerseUpdatePeriod = newValue; } if (options.ContainsKey("pbackup")) { bool active; if (bool.TryParse(options["pbackup"], out active)) m_scene.PeriodicBackup = active; } if (options.ContainsKey("scripting")) { bool enableScripts = true; if (bool.TryParse(options["scripting"], out enableScripts)) m_scene.ScriptsEnabled = enableScripts; } if (options.ContainsKey("physics")) { bool enablePhysics; if (bool.TryParse(options["physics"], out enablePhysics)) m_scene.PhysicsEnabled = enablePhysics; } // if (options.ContainsKey("collisions")) // { // // TODO: Implement. If false, should stop objects colliding, though possibly should still allow // // the avatar themselves to collide with the ground. // } if (options.ContainsKey("teleport")) { bool enableTeleportDebugging; if (bool.TryParse(options["teleport"], out enableTeleportDebugging)) m_scene.DebugTeleporting = enableTeleportDebugging; } if (options.ContainsKey("update-on-timer")) { bool enableUpdateOnTimer; if (bool.TryParse(options["update-on-timer"], out enableUpdateOnTimer)) { // m_scene.UpdateOnTimer = enableUpdateOnTimer; m_scene.Active = false; while (m_scene.IsRunning) Thread.Sleep(20); m_scene.Active = true; } } if (options.ContainsKey("updates")) { bool enableUpdateDebugging; if (bool.TryParse(options["updates"], out enableUpdateDebugging)) { m_scene.DebugUpdates = enableUpdateDebugging; GcNotify.Enabled = enableUpdateDebugging; } } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedContextsClientSnippets { /// <summary>Snippet for ListContexts</summary> public void ListContextsRequestObject() { // Snippet: ListContexts(ListContextsRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ListContextsRequest request = new ListContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request PagedEnumerable<ListContextsResponse, Context> response = contextsClient.ListContexts(request); // Iterate over all response items, lazily performing RPCs as required foreach (Context item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListContextsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContextsAsync</summary> public async Task ListContextsRequestObjectAsync() { // Snippet: ListContextsAsync(ListContextsRequest, CallSettings) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ListContextsRequest request = new ListContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request PagedAsyncEnumerable<ListContextsResponse, Context> response = contextsClient.ListContextsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Context item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListContextsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContexts</summary> public void ListContexts() { // Snippet: ListContexts(string, string, int?, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request PagedEnumerable<ListContextsResponse, Context> response = contextsClient.ListContexts(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Context item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListContextsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContextsAsync</summary> public async Task ListContextsAsync() { // Snippet: ListContextsAsync(string, string, int?, CallSettings) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request PagedAsyncEnumerable<ListContextsResponse, Context> response = contextsClient.ListContextsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Context item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListContextsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContexts</summary> public void ListContextsResourceNames() { // Snippet: ListContexts(SessionName, string, int?, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request PagedEnumerable<ListContextsResponse, Context> response = contextsClient.ListContexts(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Context item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListContextsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContextsAsync</summary> public async Task ListContextsResourceNamesAsync() { // Snippet: ListContextsAsync(SessionName, string, int?, CallSettings) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request PagedAsyncEnumerable<ListContextsResponse, Context> response = contextsClient.ListContextsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Context item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListContextsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetContext</summary> public void GetContextRequestObject() { // Snippet: GetContext(GetContextRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request Context response = contextsClient.GetContext(request); // End snippet } /// <summary>Snippet for GetContextAsync</summary> public async Task GetContextRequestObjectAsync() { // Snippet: GetContextAsync(GetContextRequest, CallSettings) // Additional: GetContextAsync(GetContextRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request Context response = await contextsClient.GetContextAsync(request); // End snippet } /// <summary>Snippet for GetContext</summary> public void GetContext() { // Snippet: GetContext(string, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/contexts/[CONTEXT]"; // Make the request Context response = contextsClient.GetContext(name); // End snippet } /// <summary>Snippet for GetContextAsync</summary> public async Task GetContextAsync() { // Snippet: GetContextAsync(string, CallSettings) // Additional: GetContextAsync(string, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/contexts/[CONTEXT]"; // Make the request Context response = await contextsClient.GetContextAsync(name); // End snippet } /// <summary>Snippet for GetContext</summary> public void GetContextResourceNames() { // Snippet: GetContext(ContextName, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ContextName name = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request Context response = contextsClient.GetContext(name); // End snippet } /// <summary>Snippet for GetContextAsync</summary> public async Task GetContextResourceNamesAsync() { // Snippet: GetContextAsync(ContextName, CallSettings) // Additional: GetContextAsync(ContextName, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ContextName name = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request Context response = await contextsClient.GetContextAsync(name); // End snippet } /// <summary>Snippet for CreateContext</summary> public void CreateContextRequestObject() { // Snippet: CreateContext(CreateContextRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; // Make the request Context response = contextsClient.CreateContext(request); // End snippet } /// <summary>Snippet for CreateContextAsync</summary> public async Task CreateContextRequestObjectAsync() { // Snippet: CreateContextAsync(CreateContextRequest, CallSettings) // Additional: CreateContextAsync(CreateContextRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; // Make the request Context response = await contextsClient.CreateContextAsync(request); // End snippet } /// <summary>Snippet for CreateContext</summary> public void CreateContext() { // Snippet: CreateContext(string, Context, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; Context context = new Context(); // Make the request Context response = contextsClient.CreateContext(parent, context); // End snippet } /// <summary>Snippet for CreateContextAsync</summary> public async Task CreateContextAsync() { // Snippet: CreateContextAsync(string, Context, CallSettings) // Additional: CreateContextAsync(string, Context, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; Context context = new Context(); // Make the request Context response = await contextsClient.CreateContextAsync(parent, context); // End snippet } /// <summary>Snippet for CreateContext</summary> public void CreateContextResourceNames() { // Snippet: CreateContext(SessionName, Context, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); Context context = new Context(); // Make the request Context response = contextsClient.CreateContext(parent, context); // End snippet } /// <summary>Snippet for CreateContextAsync</summary> public async Task CreateContextResourceNamesAsync() { // Snippet: CreateContextAsync(SessionName, Context, CallSettings) // Additional: CreateContextAsync(SessionName, Context, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); Context context = new Context(); // Make the request Context response = await contextsClient.CreateContextAsync(parent, context); // End snippet } /// <summary>Snippet for UpdateContext</summary> public void UpdateContextRequestObject() { // Snippet: UpdateContext(UpdateContextRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), UpdateMask = new FieldMask(), }; // Make the request Context response = contextsClient.UpdateContext(request); // End snippet } /// <summary>Snippet for UpdateContextAsync</summary> public async Task UpdateContextRequestObjectAsync() { // Snippet: UpdateContextAsync(UpdateContextRequest, CallSettings) // Additional: UpdateContextAsync(UpdateContextRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), UpdateMask = new FieldMask(), }; // Make the request Context response = await contextsClient.UpdateContextAsync(request); // End snippet } /// <summary>Snippet for UpdateContext</summary> public void UpdateContext() { // Snippet: UpdateContext(Context, FieldMask, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) Context context = new Context(); FieldMask updateMask = new FieldMask(); // Make the request Context response = contextsClient.UpdateContext(context, updateMask); // End snippet } /// <summary>Snippet for UpdateContextAsync</summary> public async Task UpdateContextAsync() { // Snippet: UpdateContextAsync(Context, FieldMask, CallSettings) // Additional: UpdateContextAsync(Context, FieldMask, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) Context context = new Context(); FieldMask updateMask = new FieldMask(); // Make the request Context response = await contextsClient.UpdateContextAsync(context, updateMask); // End snippet } /// <summary>Snippet for DeleteContext</summary> public void DeleteContextRequestObject() { // Snippet: DeleteContext(DeleteContextRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request contextsClient.DeleteContext(request); // End snippet } /// <summary>Snippet for DeleteContextAsync</summary> public async Task DeleteContextRequestObjectAsync() { // Snippet: DeleteContextAsync(DeleteContextRequest, CallSettings) // Additional: DeleteContextAsync(DeleteContextRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request await contextsClient.DeleteContextAsync(request); // End snippet } /// <summary>Snippet for DeleteContext</summary> public void DeleteContext() { // Snippet: DeleteContext(string, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/contexts/[CONTEXT]"; // Make the request contextsClient.DeleteContext(name); // End snippet } /// <summary>Snippet for DeleteContextAsync</summary> public async Task DeleteContextAsync() { // Snippet: DeleteContextAsync(string, CallSettings) // Additional: DeleteContextAsync(string, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/contexts/[CONTEXT]"; // Make the request await contextsClient.DeleteContextAsync(name); // End snippet } /// <summary>Snippet for DeleteContext</summary> public void DeleteContextResourceNames() { // Snippet: DeleteContext(ContextName, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ContextName name = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request contextsClient.DeleteContext(name); // End snippet } /// <summary>Snippet for DeleteContextAsync</summary> public async Task DeleteContextResourceNamesAsync() { // Snippet: DeleteContextAsync(ContextName, CallSettings) // Additional: DeleteContextAsync(ContextName, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ContextName name = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request await contextsClient.DeleteContextAsync(name); // End snippet } /// <summary>Snippet for DeleteAllContexts</summary> public void DeleteAllContextsRequestObject() { // Snippet: DeleteAllContexts(DeleteAllContextsRequest, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request contextsClient.DeleteAllContexts(request); // End snippet } /// <summary>Snippet for DeleteAllContextsAsync</summary> public async Task DeleteAllContextsRequestObjectAsync() { // Snippet: DeleteAllContextsAsync(DeleteAllContextsRequest, CallSettings) // Additional: DeleteAllContextsAsync(DeleteAllContextsRequest, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request await contextsClient.DeleteAllContextsAsync(request); // End snippet } /// <summary>Snippet for DeleteAllContexts</summary> public void DeleteAllContexts() { // Snippet: DeleteAllContexts(string, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request contextsClient.DeleteAllContexts(parent); // End snippet } /// <summary>Snippet for DeleteAllContextsAsync</summary> public async Task DeleteAllContextsAsync() { // Snippet: DeleteAllContextsAsync(string, CallSettings) // Additional: DeleteAllContextsAsync(string, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request await contextsClient.DeleteAllContextsAsync(parent); // End snippet } /// <summary>Snippet for DeleteAllContexts</summary> public void DeleteAllContextsResourceNames() { // Snippet: DeleteAllContexts(SessionName, CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request contextsClient.DeleteAllContexts(parent); // End snippet } /// <summary>Snippet for DeleteAllContextsAsync</summary> public async Task DeleteAllContextsResourceNamesAsync() { // Snippet: DeleteAllContextsAsync(SessionName, CallSettings) // Additional: DeleteAllContextsAsync(SessionName, CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request await contextsClient.DeleteAllContextsAsync(parent); // End snippet } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.PreferTypedStringBuilderAppendOverloads, Microsoft.NetCore.Analyzers.Runtime.PreferTypedStringBuilderAppendOverloadsFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.PreferTypedStringBuilderAppendOverloads, Microsoft.NetCore.Analyzers.Runtime.PreferTypedStringBuilderAppendOverloadsFixer>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class PreferTypedStringBuilderAppendOverloadsTests { [Theory] [InlineData("int", true)] [InlineData("Int32", true)] [InlineData("string", true)] [InlineData("String", true)] [InlineData("ulong", true)] [InlineData("object", false)] [InlineData("char[]", false)] [InlineData("DateTime", false)] [InlineData("DayOfWeek", false)] public async Task ArgumentIsToStringMethodCallOnLocal_CSharpAsync(string receiverType, bool diagnosticExpected) { string toString = diagnosticExpected ? "[|value.ToString()|]" : "value.ToString()"; string original = @" using System; using System.Text; class C { public void M() { " + receiverType + @" value = default; var sb = new StringBuilder(); sb.Append(" + toString + @"); sb.Insert(42, " + toString + @"); } } "; await VerifyCS.VerifyCodeFixAsync(original, !diagnosticExpected ? original : @" using System; using System.Text; class C { public void M() { " + receiverType + @" value = default; var sb = new StringBuilder(); sb.Append(value); sb.Insert(42, value); } } "); } [Theory] [InlineData("Integer", true)] [InlineData("Int32", true)] [InlineData("String", true)] [InlineData("Object", false)] [InlineData("DateTime", false)] [InlineData("DayOfWeek", false)] public async Task ArgumentIsToStringMethodCallOnLocal_VBAsync(string receiverType, bool diagnosticExpected) { string toString = diagnosticExpected ? "[|value.ToString()|]" : "value.ToString()"; string original = @" Imports System Imports System.Text Class C Public Sub M() Dim value As " + receiverType + @" Dim sb As New StringBuilder() sb.Append(" + toString + @") sb.Insert(42, " + toString + @") End Sub End Class"; await VerifyVB.VerifyCodeFixAsync(original, !diagnosticExpected ? original : @" Imports System Imports System.Text Class C Public Sub M() Dim value As " + receiverType + @" Dim sb As New StringBuilder() sb.Append(value) sb.Insert(42, value) End Sub End Class"); } [Theory] [InlineData("int", true)] [InlineData("Int32", true)] [InlineData("string", true)] [InlineData("String", true)] [InlineData("ulong", true)] [InlineData("object", false)] [InlineData("char[]", false)] [InlineData("DateTime", false)] [InlineData("DayOfWeek", false)] public async Task ArgumentIsToStringMethodCallOnResult_CSharpAsync(string receiverType, bool diagnosticExpected) { string toString = diagnosticExpected ? "[|Prop.ToString()|]" : "Prop.ToString()"; string original = @" using System; using System.Text; class C { public void M() { var sb = new StringBuilder(); sb.Append(" + toString + @"); sb.Insert(42, " + toString + @"); } private static " + receiverType + @" Prop => default; } "; await VerifyCS.VerifyCodeFixAsync(original, !diagnosticExpected ? original : @" using System; using System.Text; class C { public void M() { var sb = new StringBuilder(); sb.Append(Prop); sb.Insert(42, Prop); } private static " + receiverType + @" Prop => default; } "); } [Theory] [InlineData("42", true)] [InlineData("\"hello\"", true)] [InlineData("DayOfWeek.Monday", false)] [InlineData("DateTime.Now", false)] public async Task ArgumentIsToStringMethodCallOnValueAsync(string value, bool diagnosticExpected) { string toString = value + ".ToString()"; if (diagnosticExpected) { toString = "[|" + toString + "|]"; } string original = @" using System; using System.Text; class C { public void M1() => new StringBuilder().Append(" + toString + @"); public void M2() => new StringBuilder().Insert(42, " + toString + @"); } "; await VerifyCS.VerifyCodeFixAsync(original, !diagnosticExpected ? original : @" using System; using System.Text; class C { public void M1() => new StringBuilder().Append(" + value + @"); public void M2() => new StringBuilder().Insert(42, " + value + @"); } "); } [Theory] [InlineData("42")] [InlineData("\"hello\"")] [InlineData("DayOfWeek.Monday")] [InlineData("DateTime.Now")] public async Task NoDiagnostic_NoToStringCallAsync(string value) { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Text; class C { public void M1() => new StringBuilder().Append(" + value + @"); public void M2() => new StringBuilder().Insert(42, " + value + @"); }"); } [Theory] [InlineData("42")] [InlineData("DayOfWeek.Monday")] [InlineData("DateTime.Now")] public async Task NoDiagnostic_FormattedToStringAsync(string value) { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Globalization; using System.Text; class C { public void M1() { new StringBuilder() .Append(" + value + @".ToString(""X4"")) .Append(" + value + @".ToString(CultureInfo.CurrentCulture)) .Append(" + value + @".ToString(""X4"", CultureInfo.CurrentCulture)) .Append(((IFormattable)" + value + @").ToString(""X4"", CultureInfo.CurrentCulture)) .Append(((IFormattable)" + value + @").ToString()); } public void M2() { new StringBuilder() .Insert(1, " + value + @".ToString(""X4"")) .Insert(1, " + value + @".ToString(CultureInfo.CurrentCulture)) .Insert(1, " + value + @".ToString(""X4"", CultureInfo.CurrentCulture)) .Insert(1, ((IFormattable)" + value + @").ToString(""X4"", CultureInfo.CurrentCulture)) .Insert(1, ((IFormattable)" + value + @").ToString()); } }"); } [Fact] public async Task NoDiagnostic_NotRelevantMethodAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Text; class C { public void M() { var sb = new StringBuilder(); sb.AppendLine(42.ToString()); sb.Replace(42.ToString(), ""42""); Console.WriteLine(42.ToString()); Append(42.ToString()); } private static void Append(string value) { } private static void Append(int value) { } }"); } } }
// dashboardSubs.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Collections; using CoreUtilities; using Submissions; using Layout; using Transactions; namespace MefAddIns { public partial class dashboardSubs : UserControl { // a way to sto prefresh during setting up the form private bool supressRefresh = false; public bool SupressRefresh { get { return supressRefresh; } set { //NewMessage.Show ("Setting to " + value.ToString()); supressRefresh = value; } } ListViewColumnSorter lvwColumnSorter; Action<string, string> UpdateOtherForms = null; private string currentFilter = Constants.BLANK; public string CurrentFilter { get { return currentFilter; } set { currentFilter = value; } } public string GetSelectedNAME { get { if (listView1.SelectedItems != null && listView1.SelectedItems.Count > 0 && listView1.SelectedItems [0].Text != Constants.BLANK) { return listView1.SelectedItems [0].Text; } return Constants.BLANK; } } public string GetSelectedGUID { get { if (listView1.SelectedItems != null && listView1.SelectedItems.Count > 0 && listView1.SelectedItems [0].Text != Constants.BLANK) { return ((LittleSubmission)listView1.SelectedItems [0].Tag).GUID; } return Constants.BLANK; } } /// <summary> /// called from former Report option /// /// </summary> public void ShowSubmissions () { //checkBoxStatus.Checked = false; checkBoxReadyToSend.Checked = false; checkBoxSent.Checked = false; } public dashboardSubs (Action<string,string> _UpdateOtherForms, bool PreventRefresh) { SupressRefresh = PreventRefresh; UpdateOtherForms = _UpdateOtherForms; InitializeComponent (); lvwColumnSorter = new ListViewColumnSorter (); this.listView1.ListViewItemSorter = lvwColumnSorter; checkBoxReadyToSend.Checked = false; checkBoxSent.Checked = false; //NOTE: listviews do not have datasources } private LittleSubmission AddTransactionRowDetailsToLittleSub(LittleSubmission Sub, Transactions.TransactionSubmission TransactionInfo) { //DateTime subDate = ((DateTime)(dr [Data.SubmissionIndexFields.SUBMISSIONDATE])); DateTime subDate = TransactionInfo.Date1; DateTime today = DateTime.Today; int nDays = ((TimeSpan)(today - subDate)).Days; Sub.Days = nDays; string days = nDays.ToString (); // pad with zeroes for proper sorting while (days.Length < 3) { days = "0" + days; } Sub.Market = days + Loc.Instance.GetStringFmt (" DAYS: {0}", TransactionInfo.MarketName); return Sub; } void AddItemsSubMethod (List<MasterOfLayouts.NameAndGuid> list, bool AddSubmissionInformation) { ArrayList submissions = new ArrayList (); foreach (MasterOfLayouts.NameAndGuid NameG in list) { LittleSubmission sub = new LittleSubmission (); sub.Story = NameG.Caption; sub.GUID = NameG.Guid; sub.Market = "-"; sub.Words = NameG.Words; sub = AddDestinationInformation (sub); // grab Current Submission information for those on this filter if (true == AddSubmissionInformation) { sub = AddSubmissionInformationToCurrentFilterItem (sub); } submissions.Add (sub); } //NewMessage.Show("Adding : " + submissions.Count.ToString ()); AddItemToListView (submissions); } void AddItemsFromCurrentFilter (bool AddSubmissionInformation) { List<MasterOfLayouts.NameAndGuid> LayoutsFound = MasterOfLayouts.GetListOfLayouts (CurrentFilter); AddItemsSubMethod(LayoutsFound, AddSubmissionInformation); } private LittleSubmission AddSubmissionInformationToCurrentFilterItem (LittleSubmission CurrentItem) { // go through Transaciton Table looking for matches List<Transactions.TransactionBase> LayoutEvents = SubmissionMaster.GetListOfSubmissionsForProject (CurrentItem.GUID); if (null != LayoutEvents) { foreach (Transactions.TransactionSubmission subs in LayoutEvents) { // filter only those with NO REPLY if (SubmissionMaster.ThisSubmissionNotResolved (subs) == true) { AddTransactionRowDetailsToLittleSub(CurrentItem, subs); // added the break because we only care if we find one unanswered sub, right?? (March 17 2013) break; } } } return CurrentItem; } public void RefreshMe () { if (true == SupressRefresh) { // NewMessage.Show ("Skipping refresh"); return; } // NewMessage.Show ("Refreshing! " + SupressRefresh.ToString()); this.Cursor = Cursors.WaitCursor; listView1.BeginUpdate(); listView1.Items.Clear (); ; // the two checkboxes override The Filter if (checkBoxSent.Checked == false && checkBoxReadyToSend.Checked == false) { AddItemsFromCurrentFilter(true); } if (checkBoxReadyToSend.Checked) Refresh_ReadyToSend (); if (checkBoxSent.Checked) Refresh_CurrentSubs (); // if (checkBoxStatus.Checked) Refresh_ByStatus(); lvwColumnSorter.SortColumn = 0; lvwColumnSorter.Order = SortOrder.Ascending; listView1.Sort (); this.Cursor = Cursors.Default; // we clear the existing project guids and such UpdateOtherForms (Constants.BLANK, Constants.BLANK); listView1.EndUpdate (); this.columnHeader1.Text = Loc.Instance.GetStringFmt("Story ({0})", listView1.Items.Count); // (Parent as CoreUtilities.RollUp).TextLabel = String.Format("Submissions ({0} found)", listView1.Items.Count); } private void buttonRefresh_Click (object sender, EventArgs e) { RefreshMe (); } private void Refresh_CurrentSubs () { ArrayList submissions = new ArrayList (); List<Transactions.TransactionBase> AllSubs = SubmissionMaster.GetListOfSubmissionsAll(); //NewMessage.Show (AllSubs.Count.ToString()); foreach (Transactions.TransactionSubmission TransactionSub in AllSubs) { if (SubmissionMaster.ThisSubmissionNotResolved(TransactionSub) == true) { LittleSubmission sub = new LittleSubmission (); sub.Story = MasterOfLayouts.GetNameFromGuid(TransactionSub.ProjectGUID); sub.GUID = TransactionSub.ProjectGUID; sub.Market = "-"; sub.Words =MasterOfLayouts.GetWordsFromGuid(TransactionSub.ProjectGUID); sub = AddDestinationInformation (sub); // grab Current Submission information for those on this filter //sub = AddSubmissionInformationToCurrentFilterItem (sub); AddTransactionRowDetailsToLittleSub(sub, TransactionSub); submissions.Add (sub); } } AddItemToListView (submissions); // code taken from fLinkPopup.cs // foreach (DataRow dr in Program.AppMainForm.data.SubmissionIndex.Rows) // { // if (dr != null) // { // // if (dr[Data.SubmissionIndexFields.REPLYTYPE].ToString().ToLower() // == English.Invalid.ToLower() && // dr[Data.SubmissionIndexFields.SUBMISSIONTYPE].ToString().ToLower() // != classSubmission.DESTINATION_SUBTYPE.ToLower()) // { // LittleSubmission sub = new LittleSubmission(); // sub.Story = dr[Data.SubmissionIndexFields.PROJECT_NAME].ToString(); // sub.GUID = dr[Data.SubmissionIndexFields.PROJECTGUID].ToString(); // // sub = AddDestinationInformation(sub); // // // // DateTime subDate = ((DateTime)(dr[Data.SubmissionIndexFields.SUBMISSIONDATE])); // DateTime today = DateTime.Today; // int nDays = ((TimeSpan)(today - subDate)).Days; // sub.Days = nDays; // string days = nDays.ToString(); // // pad with zeroes for proper sorting // while (days.Length < 3) // { // days = "0" + days; // } // sub.Market = days+" DAYS: " + dr[Data.SubmissionIndexFields.MARKET_NAME].ToString() ; // submissions.Add(sub); // // } // // // // // } // } //AddItemToListView (submissions); /* foreach (LittleSubmission sub in submissions) { ListViewItem item = new ListViewItem(sub.Story); item.Font = new Font("Courier New",12, FontStyle.Regular); item.SubItems.Add(sub.Market); item.SubItems.Add(sub.NextMarket); if (sub.Days > 120) { item.BackColor = Color.Red; } listView1.Items.Add(item); }*/ } /// <summary> /// takes the little submission object and adds Market (if at a market) and NextMarket (destinatino) /// information. /// </summary> /// <param name="sub"></param> /// <returns></returns> private LittleSubmission AddDestinationInformation (LittleSubmission sub) { try { ArrayList destinations = new ArrayList (); List<TransactionBase> Destinations = SubmissionMaster.GetListOfDestinationsForProject(sub.GUID); foreach (TransactionBase transaction in Destinations) { LittleDestination destination = new LittleDestination(); destination.Market = ((TransactionSubmissionDestination)transaction).MarketName;// dr[Data.SubmissionIndexFields.MARKET_NAME].ToString(); destination.Priority = 0.0f; float.TryParse(((TransactionSubmissionDestination)transaction).Priority, out destination.Priority);//(float)dr[Data.SubmissionIndexFields.DESTINATION_PRIORITY]; destinations.Add(destination); } // foreach (DataRow dr in Program.AppMainForm.data.SubmissionIndex.Rows) // { // if (dr != null) // { // // // destinations with this GUID // if (dr[Data.SubmissionIndexFields.PROJECTGUID].ToString() == sub.GUID // && dr[Data.SubmissionIndexFields.SUBMISSIONTYPE].ToString().ToLower() == classSubmission.DESTINATION_SUBTYPE.ToLower()) // { // // this matches the project // // now we grab all destinations // LittleDestination destination = new LittleDestination(); // destination.Market = dr[Data.SubmissionIndexFields.MARKET_NAME].ToString(); // destination.Priority = (float)dr[Data.SubmissionIndexFields.DESTINATION_PRIORITY]; // destinations.Add(destination); // } // // // } // // } sub.NextMarket = ""; // TO DO : Sort destinations destinations.Sort (); destinations.Reverse (); int count = 1; foreach (LittleDestination destination in destinations) { sub.NextMarket = sub.NextMarket + "(" + count.ToString () + ")" + destination.Market + " "; count++; } } catch (Exception ex) { MessageBox.Show (ex.ToString ()); } /* Removed, handled by NameAndGUID // jan 2012 // adding some info for words try { // classPageProject page = (classPageProject)Data.GoToPage(sub.Story); // if (page.IsProject()) // { // sub.Words = page.Words; //HACK for words? // // its own column? // //sub.Story = sub.Story + " " + sub.Days.ToString(); // } } catch (Exception) { } */ return sub; } private void Refresh_ReadyToSend () { try { ArrayList submissions = new ArrayList (); listView1.BeginUpdate(); //Step 1: Use current Filter and REMOVE those entities that // are currently at Markets // AddItemsFromCurrentFilter(false); * List<MasterOfLayouts.NameAndGuid> ItemsToKeep = new List<MasterOfLayouts.NameAndGuid>(); List<MasterOfLayouts.NameAndGuid> LayoutsFound = MasterOfLayouts.GetListOfLayouts (CurrentFilter); // THIS IS the SLOW PART. // 10 seconds + // really we want the list of Transactions that contain ReplyType=Acceptance or ReplyType=Invalid // if this list is greater than 0 than we have a match List<string> OutstandingReply = LayoutDetails.Instance.CurrentLayout.GetListOfStringsFromSystemTable (SubmissionMaster.TABLE_ReplyTypes, 1, String.Format ("2|{0}", SubmissionMaster.CODE_NO_REPLY_YET)); List<string> Acceptances = LayoutDetails.Instance.CurrentLayout.GetListOfStringsFromSystemTable (SubmissionMaster.TABLE_ReplyTypes, 1, String.Format ("2|{0}", SubmissionMaster.CODE_ACCEPTANCE)); string query = ""; foreach (string s in OutstandingReply) { if (query != "") query = query + " or "; query = query + String.Format (" {1}='{0}' ", s, TransactionsTable.DATA7); } foreach (string s in Acceptances) { if (query != "") query = query + " or "; query = query + String.Format (" {1}='{0}' ", s, TransactionsTable.DATA7); } string querywrapper = String.Format ("and {1}='{2}' and ({0})", query, TransactionsTable.TYPE, TransactionSubmission.T_SUBMISSION); // foreach (ListViewItem item in listView1.Items) foreach (MasterOfLayouts.NameAndGuid item in LayoutsFound) { // LittleSubmission Sub = (LittleSubmission) item.Tag; // if (Sub != null) { if (OutstandingReply == null || OutstandingReply.Count <= 0 || Acceptances == null || Acceptances.Count <=0) { throw new Exception("Default lists not defined."); } List<Transactions.TransactionBase> ListOfSubs = SubmissionMaster.GetListOfOutstandingSubmissionsOrAcceptances(item.Guid, querywrapper); // we found no Acceptances and no invalid replies which mean we are free to SEND if (ListOfSubs.Count == 0) { ItemsToKeep.Add (item); } /* List<Transactions.TransactionBase> ListOfSubs = SubmissionMaster.GetListOfSubmissionsForProject(item.Guid); if (ListOfSubs != null && ListOfSubs.Count > 0) {bool FoundAtLeastOneSub = false; foreach(Transactions.TransactionBase transaction in ListOfSubs) { if (transaction is Transactions.TransactionSubmission) { if (SubmissionMaster.IsValidReply( ((Transactions.TransactionSubmission)transaction).ReplyType) == false) { // NewMessage.Show ("Removing " + item.Text); // if there are oustanding submissions // for this project // remove it from the list of Ready To send // ItemsToRemove.Add (item); * FoundAtLeastOneSub = true; } if (SubmissionMaster.IsAcceptance( ((Transactions.TransactionSubmission)transaction).ReplyType) == true) { FoundAtLeastOneSub = true; } if (true == FoundAtLeastOneSub) { break; } } } if (false == FoundAtLeastOneSub) { ItemsToKeep.Add (item); } } */ } } // foreach (ListViewItem DeleteMe in ItemsToRemove) // { // listView1.Items.Remove (DeleteMe); // } // I flipped the logic to make this fstaer (march 17 2013) // so: we now add them AddItemsSubMethod(ItemsToKeep, false); listView1.EndUpdate(); // STOP: March 2013. Maybe I do not need to make this mor ecomplicated. // Can I solve it witht he right query? // i.e., notebook='Writing' and status='4 Complete' and section='Projects' // Step 2: Come up with Advanced Criteria to UNDERSTAND when a complete market is ready to send out // DataView dv = new DataView(Program.AppMainForm.data.pageIndex); // Program.AppMainForm.data.CreateTableRelationship(); // dv.RowFilter = "(Retired=false) AND (StatusType <>'Rewriting') AND (StatusType <>'rewriting') AND(((Sum(Child.CalcBusy) <= 0) AND Finished = true ) OR ( (IsNull(Sum(Child.CalcBusy),-1) = -1) AND (Finished = true) ) )"; // foreach (DataRow r in dv.ToTable().Rows) // { // string sPageName = r[Data.PageIndexFields.NAME].ToString(); // // AddSubmissionPanelLabel(sPageName, sPageName, linkLabel1.LinkColor); // // LittleSubmission sub = new LittleSubmission(); // sub.Story = sPageName; // sub.GUID = r[Data.PageIndexFields.GUID].ToString(); // sub.Market = "-"; // sub = AddDestinationInformation(sub); // // submissions.Add(sub); // // } // dv = null; // AddItemToListView (submissions); /* foreach (LittleSubmission sub in submissions) { ListViewItem item = new ListViewItem(sub.Story); item.Font = new Font("Courier New", 12, FontStyle.Bold); item.SubItems.Add(sub.Market); item.SubItems.Add(sub.NextMarket); listView1.Items.Add(item); }*/ } catch (Exception ex) { MessageBox.Show (ex.ToString ()); } } private void checkBoxReadyToSend_CheckedChanged (object sender, EventArgs e) { RefreshMe (); } private void checkBoxSent_CheckedChanged (object sender, EventArgs e) { RefreshMe (); } /// <summary> /// double click and go to that page in a new window /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listView1_MouseDoubleClick (object sender, MouseEventArgs e) { if (listView1.SelectedItems != null) { // Program.AppMainForm.OpenNewWindow( listView1.SelectedItems[0].Text, 0, false); if (listView1.SelectedItems[0].Tag != null) { LittleSubmission sub = (LittleSubmission)listView1.SelectedItems[0].Tag; LayoutDetails.Instance.LoadLayout(sub.GUID); } // NewMessage.Show (listView1.SelectedItems[0].Text); //LayoutDetails.Instance.LoadLayout( } } private void listView1_SelectedIndexChanged (object sender, EventArgs e) { if ((sender as ListView).SelectedItems != null && (sender as ListView).SelectedItems.Count > 0) { if (UpdateOtherForms != null) { LittleSubmission sub = (LittleSubmission)(sender as ListView).SelectedItems [0].Tag; UpdateOtherForms ((sender as ListView).SelectedItems [0].Text, sub.GUID); } } } private void comboBoxStatus_DropDown (object sender, EventArgs e) { // draw list of status // comboBoxStatus.Items.Clear(); // ClassSubtypes subs = new ClassSubtypes(); // subs = ClassSubtypes.LoadUserInfo("statustypes"); // comboBoxStatus.Items.AddRange(subs.getSubtypes()); } /// <summary> /// can only use the dropdown if this is checked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void checkBoxStatus_CheckedChanged (object sender, EventArgs e) { // disable the other two checks because they are no longer relevant. // if (true == checkBoxStatus.Checked) // { // checkBoxReadyToSend.Checked = false; // checkBoxSent.Checked = false; // } // // comboBoxStatus.Enabled = checkBoxStatus.Checked; // checkBoxReadyToSend.Enabled = !checkBoxStatus.Checked; // checkBoxSent.Enabled = !checkBoxStatus.Checked; } private void Refresh_ByStatus () { // now redraw the list according to the status set try { ArrayList submissions = new ArrayList (); // DataView dv = new DataView(Program.AppMainForm.data.pageIndex); // Program.AppMainForm.data.CreateTableRelationship(); // // string sValue = ""; // try // { // sValue = comboBoxStatus.Items[comboBoxStatus.SelectedIndex].ToString(); // } // catch // { // // // sValue = ""; // } // // // dv.RowFilter = String.Format("((StatusType ='{0}') or (StatusType ='{1}'))", sValue, // sValue.ToLower()); // foreach (DataRow r in dv.ToTable().Rows) // { // string sPageName = r[Data.PageIndexFields.NAME].ToString(); // // AddSubmissionPanelLabel(sPageName, sPageName, linkLabel1.LinkColor); // // LittleSubmission sub = new LittleSubmission(); // sub.Story = sPageName; // sub.GUID = r[Data.PageIndexFields.GUID].ToString(); // sub.Market = "-"; // // // // sub = AddDestinationInformation(sub); // // submissions.Add(sub); // // } // dv = null; AddItemToListView (submissions); } catch (Exception ex) { MessageBox.Show (ex.ToString ()); } } /// <summary> /// wrapper to add the array to the items /// </summary> /// <param name="subs"></param> private void AddItemToListView (ArrayList subs) { foreach (LittleSubmission sub in subs) { ListViewItem item = new ListViewItem (sub.Story); item.Tag = sub; item.Font = new Font ("Courier New", 12, FontStyle.Bold); item.SubItems.Add (sub.Words.ToString ()); item.SubItems.Add (sub.Market); item.SubItems.Add (sub.NextMarket); if (sub.Days > 120) { item.BackColor = Color.Red; } // item.ToolTipText = "boo!"; listView1.Items.Add (item); } } private void comboBoxStatus_SelectedIndexChanged (object sender, EventArgs e) { RefreshMe (); } /// <summary> /// override tooltip behavior to show current item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listView1_MouseMove (object sender, MouseEventArgs e) {/* ListViewItem item = listView1.GetItemAt(e.X, e.Y); //item.ToolTipText = item.Text; if (item != null) { //we care about destination infor here string text = item.SubItems[3].Text; if (text != "" /*&& this.toolTip1.GetToolTip(listView1) != text) { toolTip1.SetToolTip(listView1, item.Text); //toolTip1.Active = true; //toolTip1.Show(text, listView1); //this.toolTip1.SetToolTip(listView1, text); //this.toolTip1.Show(text); } else { this.toolTip1.RemoveAll(); } } else { this.toolTip1.RemoveAll(); } */ } /// <summary> /// reorder /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listView1_ColumnClick (object sender, ColumnClickEventArgs e) { lvwColumnSorter.SortColumn = e.Column; if (lvwColumnSorter.Order == SortOrder.Ascending) { lvwColumnSorter.Order = SortOrder.Descending; } else { lvwColumnSorter.Order = SortOrder.Ascending; } listView1.Sort (); } public void UpdateAppearance (AppearanceClass app) { this.ForeColor = app.captionForeground; buttonRefresh.BackColor = app.mainBackground; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.Cx.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedIntentsClientTest { [xunit::FactAttribute] public void GetIntentRequestObject() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); GetIntentRequest request = new GetIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), LanguageCode = "language_code2f6c7160", }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent response = client.GetIntent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIntentRequestObjectAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); GetIntentRequest request = new GetIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), LanguageCode = "language_code2f6c7160", }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Intent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent responseCallSettings = await client.GetIntentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Intent responseCancellationToken = await client.GetIntentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIntent() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); GetIntentRequest request = new GetIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent response = client.GetIntent(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIntentAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); GetIntentRequest request = new GetIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Intent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent responseCallSettings = await client.GetIntentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Intent responseCancellationToken = await client.GetIntentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIntentResourceNames() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); GetIntentRequest request = new GetIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent response = client.GetIntent(request.IntentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIntentResourceNamesAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); GetIntentRequest request = new GetIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Intent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent responseCallSettings = await client.GetIntentAsync(request.IntentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Intent responseCancellationToken = await client.GetIntentAsync(request.IntentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateIntentRequestObject() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); CreateIntentRequest request = new CreateIntentRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Intent = new Intent(), LanguageCode = "language_code2f6c7160", }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent response = client.CreateIntent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateIntentRequestObjectAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); CreateIntentRequest request = new CreateIntentRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Intent = new Intent(), LanguageCode = "language_code2f6c7160", }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Intent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent responseCallSettings = await client.CreateIntentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Intent responseCancellationToken = await client.CreateIntentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateIntent() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); CreateIntentRequest request = new CreateIntentRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Intent = new Intent(), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent response = client.CreateIntent(request.Parent, request.Intent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateIntentAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); CreateIntentRequest request = new CreateIntentRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Intent = new Intent(), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Intent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent responseCallSettings = await client.CreateIntentAsync(request.Parent, request.Intent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Intent responseCancellationToken = await client.CreateIntentAsync(request.Parent, request.Intent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateIntentResourceNames() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); CreateIntentRequest request = new CreateIntentRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Intent = new Intent(), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent response = client.CreateIntent(request.ParentAsAgentName, request.Intent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateIntentResourceNamesAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); CreateIntentRequest request = new CreateIntentRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Intent = new Intent(), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.CreateIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Intent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent responseCallSettings = await client.CreateIntentAsync(request.ParentAsAgentName, request.Intent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Intent responseCancellationToken = await client.CreateIntentAsync(request.ParentAsAgentName, request.Intent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateIntentRequestObject() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); UpdateIntentRequest request = new UpdateIntentRequest { Intent = new Intent(), LanguageCode = "language_code2f6c7160", UpdateMask = new wkt::FieldMask(), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent response = client.UpdateIntent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateIntentRequestObjectAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); UpdateIntentRequest request = new UpdateIntentRequest { Intent = new Intent(), LanguageCode = "language_code2f6c7160", UpdateMask = new wkt::FieldMask(), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Intent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent responseCallSettings = await client.UpdateIntentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Intent responseCancellationToken = await client.UpdateIntentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateIntent() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); UpdateIntentRequest request = new UpdateIntentRequest { Intent = new Intent(), UpdateMask = new wkt::FieldMask(), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent response = client.UpdateIntent(request.Intent, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateIntentAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); UpdateIntentRequest request = new UpdateIntentRequest { Intent = new Intent(), UpdateMask = new wkt::FieldMask(), }; Intent expectedResponse = new Intent { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), DisplayName = "display_name137f65c2", TrainingPhrases = { new Intent.Types.TrainingPhrase(), }, Parameters = { new Intent.Types.Parameter(), }, Priority = 1546225849, IsFallback = true, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.UpdateIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Intent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent responseCallSettings = await client.UpdateIntentAsync(request.Intent, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Intent responseCancellationToken = await client.UpdateIntentAsync(request.Intent, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteIntentRequestObject() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); DeleteIntentRequest request = new DeleteIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); client.DeleteIntent(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteIntentRequestObjectAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); DeleteIntentRequest request = new DeleteIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); await client.DeleteIntentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteIntentAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteIntent() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); DeleteIntentRequest request = new DeleteIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); client.DeleteIntent(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteIntentAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); DeleteIntentRequest request = new DeleteIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); await client.DeleteIntentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteIntentAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteIntentResourceNames() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); DeleteIntentRequest request = new DeleteIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteIntent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); client.DeleteIntent(request.IntentName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteIntentResourceNamesAsync() { moq::Mock<Intents.IntentsClient> mockGrpcClient = new moq::Mock<Intents.IntentsClient>(moq::MockBehavior.Strict); DeleteIntentRequest request = new DeleteIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteIntentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); await client.DeleteIntentAsync(request.IntentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteIntentAsync(request.IntentName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Client { /// <summary> /// <para>Signals violation of HTTP specification caused by an invalid redirect</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RedirectException /// </java-name> [Dot42.DexImport("org/apache/http/client/RedirectException", AccessFlags = 33)] public partial class RedirectException : global::Org.Apache.Http.ProtocolException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new RedirectException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RedirectException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new RedirectException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public RedirectException(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new RedirectException with the specified detail message and cause.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public RedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Signals an error in the HTTP protocol. </para> /// </summary> /// <java-name> /// org/apache/http/client/ClientProtocolException /// </java-name> [Dot42.DexImport("org/apache/http/client/ClientProtocolException", AccessFlags = 33)] public partial class ClientProtocolException : global::System.IO.IOException /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ClientProtocolException() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public ClientProtocolException(string @string) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/Throwable;)V", AccessFlags = 1)] public ClientProtocolException(global::System.Exception exception) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public ClientProtocolException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/HttpClient /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpClient", AccessFlags = 1537)] public partial interface IHttpClient /* scope: __dot42__ */ { /// <summary> /// <para>Obtains the parameters for this client. These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client.</para><para></para> /// </summary> /// <returns> /// <para>the default parameters </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams GetParams() /* MethodBuilder.Create */ ; /// <summary> /// <para>Obtains the connection manager used by this client.</para><para></para> /// </summary> /// <returns> /// <para>the connection manager </para> /// </returns> /// <java-name> /// getConnectionManager /// </java-name> [Dot42.DexImport("getConnectionManager", "()Lorg/apache/http/conn/ClientConnectionManager;", AccessFlags = 1025)] global::Org.Apache.Http.Conn.IClientConnectionManager GetConnectionManager() /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the default context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/protocol/HttpCon" + "text;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;)Lorg/apache/http/HttpRes" + "ponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost request, global::Org.Apache.Http.IHttpRequest context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" + "/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" + "andler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" + "/http/client/ResponseHandler<+TT;>;)TT;")] T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" + "andler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" + "/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext;)TT;")] T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest target, global::Org.Apache.Http.Client.IResponseHandler<T> request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" + "esponseHandler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" + "g/apache/http/client/ResponseHandler<+TT;>;)TT;")] T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context and processes the response using the given response handler.</para><para></para> /// </summary> /// <returns> /// <para>the response object as generated by the response handler. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" + "esponseHandler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" + "g/apache/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext" + ";)TT;")] T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> responseHandler, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A handler for determining if an HTTP request should be redirected to a new location in response to an HTTP response received from the target server.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RedirectHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/RedirectHandler", AccessFlags = 1537)] public partial interface IRedirectHandler /* scope: __dot42__ */ { /// <summary> /// <para>Determines if a request should be redirected to a new location given the response from the target server.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request should be redirected, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// isRedirectRequested /// </java-name> [Dot42.DexImport("isRedirectRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool IsRedirectRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Determines the location request is expected to be redirected to given the response from the target server and the current request execution context.</para><para></para> /// </summary> /// <returns> /// <para>redirect URI </para> /// </returns> /// <java-name> /// getLocationURI /// </java-name> [Dot42.DexImport("getLocationURI", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/net/U" + "RI;", AccessFlags = 1025)] global::System.Uri GetLocationURI(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A handler for determining if an HttpRequest should be retried after a recoverable exception during execution.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/HttpRequestRetryHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpRequestRetryHandler", AccessFlags = 1537)] public partial interface IHttpRequestRetryHandler /* scope: __dot42__ */ { /// <summary> /// <para>Determines if a method should be retried after an IOException occurs during execution.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the method should be retried, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// retryRequest /// </java-name> [Dot42.DexImport("retryRequest", "(Ljava/io/IOException;ILorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool RetryRequest(global::System.IO.IOException exception, int executionCount, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals failure to retry the request due to non-repeatable request entity.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/NonRepeatableRequestException /// </java-name> [Dot42.DexImport("org/apache/http/client/NonRepeatableRequestException", AccessFlags = 33)] public partial class NonRepeatableRequestException : global::Org.Apache.Http.ProtocolException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new NonRepeatableEntityException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public NonRepeatableRequestException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new NonRepeatableEntityException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public NonRepeatableRequestException(string message) /* MethodBuilder.Create */ { } } /// <summary> /// <para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/AuthenticationHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/AuthenticationHandler", AccessFlags = 1537)] public partial interface IAuthenticationHandler /* scope: __dot42__ */ { /// <java-name> /// isAuthenticationRequested /// </java-name> [Dot42.DexImport("isAuthenticationRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool IsAuthenticationRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <java-name> /// getChallenges /// </java-name> [Dot42.DexImport("getChallenges", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" + "Map;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" + "Map<Ljava/lang/String;Lorg/apache/http/Header;>;")] global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> GetChallenges(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <java-name> /// selectScheme /// </java-name> [Dot42.DexImport("selectScheme", "(Ljava/util/Map;Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpConte" + "xt;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1025, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/Header;>;Lorg/apache/http/Http" + "Response;Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/auth/AuthScheme" + ";")] global::Org.Apache.Http.Auth.IAuthScheme SelectScheme(global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> challenges, global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A client-side request director. The director decides which steps are necessary to execute a request. It establishes connections and optionally processes redirects and authentication challenges. The director may therefore generate and send a sequence of requests in order to execute one initial request.</para><para><br></br><b>Note:</b> It is most likely that implementations of this interface will allocate connections, and return responses that depend on those connections for reading the response entity. Such connections MUST be released, but that is out of the scope of a request director.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RequestDirector /// </java-name> [Dot42.DexImport("org/apache/http/client/RequestDirector", AccessFlags = 1537)] public partial interface IRequestDirector /* scope: __dot42__ */ { /// <summary> /// <para>Executes a request. <br></br><b>Note:</b> For the time being, a new director is instantiated for each request. This is the same behavior as for <code>HttpMethodDirector</code> in HttpClient 3.</para><para></para> /// </summary> /// <returns> /// <para>the final response to the request. This is never an intermediate response with status code 1xx.</para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" + "/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Abstract cookie store.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CookieStore /// </java-name> [Dot42.DexImport("org/apache/http/client/CookieStore", AccessFlags = 1537)] public partial interface ICookieStore /* scope: __dot42__ */ { /// <summary> /// <para>Adds an HTTP cookie, replacing any existing equivalent cookies. If the given cookie has already expired it will not be added, but existing values will still be removed.</para><para></para> /// </summary> /// <java-name> /// addCookie /// </java-name> [Dot42.DexImport("addCookie", "(Lorg/apache/http/cookie/Cookie;)V", AccessFlags = 1025)] void AddCookie(global::Org.Apache.Http.Cookie.ICookie cookie) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns all cookies contained in this store.</para><para></para> /// </summary> /// <returns> /// <para>all cookies </para> /// </returns> /// <java-name> /// getCookies /// </java-name> [Dot42.DexImport("getCookies", "()Ljava/util/List;", AccessFlags = 1025, Signature = "()Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;")] global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> GetCookies() /* MethodBuilder.Create */ ; /// <summary> /// <para>Removes all of cookies in this store that have expired by the specified date.</para><para></para> /// </summary> /// <returns> /// <para>true if any cookies were purged. </para> /// </returns> /// <java-name> /// clearExpired /// </java-name> [Dot42.DexImport("clearExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)] bool ClearExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ; /// <summary> /// <para>Clears all cookies. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1025)] void Clear() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Handler that encapsulates the process of generating a response object from a HttpResponse.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/ResponseHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/ResponseHandler", AccessFlags = 1537, Signature = "<T:Ljava/lang/Object;>Ljava/lang/Object;")] public partial interface IResponseHandler<T> /* scope: __dot42__ */ { /// <summary> /// <para>Processes an HttpResponse and returns some value corresponding to that response.</para><para></para> /// </summary> /// <returns> /// <para>A value determined by the response</para> /// </returns> /// <java-name> /// handleResponse /// </java-name> [Dot42.DexImport("handleResponse", "(Lorg/apache/http/HttpResponse;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;)TT;")] T HandleResponse(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Abstract credentials provider.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CredentialsProvider /// </java-name> [Dot42.DexImport("org/apache/http/client/CredentialsProvider", AccessFlags = 1537)] public partial interface ICredentialsProvider /* scope: __dot42__ */ { /// <summary> /// <para>Sets the credentials for the given authentication scope. Any previous credentials for the given scope will be overwritten.</para><para><para>getCredentials(AuthScope) </para></para> /// </summary> /// <java-name> /// setCredentials /// </java-name> [Dot42.DexImport("setCredentials", "(Lorg/apache/http/auth/AuthScope;Lorg/apache/http/auth/Credentials;)V", AccessFlags = 1025)] void SetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope, global::Org.Apache.Http.Auth.ICredentials credentials) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the credentials for the given authentication scope.</para><para><para>setCredentials(AuthScope, Credentials) </para></para> /// </summary> /// <returns> /// <para>the credentials</para> /// </returns> /// <java-name> /// getCredentials /// </java-name> [Dot42.DexImport("getCredentials", "(Lorg/apache/http/auth/AuthScope;)Lorg/apache/http/auth/Credentials;", AccessFlags = 1025)] global::Org.Apache.Http.Auth.ICredentials GetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope) /* MethodBuilder.Create */ ; /// <summary> /// <para>Clears all credentials. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1025)] void Clear() /* MethodBuilder.Create */ ; } /// <summary> /// <para>A handler for determining if the given execution context is user specific or not. The token object returned by this handler is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if the context does not contain any resources or details specific to the current user. </para><para>The user token will be used to ensure that user specific resouces will not shared with or reused by other users.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/UserTokenHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/UserTokenHandler", AccessFlags = 1537)] public partial interface IUserTokenHandler /* scope: __dot42__ */ { /// <summary> /// <para>The token object returned by this method is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if it is not.</para><para></para> /// </summary> /// <returns> /// <para>user token that uniquely identifies the user or <code>null&lt;/null&gt; if the context is not user specific. </code></para> /// </returns> /// <java-name> /// getUserToken /// </java-name> [Dot42.DexImport("getUserToken", "(Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025)] object GetUserToken(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals a non 2xx HTTP response. </para> /// </summary> /// <java-name> /// org/apache/http/client/HttpResponseException /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpResponseException", AccessFlags = 33)] public partial class HttpResponseException : global::Org.Apache.Http.Client.ClientProtocolException /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(ILjava/lang/String;)V", AccessFlags = 1)] public HttpResponseException(int statusCode, string s) /* MethodBuilder.Create */ { } /// <java-name> /// getStatusCode /// </java-name> [Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)] public virtual int GetStatusCode() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpResponseException() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getStatusCode /// </java-name> public int StatusCode { [Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)] get{ return GetStatusCode(); } } } /// <summary> /// <para>Signals a circular redirect</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CircularRedirectException /// </java-name> [Dot42.DexImport("org/apache/http/client/CircularRedirectException", AccessFlags = 33)] public partial class CircularRedirectException : global::Org.Apache.Http.Client.RedirectException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new CircularRedirectException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CircularRedirectException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new CircularRedirectException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public CircularRedirectException(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new CircularRedirectException with the specified detail message and cause.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public CircularRedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: CollectorMessageRS.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 me.bpulse.domain.proto.collector { /// <summary>Holder for reflection information generated from CollectorMessageRS.proto</summary> public static partial class CollectorMessageRSReflection { #region Descriptor /// <summary>File descriptor for CollectorMessageRS.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CollectorMessageRSReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChhDb2xsZWN0b3JNZXNzYWdlUlMucHJvdG8SCWNvbGxlY3RvciJ6CghQdWxz", "ZXNSUxIOCgZyc1RpbWUYASABKAMSLgoGc3RhdHVzGAIgASgOMh4uY29sbGVj", "dG9yLlB1bHNlc1JTLlN0YXR1c1R5cGUSDQoFZXJyb3IYAyABKAkiHwoKU3Rh", "dHVzVHlwZRIGCgJPSxAAEgkKBUVSUk9SEAFCJUgBqgIgbWUuYnB1bHNlLmRv", "bWFpbi5wcm90by5jb2xsZWN0b3JiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::me.bpulse.domain.proto.collector.PulsesRS), global::me.bpulse.domain.proto.collector.PulsesRS.Parser, new[]{ "RsTime", "Status", "Error" }, null, new[]{ typeof(global::me.bpulse.domain.proto.collector.PulsesRS.Types.StatusType) }, null) })); } #endregion } #region Messages public sealed partial class PulsesRS : pb::IMessage<PulsesRS> { private static readonly pb::MessageParser<PulsesRS> _parser = new pb::MessageParser<PulsesRS>(() => new PulsesRS()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PulsesRS> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::me.bpulse.domain.proto.collector.CollectorMessageRSReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PulsesRS() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PulsesRS(PulsesRS other) : this() { rsTime_ = other.rsTime_; status_ = other.status_; error_ = other.error_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PulsesRS Clone() { return new PulsesRS(this); } /// <summary>Field number for the "rsTime" field.</summary> public const int RsTimeFieldNumber = 1; private long rsTime_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long RsTime { get { return rsTime_; } set { rsTime_ = value; } } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 2; private global::me.bpulse.domain.proto.collector.PulsesRS.Types.StatusType status_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::me.bpulse.domain.proto.collector.PulsesRS.Types.StatusType Status { get { return status_; } set { status_ = value; } } /// <summary>Field number for the "error" field.</summary> public const int ErrorFieldNumber = 3; private string error_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Error { get { return error_; } set { error_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PulsesRS); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PulsesRS other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (RsTime != other.RsTime) return false; if (Status != other.Status) return false; if (Error != other.Error) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (RsTime != 0L) hash ^= RsTime.GetHashCode(); if (Status != 0) hash ^= Status.GetHashCode(); if (Error.Length != 0) hash ^= Error.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (RsTime != 0L) { output.WriteRawTag(8); output.WriteInt64(RsTime); } if (Status != 0) { output.WriteRawTag(16); output.WriteEnum((int) Status); } if (Error.Length != 0) { output.WriteRawTag(26); output.WriteString(Error); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (RsTime != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(RsTime); } if (Status != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status); } if (Error.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Error); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PulsesRS other) { if (other == null) { return; } if (other.RsTime != 0L) { RsTime = other.RsTime; } if (other.Status != 0) { Status = other.Status; } if (other.Error.Length != 0) { Error = other.Error; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { RsTime = input.ReadInt64(); break; } case 16: { status_ = (global::me.bpulse.domain.proto.collector.PulsesRS.Types.StatusType) input.ReadEnum(); break; } case 26: { Error = input.ReadString(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the PulsesRS message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum StatusType { [pbr::OriginalName("OK")] Ok = 0, [pbr::OriginalName("ERROR")] Error = 1, } } #endregion } #endregion } #endregion Designer generated code
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; using DriveProxy.API; using DriveProxy.Utils; namespace DriveProxy.Forms { partial class FeedbackForm : Form { protected static bool _IsCancelling = false; protected static FeedbackForm _Instance = null; protected static string _Message = ""; protected bool _AllowClose = false; protected bool _Visibility = false; public FeedbackForm() { InitializeComponent(); } //Hide form from alt-tab protected override CreateParams CreateParams { get { // Turn on WS_EX_TOOLWINDOW style bit CreateParams cp = base.CreateParams; cp.ExStyle |= 0x80; return cp; } } public bool AllowClose { get { return _AllowClose; } set { _AllowClose = value; } } public static bool IsCancelling { get { return _IsCancelling; } set { _IsCancelling = value; } } protected void ShowVisibility() { _Visibility = true; Visible = true; } protected void HideVisibility() { _Visibility = false; Visible = false; } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); Visible = _Visibility; } private void StatusForm_Load(object sender, EventArgs e) { try { if (InvokeRequired) { BeginInvoke(new MethodInvoker(() => StatusForm_Load(null, null))); return; } Left = -1000; Top = -1000; Opacity = 0; HideVisibility(); timer1.Stop(); timer2.Stop(); } catch (Exception exception) { Log.Error(exception, false); } } private void StatusForm_FormClosing(object sender, FormClosingEventArgs e) { try { if (InvokeRequired) { BeginInvoke(new MethodInvoker(() => { StatusForm_FormClosing(null, e); })); return; } if (!AllowClose) { if (!Win32.IsSystemShuttingDown()) { e.Cancel = true; CloseDialog(); } } } catch (Exception exception) { Log.Error(exception, false); } } private void timer1_Tick(object sender, EventArgs e) { try { if (InvokeRequired) { BeginInvoke(new MethodInvoker(() => { timer1_Tick(null, null); })); return; } timer1.Stop(); double left = (System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width / (double)2) - (_Instance.Width / (double)2); double top = (System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height / (double)2) - (_Instance.Height / (double)2); Left = Convert.ToInt32(left); Top = Convert.ToInt32(top); Opacity = 100; TopLevel = true; TopMost = true; ShowVisibility(); Focus(); Win32.SetForegroundWindow(Handle); Refresh(); Application.DoEvents(); } catch (Exception exception) { Log.Error(exception, false); } } private void timer2_Tick(object sender, EventArgs e) { try { if (InvokeRequired) { BeginInvoke(new MethodInvoker(() => { timer2_Tick(null, null); })); return; } timer2.Stop(); Left = -1000; Top = -1000; Opacity = 0; HideVisibility(); } catch (Exception exception) { Log.Error(exception, false); } } private void buttonCancel_Click(object sender, EventArgs e) { try { CloseDialog(); _IsCancelling = true; } catch (Exception exception) { Log.Error(exception, false); } } public static void Init() { try { if (_Instance == null) { _Instance = new FeedbackForm(); _Instance.Show(); } } catch (Exception exception) { Log.Error(exception, false); } } public static void ShowDialog(string message = null) { try { if (!DriveService.UseFeedbackForm) { return; } if (_Instance == null) { return; } if (_Instance.InvokeRequired) { _Instance.BeginInvoke(new MethodInvoker(() => { ShowDialog(message); })); return; } _Instance.label1.Text = message; _IsCancelling = false; _Message = message; _Instance.timer2.Enabled = false; _Instance.timer1.Enabled = true; } catch (Exception exception) { Log.Error(exception, false); } } public static void Message(string message) { try { if (_Instance == null) { return; } if (_Instance.InvokeRequired) { _Instance.BeginInvoke(new MethodInvoker(() => { Message(message); })); return; } _Instance.label1.Text = message; } catch (Exception exception) { Log.Error(exception, false); } } public static void CloseDialog() { try { if (_Instance == null) { return; } if (_Instance.InvokeRequired) { try { IAsyncResult asyncResult = _Instance.BeginInvoke(new MethodInvoker(() => { CloseDialog(); })); System.Threading.Tasks.Task<object> task = System.Threading.Tasks.Task<object>.Factory.FromAsync( asyncResult, _Instance .EndInvoke); task.Wait(); // need to wait until this is finished, or the window could flicker on/off screen annoyingly return; } catch (Exception exception) { Log.Warning(exception.Message); return; } } _Instance.HideVisibility(); _IsCancelling = false; _Instance.timer1.Enabled = false; _Instance.timer2.Enabled = true; } catch (Exception exception) { Log.Error(exception, false); } } public new static void Close() { try { if (_Instance == null) { return; } if (_Instance != null) { _Instance.AllowClose = true; _Instance.timer1.Stop(); _Instance.timer2.Stop(); Form form = _Instance; form.Close(); } } catch (Exception exception) { Log.Error(exception, false); } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using System.IO; using System.Threading; using SR = System.Reflection; using SquabPie.Mono.Cecil.Cil; using SquabPie.Mono.Cecil.Metadata; using SquabPie.Mono.Cecil.PE; using SquabPie.Mono.Collections.Generic; namespace SquabPie.Mono.Cecil { public enum ReadingMode { Immediate = 1, Deferred = 2, } public sealed class ReaderParameters { ReadingMode reading_mode; internal IAssemblyResolver assembly_resolver; internal IMetadataResolver metadata_resolver; #if !READ_ONLY internal IMetadataImporterProvider metadata_importer_provider; #if !PCL internal IReflectionImporterProvider reflection_importer_provider; #endif #endif Stream symbol_stream; ISymbolReaderProvider symbol_reader_provider; bool read_symbols; public ReadingMode ReadingMode { get { return reading_mode; } set { reading_mode = value; } } public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } set { assembly_resolver = value; } } public IMetadataResolver MetadataResolver { get { return metadata_resolver; } set { metadata_resolver = value; } } #if !READ_ONLY public IMetadataImporterProvider MetadataImporterProvider { get { return metadata_importer_provider; } set { metadata_importer_provider = value; } } #if !PCL public IReflectionImporterProvider ReflectionImporterProvider { get { return reflection_importer_provider; } set { reflection_importer_provider = value; } } #endif #endif public Stream SymbolStream { get { return symbol_stream; } set { symbol_stream = value; } } public ISymbolReaderProvider SymbolReaderProvider { get { return symbol_reader_provider; } set { symbol_reader_provider = value; } } public bool ReadSymbols { get { return read_symbols; } set { read_symbols = value; } } public ReaderParameters () : this (ReadingMode.Deferred) { } public ReaderParameters (ReadingMode readingMode) { this.reading_mode = readingMode; } } #if !READ_ONLY public sealed class ModuleParameters { ModuleKind kind; TargetRuntime runtime; TargetArchitecture architecture; IAssemblyResolver assembly_resolver; IMetadataResolver metadata_resolver; #if !READ_ONLY IMetadataImporterProvider metadata_importer_provider; #if !PCL IReflectionImporterProvider reflection_importer_provider; #endif #endif public ModuleKind Kind { get { return kind; } set { kind = value; } } public TargetRuntime Runtime { get { return runtime; } set { runtime = value; } } public TargetArchitecture Architecture { get { return architecture; } set { architecture = value; } } public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } set { assembly_resolver = value; } } public IMetadataResolver MetadataResolver { get { return metadata_resolver; } set { metadata_resolver = value; } } #if !READ_ONLY public IMetadataImporterProvider MetadataImporterProvider { get { return metadata_importer_provider; } set { metadata_importer_provider = value; } } #if !PCL public IReflectionImporterProvider ReflectionImporterProvider { get { return reflection_importer_provider; } set { reflection_importer_provider = value; } } #endif #endif public ModuleParameters () { this.kind = ModuleKind.Dll; this.Runtime = GetCurrentRuntime (); this.architecture = TargetArchitecture.I386; } static TargetRuntime GetCurrentRuntime () { #if !PCL return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime (); #else var corlib_name = AssemblyNameReference.Parse (typeof (object).Assembly.FullName); var corlib_version = corlib_name.Version; switch (corlib_version.Major) { case 1: return corlib_version.Minor == 0 ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case 2: return TargetRuntime.Net_2_0; case 4: return TargetRuntime.Net_4_0; default: throw new NotSupportedException (); } #endif } } public sealed class WriterParameters { Stream symbol_stream; ISymbolWriterProvider symbol_writer_provider; bool write_symbols; #if !PCL SR.StrongNameKeyPair key_pair; #endif public Stream SymbolStream { get { return symbol_stream; } set { symbol_stream = value; } } public ISymbolWriterProvider SymbolWriterProvider { get { return symbol_writer_provider; } set { symbol_writer_provider = value; } } public bool WriteSymbols { get { return write_symbols; } set { write_symbols = value; } } #if !PCL public SR.StrongNameKeyPair StrongNameKeyPair { get { return key_pair; } set { key_pair = value; } } #endif } #endif public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider { internal Image Image; internal MetadataSystem MetadataSystem; internal ReadingMode ReadingMode; internal ISymbolReaderProvider SymbolReaderProvider; internal ISymbolReader symbol_reader; internal IAssemblyResolver assembly_resolver; internal IMetadataResolver metadata_resolver; internal TypeSystem type_system; readonly MetadataReader reader; readonly string fq_name; internal string runtime_version; internal ModuleKind kind; TargetRuntime runtime; TargetArchitecture architecture; ModuleAttributes attributes; ModuleCharacteristics characteristics; Guid mvid; internal AssemblyDefinition assembly; MethodDefinition entry_point; #if !READ_ONLY #if !PCL internal IReflectionImporter reflection_importer; #endif internal IMetadataImporter metadata_importer; #endif Collection<CustomAttribute> custom_attributes; Collection<AssemblyNameReference> references; Collection<ModuleReference> modules; Collection<Resource> resources; Collection<ExportedType> exported_types; TypeDefinitionCollection types; public bool IsMain { get { return kind != ModuleKind.NetModule; } } public ModuleKind Kind { get { return kind; } set { kind = value; } } public TargetRuntime Runtime { get { return runtime; } set { runtime = value; runtime_version = runtime.RuntimeVersionString (); } } public string RuntimeVersion { get { return runtime_version; } set { runtime_version = value; runtime = runtime_version.ParseRuntime (); } } public TargetArchitecture Architecture { get { return architecture; } set { architecture = value; } } public ModuleAttributes Attributes { get { return attributes; } set { attributes = value; } } public ModuleCharacteristics Characteristics { get { return characteristics; } set { characteristics = value; } } public string FullyQualifiedName { get { return fq_name; } } public Guid Mvid { get { return mvid; } set { mvid = value; } } internal bool HasImage { get { return Image != null; } } public bool HasSymbols { get { return symbol_reader != null; } } public ISymbolReader SymbolReader { get { return symbol_reader; } } public override MetadataScopeType MetadataScopeType { get { return MetadataScopeType.ModuleDefinition; } } public AssemblyDefinition Assembly { get { return assembly; } } #if !READ_ONLY #if !PCL internal IReflectionImporter ReflectionImporter { get { if (reflection_importer == null) Interlocked.CompareExchange (ref reflection_importer, new ReflectionImporter (this), null); return reflection_importer; } } #endif internal IMetadataImporter MetadataImporter { get { if (metadata_importer == null) Interlocked.CompareExchange (ref metadata_importer, new MetadataImporter (this), null); return metadata_importer; } } #endif public IAssemblyResolver AssemblyResolver { get { #if !PCL if (assembly_resolver == null) Interlocked.CompareExchange (ref assembly_resolver, new DefaultAssemblyResolver (), null); #endif return assembly_resolver; } } public IMetadataResolver MetadataResolver { get { if (metadata_resolver == null) Interlocked.CompareExchange (ref metadata_resolver, new MetadataResolver (this.AssemblyResolver), null); return metadata_resolver; } } public TypeSystem TypeSystem { get { if (type_system == null) Interlocked.CompareExchange (ref type_system, TypeSystem.CreateTypeSystem (this), null); return type_system; } } public bool HasAssemblyReferences { get { if (references != null) return references.Count > 0; return HasImage && Image.HasTable (Table.AssemblyRef); } } public Collection<AssemblyNameReference> AssemblyReferences { get { if (references != null) return references; if (HasImage) return Read (ref references, this, (_, reader) => reader.ReadAssemblyReferences ()); return references = new Collection<AssemblyNameReference> (); } } public bool HasModuleReferences { get { if (modules != null) return modules.Count > 0; return HasImage && Image.HasTable (Table.ModuleRef); } } public Collection<ModuleReference> ModuleReferences { get { if (modules != null) return modules; if (HasImage) return Read (ref modules, this, (_, reader) => reader.ReadModuleReferences ()); return modules = new Collection<ModuleReference> (); } } public bool HasResources { get { if (resources != null) return resources.Count > 0; if (HasImage) return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ()); return false; } } public Collection<Resource> Resources { get { if (resources != null) return resources; if (HasImage) return Read (ref resources, this, (_, reader) => reader.ReadResources ()); return resources = new Collection<Resource> (); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (this); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, this)); } } public bool HasTypes { get { if (types != null) return types.Count > 0; return HasImage && Image.HasTable (Table.TypeDef); } } public Collection<TypeDefinition> Types { get { if (types != null) return types; if (HasImage) return Read (ref types, this, (_, reader) => reader.ReadTypes ()); return types = new TypeDefinitionCollection (this); } } public bool HasExportedTypes { get { if (exported_types != null) return exported_types.Count > 0; return HasImage && Image.HasTable (Table.ExportedType); } } public Collection<ExportedType> ExportedTypes { get { if (exported_types != null) return exported_types; if (HasImage) return Read (ref exported_types, this, (_, reader) => reader.ReadExportedTypes ()); return exported_types = new Collection<ExportedType> (); } } public MethodDefinition EntryPoint { get { if (entry_point != null) return entry_point; if (HasImage) return Read (ref entry_point, this, (_, reader) => reader.ReadEntryPoint ()); return entry_point = null; } set { entry_point = value; } } internal ModuleDefinition () { this.MetadataSystem = new MetadataSystem (); this.token = new MetadataToken (TokenType.Module, 1); } internal ModuleDefinition (Image image) : this () { this.Image = image; this.kind = image.Kind; this.RuntimeVersion = image.RuntimeVersion; this.architecture = image.Architecture; this.attributes = image.Attributes; this.characteristics = image.Characteristics; this.fq_name = image.FileName; this.reader = new MetadataReader (this); } public bool HasTypeReference (string fullName) { return HasTypeReference (string.Empty, fullName); } public bool HasTypeReference (string scope, string fullName) { CheckFullName (fullName); if (!HasImage) return false; return GetTypeReference (scope, fullName) != null; } public bool TryGetTypeReference (string fullName, out TypeReference type) { return TryGetTypeReference (string.Empty, fullName, out type); } public bool TryGetTypeReference (string scope, string fullName, out TypeReference type) { CheckFullName (fullName); if (!HasImage) { type = null; return false; } return (type = GetTypeReference (scope, fullName)) != null; } TypeReference GetTypeReference (string scope, string fullname) { return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2)); } public IEnumerable<TypeReference> GetTypeReferences () { if (!HasImage) return Empty<TypeReference>.Array; return Read (this, (_, reader) => reader.GetTypeReferences ()); } public IEnumerable<MemberReference> GetMemberReferences () { if (!HasImage) return Empty<MemberReference>.Array; return Read (this, (_, reader) => reader.GetMemberReferences ()); } public TypeReference GetType (string fullName, bool runtimeName) { return runtimeName ? TypeParser.ParseType (this, fullName) : GetType (fullName); } public TypeDefinition GetType (string fullName) { CheckFullName (fullName); var position = fullName.IndexOf ('/'); if (position > 0) return GetNestedType (fullName); return ((TypeDefinitionCollection) this.Types).GetType (fullName); } public TypeDefinition GetType (string @namespace, string name) { Mixin.CheckName (name); return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name); } public IEnumerable<TypeDefinition> GetTypes () { return GetTypes (Types); } static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types) { for (int i = 0; i < types.Count; i++) { var type = types [i]; yield return type; if (!type.HasNestedTypes) continue; foreach (var nested in GetTypes (type.NestedTypes)) yield return nested; } } static void CheckFullName (string fullName) { if (fullName == null) throw new ArgumentNullException ("fullName"); if (fullName.Length == 0) throw new ArgumentException (); } TypeDefinition GetNestedType (string fullname) { var names = fullname.Split ('/'); var type = GetType (names [0]); if (type == null) return null; for (int i = 1; i < names.Length; i++) { var nested_type = type.GetNestedType (names [i]); if (nested_type == null) return null; type = nested_type; } return type; } internal FieldDefinition Resolve (FieldReference field) { #if PCL if (MetadataResolver == null) throw new NotSupportedException (); #endif return MetadataResolver.Resolve (field); } internal MethodDefinition Resolve (MethodReference method) { #if PCL if (MetadataResolver == null) throw new NotSupportedException (); #endif return MetadataResolver.Resolve (method); } internal TypeDefinition Resolve (TypeReference type) { #if PCL if (MetadataResolver == null) throw new NotSupportedException (); #endif return MetadataResolver.Resolve (type); } #if !READ_ONLY static void CheckContext (IGenericParameterProvider context, ModuleDefinition module) { if (context == null) return; if (context.Module != module) throw new ArgumentException (); } #if !PCL [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (Type type) { return ImportReference (type, null); } public TypeReference ImportReference (Type type) { return ImportReference (type, null); } [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (Type type, IGenericParameterProvider context) { return ImportReference (type, context); } public TypeReference ImportReference (Type type, IGenericParameterProvider context) { Mixin.CheckType (type); CheckContext (context, this); return ReflectionImporter.ImportReference (type, context); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (SR.FieldInfo field) { return ImportReference (field, null); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context) { return ImportReference (field, context); } public FieldReference ImportReference (SR.FieldInfo field) { return ImportReference (field, null); } public FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context) { Mixin.CheckField (field); CheckContext (context, this); return ReflectionImporter.ImportReference (field, context); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (SR.MethodBase method) { return ImportReference (method, null); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (SR.MethodBase method, IGenericParameterProvider context) { return ImportReference (method, context); } public MethodReference ImportReference (SR.MethodBase method) { return ImportReference (method, null); } public MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context) { Mixin.CheckMethod (method); CheckContext (context, this); return ReflectionImporter.ImportReference (method, context); } #endif [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (TypeReference type) { return ImportReference (type, null); } [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (TypeReference type, IGenericParameterProvider context) { return ImportReference (type, context); } public TypeReference ImportReference (TypeReference type) { return ImportReference (type, null); } public TypeReference ImportReference (TypeReference type, IGenericParameterProvider context) { Mixin.CheckType (type); if (type.Module == this) return type; CheckContext (context, this); return MetadataImporter.ImportReference (type, context); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (FieldReference field) { return ImportReference (field, null); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (FieldReference field, IGenericParameterProvider context) { return ImportReference (field, context); } public FieldReference ImportReference (FieldReference field) { return ImportReference (field, null); } public FieldReference ImportReference (FieldReference field, IGenericParameterProvider context) { Mixin.CheckField (field); if (field.Module == this) return field; CheckContext (context, this); return MetadataImporter.ImportReference (field, context); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (MethodReference method) { return ImportReference (method, null); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (MethodReference method, IGenericParameterProvider context) { return ImportReference (method, context); } public MethodReference ImportReference (MethodReference method) { return ImportReference (method, null); } public MethodReference ImportReference (MethodReference method, IGenericParameterProvider context) { Mixin.CheckMethod (method); if (method.Module == this) return method; CheckContext (context, this); return MetadataImporter.ImportReference (method, context); } #endif public IMetadataTokenProvider LookupToken (int token) { return LookupToken (new MetadataToken ((uint) token)); } public IMetadataTokenProvider LookupToken (MetadataToken token) { return Read (token, (t, reader) => reader.LookupToken (t)); } readonly object module_lock = new object(); internal object SyncRoot { get { return module_lock; } } internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read) { lock (module_lock) { var position = reader.position; var context = reader.context; var ret = read (item, reader); reader.position = position; reader.context = context; return ret; } } internal TRet Read<TItem, TRet> (ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class { lock (module_lock) { if (variable != null) return variable; var position = reader.position; var context = reader.context; var ret = read (item, reader); reader.position = position; reader.context = context; return variable = ret; } } public bool HasDebugHeader { get { return Image != null && !Image.Debug.IsZero; } } public ImageDebugDirectory GetDebugHeader (out byte [] header) { if (!HasDebugHeader) throw new InvalidOperationException (); return Image.GetDebugHeader (out header); } void ProcessDebugHeader () { if (!HasDebugHeader) return; byte [] header; var directory = GetDebugHeader (out header); if (!symbol_reader.ProcessDebugHeader (directory, header)) throw new InvalidOperationException (); } #if !READ_ONLY public static ModuleDefinition CreateModule (string name, ModuleKind kind) { return CreateModule (name, new ModuleParameters { Kind = kind }); } public static ModuleDefinition CreateModule (string name, ModuleParameters parameters) { Mixin.CheckName (name); Mixin.CheckParameters (parameters); var module = new ModuleDefinition { Name = name, kind = parameters.Kind, Runtime = parameters.Runtime, architecture = parameters.Architecture, mvid = Guid.NewGuid (), Attributes = ModuleAttributes.ILOnly, Characteristics = (ModuleCharacteristics) 0x8540, }; if (parameters.AssemblyResolver != null) module.assembly_resolver = parameters.AssemblyResolver; if (parameters.MetadataResolver != null) module.metadata_resolver = parameters.MetadataResolver; #if !READ_ONLY if (parameters.MetadataImporterProvider != null) module.metadata_importer = parameters.MetadataImporterProvider.GetMetadataImporter (module); #if !PCL if (parameters.ReflectionImporterProvider != null) module.reflection_importer = parameters.ReflectionImporterProvider.GetReflectionImporter (module); #endif #endif if (parameters.Kind != ModuleKind.NetModule) { var assembly = new AssemblyDefinition (); module.assembly = assembly; module.assembly.Name = CreateAssemblyName (name); assembly.main_module = module; } module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic)); return module; } static AssemblyNameDefinition CreateAssemblyName (string name) { if (name.EndsWith (".dll") || name.EndsWith (".exe")) name = name.Substring (0, name.Length - 4); return new AssemblyNameDefinition (name, Mixin.ZeroVersion); } #endif #if !PCL public void ReadSymbols () { if (string.IsNullOrEmpty (fq_name)) throw new InvalidOperationException (); var provider = SymbolProvider.GetPlatformReaderProvider (); if (provider == null) throw new InvalidOperationException (); ReadSymbols (provider.GetSymbolReader (this, fq_name)); } #endif public void ReadSymbols (ISymbolReader reader) { if (reader == null) throw new ArgumentNullException ("reader"); symbol_reader = reader; ProcessDebugHeader (); } #if !PCL public static ModuleDefinition ReadModule (string fileName) { return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred)); } public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters) { using (var stream = GetFileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { return ReadModule (stream, parameters); } } static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (fileName.Length == 0) throw new ArgumentException (); return new FileStream (fileName, mode, access, share); } #endif public static ModuleDefinition ReadModule (Stream stream) { return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred)); } static void CheckStream (object stream) { if (stream == null) throw new ArgumentNullException ("stream"); } public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters) { Mixin.CheckStream (stream); if (!stream.CanRead || !stream.CanSeek) throw new ArgumentException (); Mixin.CheckParameters (parameters); return ModuleReader.CreateModuleFrom ( ImageReader.ReadImageFrom (stream), parameters); } #if !READ_ONLY #if !PCL public void Write (string fileName) { Write (fileName, new WriterParameters ()); } public void Write (string fileName, WriterParameters parameters) { using (var stream = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { Write (stream, parameters); } } #endif public void Write (Stream stream) { Write (stream, new WriterParameters ()); } public void Write (Stream stream, WriterParameters parameters) { Mixin.CheckStream (stream); if (!stream.CanWrite || !stream.CanSeek) throw new ArgumentException (); Mixin.CheckParameters (parameters); ModuleWriter.WriteModuleTo (this, stream, parameters); } #endif } static partial class Mixin { public static void CheckStream (object stream) { if (stream == null) throw new ArgumentNullException ("stream"); } #if !READ_ONLY public static void CheckType (object type) { if (type == null) throw new ArgumentNullException ("type"); } public static void CheckField (object field) { if (field == null) throw new ArgumentNullException ("field"); } public static void CheckMethod (object method) { if (method == null) throw new ArgumentNullException ("method"); } #endif public static void CheckParameters (object parameters) { if (parameters == null) throw new ArgumentNullException ("parameters"); } public static bool HasImage (this ModuleDefinition self) { return self != null && self.HasImage; } public static bool IsCoreLibrary (this ModuleDefinition module) { if (module.Assembly == null) return false; var assembly_name = module.Assembly.Name.Name; if (assembly_name != "mscorlib" && assembly_name != "System.Runtime") return false; if (module.HasImage && !module.Read (module, (m, reader) => reader.image.GetTableLength (Table.TypeDef) > 1)) return false; return true; } public static string GetFullyQualifiedName (this Stream self) { #if !PCL var file_stream = self as FileStream; if (file_stream == null) return string.Empty; return Path.GetFullPath (file_stream.Name); #else return string.Empty; #endif } public static TargetRuntime ParseRuntime (this string self) { switch (self [1]) { case '1': return self [3] == '0' ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case '2': return TargetRuntime.Net_2_0; case '4': default: return TargetRuntime.Net_4_0; } } public static string RuntimeVersionString (this TargetRuntime runtime) { switch (runtime) { case TargetRuntime.Net_1_0: return "v1.0.3705"; case TargetRuntime.Net_1_1: return "v1.1.4322"; case TargetRuntime.Net_2_0: return "v2.0.50727"; case TargetRuntime.Net_4_0: default: return "v4.0.30319"; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { using System; using Debugging; using static MethodDebugInfoValidation; public class UsingDebugInfoTests : ExpressionCompilerTestBase { #region Grouped import strings [Fact] public void SimplestCase() { var source = @" using System; class C { void M() { } } "; var comp = CreateStandardCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "C.M").ImportRecordGroups.Verify(@" { Namespace: string='System' }"); }); } [Fact] public void NestedScopes() { var source = @" using System; class C { void M() { int i = 1; { int j = 2; } } } "; var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(comp).VerifyIL("C.M", @" { // Code size 8 (0x8) .maxstack 1 .locals init (int V_0, //i int V_1) //j IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: nop IL_0004: ldc.i4.2 IL_0005: stloc.1 IL_0006: nop IL_0007: ret } "); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "C.M", ilOffset: 0x0004).ImportRecordGroups.Verify(@" { Namespace: string='System' }"); }); } [Fact] public void NestedNamespaces() { var source = @" using System; namespace A { using System.IO; using System.Text; class C { void M() { } } } "; var comp = CreateStandardCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "A.C.M").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); }); } [Fact] public void Forward() { var source = @" using System; namespace A { using System.IO; using System.Text; class C { // One of these methods will forward to the other since they're adjacent. void M1() { } void M2() { } } } "; var comp = CreateStandardCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "A.C.M1").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); GetMethodDebugInfo(runtime, "A.C.M2").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); }); } [Fact] public void ImportKinds() { var source = @" extern alias A; using S = System; namespace B { using F = S.IO.File; using System.Text; class C { void M() { } } } "; var aliasedRef = CreateCompilation("", assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateStandardCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var info = GetMethodDebugInfo(runtime, "B.C.M"); info.ImportRecordGroups.Verify(@" { Namespace: string='System.Text' Type: alias='F' type='System.IO.File' } { Assembly: alias='A' Namespace: alias='S' string='System' }"); info.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void ImportKinds_StaticType() { var libSource = @" namespace N { public static class Static { } } "; var source = @" extern alias A; using static System.Math; namespace B { using static A::N.Static; class C { void M() { } } } "; var aliasedRef = CreateStandardCompilation(libSource, assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateStandardCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var info = GetMethodDebugInfo(runtime, "B.C.M"); info.ImportRecordGroups.Verify(@" { Type: type='N.Static' } { Assembly: alias='A' Type: type='System.Math' }"); info.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } [Fact] public void ForwardToModule() { var source = @" extern alias A; namespace B { using System; class C { void M1() { } } } namespace D { using System.Text; // Different using to prevent normal forwarding. class E { void M2() { } } } "; var aliasedRef = CreateCompilation("", assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateStandardCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var debugInfo1 = GetMethodDebugInfo(runtime, "B.C.M1"); debugInfo1.ImportRecordGroups.Verify(@" { Namespace: string='System' } { Assembly: alias='A' }"); debugInfo1.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); var debugInfo2 = GetMethodDebugInfo(runtime, "D.E.M2"); debugInfo2.ImportRecordGroups.Verify(@" { Namespace: string='System.Text' } { Assembly: alias='A' }"); debugInfo2.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } #endregion #region Invalid PDBs [Fact] public void BadPdb_ForwardChain() { const int methodToken1 = 0x600057a; // Forwards to 2 const int methodToken2 = 0x600055d; // Forwards to 3 const int methodToken3 = 0x6000540; // Has a using const string importString = "USystem"; var getMethodCustomDebugInfo = new Func<int, int, byte[]>((token, _) => { switch (token) { case methodToken1: return new MethodDebugInfoBytes.Builder().AddForward(methodToken2).Build().Bytes.ToArray(); case methodToken2: return new MethodDebugInfoBytes.Builder().AddForward(methodToken3).Build().Bytes.ToArray(); case methodToken3: return new MethodDebugInfoBytes.Builder(new[] { new[] { importString } }).Build().Bytes.ToArray(); default: throw null; } }); var getMethodImportStrings = new Func<int, int, ImmutableArray<string>>((token, _) => { switch (token) { case methodToken3: return ImmutableArray.Create(importString); default: throw null; } }); ImmutableArray < string> externAliasStrings; var importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken1, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.True(importStrings.IsDefault); Assert.True(externAliasStrings.IsDefault); importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken2, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.Equal(importString, importStrings.Single().Single()); Assert.Equal(0, externAliasStrings.Length); importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken2, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.Equal(importString, importStrings.Single().Single()); Assert.Equal(0, externAliasStrings.Length); } [Fact] public void BadPdb_Cycle() { const int methodToken1 = 0x600057a; // Forwards to itself var getMethodCustomDebugInfo = new Func<int, int, byte[]>((token, _) => { switch (token) { case methodToken1: return new MethodDebugInfoBytes.Builder().AddForward(methodToken1).Build().Bytes.ToArray(); default: throw null; } }); var getMethodImportStrings = new Func<int, int, ImmutableArray<string>>((token, _) => { return ImmutableArray<string>.Empty; }); ImmutableArray<string> externAliasStrings; var importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken1, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.True(importStrings.IsDefault); Assert.True(externAliasStrings.IsDefault); } [WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")] [Fact] public void BadPdb_InvalidAliasSyntax() { var source = @" public class C { public static void Main() { } } "; var comp = CreateStandardCompilation(source); var peImage = comp.EmitToArray(); var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( peImage, "Main", "USystem", // Valid. "UACultureInfo TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped. "ASI USystem.IO"); // Valid. var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); // Used to throw. var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); Assert.Equal("SI", imports.UsingAliases.Keys.Single()); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")] [Fact] public void BadPdb_DotInAlias() { var source = @" public class C { public static void Main() { } } "; var comp = CreateStandardCompilation(source); var peImage = comp.EmitToArray(); var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( peImage, "Main", "USystem", // Valid. "AMy.Alias TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped. "ASI USystem.IO"); // Valid. var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); // Used to throw. var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); Assert.Equal("SI", imports.UsingAliases.Keys.Single()); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1007917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007917")] [Fact] public void BadPdb_NestingLevel_TooMany() { var source = @" public class C { public static void Main() { } } "; var comp = CreateStandardCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem", "USystem.IO" } }, suppressUsingInfo: true).AddUsingInfo(1, 1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System.IO", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved. Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1007917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007917")] [Fact] public void BadPdb_NestingLevel_TooFew() { var source = @" namespace N { public class C { public static void Main() { } } } "; var comp = CreateStandardCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "N.C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved. Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void BadPdb_NonStaticTypeImport() { var source = @" namespace N { public class C { public static void Main() { } } } "; var comp = CreateStandardCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "TSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "N.C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal(0, imports.Usings.Length); // Note: the import is dropped Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } #endregion Invalid PDBs #region Binder chain [Fact] public void ImportsForSimpleUsing() { var source = @" using System; class C { int M() { return 1; } } "; var comp = CreateStandardCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualNamespace = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal("System", actualNamespace.ToTestDisplayString()); }); } [Fact] public void ImportsForMultipleUsings() { var source = @" using System; using System.IO; using System.Text; class C { int M() { return 1; } } "; var comp = CreateStandardCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var usings = imports.Usings.Select(u => u.NamespaceOrType).ToArray(); Assert.Equal(3, usings.Length); var expectedNames = new[] { "System", "System.IO", "System.Text" }; for (int i = 0; i < usings.Length; i++) { var actualNamespace = usings[i]; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString()); } }); } [Fact] public void ImportsForNestedNamespaces() { var source = @" using System; namespace A { using System.IO; class C { int M() { return 1; } } } "; var comp = CreateStandardCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "A.C.M").AsEnumerable().ToArray(); Assert.Equal(2, importsList.Length); var expectedNames = new[] { "System.IO", "System" }; // Innermost-to-outermost for (int i = 0; i < importsList.Length; i++) { var imports = importsList[i]; Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualNamespace = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString()); } }); } [Fact] public void ImportsForNamespaceAlias() { var source = @" using S = System; class C { int M() { return 1; } } "; var comp = CreateStandardCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("S", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("S", aliasSymbol.Name); var namespaceSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.Namespace, namespaceSymbol.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)namespaceSymbol).Extent.Kind); Assert.Equal("System", namespaceSymbol.ToTestDisplayString()); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void ImportsForStaticType() { var source = @" using static System.Math; class C { int M() { return 1; } } "; var comp = CreateStandardCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualType = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.NamedType, actualType.Kind); Assert.Equal("System.Math", actualType.ToTestDisplayString()); }); } [Fact] public void ImportsForTypeAlias() { var source = @" using I = System.Int32; class C { int M() { return 1; } } "; var comp = CreateStandardCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("I", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("I", aliasSymbol.Name); var typeSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind); Assert.Equal(SpecialType.System_Int32, ((NamedTypeSymbol)typeSymbol).SpecialType); }); } [Fact] public void ImportsForVerbatimIdentifiers() { var source = @" using @namespace; using @object = @namespace; using @string = @namespace.@class<@namespace.@interface>.@struct; namespace @namespace { public class @class<T> { public struct @struct { } } public interface @interface { } } class C { int M() { return 1; } } "; var comp = CreateStandardCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.ExternAliases.Length); var @using = imports.Usings.Single(); var importedNamespace = @using.NamespaceOrType; Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind); Assert.Equal("namespace", importedNamespace.Name); var usingAliases = imports.UsingAliases; const string keyword1 = "object"; const string keyword2 = "string"; AssertEx.SetEqual(usingAliases.Keys, keyword1, keyword2); var namespaceAlias = usingAliases[keyword1]; var typeAlias = usingAliases[keyword2]; Assert.Equal(keyword1, namespaceAlias.Alias.Name); var aliasedNamespace = namespaceAlias.Alias.Target; Assert.Equal(SymbolKind.Namespace, aliasedNamespace.Kind); Assert.Equal("@namespace", aliasedNamespace.ToTestDisplayString()); Assert.Equal(keyword2, typeAlias.Alias.Name); var aliasedType = typeAlias.Alias.Target; Assert.Equal(SymbolKind.NamedType, aliasedType.Kind); Assert.Equal("@namespace.@class<@namespace.@interface>.@struct", aliasedType.ToTestDisplayString()); }); } [Fact] public void ImportsForGenericTypeAlias() { var source = @" using I = System.Collections.Generic.IEnumerable<string>; class C { int M() { return 1; } } "; var comp = CreateStandardCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("I", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("I", aliasSymbol.Name); var typeSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind); Assert.Equal("System.Collections.Generic.IEnumerable<System.String>", typeSymbol.ToTestDisplayString()); }); } [Fact] public void ImportsForExternAlias() { var source = @" extern alias X; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateStandardCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); comp.VerifyDiagnostics(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.UsingAliases.Count); var externAliases = imports.ExternAliases; Assert.Equal(1, externAliases.Length); var aliasSymbol = externAliases.Single().Alias; Assert.Equal("X", aliasSymbol.Name); var targetSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.Namespace, targetSymbol.Kind); Assert.True(((NamespaceSymbol)targetSymbol).IsGlobalNamespace); Assert.Equal("System.Xml.Linq", targetSymbol.ContainingAssembly.Name); }); } [Fact] public void ImportsForUsingsConsumingExternAlias() { var source = @" extern alias X; using SXL = X::System.Xml.Linq; using LO = X::System.Xml.Linq.LoadOptions; using X::System.Xml; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateStandardCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(1, imports.ExternAliases.Length); var @using = imports.Usings.Single(); var importedNamespace = @using.NamespaceOrType; Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind); Assert.Equal("System.Xml", importedNamespace.ToTestDisplayString()); var usingAliases = imports.UsingAliases; Assert.Equal(2, usingAliases.Count); AssertEx.SetEqual(usingAliases.Keys, "SXL", "LO"); var typeAlias = usingAliases["SXL"].Alias; Assert.Equal("SXL", typeAlias.Name); Assert.Equal("System.Xml.Linq", typeAlias.Target.ToTestDisplayString()); var namespaceAlias = usingAliases["LO"].Alias; Assert.Equal("LO", namespaceAlias.Name); Assert.Equal("System.Xml.Linq.LoadOptions", namespaceAlias.Target.ToTestDisplayString()); }); } [Fact] public void ImportsForUsingsConsumingExternAliasAndGlobal() { var source = @" extern alias X; using A = X::System.Xml.Linq; using B = global::System.Xml.Linq; class C { int M() { A.LoadOptions.None.ToString(); B.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateStandardCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("global", "X")) }); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(1, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(2, usingAliases.Count); AssertEx.SetEqual(usingAliases.Keys, "A", "B"); var aliasA = usingAliases["A"].Alias; Assert.Equal("A", aliasA.Name); Assert.Equal("System.Xml.Linq", aliasA.Target.ToTestDisplayString()); var aliasB = usingAliases["B"].Alias; Assert.Equal("B", aliasB.Name); Assert.Equal(aliasA.Target, aliasB.Target); }); } private static ImportChain GetImports(RuntimeInstance runtime, string methodName) { var evalContext = CreateMethodContext(runtime, methodName); var compContext = evalContext.CreateCompilationContext(); return compContext.NamespaceBinder.ImportChain; } #endregion Binder chain [Fact] public void NoSymbols() { var source = @"using N; class A { static void M() { } } namespace N { class B { static void M() { } } }"; ResultProperties resultProperties; string error; // With symbols, type reference without namespace qualifier. var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "A.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: true); Assert.Null(error); // Without symbols, type reference without namespace qualifier. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "A.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: false); Assert.Equal(error, "error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)"); // With symbols, type reference inside namespace. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.B.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: true); Assert.Null(error); // Without symbols, type reference inside namespace. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.B.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: false); Assert.Null(error); } [WorkItem(2441, "https://github.com/dotnet/roslyn/issues/2441")] [Fact] public void AssemblyQualifiedNameResolutionWithUnification() { var source1 = @" using SI = System.Int32; public class C1 { void M() { } } "; var source2 = @" public class C2 : C1 { } "; var comp1 = CreateCompilation(source1, new[] { MscorlibRef_v20 }, TestOptions.DebugDll); var module1 = comp1.ToModuleInstance(); var comp2 = CreateCompilation(source2, new[] { MscorlibRef_v4_0_30316_17626, module1.GetReference() }, TestOptions.DebugDll); var module2 = comp2.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { module1, module2, MscorlibRef_v4_0_30316_17626.ToModuleInstance(), ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); var context = CreateMethodContext(runtime, "C1.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(SI)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""int"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } } internal static class ImportChainExtensions { internal static Imports Single(this ImportChain importChain) { return importChain.AsEnumerable().Single(); } internal static IEnumerable<Imports> AsEnumerable(this ImportChain importChain) { for (var chain = importChain; chain != null; chain = chain.ParentOpt) { yield return chain.Imports; } } } }
using System; using System.Reactive.Linq; using Avalonia.Automation.Peers; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; namespace Avalonia.Controls { /// <summary> /// A control which scrolls its content if the content is bigger than the space available. /// </summary> public class ScrollViewer : ContentControl, IScrollable, IScrollAnchorProvider { /// <summary> /// Defines the <see cref="CanHorizontallyScroll"/> property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, bool> CanHorizontallyScrollProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, bool>( nameof(CanHorizontallyScroll), o => o.CanHorizontallyScroll); /// <summary> /// Defines the <see cref="CanVerticallyScroll"/> property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, bool> CanVerticallyScrollProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, bool>( nameof(CanVerticallyScroll), o => o.CanVerticallyScroll); /// <summary> /// Defines the <see cref="Extent"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ExtentProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Extent), o => o.Extent, (o, v) => o.Extent = v); /// <summary> /// Defines the <see cref="Offset"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Vector>( nameof(Offset), o => o.Offset, (o, v) => o.Offset = v); /// <summary> /// Defines the <see cref="Viewport"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ViewportProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Viewport), o => o.Viewport, (o, v) => o.Viewport = v); /// <summary> /// Defines the <see cref="LargeChange"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> LargeChangeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>( nameof(LargeChange), o => o.LargeChange); /// <summary> /// Defines the <see cref="SmallChange"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> SmallChangeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>( nameof(SmallChange), o => o.SmallChange); /// <summary> /// Defines the HorizontalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarMaximum), o => o.HorizontalScrollBarMaximum); /// <summary> /// Defines the HorizontalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarValue), o => o.HorizontalScrollBarValue, (o, v) => o.HorizontalScrollBarValue = v); /// <summary> /// Defines the HorizontalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarViewportSize), o => o.HorizontalScrollBarViewportSize); /// <summary> /// Defines the <see cref="HorizontalScrollBarVisibility"/> property. /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(HorizontalScrollBarVisibility), ScrollBarVisibility.Disabled); /// <summary> /// Defines the VerticalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarMaximum), o => o.VerticalScrollBarMaximum); /// <summary> /// Defines the VerticalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarValue), o => o.VerticalScrollBarValue, (o, v) => o.VerticalScrollBarValue = v); /// <summary> /// Defines the VerticalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarViewportSize), o => o.VerticalScrollBarViewportSize); /// <summary> /// Defines the <see cref="VerticalScrollBarVisibility"/> property. /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(VerticalScrollBarVisibility), ScrollBarVisibility.Auto); /// <summary> /// Defines the <see cref="IsExpandedProperty"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, bool> IsExpandedProperty = ScrollBar.IsExpandedProperty.AddOwner<ScrollViewer>(o => o.IsExpanded); /// <summary> /// Defines the <see cref="AllowAutoHide"/> property. /// </summary> public static readonly AttachedProperty<bool> AllowAutoHideProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, bool>( nameof(AllowAutoHide), true); /// <summary> /// Defines the <see cref="IsScrollChainingEnabled"/> property. /// </summary> public static readonly AttachedProperty<bool> IsScrollChainingEnabledProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, bool>( nameof(IsScrollChainingEnabled), defaultValue: true); /// <summary> /// Defines the <see cref="ScrollChanged"/> event. /// </summary> public static readonly RoutedEvent<ScrollChangedEventArgs> ScrollChangedEvent = RoutedEvent.Register<ScrollViewer, ScrollChangedEventArgs>( nameof(ScrollChanged), RoutingStrategies.Bubble); internal const double DefaultSmallChange = 16; private IDisposable? _childSubscription; private ILogicalScrollable? _logicalScrollable; private Size _extent; private Vector _offset; private Size _viewport; private Size _oldExtent; private Vector _oldOffset; private Size _oldViewport; private Size _largeChange; private Size _smallChange = new Size(DefaultSmallChange, DefaultSmallChange); private bool _isExpanded; private IDisposable? _scrollBarExpandSubscription; /// <summary> /// Initializes static members of the <see cref="ScrollViewer"/> class. /// </summary> static ScrollViewer() { HorizontalScrollBarVisibilityProperty.Changed.AddClassHandler<ScrollViewer, ScrollBarVisibility>((x, e) => x.ScrollBarVisibilityChanged(e)); VerticalScrollBarVisibilityProperty.Changed.AddClassHandler<ScrollViewer, ScrollBarVisibility>((x, e) => x.ScrollBarVisibilityChanged(e)); } /// <summary> /// Initializes a new instance of the <see cref="ScrollViewer"/> class. /// </summary> public ScrollViewer() { LayoutUpdated += OnLayoutUpdated; } /// <summary> /// Occurs when changes are detected to the scroll position, extent, or viewport size. /// </summary> public event EventHandler<ScrollChangedEventArgs>? ScrollChanged { add => AddHandler(ScrollChangedEvent, value); remove => RemoveHandler(ScrollChangedEvent, value); } /// <summary> /// Gets the extent of the scrollable content. /// </summary> public Size Extent { get { return _extent; } private set { if (SetAndRaise(ExtentProperty, ref _extent, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets or sets the current scroll offset. /// </summary> public Vector Offset { get { return _offset; } set { if (SetAndRaise(OffsetProperty, ref _offset, CoerceOffset(Extent, Viewport, value))) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets the size of the viewport on the scrollable content. /// </summary> public Size Viewport { get { return _viewport; } private set { if (SetAndRaise(ViewportProperty, ref _viewport, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets the large (page) change value for the scroll viewer. /// </summary> public Size LargeChange => _largeChange; /// <summary> /// Gets the small (line) change value for the scroll viewer. /// </summary> public Size SmallChange => _smallChange; /// <summary> /// Gets or sets the horizontal scrollbar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get { return GetValue(HorizontalScrollBarVisibilityProperty); } set { SetValue(HorizontalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets or sets the vertical scrollbar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get { return GetValue(VerticalScrollBarVisibilityProperty); } set { SetValue(VerticalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets a value indicating whether the viewer can scroll horizontally. /// </summary> protected bool CanHorizontallyScroll { get { return HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled; } } /// <summary> /// Gets a value indicating whether the viewer can scroll vertically. /// </summary> protected bool CanVerticallyScroll { get { return VerticalScrollBarVisibility != ScrollBarVisibility.Disabled; } } /// <inheritdoc/> public IControl? CurrentAnchor => (Presenter as IScrollAnchorProvider)?.CurrentAnchor; /// <summary> /// Gets the maximum horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarMaximum { get { return Max(_extent.Width - _viewport.Width, 0); } } /// <summary> /// Gets or sets the horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarValue { get { return _offset.X; } set { if (_offset.X != value) { var old = Offset.X; Offset = Offset.WithX(value); RaisePropertyChanged(HorizontalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the horizontal scrollbar viewport. /// </summary> protected double HorizontalScrollBarViewportSize { get { return _viewport.Width; } } /// <summary> /// Gets the maximum vertical scrollbar value. /// </summary> protected double VerticalScrollBarMaximum { get { return Max(_extent.Height - _viewport.Height, 0); } } /// <summary> /// Gets or sets the vertical scrollbar value. /// </summary> protected double VerticalScrollBarValue { get { return _offset.Y; } set { if (_offset.Y != value) { var old = Offset.Y; Offset = Offset.WithY(value); RaisePropertyChanged(VerticalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the vertical scrollbar viewport. /// </summary> protected double VerticalScrollBarViewportSize { get { return _viewport.Height; } } /// <summary> /// Gets a value that indicates whether any scrollbar is expanded. /// </summary> public bool IsExpanded { get => _isExpanded; private set => SetAndRaise(ScrollBar.IsExpandedProperty, ref _isExpanded, value); } /// <summary> /// Gets a value that indicates whether scrollbars can hide itself when user is not interacting with it. /// </summary> public bool AllowAutoHide { get => GetValue(AllowAutoHideProperty); set => SetValue(AllowAutoHideProperty, value); } /// <summary> /// Gets or sets if scroll chaining is enabled. The default value is true. /// </summary> /// <remarks> /// After a user hits a scroll limit on an element that has been nested within another scrollable element, /// you can specify whether that parent element should continue the scrolling operation begun in its child element. /// This is called scroll chaining. /// </remarks> public bool IsScrollChainingEnabled { get => GetValue(IsScrollChainingEnabledProperty); set => SetValue(IsScrollChainingEnabledProperty, value); } /// <summary> /// Scrolls the content up one line. /// </summary> public void LineUp() { Offset -= new Vector(0, _smallChange.Height); } /// <summary> /// Scrolls the content down one line. /// </summary> public void LineDown() { Offset += new Vector(0, _smallChange.Height); } /// <summary> /// Scrolls the content left one line. /// </summary> public void LineLeft() { Offset -= new Vector(_smallChange.Width, 0); } /// <summary> /// Scrolls the content right one line. /// </summary> public void LineRight() { Offset += new Vector(_smallChange.Width, 0); } /// <summary> /// Scrolls the content upward by one page. /// </summary> public void PageUp() { VerticalScrollBarValue = Math.Max(_offset.Y - _viewport.Height, 0); } /// <summary> /// Scrolls the content downward by one page. /// </summary> public void PageDown() { VerticalScrollBarValue = Math.Min(_offset.Y + _viewport.Height, VerticalScrollBarMaximum); } /// <summary> /// Scrolls the content left by one page. /// </summary> public void PageLeft() { HorizontalScrollBarValue = Math.Max(_offset.X - _viewport.Width, 0); } /// <summary> /// Scrolls the content tight by one page. /// </summary> public void PageRight() { HorizontalScrollBarValue = Math.Min(_offset.X + _viewport.Width, HorizontalScrollBarMaximum); } /// <summary> /// Scrolls to the top-left corner of the content. /// </summary> public void ScrollToHome() { Offset = new Vector(double.NegativeInfinity, double.NegativeInfinity); } /// <summary> /// Scrolls to the bottom-left corner of the content. /// </summary> public void ScrollToEnd() { Offset = new Vector(double.NegativeInfinity, double.PositiveInfinity); } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public static ScrollBarVisibility GetHorizontalScrollBarVisibility(Control control) { return control.GetValue(HorizontalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public static void SetHorizontalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public static ScrollBarVisibility GetVerticalScrollBarVisibility(Control control) { return control.GetValue(VerticalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the AllowAutoHideProperty attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public static void SetAllowAutoHide(Control control, bool value) { control.SetValue(AllowAutoHideProperty, value); } /// <summary> /// Gets the value of the AllowAutoHideProperty attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public static bool GetAllowAutoHide(Control control) { return control.GetValue(AllowAutoHideProperty); } /// <summary> /// Sets the value of the IsScrollChainingEnabled attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> /// <remarks> /// After a user hits a scroll limit on an element that has been nested within another scrollable element, /// you can specify whether that parent element should continue the scrolling operation begun in its child element. /// This is called scroll chaining. /// </remarks> public static void SetIsScrollChainingEnabled(Control control, bool value) { control.SetValue(IsScrollChainingEnabledProperty, value); } /// <summary> /// Gets the value of the IsScrollChainingEnabled attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> /// <remarks> /// After a user hits a scroll limit on an element that has been nested within another scrollable element, /// you can specify whether that parent element should continue the scrolling operation begun in its child element. /// This is called scroll chaining. /// </remarks> public static bool GetIsScrollChainingEnabled(Control control) { return control.GetValue(IsScrollChainingEnabledProperty); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public static void SetVerticalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(VerticalScrollBarVisibilityProperty, value); } /// <inheritdoc/> public void RegisterAnchorCandidate(IControl element) { (Presenter as IScrollAnchorProvider)?.RegisterAnchorCandidate(element); } /// <inheritdoc/> public void UnregisterAnchorCandidate(IControl element) { (Presenter as IScrollAnchorProvider)?.UnregisterAnchorCandidate(element); } protected override bool RegisterContentPresenter(IContentPresenter presenter) { _childSubscription?.Dispose(); _childSubscription = null; if (base.RegisterContentPresenter(presenter)) { _childSubscription = Presenter? .GetObservable(ContentPresenter.ChildProperty) .Subscribe(ChildChanged); return true; } return false; } internal static Vector CoerceOffset(Size extent, Size viewport, Vector offset) { var maxX = Math.Max(extent.Width - viewport.Width, 0); var maxY = Math.Max(extent.Height - viewport.Height, 0); return new Vector(Clamp(offset.X, 0, maxX), Clamp(offset.Y, 0, maxY)); } private static double Clamp(double value, double min, double max) { return (value < min) ? min : (value > max) ? max : value; } private static double Max(double x, double y) { var result = Math.Max(x, y); return double.IsNaN(result) ? 0 : result; } private void ChildChanged(IControl? child) { if (_logicalScrollable is object) { _logicalScrollable.ScrollInvalidated -= LogicalScrollInvalidated; _logicalScrollable = null; } if (child is ILogicalScrollable logical) { _logicalScrollable = logical; logical.ScrollInvalidated += LogicalScrollInvalidated; } CalculatedPropertiesChanged(); } private void LogicalScrollInvalidated(object? sender, EventArgs e) { CalculatedPropertiesChanged(); } private void ScrollBarVisibilityChanged(AvaloniaPropertyChangedEventArgs<ScrollBarVisibility> e) { var wasEnabled = e.OldValue.GetValueOrDefault() != ScrollBarVisibility.Disabled; var isEnabled = e.NewValue.GetValueOrDefault() != ScrollBarVisibility.Disabled; if (wasEnabled != isEnabled) { if (e.Property == HorizontalScrollBarVisibilityProperty) { RaisePropertyChanged( CanHorizontallyScrollProperty, wasEnabled, isEnabled); } else if (e.Property == VerticalScrollBarVisibilityProperty) { RaisePropertyChanged( CanVerticallyScrollProperty, wasEnabled, isEnabled); } } } private void CalculatedPropertiesChanged() { // Pass old values of 0 here because we don't have the old values at this point, // and it shouldn't matter as only the template uses these properties. RaisePropertyChanged(HorizontalScrollBarMaximumProperty, 0, HorizontalScrollBarMaximum); RaisePropertyChanged(HorizontalScrollBarValueProperty, 0, HorizontalScrollBarValue); RaisePropertyChanged(HorizontalScrollBarViewportSizeProperty, 0, HorizontalScrollBarViewportSize); RaisePropertyChanged(VerticalScrollBarMaximumProperty, 0, VerticalScrollBarMaximum); RaisePropertyChanged(VerticalScrollBarValueProperty, 0, VerticalScrollBarValue); RaisePropertyChanged(VerticalScrollBarViewportSizeProperty, 0, VerticalScrollBarViewportSize); if (_logicalScrollable?.IsLogicalScrollEnabled == true) { SetAndRaise(SmallChangeProperty, ref _smallChange, _logicalScrollable.ScrollSize); SetAndRaise(LargeChangeProperty, ref _largeChange, _logicalScrollable.PageScrollSize); } else { SetAndRaise(SmallChangeProperty, ref _smallChange, new Size(DefaultSmallChange, DefaultSmallChange)); SetAndRaise(LargeChangeProperty, ref _largeChange, Viewport); } } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.PageUp) { PageUp(); e.Handled = true; } else if (e.Key == Key.PageDown) { PageDown(); e.Handled = true; } } /// <summary> /// Called when a change in scrolling state is detected, such as a change in scroll /// position, extent, or viewport size. /// </summary> /// <param name="e">The event args.</param> /// <remarks> /// If you override this method, call `base.OnScrollChanged(ScrollChangedEventArgs)` to /// ensure that this event is raised. /// </remarks> protected virtual void OnScrollChanged(ScrollChangedEventArgs e) { RaiseEvent(e); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _scrollBarExpandSubscription?.Dispose(); _scrollBarExpandSubscription = SubscribeToScrollBars(e); } protected override AutomationPeer OnCreateAutomationPeer() { return new ScrollViewerAutomationPeer(this); } private IDisposable? SubscribeToScrollBars(TemplateAppliedEventArgs e) { static IObservable<bool>? GetExpandedObservable(ScrollBar? scrollBar) { return scrollBar?.GetObservable(ScrollBar.IsExpandedProperty); } var horizontalScrollBar = e.NameScope.Find<ScrollBar>("PART_HorizontalScrollBar"); var verticalScrollBar = e.NameScope.Find<ScrollBar>("PART_VerticalScrollBar"); var horizontalExpanded = GetExpandedObservable(horizontalScrollBar); var verticalExpanded = GetExpandedObservable(verticalScrollBar); IObservable<bool>? actualExpanded = null; if (horizontalExpanded != null && verticalExpanded != null) { actualExpanded = horizontalExpanded.CombineLatest(verticalExpanded, (h, v) => h || v); } else { if (horizontalExpanded != null) { actualExpanded = horizontalExpanded; } else if (verticalExpanded != null) { actualExpanded = verticalExpanded; } } return actualExpanded?.Subscribe(OnScrollBarExpandedChanged); } private void OnScrollBarExpandedChanged(bool isExpanded) { IsExpanded = isExpanded; } private void OnLayoutUpdated(object? sender, EventArgs e) => RaiseScrollChanged(); private void RaiseScrollChanged() { var extentDelta = new Vector(Extent.Width - _oldExtent.Width, Extent.Height - _oldExtent.Height); var offsetDelta = Offset - _oldOffset; var viewportDelta = new Vector(Viewport.Width - _oldViewport.Width, Viewport.Height - _oldViewport.Height); if (!extentDelta.NearlyEquals(default) || !offsetDelta.NearlyEquals(default) || !viewportDelta.NearlyEquals(default)) { var e = new ScrollChangedEventArgs(extentDelta, offsetDelta, viewportDelta); OnScrollChanged(e); _oldExtent = Extent; _oldOffset = Offset; _oldViewport = Viewport; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Utils ** ** Purpose: Random functionality that is useful for the ** Add-In model ** ===========================================================*/ using System; using System.Collections.Generic; using System.Collections; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Text; using System.Diagnostics; using System.AddIn.MiniReflection; using System.Diagnostics.Contracts; namespace System.AddIn.Hosting { [Serializable] internal static class Utils { // This method requires that the types passed in are from the same CLR // loader context. The V2 loader defines 4 loader contexts, and only 2 of // them will exist in the CLR V3. A type from an assembly loaded in one // loader context is not assignable to the same type in a different loader // context. This applies for normal assignment, but also shows up in // Reflection, as getting different System.Type instances. This method // wants to be relatively fast, so instead of doing string comparisons on // type names, we leverage Reflection's guarantees about singleton Type // instances for assemblies loaded in the same loader context. That's why // the loop below can do a reference equality test. internal static bool HasCustomAttribute(Type attributeType, Type inspectType) { return GetCustomAttributeData(attributeType, inspectType) != null; } internal static CustomAttributeData GetCustomAttributeData(Type attributeType, Type inspectType) { // Spec#: Should this be a DebugRequires or RequiresExpensive? System.Diagnostics.Contracts.Contract.Requires(typeof(Attribute).IsAssignableFrom(attributeType)); // The following precondition isn't strictly sufficient for the V2 CLR // because we define 4 loader contexts and expose only one boolean // predicate for testing which loader context an assembly is loaded in. // But it is still very useful - our types must be in the same loader context. // // Removed because sometimes we look for attributes on a type's Base type which may be Object // System.Diagnostics.Contracts.Contract.Requires(attributeType.Assembly.ReflectionOnly == inspectType.Assembly.ReflectionOnly); foreach (CustomAttributeData ca in CustomAttributeData.GetCustomAttributes(inspectType)) { if (Object.ReferenceEquals(ca.Constructor.DeclaringType, attributeType)) return ca; } return null; } /* internal static bool PublicKeyTokensEqual(String token1, byte[] token2) { if (token2 == null || token2.Length == 0) return token1 == "null"; if (token1 == "null") return false; Contract.Assert(token1.Length == 2 * token2.Length, "Lengths didn't match"); for (int i = 0; i < token2.Length; i++) { int firstPart = (token1[2 * i] <= '9') ? token1[2 * i] - '0' : token1[2 * i] - 'a' + 10; int secondPart = (token1[2 * i + 1] <= '9') ? token1[2 * i + 1] - '0' : token1[2 * i + 1] - 'a' + 10; byte b1 = (byte)((firstPart << 4) + secondPart); if (b1 != token2[i]) return false; } return true; } */ /* internal static bool PublicKeyTokensEqual(byte[] token1, byte[] token2) { if (token2 == null || token2.Length == 0) return token1 == null || token1.Length == 0; if (token1 == null) return false; System.Diagnostics.Contracts.Contract.Assert(token1.Length == token2.Length, "Lengths didn't match"); for (int i = 0; i < token1.Length; i++) if (token1[i] != token2[i]) return false; return true; } */ internal static bool PublicKeyMatches(AssemblyName a1, AssemblyName a2) { byte[] key = a2.GetPublicKey(); return PublicKeyMatches(a1, key); } internal static bool PublicKeyMatches(System.Reflection.AssemblyName a1, byte[] publicKeyOrToken) { if (publicKeyOrToken == null) return a1.GetPublicKey() == null; byte[] publicKey = a1.GetPublicKey(); if (publicKey != null && publicKeyOrToken.Length == publicKey.Length) { for (int i = 0; i < publicKey.Length; i++) if (publicKey[i] != publicKeyOrToken[i]) return false; return true; } byte[] publicKeyToken = a1.GetPublicKeyToken(); if (publicKeyOrToken.Length == publicKeyToken.Length) { for (int i = 0; i < publicKeyToken.Length; i++) if (publicKeyToken[i] != publicKeyOrToken[i]) return false; return true; } return false; } internal static String PublicKeyToString(byte[] key) { if (key == null || key.Length == 0) return "null"; StringBuilder sb = new StringBuilder(key.Length); foreach (byte b in key) { sb.Append(b.ToString("x2", System.Globalization.CultureInfo.InvariantCulture)); } return sb.ToString(); } // You must have already normalized the paths! internal static String MakeRelativePath(String path, String root) { System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(path)); System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(root)); if (!path.StartsWith(root, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Res.MakeRelativePathArgs); System.Diagnostics.Contracts.Contract.Requires(String.Equals(path, Path.GetFullPath(path))); System.Diagnostics.Contracts.Contract.Requires(String.Equals(root, Path.GetFullPath(root))); System.Diagnostics.Contracts.Contract.Ensures(!Path.IsPathRooted(System.Diagnostics.Contracts.Contract.Result<String>())); System.Diagnostics.Contracts.Contract.EndContractBlock(); int skip = 0; char lastChar = root[root.Length - 1]; if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar) skip++; String relPath = path.Substring(root.Length + skip); return relPath; } // Pass in fully qualified names. We've factored out our assembly names // comparisons so that we can handle policy if necessary, and also deal with // potentially mal-formed assembly refs, or assembly refs that include // processor architecture, etc. (I haven't implemented that, but it could be done.) internal static bool AssemblyRefEqualsDef(String assemblyRef, String assemblyDef) { System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(assemblyRef)); System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(assemblyDef)); return String.Equals(assemblyRef, assemblyDef); } // Pass in fully qualified names. We've factored out our assembly names // comparisons so that we can handle policy if necessary. internal static bool AssemblyDefEqualsDef(String assemblyDef1, String assemblyDef2) { System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(assemblyDef1)); System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(assemblyDef2)); return String.Equals(assemblyDef1, assemblyDef2); } // Pass in fully qualified type names. We've factored out our assembly names // comparisons so that we can handle policy if necessary. internal static bool FullTypeNameDefEqualsDef(String typeAndAssemblyName1, String typeAndAssemblyName2) { System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(typeAndAssemblyName1)); System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(typeAndAssemblyName2)); return String.Equals(typeAndAssemblyName1, typeAndAssemblyName2); } // If you're calling this method, you suspect that you've already loaded this // assembly, but you need to upgrade the assembly from the LoadFrom loader // context to the default loader context. However, we'll have to call it // for an unbound set of assemblies. internal static Assembly FindLoadedAssemblyRef(String assemblyRef) { System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(assemblyRef)); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { if (Utils.AssemblyRefEqualsDef(assemblyRef, a.FullName)) { //Console.WriteLine("FindLoadedAssemblyRef found its target (probably in the LoadFrom context). Returning, in hopes of upgrading to default loader context. Code base: {0}", a.CodeBase); return a; } } return null; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification="LoadFrom was designed for addins")] internal static Assembly LoadAssemblyFrom(List<String> dirsToLookIn, String assemblyRef) { int firstComma = assemblyRef.IndexOf(','); if (firstComma == -1) return null; String simpleName = assemblyRef.Substring(0, firstComma); List<String> potentialFileNames = new List<string>(dirsToLookIn.Count * 2); foreach (String path in dirsToLookIn) { String simpleFileName = Path.Combine(path, simpleName); String dllName = simpleFileName + ".dll"; if (File.Exists(dllName)) potentialFileNames.Add(dllName); else if (File.Exists(simpleFileName + ".exe")) potentialFileNames.Add(simpleFileName + ".exe"); } foreach (String fileName in potentialFileNames) { try { Assembly assembly = Assembly.LoadFrom(fileName); // We should at least be comparing the public key token // for the two assemblies here. The version numbers may // potentially be different, dependent on publisher policy. if (Utils.AssemblyRefEqualsDef(assemblyRef, assembly.FullName)) { return assembly; } } catch (BadImageFormatException) { } } return null; } // If they have full trust, give a good error message. Otherwise, prevent information disclosure. [SecuritySafeCritical] internal static bool HasFullTrust() { try { new PermissionSet(PermissionState.Unrestricted).Demand(); return true; } catch(SecurityException) { return false; } } //Utility method to assert permission and unload the appdomain [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.Assert, ControlAppDomain = true)] internal static void UnloadAppDomain(AppDomain domain) { AppDomain.Unload(domain); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Encog.ML.EA.Genome; using Encog.Engine.Network.Activation; using Encog.MathUtil.Randomize; using Encog.Util; namespace Encog.Neural.NEAT.Training { /// <summary> /// Implements a NEAT genome. This is a "blueprint" for creating a neural /// network. /// /// ----------------------------------------------------------------------------- /// http://www.cs.ucf.edu/~kstanley/ Encog's NEAT implementation was drawn from /// the following three Journal Articles. For more complete BibTeX sources, see /// NEATNetwork.java. /// /// Evolving Neural Networks Through Augmenting Topologies /// /// Generating Large-Scale Neural Networks Through Discovering Geometric /// Regularities /// /// Automatic feature selection in neuroevolution /// </summary> [Serializable] public class NEATGenome : BasicGenome, ICloneable { /// <summary> /// The number of inputs. /// </summary> public int InputCount { get; set; } /// <summary> /// The list that holds the links. /// </summary> private readonly List<NEATLinkGene> _linksList = new List<NEATLinkGene>(); /// <summary> /// The network depth. /// </summary> public int NetworkDepth { get; set; } /// <summary> /// The list that holds the neurons. /// </summary> private readonly IList<NEATNeuronGene> _neuronsList = new List<NEATNeuronGene>(); /// <summary> /// The number of outputs. /// </summary> public int OutputCount { get; set; } /// <summary> /// Construct a genome by copying another. /// </summary> /// <param name="other">The other genome.</param> public NEATGenome(NEATGenome other) { NetworkDepth = other.NetworkDepth; Population = other.Population; Score = other.Score; AdjustedScore = other.AdjustedScore; InputCount = other.InputCount; OutputCount = other.OutputCount; Species = other.Species; // copy neurons foreach (NEATNeuronGene oldGene in other.NeuronsChromosome) { var newGene = new NEATNeuronGene(oldGene); _neuronsList.Add(newGene); } // copy links foreach (var oldGene in other.LinksChromosome) { var newGene = new NEATLinkGene( oldGene.FromNeuronId, oldGene.ToNeuronId, oldGene.Enabled, oldGene.InnovationId, oldGene.Weight); _linksList.Add(newGene); } } /// <summary> /// Create a NEAT gnome. Neuron genes will be added by reference, links will /// be copied. /// </summary> /// <param name="neurons">The neurons to create.</param> /// <param name="links">The links to create.</param> /// <param name="inputCount">The input count.</param> /// <param name="outputCount">The output count.</param> public NEATGenome(IEnumerable<NEATNeuronGene> neurons, IEnumerable<NEATLinkGene> links, int inputCount, int outputCount) { AdjustedScore = 0; InputCount = inputCount; OutputCount = outputCount; foreach (NEATLinkGene gene in links) { _linksList.Add(new NEATLinkGene(gene)); } _neuronsList = _neuronsList.Union(neurons).ToList(); } /// <summary> /// Create a new genome with the specified connection density. This /// constructor is typically used to create the initial population. /// </summary> /// <param name="rnd">Random number generator.</param> /// <param name="pop">The population.</param> /// <param name="inputCount">The input count.</param> /// <param name="outputCount">The output count.</param> /// <param name="connectionDensity">The connection density.</param> public NEATGenome(EncogRandom rnd, NEATPopulation pop, int inputCount, int outputCount, double connectionDensity) { AdjustedScore = 0; InputCount = inputCount; OutputCount = outputCount; // get the activation function IActivationFunction af = pop.ActivationFunctions.PickFirst(); // first bias int innovationId = 0; var biasGene = new NEATNeuronGene(NEATNeuronType.Bias, af, inputCount, innovationId++); _neuronsList.Add(biasGene); // then inputs for (var i = 0; i < inputCount; i++) { var gene = new NEATNeuronGene(NEATNeuronType.Input, af, i, innovationId++); _neuronsList.Add(gene); } // then outputs for (int i = 0; i < outputCount; i++) { var gene = new NEATNeuronGene(NEATNeuronType.Output, af, i + inputCount + 1, innovationId++); _neuronsList.Add(gene); } // and now links for (var i = 0; i < inputCount + 1; i++) { for (var j = 0; j < outputCount; j++) { // make sure we have at least one connection if (_linksList.Count < 1 || rnd.NextDouble() < connectionDensity) { long fromId = this._neuronsList[i].Id; long toId = this._neuronsList[inputCount + j + 1].Id; double w = RangeRandomizer.Randomize(rnd, -pop.WeightRange, pop.WeightRange); var gene = new NEATLinkGene(fromId, toId, true, innovationId++, w); _linksList.Add(gene); } } } } /// <summary> /// Empty constructor for persistence. /// </summary> public NEATGenome() { } /// <summary> /// The number of genes in the links chromosome. /// </summary> public int NumGenes { get { return _linksList.Count; } } /// <summary> /// Sort the genes. /// </summary> public void SortGenes() { _linksList.Sort(); } /// <summary> /// The link neurons. /// </summary> public IList<NEATLinkGene> LinksChromosome { get { return _linksList; } } /// <summary> /// The neurons /// </summary> public IList<NEATNeuronGene> NeuronsChromosome { get { return _neuronsList; } } /// <summary> /// Validate the structure of this genome. /// </summary> public void Validate() { // make sure that the bias neuron is where it should be NEATNeuronGene g = _neuronsList[0]; if (g.NeuronType != NEATNeuronType.Bias) { throw new EncogError("NEAT Neuron Gene 0 should be a bias gene."); } // make sure all input neurons are at the beginning for (int i = 1; i <= InputCount; i++) { NEATNeuronGene gene = _neuronsList[i]; if (gene.NeuronType != NEATNeuronType.Input) { throw new EncogError("NEAT Neuron Gene " + i + " should be an input gene."); } } // make sure that there are no double links IDictionary<String, NEATLinkGene> map = new Dictionary<String, NEATLinkGene>(); foreach (NEATLinkGene nlg in _linksList) { String key = nlg.FromNeuronId + "->" + nlg.ToNeuronId; if (map.ContainsKey(key)) { throw new EncogError("Double link found: " + key); } map[key] = nlg; } } /// <inheritdoc/> public override void Copy(IGenome source) { throw new NotImplementedException(); } /// <inheritdoc/> public override int Size { get { throw new NotImplementedException(); } } /// <summary> /// Find the neuron with the specified nodeID. /// </summary> /// <param name="nodeId">The nodeID to look for.</param> /// <returns>The neuron, if found, otherwise null.</returns> public NEATNeuronGene FindNeuron(long nodeId) { foreach (NEATNeuronGene gene in this._neuronsList) { if (gene.Id == nodeId) return gene; } return null; } /// <inheritdoc/> public override String ToString() { var result = new StringBuilder(); result.Append("["); result.Append(GetType().Name); result.Append(",score="); result.Append(Format.FormatDouble(Score, 2)); result.Append(",adjusted score="); result.Append(Format.FormatDouble(AdjustedScore, 2)); result.Append(",birth generation="); result.Append(BirthGeneration); result.Append(",neurons="); result.Append(_neuronsList.Count); result.Append(",links="); result.Append(_linksList.Count); result.Append("]"); return result.ToString(); } /// <inheritdoc/> public object Clone() { var result = new NEATGenome(); result.Copy(this); return result; } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DynamoDBv2.Model { /// <summary> /// Container for the parameters to the PutItem operation. /// <para>Creates a new item, or replaces an old item with a new item. If an item already exists in the specified table with the same primary /// key, the new item completely replaces the existing item. You can perform a conditional put (insert a new item if one with the specified /// primary key doesn't exist), or replace an existing item if it has certain attribute values. </para> <para>In addition to putting an item, /// you can also return the item's attribute values in the same operation, using the <i>ReturnValues</i> parameter.</para> <para>When you add an /// item, the primary key attribute(s) are the only required attributes. Attribute values cannot be null. String and binary type attributes must /// have lengths greater than zero. Set type attributes cannot be empty. Requests with empty values will be rejected with a /// <i>ValidationException</i> .</para> <para>You can request that <i>PutItem</i> return either a copy of the old item (before the update) or a /// copy of the new item (after the update). For more information, see the <i>ReturnValues</i> description.</para> <para><b>NOTE:</b> To prevent /// a new item from replacing an existing item, use a conditional put operation with Exists set to false for the primary key attribute, or /// attributes. </para> <para>For more information about using this API, see Working with Items in the <i>Amazon DynamoDB Developer Guide</i> /// .</para> /// </summary> /// <seealso cref="Amazon.DynamoDBv2.AmazonDynamoDB.PutItem"/> public class PutItemRequest : AmazonWebServiceRequest { private string tableName; private Dictionary<string,AttributeValue> item = new Dictionary<string,AttributeValue>(); private Dictionary<string,ExpectedAttributeValue> expected = new Dictionary<string,ExpectedAttributeValue>(); private string returnValues; private string returnConsumedCapacity; private string returnItemCollectionMetrics; /// <summary> /// The name of the table to contain the item. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>3 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[a-zA-Z0-9_.-]+</description> /// </item> /// </list> /// </para> /// </summary> public string TableName { get { return this.tableName; } set { this.tableName = value; } } /// <summary> /// Sets the TableName property /// </summary> /// <param name="tableName">The value to set for the TableName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutItemRequest WithTableName(string tableName) { this.tableName = tableName; return this; } // Check to see if TableName property is set internal bool IsSetTableName() { return this.tableName != null; } /// <summary> /// A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other /// attribute name-value pairs for the item. If you specify any attributes that are part of an index key, then the data types for those /// attributes must match those of the schema in the table's attribute definition. For more information about primary keys, see <a /// href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelPrimaryKey">Primary Key</a> in the <i>Amazon /// DynamoDB Developer Guide</i>. Each element in the <i>Item</i> map is an <i>AttributeValue</i> object. /// /// </summary> public Dictionary<string,AttributeValue> Item { get { return this.item; } set { this.item = value; } } /// <summary> /// Adds the KeyValuePairs to the Item dictionary. /// </summary> /// <param name="pairs">The pairs to be added to the Item dictionary.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutItemRequest WithItem(params KeyValuePair<string, AttributeValue>[] pairs) { foreach (KeyValuePair<string, AttributeValue> pair in pairs) { this.Item[pair.Key] = pair.Value; } return this; } // Check to see if Item property is set internal bool IsSetItem() { return this.item != null; } /// <summary> /// A map of attribute/condition pairs. This is the conditional block for the <i>PutItem</i> operation. All the conditions must be met for the /// operation to succeed. <i>Expected</i> allows you to provide an attribute name, and whether or not Amazon DynamoDB should check to see if the /// attribute value already exists; or if the attribute value exists and has a particular value before changing it. Each item in <i>Expected</i> /// represents an attribute name for Amazon DynamoDB to check, along with the following: <ul> <li> <i>Value</i> - The attribute value for Amazon /// DynamoDB to check. </li> <li> <i>Exists</i> - Causes Amazon DynamoDB to evaluate the value before attempting a conditional operation: <ul> /// <li> If <i>Exists</i> is <c>true</c>, Amazon DynamoDB will check to see if that attribute value already exists in the table. If it is found, /// then the operation succeeds. If it is not found, the operation fails with a <i>ConditionalCheckFailedException</i>. </li> <li> If /// <i>Exists</i> is <c>false</c>, Amazon DynamoDB assumes that the attribute value does <i>not</i> exist in the table. If in fact the value /// does not exist, then the assumption is valid and the operation succeeds. If the value is found, despite the assumption that it does not /// exist, the operation fails with a <i>ConditionalCheckFailedException</i>. </li> </ul> The default setting for <i>Exists</i> is <c>true</c>. /// If you supply a <i>Value</i> all by itself, Amazon DynamoDB assumes the attribute exists: You don't have to set <i>Exists</i> to /// <c>true</c>, because it is implied. Amazon DynamoDB returns a <i>ValidationException</i> if: <ul> <li> <i>Exists</i> is <c>true</c> but /// there is no <i>Value</i> to check. (You expect a value to exist, but don't specify what that value is.) </li> <li> <i>Exists</i> is /// <c>false</c> but you also specify a <i>Value</i>. (You cannot expect an attribute to have a value, while also expecting it not to exist.) /// </li> </ul> </li> </ul> If you specify more than one condition for <i>Exists</i>, then all of the conditions must evaluate to true. (In /// other words, the conditions are ANDed together.) Otherwise, the conditional operation will fail. /// /// </summary> public Dictionary<string,ExpectedAttributeValue> Expected { get { return this.expected; } set { this.expected = value; } } /// <summary> /// Adds the KeyValuePairs to the Expected dictionary. /// </summary> /// <param name="pairs">The pairs to be added to the Expected dictionary.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutItemRequest WithExpected(params KeyValuePair<string, ExpectedAttributeValue>[] pairs) { foreach (KeyValuePair<string, ExpectedAttributeValue> pair in pairs) { this.Expected[pair.Key] = pair.Value; } return this; } // Check to see if Expected property is set internal bool IsSetExpected() { return this.expected != null; } /// <summary> /// Use <i>ReturnValues</i> if you want to get the item attributes as they appeared before they were updated with the <i>PutItem</i> request. /// For <i>PutItem</i>, the valid values are: <ul> <li> <c>NONE</c> - If <i>ReturnValues</i> is not specified, or if its value is <c>NONE</c>, /// then nothing is returned. (This is the default for <i>ReturnValues</i>.) </li> <li> <c>ALL_OLD</c> - If <i>PutItem</i> overwrote an /// attribute name-value pair, then the content of the old item is returned. </li> </ul> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>NONE, ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATED_NEW</description> /// </item> /// </list> /// </para> /// </summary> public string ReturnValues { get { return this.returnValues; } set { this.returnValues = value; } } /// <summary> /// Sets the ReturnValues property /// </summary> /// <param name="returnValues">The value to set for the ReturnValues property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutItemRequest WithReturnValues(string returnValues) { this.returnValues = returnValues; return this; } // Check to see if ReturnValues property is set internal bool IsSetReturnValues() { return this.returnValues != null; } /// <summary> /// If set to <c>TOTAL</c>, <i>ConsumedCapacity</i> is included in the response; if set to <c>NONE</c> (the default), <i>ConsumedCapacity</i> is /// not included. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>TOTAL, NONE</description> /// </item> /// </list> /// </para> /// </summary> public string ReturnConsumedCapacity { get { return this.returnConsumedCapacity; } set { this.returnConsumedCapacity = value; } } /// <summary> /// Sets the ReturnConsumedCapacity property /// </summary> /// <param name="returnConsumedCapacity">The value to set for the ReturnConsumedCapacity property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutItemRequest WithReturnConsumedCapacity(string returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } // Check to see if ReturnConsumedCapacity property is set internal bool IsSetReturnConsumedCapacity() { return this.returnConsumedCapacity != null; } /// <summary> /// If set to <c>SIZE</c>, statistics about item collections, if any, that were modified during the operation are returned in the response. If /// set to <c>NONE</c> (the default), no statistics are returned.. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>SIZE, NONE</description> /// </item> /// </list> /// </para> /// </summary> public string ReturnItemCollectionMetrics { get { return this.returnItemCollectionMetrics; } set { this.returnItemCollectionMetrics = value; } } /// <summary> /// Sets the ReturnItemCollectionMetrics property /// </summary> /// <param name="returnItemCollectionMetrics">The value to set for the ReturnItemCollectionMetrics property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutItemRequest WithReturnItemCollectionMetrics(string returnItemCollectionMetrics) { this.returnItemCollectionMetrics = returnItemCollectionMetrics; return this; } // Check to see if ReturnItemCollectionMetrics property is set internal bool IsSetReturnItemCollectionMetrics() { return this.returnItemCollectionMetrics != null; } } }
#if WINDOWS #define USE_CUSTOM_SHADER #endif using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Math; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using FlatRedBall.Math.Geometry; using FlatRedBall.Performance.Measurement; namespace FlatRedBall.Graphics { #region Enums #region XML Docs /// <summary> /// Rendering modes available in FlatRedBall /// </summary> #endregion public enum RenderMode { #region XML Docs /// <summary> /// Default rendering mode (uses embedded effects in models) /// </summary> #endregion Default, #region XML Docs /// <summary> /// Color rendering mode - renders color values for a model /// (does not include lighting information) /// Effect technique: RenderColor /// </summary> #endregion Color, #region XML Docs /// <summary> /// Normals rendering mode - renders normals /// Effect technique: RenderNormals /// </summary> #endregion Normals, #region XML Docs /// <summary> /// Depth rendering mode - renders depth /// Effect technique: RenderDepth /// </summary> #endregion Depth, #region XML Docs /// <summary> /// Position rendering mode - renders position /// Effect technique: RenderPosition /// </summary> #endregion Position } #endregion static partial class Renderer { static IComparer<Sprite> mSpriteComparer; static IComparer<Text> mTextComparer; static IComparer<IDrawableBatch> mDrawableBatchComparer; #region XML Docs /// <summary> /// Gets the default Camera (SpriteManager.Camera) /// </summary> #endregion static public Camera Camera { get { return SpriteManager.Camera; } } #region XML Docs /// <summary> /// Gets the list of cameras (SpriteManager.Cameras) /// </summary> #endregion static public PositionedObjectList<Camera> Cameras { get { return SpriteManager.Cameras; } } public static IComparer<Sprite> SpriteComparer { get { return mSpriteComparer; } set { mSpriteComparer = value; } } public static IComparer<Text> TextComparer { get { return mTextComparer; } set { mTextComparer = value; } } public static IComparer<IDrawableBatch> DrawableBatchComparer { get { return mDrawableBatchComparer; } set { mDrawableBatchComparer = value; } } private static void DrawIndividualLayer(Camera camera, RenderMode renderMode, Layer layer, Section section, ref RenderTarget2D lastRenderTarget) { bool hasLayerModifiedCamera = false; if (layer.Visible) { Renderer.CurrentLayer = layer; if (section != null) { string layerName = "No Layer"; if(layer != null) { layerName = layer.Name; } Section.GetAndStartContextAndTime("Layer: " + layerName); } bool didSetRenderTarget = layer.RenderTarget != lastRenderTarget; if(didSetRenderTarget) { lastRenderTarget = layer.RenderTarget; GraphicsDevice.SetRenderTarget(layer.RenderTarget); if(layer.RenderTarget != null) { mGraphics.GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 1, 0); } } // No need to clear depth buffer if it's a render target if(!didSetRenderTarget) { ClearBackgroundForLayer(camera); } #region Set View and Projection // Store the camera's FieldOfView in the oldFieldOfView and // set the camera's FieldOfView to the layer's OverridingFieldOfView // if necessary. mOldCameraLayerSettings.SetFromCamera(camera); Vector3 oldPosition = camera.Position; var oldUpVector = camera.UpVector; if (layer.LayerCameraSettings != null) { layer.LayerCameraSettings.ApplyValuesToCamera(camera, SetCameraOptions.PerformZRotation, null, layer.RenderTarget); hasLayerModifiedCamera = true; } camera.SetDeviceViewAndProjection(mCurrentEffect, layer.RelativeToCamera); #endregion if (renderMode == RenderMode.Default) { if (layer.mZBufferedSprites.Count > 0) { DrawZBufferedSprites(camera, layer.mZBufferedSprites); } // Draw the camera's layer DrawMixed(layer.mSprites, layer.mSortType, layer.mTexts, layer.mBatches, layer.RelativeToCamera, camera, section); #region Draw Shapes DrawShapes(camera, layer.mSpheres, layer.mCubes, layer.mRectangles, layer.mCircles, layer.mPolygons, layer.mLines, layer.mCapsule2Ds, layer); #endregion } // Set the Camera's FieldOfView back // Vic asks: What if the user wants to have a wacky field of view? // Does that mean that this will regulate it on layers? This is something // that may need to be fixed in the future, but it seems rare and will bloat // the visible property list considerably. Let's leave it like this for now // to establish a pattern then if the time comes to change this we'll be comfortable // with the overriding field of view pattern so a better decision can be made. if (hasLayerModifiedCamera) { // use the render target here, because it may not have been unset yet. mOldCameraLayerSettings.ApplyValuesToCamera(camera, SetCameraOptions.ApplyMatrix, layer.LayerCameraSettings, layer.RenderTarget); camera.Position = oldPosition; camera.UpVector = oldUpVector; } if (section != null) { Section.EndContextAndTime(); } } } static List<Sprite> mVisibleSprites = new List<Sprite>(); static List<Text> mVisibleTexts = new List<Text>(); private static void DrawMixed(SpriteList spriteListUnfiltered, SortType sortType, PositionedObjectList<Text> textListUnfiltered, List<IDrawableBatch> batches, bool relativeToCamera, Camera camera, Section section) { if (section != null) { Section.GetAndStartContextAndTime("Start of Draw Mixed"); } DrawMixedStart(camera); int spriteIndex = 0; int textIndex = 0; int batchIndex = 0; // The sort values can represent different // things depending on the sortType argument. // They can either represent pure Z values or they // can represent distance from the camera (squared). // The problem is that a larger Z means closer to the // camera, but a larger distance means further from the // camera. Therefore, to fix this problem if these values // represent distance from camera, they will be multiplied by // negative 1. float nextSpriteSortValue = float.PositiveInfinity; float nextTextSortValue = float.PositiveInfinity; float nextBatchSortValue = float.PositiveInfinity; if (section != null) { Section.EndContextAndTime(); Section.GetAndStartContextAndTime("Sort Lists"); } SortAllLists(spriteListUnfiltered, sortType, textListUnfiltered, batches, relativeToCamera, camera); mVisibleSprites.Clear(); mVisibleTexts.Clear(); for (int i = 0; i < spriteListUnfiltered.Count; i++) { Sprite sprite = spriteListUnfiltered[i]; bool isVisible = sprite.AbsoluteVisible && (sprite.ColorOperation == ColorOperation.InterpolateColor || sprite.Alpha > .0001) && camera.IsSpriteInView(sprite, relativeToCamera); if (isVisible) { mVisibleSprites.Add(sprite); } } for (int i = 0; i < textListUnfiltered.Count; i++) { Text text = textListUnfiltered[i]; if (text.AbsoluteVisible && text.Alpha > .0001 && camera.IsTextInView(text, relativeToCamera)) { mVisibleTexts.Add(text); } } int indexOfNextSpriteToReposition = 0; GetNextZValuesByCategory(mVisibleSprites, sortType, mVisibleTexts, batches, camera, ref spriteIndex, ref textIndex, ref nextSpriteSortValue, ref nextTextSortValue, ref nextBatchSortValue); int numberToDraw = 0; // This is used as a temporary variable for Z or distance from camera float sortingValue = 0; Section performDrawingSection = null; if (section != null) { Section.EndContextAndTime(); performDrawingSection = Section.GetAndStartContextAndTime("Perform Drawing"); } while (spriteIndex < mVisibleSprites.Count || textIndex < mVisibleTexts.Count || (batches != null && batchIndex < batches.Count)) { #region only 1 array remains to be drawn so finish it off completely #region Draw Texts if (spriteIndex >= mVisibleSprites.Count && (batches == null || batchIndex >= batches.Count) && textIndex < mVisibleTexts.Count) { if (section != null) { if (Section.Context != performDrawingSection) { Section.EndContextAndTime(); } Section.GetAndStartMergedContextAndTime("Draw Texts"); } if (sortType == SortType.DistanceAlongForwardVector) { int temporaryCount = mVisibleTexts.Count; for (int i = textIndex; i < temporaryCount; i++) { mVisibleTexts[i].Position = mVisibleTexts[i].mOldPosition; } } // TEXTS: draw all texts from textIndex to numberOfVisibleTexts - textIndex DrawTexts(mVisibleTexts, textIndex, mVisibleTexts.Count - textIndex, camera, section); break; } #endregion #region Draw Sprites else if (textIndex >= mVisibleTexts.Count && (batches == null || batchIndex >= batches.Count) && spriteIndex < mVisibleSprites.Count) { if (section != null) { if (Section.Context != performDrawingSection) { Section.EndContextAndTime(); } Section.GetAndStartMergedContextAndTime("Draw Sprites"); } numberToDraw = mVisibleSprites.Count - spriteIndex; if (sortType == SortType.DistanceAlongForwardVector) { int temporaryCount = mVisibleSprites.Count; for (int i = indexOfNextSpriteToReposition; i < temporaryCount; i++) { mVisibleSprites[i].Position = mVisibleSprites[i].mOldPosition; indexOfNextSpriteToReposition++; } } PrepareSprites( mSpriteVertices, mSpriteRenderBreaks, mVisibleSprites, spriteIndex, numberToDraw ); DrawSprites( mSpriteVertices, mSpriteRenderBreaks, mVisibleSprites, spriteIndex, numberToDraw, camera); break; } #endregion #region Draw DrawableBatches else if (spriteIndex >= mVisibleSprites.Count && textIndex >= mVisibleTexts.Count && batches != null && batchIndex < batches.Count) { if (section != null) { if (Section.Context != performDrawingSection) { Section.EndContextAndTime(); } Section.GetAndStartMergedContextAndTime("Draw IDrawableBatches"); } // DRAWABLE BATCHES: Only DrawableBatches remain so draw them all. while (batchIndex < batches.Count) { IDrawableBatch batchAtIndex = batches[batchIndex]; if (batchAtIndex.UpdateEveryFrame) { batchAtIndex.Update(); } if (Renderer.RecordRenderBreaks) { // Even though we aren't using a RenderBreak here, we should record a render break // for this batch as it does cause rendering to be interrupted: RenderBreak renderBreak = new RenderBreak(); #if DEBUG renderBreak.ObjectCausingBreak = batchAtIndex; #endif renderBreak.LayerName = CurrentLayerName; LastFrameRenderBreakList.Add(renderBreak); } batchAtIndex.Draw(camera); batchIndex++; } FixRenderStatesAfterBatchDraw(); break; } #endregion #endregion #region more than 1 list remains so find which group of objects to render #region Sprites else if (nextSpriteSortValue <= nextTextSortValue && nextSpriteSortValue <= nextBatchSortValue && spriteIndex < mVisibleSprites.Count) { if (section != null) { if (Section.Context != performDrawingSection) { Section.EndContextAndTime(); } Section.GetAndStartMergedContextAndTime("Draw Sprites"); } // The next furthest object is a Sprite. Find how many to draw. #region Count how many Sprites to draw and store it in numberToDraw numberToDraw = 0; if (sortType == SortType.Z || sortType == SortType.DistanceAlongForwardVector) sortingValue = mVisibleSprites[spriteIndex + numberToDraw].Position.Z; else sortingValue = -(camera.Position - mVisibleSprites[spriteIndex + numberToDraw].Position).LengthSquared(); while (sortingValue <= nextTextSortValue && sortingValue <= nextBatchSortValue) { numberToDraw++; if (spriteIndex + numberToDraw == mVisibleSprites.Count) { break; } if (sortType == SortType.Z || sortType == SortType.DistanceAlongForwardVector) sortingValue = mVisibleSprites[spriteIndex + numberToDraw].Position.Z; else sortingValue = -(camera.Position - mVisibleSprites[spriteIndex + numberToDraw].Position).LengthSquared(); } #endregion if (sortType == SortType.DistanceAlongForwardVector) { for (int i = indexOfNextSpriteToReposition; i < numberToDraw + spriteIndex; i++) { mVisibleSprites[i].Position = mVisibleSprites[i].mOldPosition; indexOfNextSpriteToReposition++; } } PrepareSprites( mSpriteVertices, mSpriteRenderBreaks, mVisibleSprites, spriteIndex, numberToDraw); DrawSprites( mSpriteVertices, mSpriteRenderBreaks, mVisibleSprites, spriteIndex, numberToDraw, camera); // numberToDraw represents a range so increase spriteIndex by that amount. spriteIndex += numberToDraw; if (spriteIndex >= mVisibleSprites.Count) { nextSpriteSortValue = float.PositiveInfinity; } else { if (sortType == SortType.Z || sortType == SortType.DistanceAlongForwardVector || sortType == SortType.ZSecondaryParentY) nextSpriteSortValue = mVisibleSprites[spriteIndex].Position.Z; else nextSpriteSortValue = -(camera.Position - mVisibleSprites[spriteIndex].Position).LengthSquared(); } } #endregion #region Texts else if (nextTextSortValue <= nextSpriteSortValue && nextTextSortValue <= nextBatchSortValue)// draw texts { if (section != null) { if (Section.Context != performDrawingSection) { Section.EndContextAndTime(); } Section.GetAndStartMergedContextAndTime("Draw Texts"); } numberToDraw = 0; if (sortType == SortType.Z || sortType == SortType.DistanceAlongForwardVector) sortingValue = mVisibleTexts[textIndex + numberToDraw].Position.Z; else sortingValue = -(camera.Position - mVisibleTexts[textIndex + numberToDraw].Position).LengthSquared(); while (sortingValue <= nextSpriteSortValue && sortingValue <= nextBatchSortValue) { numberToDraw++; if (textIndex + numberToDraw == mVisibleTexts.Count) { break; } if (sortType == SortType.Z || sortType == SortType.DistanceAlongForwardVector) sortingValue = mVisibleTexts[textIndex + numberToDraw].Position.Z; else sortingValue = -(camera.Position - mVisibleTexts[textIndex + numberToDraw].Position).LengthSquared(); } if (sortType == SortType.DistanceAlongForwardVector) { for (int i = textIndex; i < textIndex + numberToDraw; i++) { mVisibleTexts[i].Position = mVisibleTexts[i].mOldPosition; } } DrawTexts(mVisibleTexts, textIndex, numberToDraw, camera, section); textIndex += numberToDraw; if (textIndex == mVisibleTexts.Count) nextTextSortValue = float.PositiveInfinity; else { if (sortType == SortType.Z || sortType == SortType.DistanceAlongForwardVector || sortType == SortType.ZSecondaryParentY) nextTextSortValue = mVisibleTexts[textIndex].Position.Z; else nextTextSortValue = -(camera.Position - mVisibleTexts[textIndex].Position).LengthSquared(); } } #endregion #region Batches else if (nextBatchSortValue <= nextSpriteSortValue && nextBatchSortValue <= nextTextSortValue) { if (section != null) { if (Section.Context != performDrawingSection) { Section.EndContextAndTime(); } Section.GetAndStartMergedContextAndTime("Draw IDrawableBatches"); } while (nextBatchSortValue <= nextSpriteSortValue && nextBatchSortValue <= nextTextSortValue && batchIndex < batches.Count) { IDrawableBatch batchAtIndex = batches[batchIndex]; if (batchAtIndex.UpdateEveryFrame) { batchAtIndex.Update(); } if(Renderer.RecordRenderBreaks) { // Even though we aren't using a RenderBreak here, we should record a render break // for this batch as it does cause rendering to be interrupted: RenderBreak renderBreak = new RenderBreak(); #if DEBUG renderBreak.ObjectCausingBreak = batchAtIndex; #endif renderBreak.LayerName = CurrentLayerName; LastFrameRenderBreakList.Add(renderBreak); } batchAtIndex.Draw(camera); batchIndex++; if (batchIndex == batches.Count) { nextBatchSortValue = float.PositiveInfinity; } else { batchAtIndex = batches[batchIndex]; if (sortType == SortType.Z || sortType == SortType.ZSecondaryParentY) { nextBatchSortValue = batchAtIndex.Z; } else if (sortType == SortType.DistanceAlongForwardVector) { Vector3 vectorDifference = new Vector3( batchAtIndex.X - camera.X, batchAtIndex.Y - camera.Y, batchAtIndex.Z - camera.Z); float firstDistance; Vector3 forwardVector = camera.RotationMatrix.Forward; Vector3.Dot(ref vectorDifference, ref forwardVector, out firstDistance); nextBatchSortValue = -firstDistance; } else { nextBatchSortValue = -(batchAtIndex.Z * batchAtIndex.Z); } } } FixRenderStatesAfterBatchDraw(); } #endregion #endregion } if (section != null) { // Hop up a level if (Section.Context != performDrawingSection) { Section.EndContextAndTime(); } Section.EndContextAndTime(); Section.GetAndStartContextAndTime("End of Draw Mixed"); } // return the position of any objects not drawn if (sortType == SortType.DistanceAlongForwardVector) { for (int i = indexOfNextSpriteToReposition; i < mVisibleSprites.Count; i++) { mVisibleSprites[i].Position = mVisibleSprites[i].mOldPosition; } } Renderer.Texture = null; Renderer.TextureOnDevice = null; if (section != null) { Section.EndContextAndTime(); } } private static void FixRenderStatesAfterBatchDraw() { // do nothing with alpha? FlatRedBallServices.GraphicsDevice.RasterizerState = RasterizerState.CullNone; // reset the texture filter: FlatRedBallServices.GraphicsOptions.TextureFilter = FlatRedBallServices.GraphicsOptions.TextureFilter; ForceSetBlendOperation(); SetCurrentEffect(Effect, SpriteManager.Camera); } private static void GetNextZValuesByCategory(List<Sprite> spriteList, SortType sortType, List<Text> textList, List<IDrawableBatch> batches, Camera camera, ref int spriteIndex, ref int textIndex, ref float nextSpriteSortValue, ref float nextTextSortValue, ref float nextBatchSortValue) { #region find out the initial Z values of the 3 categories of objects to know which to render first if (sortType == SortType.Z || sortType == SortType.DistanceAlongForwardVector || sortType == SortType.ZSecondaryParentY) { lock (spriteList) { int spriteNumber = 0; while (spriteNumber < spriteList.Count) { nextSpriteSortValue = spriteList[spriteNumber].Z; spriteIndex = spriteNumber; break; } } if (textList != null && textList.Count != 0) nextTextSortValue = textList[0].Position.Z; else if (textList != null) textIndex = textList.Count; if (batches != null && batches.Count != 0) { if (sortType == SortType.Z || sortType == SortType.ZSecondaryParentY) { // The Z value of the current batch is used. Batches are always visible // to this code. nextBatchSortValue = batches[0].Z; } else { Vector3 vectorDifference = new Vector3( batches[0].X - camera.X, batches[0].Y - camera.Y, batches[0].Z - camera.Z); float firstDistance; Vector3 forwardVector = camera.RotationMatrix.Forward; Vector3.Dot(ref vectorDifference, ref forwardVector, out firstDistance); nextBatchSortValue = -firstDistance; } } } else if (sortType == SortType.Texture) { throw new Exception("Sorting based on texture is not supported on non z-buffered Sprites"); } else if (sortType == SortType.DistanceFromCamera) { // code duplication to prevent tight-loop if statements lock (spriteList) { int spriteNumber = 0; while (spriteNumber < spriteList.Count) { nextSpriteSortValue = -(camera.Position - spriteList[spriteNumber].Position).LengthSquared(); spriteIndex = spriteNumber; break; } } if (textList != null && textList.Count != 0) { nextTextSortValue = -(camera.Position - textList[0].Position).LengthSquared(); } else if (textList != null) { textIndex = textList.Count; } // The Z value of the current batch is used. Batches are always visible // to this code. if (batches != null && batches.Count != 0) { // workign with squared length, so use that here nextBatchSortValue = -(batches[0].Z * batches[0].Z); } } #endregion } private static void SortAllLists(SpriteList spriteList, SortType sortType, PositionedObjectList<Text> textList, List<IDrawableBatch> batches, bool relativeToCamera, Camera camera) { StoreOldPositionsForDistanceAlongForwardVectorSort(spriteList, sortType, textList, batches, camera); #region Sort the SpriteList and get the number of visible Sprites in numberOfVisibleSprites if (spriteList != null && spriteList.Count != 0) { lock (spriteList) { switch (sortType) { case SortType.Z: case SortType.DistanceAlongForwardVector: // Sorting ascending means everything will be drawn back to front. This // is slower but necessary for translucent objects. // Sorting descending means everything will be drawn back to front. This // is faster but will cause problems for translucency. spriteList.SortZInsertionAscending(); break; case SortType.DistanceFromCamera: spriteList.SortCameraDistanceInsersionDescending(camera); break; case SortType.ZSecondaryParentY: spriteList.SortZInsertionAscending(); spriteList.SortParentYInsertionDescendingOnZBreaks(); break; case SortType.CustomComparer: if (mSpriteComparer != null) { spriteList.Sort(mSpriteComparer); } else { spriteList.SortZInsertionAscending(); } break; case SortType.None: // This will improve render times slightly...maybe? spriteList.SortTextureInsertion(); break; default: break; } } } #endregion #region Sort the TextList if (textList != null && textList.Count != 0) { switch (sortType) { case SortType.Z: case SortType.DistanceAlongForwardVector: textList.SortZInsertionAscending(); break; case SortType.DistanceFromCamera: textList.SortCameraDistanceInsersionDescending(camera); break; case SortType.CustomComparer: if (mTextComparer != null) { textList.Sort(mTextComparer); } else { textList.SortZInsertionAscending(); } break; default: break; } } #endregion #region Sort the Batches if (batches != null && batches.Count != 0) { switch (sortType) { case SortType.Z: // Z serves as the radius if using SortType.DistanceFromCamera. // If Z represents actual Z or radius, the larger the value the further // away from the camera the object will be. SortBatchesZInsertionAscending(batches); break; case SortType.DistanceAlongForwardVector: batches.Sort(new FlatRedBall.Graphics.BatchForwardVectorSorter(camera)); break; case SortType.ZSecondaryParentY: SortBatchesZInsertionAscending(batches); // Even though the sort type is by parent, IDB doesn't have a Parent object, so we'll just rely on Y. // May need to revisit this if it causes problems SortBatchesYInsertionDescendingOnZBreaks(batches); break; case SortType.CustomComparer: if (mDrawableBatchComparer != null) { batches.Sort(mDrawableBatchComparer); } else { SortBatchesZInsertionAscending(batches); } break; } } #endregion } static List<int> batchZBreaks = new List<int>(10); private static void SortBatchesYInsertionDescendingOnZBreaks(List<IDrawableBatch> batches) { GetBatchZBreaks(batches, batchZBreaks); batchZBreaks.Insert(0, 0); batchZBreaks.Add(batches.Count); for (int i = 0; i < batchZBreaks.Count - 1; i++) { SortBatchInsertionDescending(batches, batchZBreaks[i], batchZBreaks[i + 1]); } } private static void SortBatchInsertionDescending(List<IDrawableBatch> batches, int firstObject, int lastObjectExclusive) { int whereObjectBelongs; float yAtI; float yAtIMinusOne; for (int i = firstObject + 1; i < lastObjectExclusive; i++) { yAtI = batches[i].Y; yAtIMinusOne = batches[i - 1].Y; if (yAtI > yAtIMinusOne) { if (i == firstObject + 1) { batches.Insert(firstObject, batches[i]); batches.RemoveAt(i + 1); continue; } for (whereObjectBelongs = i - 2; whereObjectBelongs > firstObject - 1; whereObjectBelongs--) { if (yAtI <= (batches[whereObjectBelongs]).Y) { batches.Insert(whereObjectBelongs + 1, batches[i]); batches.RemoveAt(i + 1); break; } else if (whereObjectBelongs == firstObject && yAtI > (batches[firstObject]).Y) { batches.Insert(firstObject, batches[i]); batches.RemoveAt(i + 1); break; } } } } } private static void GetBatchZBreaks(List<IDrawableBatch> batches, List<int> zBreaks) { zBreaks.Clear(); if (batches.Count == 0 || batches.Count == 1) return; for (int i = 1; i < batches.Count; i++) { if (batches[i].Z != batches[i - 1].Z) zBreaks.Add(i); } } static LayerCameraSettings mOldCameraLayerSettings = new LayerCameraSettings(); private static void DrawLayers(Camera camera, RenderMode renderMode, Section section) { //TimeManager.SumTimeSection("Set device settings"); RenderTarget2D lastRenderTarget = null; #region Draw World Layers // Draw layers that belong to the World "SpriteEditor" if (camera.DrawsWorld) { // These layers are still considered in the "world" because all // Cameras can see them. for (int i = 0; i < SpriteManager.LayersWriteable.Count; i++) { Layer layer = SpriteManager.LayersWriteable[i]; DrawIndividualLayer(camera, renderMode, layer, section, ref lastRenderTarget); } } #endregion //TimeManager.SumTimeSection("Draw World Layers"); #region Draw Camera Layers if (camera.DrawsCameraLayer) { int layerCount = camera.Layers.Count; for (int i = 0; i < layerCount; i++) { Layer layer = camera.Layers[i]; DrawIndividualLayer(camera, renderMode, layer, section, ref lastRenderTarget); } } #endregion //TimeManager.SumTimeSection("Draw Camera Layers"); #region Last, draw the top layer if (camera.DrawsWorld && !SpriteManager.TopLayer.IsEmpty) { Layer layer = SpriteManager.TopLayer; DrawIndividualLayer(camera, renderMode, layer, section, ref lastRenderTarget); } #endregion if(lastRenderTarget != null) { mGraphics.GraphicsDevice.SetRenderTarget(null); } //TimeManager.SumTimeSection("Last, draw the top layer"); } private static void DrawUnlayeredObjects(Camera camera, RenderMode renderMode, Section section) { CurrentLayer = null; if (section != null) { Section.GetAndStartContextAndTime("Draw above shapes"); } #region Draw Shapes if UnderEverything if (camera.DrawsWorld && renderMode == RenderMode.Default && camera.DrawsShapes && ShapeManager.ShapeDrawingOrder == FlatRedBall.Math.Geometry.ShapeDrawingOrder.UnderEverything) { // Draw shapes DrawShapes( camera, ShapeManager.mSpheres, ShapeManager.mCubes, ShapeManager.mRectangles, ShapeManager.mCircles, ShapeManager.mPolygons, ShapeManager.mLines, ShapeManager.mCapsule2Ds, null ); } #endregion //TimeManager.SumTimeSection("Draw models"); #region Draw ZBuffered Sprites and Mixed // Only draw the rest if in default rendering mode if (renderMode == RenderMode.Default) { if (camera.DrawsWorld) { if (section != null) { Section.EndContextAndTime(); Section.GetAndStartContextAndTime("Draw Z Buffered Sprites"); } if (SpriteManager.ZBufferedSpritesWriteable.Count != 0) { #if !USE_CUSTOM_SHADER // Note, this means that we can't use the "Color" color operation. // For PC we do clip() in the shader. We can't do that on WP7 so we use an alpha test effect SetCurrentEffect(mAlphaTestEffect, camera); #endif // Draw the Z Buffered Sprites DrawZBufferedSprites(camera, SpriteManager.ZBufferedSpritesWriteable); #if !USE_CUSTOM_SHADER SetCurrentEffect(mEffect, camera); #endif } foreach (var drawableBatch in SpriteManager.mZBufferedDrawableBatches) { if (drawableBatch.UpdateEveryFrame) { drawableBatch.Update(); } drawableBatch.Draw(camera); } if (section != null) { Section.EndContextAndTime(); Section.GetAndStartContextAndTime("Draw Ordered objects"); } // Draw the OrderedByDistanceFromCamera Objects (Sprites, Texts, DrawableBatches) DrawOrderedByDistanceFromCamera(camera, section); } } #endregion if (section != null) { Section.EndContextAndTime(); Section.GetAndStartContextAndTime("Draw below shapes"); } #region Draw Shapes if OverEverything if (camera.DrawsWorld && renderMode == RenderMode.Default && camera.DrawsShapes && ShapeManager.ShapeDrawingOrder == ShapeDrawingOrder.OverEverything) { // Draw shapes DrawShapes( camera, ShapeManager.mSpheres, ShapeManager.mCubes, ShapeManager.mRectangles, ShapeManager.mCircles, ShapeManager.mPolygons, ShapeManager.mLines, ShapeManager.mCapsule2Ds, null ); } #endregion //TimeManager.SumTimeSection("Draw ZBuffered and Mixed"); if (section != null) { Section.EndContextAndTime(); } } public static void DrawCamera(Camera camera, Section section) { DrawCamera(camera, RenderMode.Default, section); } static void DrawCamera(Camera camera, RenderMode renderMode, Section section) { if (section != null) { Section.GetAndStartContextAndTime("Start of camera draw"); } PrepareForDrawScene(camera, renderMode); if (section != null) { Section.EndContextAndTime(); Section.GetAndStartContextAndTime("Draw UnderAllLayer"); } if (camera.DrawsWorld && !SpriteManager.UnderAllDrawnLayer.IsEmpty) { Layer layer = SpriteManager.UnderAllDrawnLayer; RenderTarget2D lastRenderTarget = null; DrawIndividualLayer(camera, RenderMode.Default, layer, section, ref lastRenderTarget); if(lastRenderTarget != null) { GraphicsDevice.SetRenderTarget(null); } } if (section != null) { Section.EndContextAndTime(); Section.GetAndStartContextAndTime("Draw Unlayered"); } DrawUnlayeredObjects(camera, renderMode, section); // Draw layers - this method will check internally for the camera's DrawsWorld and DrawsCameraLayers properties if (section != null) { Section.EndContextAndTime(); Section.GetAndStartContextAndTime("Draw Regular Layers"); } DrawLayers(camera, renderMode, section); if (section != null) { Section.EndContextAndTime(); } } private static void StoreOldPositionsForDistanceAlongForwardVectorSort(PositionedObjectList<Sprite> spriteList, SortType sortType, PositionedObjectList<Text> textList, List<IDrawableBatch> batches, Camera camera) { #region If DistanceAlongForwardVector store old values // If the objects are using SortType.DistanceAlongForwardVector // then store the old positions, then rotate the objects by the matrix that // moves the forward vector to the Z = -1 vector (the camera's inverse rotation // matrix) if (sortType == SortType.DistanceAlongForwardVector) { Matrix inverseRotationMatrix = camera.RotationMatrix; Matrix.Invert(ref inverseRotationMatrix, out inverseRotationMatrix); int temporaryCount = spriteList.Count; for (int i = 0; i < temporaryCount; i++) { spriteList[i].mOldPosition = spriteList[i].Position; spriteList[i].Position -= camera.Position; Vector3.Transform(ref spriteList[i].Position, ref inverseRotationMatrix, out spriteList[i].Position); } temporaryCount = textList.Count; for (int i = 0; i < temporaryCount; i++) { textList[i].mOldPosition = textList[i].Position; textList[i].Position -= camera.Position; Vector3.Transform(ref textList[i].Position, ref inverseRotationMatrix, out textList[i].Position); } temporaryCount = batches.Count; for (int i = 0; i < temporaryCount; i++) { } } #endregion } private static void DrawOrderedByDistanceFromCamera(Camera camera, Section section) { if (SpriteManager.OrderedByDistanceFromCameraSprites.Count != 0 || SpriteManager.WritableDrawableBatchesList.Count != 0 || TextManager.mDrawnTexts.Count != 0) { Renderer.CurrentLayer = null; // Draw DrawMixed( SpriteManager.OrderedByDistanceFromCameraSprites, SpriteManager.OrderedSortType, TextManager.mDrawnTexts, SpriteManager.WritableDrawableBatchesList, false, camera, section); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.ContentElement.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows { public partial class ContentElement : DependencyObject, IInputElement, System.Windows.Media.Animation.IAnimatable { #region Methods and constructors public void AddHandler(RoutedEvent routedEvent, Delegate handler, bool handledEventsToo) { } public void AddHandler(RoutedEvent routedEvent, Delegate handler) { } public void AddToEventRoute(EventRoute route, RoutedEventArgs e) { } public void ApplyAnimationClock(DependencyProperty dp, System.Windows.Media.Animation.AnimationClock clock) { } public void ApplyAnimationClock(DependencyProperty dp, System.Windows.Media.Animation.AnimationClock clock, System.Windows.Media.Animation.HandoffBehavior handoffBehavior) { } public void BeginAnimation(DependencyProperty dp, System.Windows.Media.Animation.AnimationTimeline animation, System.Windows.Media.Animation.HandoffBehavior handoffBehavior) { } public void BeginAnimation(DependencyProperty dp, System.Windows.Media.Animation.AnimationTimeline animation) { } public bool CaptureMouse() { return default(bool); } public bool CaptureStylus() { return default(bool); } public bool CaptureTouch(System.Windows.Input.TouchDevice touchDevice) { return default(bool); } public ContentElement() { } public bool Focus() { return default(bool); } public Object GetAnimationBaseValue(DependencyProperty dp) { return default(Object); } protected internal virtual new DependencyObject GetUIParentCore() { return default(DependencyObject); } public virtual new bool MoveFocus(System.Windows.Input.TraversalRequest request) { return default(bool); } protected virtual new System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected internal virtual new void OnDragEnter(DragEventArgs e) { } protected internal virtual new void OnDragLeave(DragEventArgs e) { } protected internal virtual new void OnDragOver(DragEventArgs e) { } protected internal virtual new void OnDrop(DragEventArgs e) { } protected internal virtual new void OnGiveFeedback(GiveFeedbackEventArgs e) { } protected virtual new void OnGotFocus(RoutedEventArgs e) { } protected internal virtual new void OnGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { } protected internal virtual new void OnGotMouseCapture(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnGotStylusCapture(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnGotTouchCapture(System.Windows.Input.TouchEventArgs e) { } protected virtual new void OnIsKeyboardFocusedChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsMouseCapturedChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsMouseCaptureWithinChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsMouseDirectlyOverChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsStylusCapturedChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsStylusCaptureWithinChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsStylusDirectlyOverChanged(DependencyPropertyChangedEventArgs e) { } protected internal virtual new void OnKeyDown(System.Windows.Input.KeyEventArgs e) { } protected internal virtual new void OnKeyUp(System.Windows.Input.KeyEventArgs e) { } protected virtual new void OnLostFocus(RoutedEventArgs e) { } protected internal virtual new void OnLostKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { } protected internal virtual new void OnLostMouseCapture(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnLostStylusCapture(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnLostTouchCapture(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnMouseDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseEnter(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnMouseLeave(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseMove(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseRightButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseWheel(System.Windows.Input.MouseWheelEventArgs e) { } protected internal virtual new void OnPreviewDragEnter(DragEventArgs e) { } protected internal virtual new void OnPreviewDragLeave(DragEventArgs e) { } protected internal virtual new void OnPreviewDragOver(DragEventArgs e) { } protected internal virtual new void OnPreviewDrop(DragEventArgs e) { } protected internal virtual new void OnPreviewGiveFeedback(GiveFeedbackEventArgs e) { } protected internal virtual new void OnPreviewGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { } protected internal virtual new void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e) { } protected internal virtual new void OnPreviewKeyUp(System.Windows.Input.KeyEventArgs e) { } protected internal virtual new void OnPreviewLostKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { } protected internal virtual new void OnPreviewMouseDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseMove(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnPreviewMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseRightButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseWheel(System.Windows.Input.MouseWheelEventArgs e) { } protected internal virtual new void OnPreviewQueryContinueDrag(QueryContinueDragEventArgs e) { } protected internal virtual new void OnPreviewStylusButtonDown(System.Windows.Input.StylusButtonEventArgs e) { } protected internal virtual new void OnPreviewStylusButtonUp(System.Windows.Input.StylusButtonEventArgs e) { } protected internal virtual new void OnPreviewStylusDown(System.Windows.Input.StylusDownEventArgs e) { } protected internal virtual new void OnPreviewStylusInAirMove(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewStylusInRange(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewStylusMove(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewStylusOutOfRange(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewStylusSystemGesture(System.Windows.Input.StylusSystemGestureEventArgs e) { } protected internal virtual new void OnPreviewStylusUp(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { } protected internal virtual new void OnPreviewTouchDown(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnPreviewTouchMove(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnPreviewTouchUp(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnQueryContinueDrag(QueryContinueDragEventArgs e) { } protected internal virtual new void OnQueryCursor(System.Windows.Input.QueryCursorEventArgs e) { } protected internal virtual new void OnStylusButtonDown(System.Windows.Input.StylusButtonEventArgs e) { } protected internal virtual new void OnStylusButtonUp(System.Windows.Input.StylusButtonEventArgs e) { } protected internal virtual new void OnStylusDown(System.Windows.Input.StylusDownEventArgs e) { } protected internal virtual new void OnStylusEnter(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusInAirMove(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusInRange(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusLeave(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusMove(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusOutOfRange(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusSystemGesture(System.Windows.Input.StylusSystemGestureEventArgs e) { } protected internal virtual new void OnStylusUp(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnTextInput(System.Windows.Input.TextCompositionEventArgs e) { } protected internal virtual new void OnTouchDown(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnTouchEnter(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnTouchLeave(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnTouchMove(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnTouchUp(System.Windows.Input.TouchEventArgs e) { } public virtual new DependencyObject PredictFocus(System.Windows.Input.FocusNavigationDirection direction) { return default(DependencyObject); } public void RaiseEvent(RoutedEventArgs e) { } public void ReleaseAllTouchCaptures() { } public void ReleaseMouseCapture() { } public void ReleaseStylusCapture() { } public bool ReleaseTouchCapture(System.Windows.Input.TouchDevice touchDevice) { return default(bool); } public void RemoveHandler(RoutedEvent routedEvent, Delegate handler) { } public bool ShouldSerializeCommandBindings() { return default(bool); } public bool ShouldSerializeInputBindings() { return default(bool); } #endregion #region Properties and indexers public bool AllowDrop { get { return default(bool); } set { } } public bool AreAnyTouchesCaptured { get { return default(bool); } } public bool AreAnyTouchesCapturedWithin { get { return default(bool); } } public bool AreAnyTouchesDirectlyOver { get { return default(bool); } } public bool AreAnyTouchesOver { get { return default(bool); } } public System.Windows.Input.CommandBindingCollection CommandBindings { get { return default(System.Windows.Input.CommandBindingCollection); } } public bool Focusable { get { return default(bool); } set { } } public bool HasAnimatedProperties { get { return default(bool); } } public System.Windows.Input.InputBindingCollection InputBindings { get { return default(System.Windows.Input.InputBindingCollection); } } public bool IsEnabled { get { return default(bool); } set { } } protected virtual new bool IsEnabledCore { get { return default(bool); } } public bool IsFocused { get { return default(bool); } } public bool IsInputMethodEnabled { get { return default(bool); } } public bool IsKeyboardFocused { get { return default(bool); } } public bool IsKeyboardFocusWithin { get { return default(bool); } } public bool IsMouseCaptured { get { return default(bool); } } public bool IsMouseCaptureWithin { get { return default(bool); } } public bool IsMouseDirectlyOver { get { return default(bool); } } public bool IsMouseOver { get { return default(bool); } } public bool IsStylusCaptured { get { return default(bool); } } public bool IsStylusCaptureWithin { get { return default(bool); } } public bool IsStylusDirectlyOver { get { return default(bool); } } public bool IsStylusOver { get { return default(bool); } } public IEnumerable<System.Windows.Input.TouchDevice> TouchesCaptured { get { return default(IEnumerable<System.Windows.Input.TouchDevice>); } } public IEnumerable<System.Windows.Input.TouchDevice> TouchesCapturedWithin { get { return default(IEnumerable<System.Windows.Input.TouchDevice>); } } public IEnumerable<System.Windows.Input.TouchDevice> TouchesDirectlyOver { get { return default(IEnumerable<System.Windows.Input.TouchDevice>); } } public IEnumerable<System.Windows.Input.TouchDevice> TouchesOver { get { return default(IEnumerable<System.Windows.Input.TouchDevice>); } } #endregion #region Events public event DragEventHandler DragEnter { add { } remove { } } public event DragEventHandler DragLeave { add { } remove { } } public event DragEventHandler DragOver { add { } remove { } } public event DragEventHandler Drop { add { } remove { } } public event DependencyPropertyChangedEventHandler FocusableChanged { add { } remove { } } public event GiveFeedbackEventHandler GiveFeedback { add { } remove { } } public event RoutedEventHandler GotFocus { add { } remove { } } public event System.Windows.Input.KeyboardFocusChangedEventHandler GotKeyboardFocus { add { } remove { } } public event System.Windows.Input.MouseEventHandler GotMouseCapture { add { } remove { } } public event System.Windows.Input.StylusEventHandler GotStylusCapture { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> GotTouchCapture { add { } remove { } } public event DependencyPropertyChangedEventHandler IsEnabledChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsKeyboardFocusedChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsKeyboardFocusWithinChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsMouseCapturedChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsMouseCaptureWithinChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsMouseDirectlyOverChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsStylusCapturedChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsStylusCaptureWithinChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsStylusDirectlyOverChanged { add { } remove { } } public event System.Windows.Input.KeyEventHandler KeyDown { add { } remove { } } public event System.Windows.Input.KeyEventHandler KeyUp { add { } remove { } } public event RoutedEventHandler LostFocus { add { } remove { } } public event System.Windows.Input.KeyboardFocusChangedEventHandler LostKeyboardFocus { add { } remove { } } public event System.Windows.Input.MouseEventHandler LostMouseCapture { add { } remove { } } public event System.Windows.Input.StylusEventHandler LostStylusCapture { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> LostTouchCapture { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseDown { add { } remove { } } public event System.Windows.Input.MouseEventHandler MouseEnter { add { } remove { } } public event System.Windows.Input.MouseEventHandler MouseLeave { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseLeftButtonDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseLeftButtonUp { add { } remove { } } public event System.Windows.Input.MouseEventHandler MouseMove { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseRightButtonDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseRightButtonUp { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseUp { add { } remove { } } public event System.Windows.Input.MouseWheelEventHandler MouseWheel { add { } remove { } } public event DragEventHandler PreviewDragEnter { add { } remove { } } public event DragEventHandler PreviewDragLeave { add { } remove { } } public event DragEventHandler PreviewDragOver { add { } remove { } } public event DragEventHandler PreviewDrop { add { } remove { } } public event GiveFeedbackEventHandler PreviewGiveFeedback { add { } remove { } } public event System.Windows.Input.KeyboardFocusChangedEventHandler PreviewGotKeyboardFocus { add { } remove { } } public event System.Windows.Input.KeyEventHandler PreviewKeyDown { add { } remove { } } public event System.Windows.Input.KeyEventHandler PreviewKeyUp { add { } remove { } } public event System.Windows.Input.KeyboardFocusChangedEventHandler PreviewLostKeyboardFocus { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseLeftButtonDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseLeftButtonUp { add { } remove { } } public event System.Windows.Input.MouseEventHandler PreviewMouseMove { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseRightButtonDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseRightButtonUp { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseUp { add { } remove { } } public event System.Windows.Input.MouseWheelEventHandler PreviewMouseWheel { add { } remove { } } public event QueryContinueDragEventHandler PreviewQueryContinueDrag { add { } remove { } } public event System.Windows.Input.StylusButtonEventHandler PreviewStylusButtonDown { add { } remove { } } public event System.Windows.Input.StylusButtonEventHandler PreviewStylusButtonUp { add { } remove { } } public event System.Windows.Input.StylusDownEventHandler PreviewStylusDown { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusInAirMove { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusInRange { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusMove { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusOutOfRange { add { } remove { } } public event System.Windows.Input.StylusSystemGestureEventHandler PreviewStylusSystemGesture { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusUp { add { } remove { } } public event System.Windows.Input.TextCompositionEventHandler PreviewTextInput { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> PreviewTouchDown { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> PreviewTouchMove { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> PreviewTouchUp { add { } remove { } } public event QueryContinueDragEventHandler QueryContinueDrag { add { } remove { } } public event System.Windows.Input.QueryCursorEventHandler QueryCursor { add { } remove { } } public event System.Windows.Input.StylusButtonEventHandler StylusButtonDown { add { } remove { } } public event System.Windows.Input.StylusButtonEventHandler StylusButtonUp { add { } remove { } } public event System.Windows.Input.StylusDownEventHandler StylusDown { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusEnter { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusInAirMove { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusInRange { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusLeave { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusMove { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusOutOfRange { add { } remove { } } public event System.Windows.Input.StylusSystemGestureEventHandler StylusSystemGesture { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusUp { add { } remove { } } public event System.Windows.Input.TextCompositionEventHandler TextInput { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchDown { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchEnter { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchLeave { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchMove { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchUp { add { } remove { } } #endregion #region Fields public readonly static DependencyProperty AllowDropProperty; public readonly static DependencyProperty AreAnyTouchesCapturedProperty; public readonly static DependencyProperty AreAnyTouchesCapturedWithinProperty; public readonly static DependencyProperty AreAnyTouchesDirectlyOverProperty; public readonly static DependencyProperty AreAnyTouchesOverProperty; public readonly static RoutedEvent DragEnterEvent; public readonly static RoutedEvent DragLeaveEvent; public readonly static RoutedEvent DragOverEvent; public readonly static RoutedEvent DropEvent; public readonly static DependencyProperty FocusableProperty; public readonly static RoutedEvent GiveFeedbackEvent; public readonly static RoutedEvent GotFocusEvent; public readonly static RoutedEvent GotKeyboardFocusEvent; public readonly static RoutedEvent GotMouseCaptureEvent; public readonly static RoutedEvent GotStylusCaptureEvent; public readonly static RoutedEvent GotTouchCaptureEvent; public readonly static DependencyProperty IsEnabledProperty; public readonly static DependencyProperty IsFocusedProperty; public readonly static DependencyProperty IsKeyboardFocusedProperty; public readonly static DependencyProperty IsKeyboardFocusWithinProperty; public readonly static DependencyProperty IsMouseCapturedProperty; public readonly static DependencyProperty IsMouseCaptureWithinProperty; public readonly static DependencyProperty IsMouseDirectlyOverProperty; public readonly static DependencyProperty IsMouseOverProperty; public readonly static DependencyProperty IsStylusCapturedProperty; public readonly static DependencyProperty IsStylusCaptureWithinProperty; public readonly static DependencyProperty IsStylusDirectlyOverProperty; public readonly static DependencyProperty IsStylusOverProperty; public readonly static RoutedEvent KeyDownEvent; public readonly static RoutedEvent KeyUpEvent; public readonly static RoutedEvent LostFocusEvent; public readonly static RoutedEvent LostKeyboardFocusEvent; public readonly static RoutedEvent LostMouseCaptureEvent; public readonly static RoutedEvent LostStylusCaptureEvent; public readonly static RoutedEvent LostTouchCaptureEvent; public readonly static RoutedEvent MouseDownEvent; public readonly static RoutedEvent MouseEnterEvent; public readonly static RoutedEvent MouseLeaveEvent; public readonly static RoutedEvent MouseLeftButtonDownEvent; public readonly static RoutedEvent MouseLeftButtonUpEvent; public readonly static RoutedEvent MouseMoveEvent; public readonly static RoutedEvent MouseRightButtonDownEvent; public readonly static RoutedEvent MouseRightButtonUpEvent; public readonly static RoutedEvent MouseUpEvent; public readonly static RoutedEvent MouseWheelEvent; public readonly static RoutedEvent PreviewDragEnterEvent; public readonly static RoutedEvent PreviewDragLeaveEvent; public readonly static RoutedEvent PreviewDragOverEvent; public readonly static RoutedEvent PreviewDropEvent; public readonly static RoutedEvent PreviewGiveFeedbackEvent; public readonly static RoutedEvent PreviewGotKeyboardFocusEvent; public readonly static RoutedEvent PreviewKeyDownEvent; public readonly static RoutedEvent PreviewKeyUpEvent; public readonly static RoutedEvent PreviewLostKeyboardFocusEvent; public readonly static RoutedEvent PreviewMouseDownEvent; public readonly static RoutedEvent PreviewMouseLeftButtonDownEvent; public readonly static RoutedEvent PreviewMouseLeftButtonUpEvent; public readonly static RoutedEvent PreviewMouseMoveEvent; public readonly static RoutedEvent PreviewMouseRightButtonDownEvent; public readonly static RoutedEvent PreviewMouseRightButtonUpEvent; public readonly static RoutedEvent PreviewMouseUpEvent; public readonly static RoutedEvent PreviewMouseWheelEvent; public readonly static RoutedEvent PreviewQueryContinueDragEvent; public readonly static RoutedEvent PreviewStylusButtonDownEvent; public readonly static RoutedEvent PreviewStylusButtonUpEvent; public readonly static RoutedEvent PreviewStylusDownEvent; public readonly static RoutedEvent PreviewStylusInAirMoveEvent; public readonly static RoutedEvent PreviewStylusInRangeEvent; public readonly static RoutedEvent PreviewStylusMoveEvent; public readonly static RoutedEvent PreviewStylusOutOfRangeEvent; public readonly static RoutedEvent PreviewStylusSystemGestureEvent; public readonly static RoutedEvent PreviewStylusUpEvent; public readonly static RoutedEvent PreviewTextInputEvent; public readonly static RoutedEvent PreviewTouchDownEvent; public readonly static RoutedEvent PreviewTouchMoveEvent; public readonly static RoutedEvent PreviewTouchUpEvent; public readonly static RoutedEvent QueryContinueDragEvent; public readonly static RoutedEvent QueryCursorEvent; public readonly static RoutedEvent StylusButtonDownEvent; public readonly static RoutedEvent StylusButtonUpEvent; public readonly static RoutedEvent StylusDownEvent; public readonly static RoutedEvent StylusEnterEvent; public readonly static RoutedEvent StylusInAirMoveEvent; public readonly static RoutedEvent StylusInRangeEvent; public readonly static RoutedEvent StylusLeaveEvent; public readonly static RoutedEvent StylusMoveEvent; public readonly static RoutedEvent StylusOutOfRangeEvent; public readonly static RoutedEvent StylusSystemGestureEvent; public readonly static RoutedEvent StylusUpEvent; public readonly static RoutedEvent TextInputEvent; public readonly static RoutedEvent TouchDownEvent; public readonly static RoutedEvent TouchEnterEvent; public readonly static RoutedEvent TouchLeaveEvent; public readonly static RoutedEvent TouchMoveEvent; public readonly static RoutedEvent TouchUpEvent; #endregion } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.IO; using System.Text; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers { /// <summary> /// Encodes and writes protocol message fields. /// </summary> /// <remarks> /// This class contains two kinds of methods: methods that write specific /// protocol message constructs and field types (e.g. WriteTag and /// WriteInt32) and methods that write low-level values (e.g. /// WriteRawVarint32 and WriteRawBytes). If you are writing encoded protocol /// messages, you should use the former methods, but if you are writing some /// other format of your own design, use the latter. The names of the former /// methods are taken from the protocol buffer type names, not .NET types. /// (Hence WriteFloat instead of WriteSingle, and WriteBool instead of WriteBoolean.) /// </remarks> public sealed class CodedOutputStream { /// <summary> /// The buffer size used by CreateInstance(Stream). /// </summary> public static readonly int DefaultBufferSize = 4096; private readonly byte[] buffer; private readonly int limit; private int position; private readonly Stream output; #region Construction private CodedOutputStream(byte[] buffer, int offset, int length) { this.output = null; this.buffer = buffer; this.position = offset; this.limit = offset + length; } private CodedOutputStream(Stream output, byte[] buffer) { this.output = output; this.buffer = buffer; this.position = 0; this.limit = buffer.Length; } /// <summary> /// Creates a new CodedOutputStream which write to the given stream. /// </summary> public static CodedOutputStream CreateInstance(Stream output) { return CreateInstance(output, DefaultBufferSize); } /// <summary> /// Creates a new CodedOutputStream which write to the given stream and uses /// the specified buffer size. /// </summary> public static CodedOutputStream CreateInstance(Stream output, int bufferSize) { return new CodedOutputStream(output, new byte[bufferSize]); } /// <summary> /// Creates a new CodedOutputStream that writes directly to the given /// byte array. If more bytes are written than fit in the array, /// OutOfSpaceException will be thrown. /// </summary> public static CodedOutputStream CreateInstance(byte[] flatArray) { return CreateInstance(flatArray, 0, flatArray.Length); } /// <summary> /// Creates a new CodedOutputStream that writes directly to the given /// byte array slice. If more bytes are written than fit in the array, /// OutOfSpaceException will be thrown. /// </summary> public static CodedOutputStream CreateInstance(byte[] flatArray, int offset, int length) { return new CodedOutputStream(flatArray, offset, length); } #endregion #region Writing of tags etc /// <summary> /// Writes a double field value, including tag, to the stream. /// </summary> public void WriteDouble(int fieldNumber, double value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteDoubleNoTag(value); } /// <summary> /// Writes a float field value, including tag, to the stream. /// </summary> public void WriteFloat(int fieldNumber, float value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteFloatNoTag(value); } /// <summary> /// Writes a uint64 field value, including tag, to the stream. /// </summary> [CLSCompliant(false)] public void WriteUInt64(int fieldNumber, ulong value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64(value); } /// <summary> /// Writes an int64 field value, including tag, to the stream. /// </summary> public void WriteInt64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64((ulong)value); } /// <summary> /// Writes an int32 field value, including tag, to the stream. /// </summary> public void WriteInt32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); if (value >= 0) { WriteRawVarint32((uint)value); } else { // Must sign-extend. WriteRawVarint64((ulong)value); } } /// <summary> /// Writes a fixed64 field value, including tag, to the stream. /// </summary> [CLSCompliant(false)] public void WriteFixed64(int fieldNumber, ulong value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteRawLittleEndian64(value); } /// <summary> /// Writes a fixed32 field value, including tag, to the stream. /// </summary> [CLSCompliant(false)] public void WriteFixed32(int fieldNumber, uint value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteRawLittleEndian32(value); } /// <summary> /// Writes a bool field value, including tag, to the stream. /// </summary> public void WriteBool(int fieldNumber, bool value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawByte(value ? (byte)1 : (byte)0); } /// <summary> /// Writes a string field value, including tag, to the stream. /// </summary> public void WriteString(int fieldNumber, string value) { WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); // Optimise the case where we have enough space to write // the string directly to the buffer, which should be common. int length = Encoding.UTF8.GetByteCount(value); WriteRawVarint32((uint) length); if (limit - position >= length) { Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, position); position += length; } else { byte[] bytes = Encoding.UTF8.GetBytes(value); WriteRawBytes(bytes); } } /// <summary> /// Writes a group field value, including tag, to the stream. /// </summary> public void WriteGroup(int fieldNumber, IMessage value) { WriteTag(fieldNumber, WireFormat.WireType.StartGroup); value.WriteTo(this); WriteTag(fieldNumber, WireFormat.WireType.EndGroup); } public void WriteUnknownGroup(int fieldNumber, UnknownFieldSet value) { WriteTag(fieldNumber, WireFormat.WireType.StartGroup); value.WriteTo(this); WriteTag(fieldNumber, WireFormat.WireType.EndGroup); } public void WriteMessage(int fieldNumber, IMessage value) { WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32((uint)value.SerializedSize); value.WriteTo(this); } public void WriteBytes(int fieldNumber, ByteString value) { // TODO(jonskeet): Optimise this! (No need to copy the bytes twice.) WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); byte[] bytes = value.ToByteArray(); WriteRawVarint32((uint)bytes.Length); WriteRawBytes(bytes); } [CLSCompliant(false)] public void WriteUInt32(int fieldNumber, uint value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint32(value); } public void WriteEnum(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint32((uint)value); } public void WriteSFixed32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteRawLittleEndian32((uint)value); } public void WriteSFixed64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteRawLittleEndian64((ulong)value); } public void WriteSInt32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint32(EncodeZigZag32(value)); } public void WriteSInt64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64(EncodeZigZag64(value)); } public void WriteMessageSetExtension(int fieldNumber, IMessage value) { WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup); WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber); WriteMessage(WireFormat.MessageSetField.Message, value); WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup); } public void WriteRawMessageSetExtension(int fieldNumber, ByteString value) { WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup); WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber); WriteBytes(WireFormat.MessageSetField.Message, value); WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup); } public void WriteField(FieldType fieldType, int fieldNumber, object value) { switch (fieldType) { case FieldType.Double: WriteDouble(fieldNumber, (double)value); break; case FieldType.Float: WriteFloat(fieldNumber, (float)value); break; case FieldType.Int64: WriteInt64(fieldNumber, (long)value); break; case FieldType.UInt64: WriteUInt64(fieldNumber, (ulong)value); break; case FieldType.Int32: WriteInt32(fieldNumber, (int)value); break; case FieldType.Fixed64: WriteFixed64(fieldNumber, (ulong)value); break; case FieldType.Fixed32: WriteFixed32(fieldNumber, (uint)value); break; case FieldType.Bool: WriteBool(fieldNumber, (bool)value); break; case FieldType.String: WriteString(fieldNumber, (string)value); break; case FieldType.Group: WriteGroup(fieldNumber, (IMessage)value); break; case FieldType.Message: WriteMessage(fieldNumber, (IMessage)value); break; case FieldType.Bytes: WriteBytes(fieldNumber, (ByteString)value); break; case FieldType.UInt32: WriteUInt32(fieldNumber, (uint)value); break; case FieldType.SFixed32: WriteSFixed32(fieldNumber, (int)value); break; case FieldType.SFixed64: WriteSFixed64(fieldNumber, (long)value); break; case FieldType.SInt32: WriteSInt32(fieldNumber, (int)value); break; case FieldType.SInt64: WriteSInt64(fieldNumber, (long)value); break; case FieldType.Enum: WriteEnum(fieldNumber, ((EnumValueDescriptor)value).Number); break; } } public void WriteFieldNoTag(FieldType fieldType, object value) { switch (fieldType) { case FieldType.Double: WriteDoubleNoTag((double)value); break; case FieldType.Float: WriteFloatNoTag((float)value); break; case FieldType.Int64: WriteInt64NoTag((long)value); break; case FieldType.UInt64: WriteUInt64NoTag((ulong)value); break; case FieldType.Int32: WriteInt32NoTag((int)value); break; case FieldType.Fixed64: WriteFixed64NoTag((ulong)value); break; case FieldType.Fixed32: WriteFixed32NoTag((uint)value); break; case FieldType.Bool: WriteBoolNoTag((bool)value); break; case FieldType.String: WriteStringNoTag((string)value); break; case FieldType.Group: WriteGroupNoTag((IMessage)value); break; case FieldType.Message: WriteMessageNoTag((IMessage)value); break; case FieldType.Bytes: WriteBytesNoTag((ByteString)value); break; case FieldType.UInt32: WriteUInt32NoTag((uint)value); break; case FieldType.SFixed32: WriteSFixed32NoTag((int)value); break; case FieldType.SFixed64: WriteSFixed64NoTag((long)value); break; case FieldType.SInt32: WriteSInt32NoTag((int)value); break; case FieldType.SInt64: WriteSInt64NoTag((long)value); break; case FieldType.Enum: WriteEnumNoTag(((EnumValueDescriptor)value).Number); break; } } #endregion #region Writing of values without tags /// <summary> /// Writes a double field value, including tag, to the stream. /// </summary> public void WriteDoubleNoTag(double value) { // TODO(jonskeet): Test this on different endiannesses #if SILVERLIGHT2 || COMPACT_FRAMEWORK_35 byte[] bytes = BitConverter.GetBytes(value); WriteRawBytes(bytes, 0, 8); #else WriteRawLittleEndian64((ulong)BitConverter.DoubleToInt64Bits(value)); #endif } /// <summary> /// Writes a float field value, without a tag, to the stream. /// </summary> public void WriteFloatNoTag(float value) { // TODO(jonskeet): Test this on different endiannesses byte[] rawBytes = BitConverter.GetBytes(value); uint asInteger = BitConverter.ToUInt32(rawBytes, 0); WriteRawLittleEndian32(asInteger); } /// <summary> /// Writes a uint64 field value, without a tag, to the stream. /// </summary> [CLSCompliant(false)] public void WriteUInt64NoTag(ulong value) { WriteRawVarint64(value); } /// <summary> /// Writes an int64 field value, without a tag, to the stream. /// </summary> public void WriteInt64NoTag(long value) { WriteRawVarint64((ulong)value); } /// <summary> /// Writes an int32 field value, without a tag, to the stream. /// </summary> public void WriteInt32NoTag(int value) { if (value >= 0) { WriteRawVarint32((uint)value); } else { // Must sign-extend. WriteRawVarint64((ulong)value); } } /// <summary> /// Writes a fixed64 field value, without a tag, to the stream. /// </summary> [CLSCompliant(false)] public void WriteFixed64NoTag(ulong value) { WriteRawLittleEndian64(value); } /// <summary> /// Writes a fixed32 field value, without a tag, to the stream. /// </summary> [CLSCompliant(false)] public void WriteFixed32NoTag(uint value) { WriteRawLittleEndian32(value); } /// <summary> /// Writes a bool field value, without a tag, to the stream. /// </summary> public void WriteBoolNoTag(bool value) { WriteRawByte(value ? (byte)1 : (byte)0); } /// <summary> /// Writes a string field value, without a tag, to the stream. /// </summary> public void WriteStringNoTag(string value) { // Optimise the case where we have enough space to write // the string directly to the buffer, which should be common. int length = Encoding.UTF8.GetByteCount(value); WriteRawVarint32((uint)length); if (limit - position >= length) { Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, position); position += length; } else { byte[] bytes = Encoding.UTF8.GetBytes(value); WriteRawBytes(bytes); } } /// <summary> /// Writes a group field value, without a tag, to the stream. /// </summary> public void WriteGroupNoTag(IMessage value) { value.WriteTo(this); } public void WriteMessageNoTag(IMessage value) { WriteRawVarint32((uint)value.SerializedSize); value.WriteTo(this); } public void WriteBytesNoTag(ByteString value) { // TODO(jonskeet): Optimise this! (No need to copy the bytes twice.) byte[] bytes = value.ToByteArray(); WriteRawVarint32((uint)bytes.Length); WriteRawBytes(bytes); } [CLSCompliant(false)] public void WriteUInt32NoTag(uint value) { WriteRawVarint32(value); } public void WriteEnumNoTag(int value) { WriteRawVarint32((uint)value); } public void WriteSFixed32NoTag(int value) { WriteRawLittleEndian32((uint)value); } public void WriteSFixed64NoTag(long value) { WriteRawLittleEndian64((ulong)value); } public void WriteSInt32NoTag(int value) { WriteRawVarint32(EncodeZigZag32(value)); } public void WriteSInt64NoTag(long value) { WriteRawVarint64(EncodeZigZag64(value)); } #endregion #region Underlying writing primitives /// <summary> /// Encodes and writes a tag. /// </summary> [CLSCompliant(false)] public void WriteTag(int fieldNumber, WireFormat.WireType type) { WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type)); } private void SlowWriteRawVarint32(uint value) { while (true) { if ((value & ~0x7F) == 0) { WriteRawByte(value); return; } else { WriteRawByte((value & 0x7F) | 0x80); value >>= 7; } } } /// <summary> /// Writes a 32 bit value as a varint. The fast route is taken when /// there's enough buffer space left to whizz through without checking /// for each byte; otherwise, we resort to calling WriteRawByte each time. /// </summary> [CLSCompliant(false)] public void WriteRawVarint32(uint value) { if (position + 5 > limit) { SlowWriteRawVarint32(value); return; } while (true) { if ((value & ~0x7F) == 0) { buffer[position++] = (byte) value; return; } else { buffer[position++] = (byte)((value & 0x7F) | 0x80); value >>= 7; } } } [CLSCompliant(false)] public void WriteRawVarint64(ulong value) { while (true) { if ((value & ~0x7FUL) == 0) { WriteRawByte((uint)value); return; } else { WriteRawByte(((uint)value & 0x7F) | 0x80); value >>= 7; } } } [CLSCompliant(false)] public void WriteRawLittleEndian32(uint value) { WriteRawByte((byte)value); WriteRawByte((byte)(value >> 8)); WriteRawByte((byte)(value >> 16)); WriteRawByte((byte)(value >> 24)); } [CLSCompliant(false)] public void WriteRawLittleEndian64(ulong value) { WriteRawByte((byte)value); WriteRawByte((byte)(value >> 8)); WriteRawByte((byte)(value >> 16)); WriteRawByte((byte)(value >> 24)); WriteRawByte((byte)(value >> 32)); WriteRawByte((byte)(value >> 40)); WriteRawByte((byte)(value >> 48)); WriteRawByte((byte)(value >> 56)); } public void WriteRawByte(byte value) { if (position == limit) { RefreshBuffer(); } buffer[position++] = value; } [CLSCompliant(false)] public void WriteRawByte(uint value) { WriteRawByte((byte)value); } /// <summary> /// Writes out an array of bytes. /// </summary> public void WriteRawBytes(byte[] value) { WriteRawBytes(value, 0, value.Length); } /// <summary> /// Writes out part of an array of bytes. /// </summary> public void WriteRawBytes(byte[] value, int offset, int length) { if (limit - position >= length) { Array.Copy(value, offset, buffer, position, length); // We have room in the current buffer. position += length; } else { // Write extends past current buffer. Fill the rest of this buffer and // flush. int bytesWritten = limit - position; Array.Copy(value, offset, buffer, position, bytesWritten); offset += bytesWritten; length -= bytesWritten; position = limit; RefreshBuffer(); // Now deal with the rest. // Since we have an output stream, this is our buffer // and buffer offset == 0 if (length <= limit) { // Fits in new buffer. Array.Copy(value, offset, buffer, 0, length); position = length; } else { // Write is very big. Let's do it all at once. output.Write(value, offset, length); } } } #endregion #region Size computations const int LittleEndian64Size = 8; const int LittleEndian32Size = 4; /// <summary> /// Compute the number of bytes that would be needed to encode a /// double field, including the tag. /// </summary> public static int ComputeDoubleSize(int fieldNumber, double value) { return ComputeTagSize(fieldNumber) + LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// float field, including the tag. /// </summary> public static int ComputeFloatSize(int fieldNumber, float value) { return ComputeTagSize(fieldNumber) + LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// uint64 field, including the tag. /// </summary> [CLSCompliant(false)] public static int ComputeUInt64Size(int fieldNumber, ulong value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size(value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// int64 field, including the tag. /// </summary> public static int ComputeInt64Size(int fieldNumber, long value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size((ulong)value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// int32 field, including the tag. /// </summary> public static int ComputeInt32Size(int fieldNumber, int value) { if (value >= 0) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value); } else { // Must sign-extend. return ComputeTagSize(fieldNumber) + 10; } } /// <summary> /// Compute the number of bytes that would be needed to encode a /// fixed64 field, including the tag. /// </summary> [CLSCompliant(false)] public static int ComputeFixed64Size(int fieldNumber, ulong value) { return ComputeTagSize(fieldNumber) + LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// fixed32 field, including the tag. /// </summary> [CLSCompliant(false)] public static int ComputeFixed32Size(int fieldNumber, uint value) { return ComputeTagSize(fieldNumber) + LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// bool field, including the tag. /// </summary> public static int ComputeBoolSize(int fieldNumber, bool value) { return ComputeTagSize(fieldNumber) + 1; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// string field, including the tag. /// </summary> public static int ComputeStringSize(int fieldNumber, String value) { int byteArraySize = Encoding.UTF8.GetByteCount(value); return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)byteArraySize) + byteArraySize; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// group field, including the tag. /// </summary> public static int ComputeGroupSize(int fieldNumber, IMessage value) { return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// group field represented by an UnknownFieldSet, including the tag. /// </summary> public static int ComputeUnknownGroupSize(int fieldNumber, UnknownFieldSet value) { return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// embedded message field, including the tag. /// </summary> public static int ComputeMessageSize(int fieldNumber, IMessage value) { int size = value.SerializedSize; return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)size) + size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// bytes field, including the tag. /// </summary> public static int ComputeBytesSize(int fieldNumber, ByteString value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value.Length) + value.Length; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// uint32 field, including the tag. /// </summary> [CLSCompliant(false)] public static int ComputeUInt32Size(int fieldNumber, uint value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size(value); } /// <summary> /// Compute the number of bytes that would be needed to encode a /// enum field, including the tag. The caller is responsible for /// converting the enum value to its numeric value. /// </summary> public static int ComputeEnumSize(int fieldNumber, int value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sfixed32 field, including the tag. /// </summary> public static int ComputeSFixed32Size(int fieldNumber, int value) { return ComputeTagSize(fieldNumber) + LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sfixed64 field, including the tag. /// </summary> public static int ComputeSFixed64Size(int fieldNumber, long value) { return ComputeTagSize(fieldNumber) + LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sint32 field, including the tag. /// </summary> public static int ComputeSInt32Size(int fieldNumber, int value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size(EncodeZigZag32(value)); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sint64 field, including the tag. /// </summary> public static int ComputeSInt64Size(int fieldNumber, long value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size(EncodeZigZag64(value)); } /// <summary> /// Compute the number of bytes that would be needed to encode a /// double field, including the tag. /// </summary> public static int ComputeDoubleSizeNoTag(double value) { return LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// float field, including the tag. /// </summary> public static int ComputeFloatSizeNoTag(float value) { return LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// uint64 field, including the tag. /// </summary> [CLSCompliant(false)] public static int ComputeUInt64SizeNoTag(ulong value) { return ComputeRawVarint64Size(value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// int64 field, including the tag. /// </summary> public static int ComputeInt64SizeNoTag(long value) { return ComputeRawVarint64Size((ulong)value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// int32 field, including the tag. /// </summary> public static int ComputeInt32SizeNoTag(int value) { if (value >= 0) { return ComputeRawVarint32Size((uint)value); } else { // Must sign-extend. return 10; } } /// <summary> /// Compute the number of bytes that would be needed to encode a /// fixed64 field, including the tag. /// </summary> [CLSCompliant(false)] public static int ComputeFixed64SizeNoTag(ulong value) { return LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// fixed32 field, including the tag. /// </summary> [CLSCompliant(false)] public static int ComputeFixed32SizeNoTag(uint value) { return LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// bool field, including the tag. /// </summary> public static int ComputeBoolSizeNoTag(bool value) { return 1; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// string field, including the tag. /// </summary> public static int ComputeStringSizeNoTag(String value) { int byteArraySize = Encoding.UTF8.GetByteCount(value); return ComputeRawVarint32Size((uint)byteArraySize) + byteArraySize; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// group field, including the tag. /// </summary> public static int ComputeGroupSizeNoTag(IMessage value) { return value.SerializedSize; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// group field represented by an UnknownFieldSet, including the tag. /// </summary> public static int ComputeUnknownGroupSizeNoTag(UnknownFieldSet value) { return value.SerializedSize; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// embedded message field, including the tag. /// </summary> public static int ComputeMessageSizeNoTag(IMessage value) { int size = value.SerializedSize; return ComputeRawVarint32Size((uint)size) + size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// bytes field, including the tag. /// </summary> public static int ComputeBytesSizeNoTag(ByteString value) { return ComputeRawVarint32Size((uint)value.Length) + value.Length; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// uint32 field, including the tag. /// </summary> [CLSCompliant(false)] public static int ComputeUInt32SizeNoTag(uint value) { return ComputeRawVarint32Size(value); } /// <summary> /// Compute the number of bytes that would be needed to encode a /// enum field, including the tag. The caller is responsible for /// converting the enum value to its numeric value. /// </summary> public static int ComputeEnumSizeNoTag(int value) { return ComputeRawVarint32Size((uint)value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sfixed32 field, including the tag. /// </summary> public static int ComputeSFixed32SizeNoTag(int value) { return LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sfixed64 field, including the tag. /// </summary> public static int ComputeSFixed64SizeNoTag(long value) { return LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sint32 field, including the tag. /// </summary> public static int ComputeSInt32SizeNoTag(int value) { return ComputeRawVarint32Size(EncodeZigZag32(value)); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sint64 field, including the tag. /// </summary> public static int ComputeSInt64SizeNoTag(long value) { return ComputeRawVarint64Size(EncodeZigZag64(value)); } /* * Compute the number of bytes that would be needed to encode a * MessageSet extension to the stream. For historical reasons, * the wire format differs from normal fields. */ /// <summary> /// Compute the number of bytes that would be needed to encode a /// MessageSet extension to the stream. For historical reasons, /// the wire format differs from normal fields. /// </summary> public static int ComputeMessageSetExtensionSize(int fieldNumber, IMessage value) { return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 + ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) + ComputeMessageSize(WireFormat.MessageSetField.Message, value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// unparsed MessageSet extension field to the stream. For /// historical reasons, the wire format differs from normal fields. /// </summary> public static int ComputeRawMessageSetExtensionSize(int fieldNumber, ByteString value) { return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 + ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) + ComputeBytesSize(WireFormat.MessageSetField.Message, value); } /// <summary> /// Compute the number of bytes that would be needed to encode a varint. /// </summary> [CLSCompliant(false)] public static int ComputeRawVarint32Size(uint value) { if ((value & (0xffffffff << 7)) == 0) return 1; if ((value & (0xffffffff << 14)) == 0) return 2; if ((value & (0xffffffff << 21)) == 0) return 3; if ((value & (0xffffffff << 28)) == 0) return 4; return 5; } /// <summary> /// Compute the number of bytes that would be needed to encode a varint. /// </summary> [CLSCompliant(false)] public static int ComputeRawVarint64Size(ulong value) { if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; return 10; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// field of arbitrary type, including the tag, to the stream. /// </summary> public static int ComputeFieldSize(FieldType fieldType, int fieldNumber, Object value) { switch (fieldType) { case FieldType.Double: return ComputeDoubleSize(fieldNumber, (double)value); case FieldType.Float: return ComputeFloatSize(fieldNumber, (float)value); case FieldType.Int64: return ComputeInt64Size(fieldNumber, (long)value); case FieldType.UInt64: return ComputeUInt64Size(fieldNumber, (ulong)value); case FieldType.Int32: return ComputeInt32Size(fieldNumber, (int)value); case FieldType.Fixed64: return ComputeFixed64Size(fieldNumber, (ulong)value); case FieldType.Fixed32: return ComputeFixed32Size(fieldNumber, (uint)value); case FieldType.Bool: return ComputeBoolSize(fieldNumber, (bool)value); case FieldType.String: return ComputeStringSize(fieldNumber, (string)value); case FieldType.Group: return ComputeGroupSize(fieldNumber, (IMessage)value); case FieldType.Message: return ComputeMessageSize(fieldNumber, (IMessage)value); case FieldType.Bytes: return ComputeBytesSize(fieldNumber, (ByteString)value); case FieldType.UInt32: return ComputeUInt32Size(fieldNumber, (uint)value); case FieldType.SFixed32: return ComputeSFixed32Size(fieldNumber, (int)value); case FieldType.SFixed64: return ComputeSFixed64Size(fieldNumber, (long)value); case FieldType.SInt32: return ComputeSInt32Size(fieldNumber, (int)value); case FieldType.SInt64: return ComputeSInt64Size(fieldNumber, (long)value); case FieldType.Enum: return ComputeEnumSize(fieldNumber, ((EnumValueDescriptor)value).Number); default: throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); } } /// <summary> /// Compute the number of bytes that would be needed to encode a /// field of arbitrary type, excluding the tag, to the stream. /// </summary> public static int ComputeFieldSizeNoTag(FieldType fieldType, Object value) { switch (fieldType) { case FieldType.Double: return ComputeDoubleSizeNoTag((double)value); case FieldType.Float: return ComputeFloatSizeNoTag((float)value); case FieldType.Int64: return ComputeInt64SizeNoTag((long)value); case FieldType.UInt64: return ComputeUInt64SizeNoTag((ulong)value); case FieldType.Int32: return ComputeInt32SizeNoTag((int)value); case FieldType.Fixed64: return ComputeFixed64SizeNoTag((ulong)value); case FieldType.Fixed32: return ComputeFixed32SizeNoTag((uint)value); case FieldType.Bool: return ComputeBoolSizeNoTag((bool)value); case FieldType.String: return ComputeStringSizeNoTag((string)value); case FieldType.Group: return ComputeGroupSizeNoTag((IMessage)value); case FieldType.Message: return ComputeMessageSizeNoTag((IMessage)value); case FieldType.Bytes: return ComputeBytesSizeNoTag((ByteString)value); case FieldType.UInt32: return ComputeUInt32SizeNoTag((uint)value); case FieldType.SFixed32: return ComputeSFixed32SizeNoTag((int)value); case FieldType.SFixed64: return ComputeSFixed64SizeNoTag((long)value); case FieldType.SInt32: return ComputeSInt32SizeNoTag((int)value); case FieldType.SInt64: return ComputeSInt64SizeNoTag((long)value); case FieldType.Enum: return ComputeEnumSizeNoTag(((EnumValueDescriptor)value).Number); default: throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); } } /// <summary> /// Compute the number of bytes that would be needed to encode a tag. /// </summary> public static int ComputeTagSize(int fieldNumber) { return ComputeRawVarint32Size(WireFormat.MakeTag(fieldNumber, 0)); } #endregion /// <summary> /// Encode a 32-bit value with ZigZag encoding. /// </summary> /// <remarks> /// ZigZag encodes signed integers into values that can be efficiently /// encoded with varint. (Otherwise, negative values must be /// sign-extended to 64 bits to be varint encoded, thus always taking /// 10 bytes on the wire.) /// </remarks> [CLSCompliant(false)] public static uint EncodeZigZag32(int n) { // Note: the right-shift must be arithmetic return (uint)((n << 1) ^ (n >> 31)); } /// <summary> /// Encode a 64-bit value with ZigZag encoding. /// </summary> /// <remarks> /// ZigZag encodes signed integers into values that can be efficiently /// encoded with varint. (Otherwise, negative values must be /// sign-extended to 64 bits to be varint encoded, thus always taking /// 10 bytes on the wire.) /// </remarks> [CLSCompliant(false)] public static ulong EncodeZigZag64(long n) { return (ulong)((n << 1) ^ (n >> 63)); } private void RefreshBuffer() { if (output == null) { // We're writing to a single buffer. throw new OutOfSpaceException(); } // Since we have an output stream, this is our buffer // and buffer offset == 0 output.Write(buffer, 0, position); position = 0; } /// <summary> /// Indicates that a CodedOutputStream wrapping a flat byte array /// ran out of space. /// </summary> public sealed class OutOfSpaceException : IOException { internal OutOfSpaceException() : base("CodedOutputStream was writing to a flat byte array and ran out of space.") { } } public void Flush() { if (output != null) { RefreshBuffer(); } } /// <summary> /// Verifies that SpaceLeft returns zero. It's common to create a byte array /// that is exactly big enough to hold a message, then write to it with /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that /// the message was actually as big as expected, which can help bugs. /// </summary> public void CheckNoSpaceLeft() { if (SpaceLeft != 0) { throw new InvalidOperationException("Did not write as much data as expected."); } } /// <summary> /// If writing to a flat array, returns the space left in the array. Otherwise, /// throws an InvalidOperationException. /// </summary> public int SpaceLeft { get { if (output == null) { return limit - position; } else { throw new InvalidOperationException( "SpaceLeft can only be called on CodedOutputStreams that are " + "writing to a flat array."); } } } } }
using System.Runtime.Serialization; namespace VkApi.Wrapper.Objects { public enum BaseUserGroupFields { [EnumMember(Value = "about")] About, [EnumMember(Value = "action_button")] ActionButton, [EnumMember(Value = "activities")] Activities, [EnumMember(Value = "activity")] Activity, [EnumMember(Value = "addresses")] Addresses, [EnumMember(Value = "admin_level")] AdminLevel, [EnumMember(Value = "age_limits")] AgeLimits, [EnumMember(Value = "author_id")] AuthorId, [EnumMember(Value = "ban_info")] BanInfo, [EnumMember(Value = "bdate")] Bdate, [EnumMember(Value = "blacklisted")] Blacklisted, [EnumMember(Value = "blacklisted_by_me")] BlacklistedByMe, [EnumMember(Value = "books")] Books, [EnumMember(Value = "can_create_topic")] CanCreateTopic, [EnumMember(Value = "can_message")] CanMessage, [EnumMember(Value = "can_post")] CanPost, [EnumMember(Value = "can_see_all_posts")] CanSeeAllPosts, [EnumMember(Value = "can_see_audio")] CanSeeAudio, [EnumMember(Value = "can_send_friend_request")] CanSendFriendRequest, [EnumMember(Value = "can_upload_video")] CanUploadVideo, [EnumMember(Value = "can_write_private_message")] CanWritePrivateMessage, [EnumMember(Value = "career")] Career, [EnumMember(Value = "city")] City, [EnumMember(Value = "common_count")] CommonCount, [EnumMember(Value = "connections")] Connections, [EnumMember(Value = "contacts")] Contacts, [EnumMember(Value = "counters")] Counters, [EnumMember(Value = "country")] Country, [EnumMember(Value = "cover")] Cover, [EnumMember(Value = "crop_photo")] CropPhoto, [EnumMember(Value = "deactivated")] Deactivated, [EnumMember(Value = "description")] Description, [EnumMember(Value = "domain")] Domain, [EnumMember(Value = "education")] Education, [EnumMember(Value = "exports")] Exports, [EnumMember(Value = "finish_date")] FinishDate, [EnumMember(Value = "fixed_post")] FixedPost, [EnumMember(Value = "followers_count")] FollowersCount, [EnumMember(Value = "friend_status")] FriendStatus, [EnumMember(Value = "games")] Games, [EnumMember(Value = "has_market_app")] HasMarketApp, [EnumMember(Value = "has_mobile")] HasMobile, [EnumMember(Value = "has_photo")] HasPhoto, [EnumMember(Value = "home_town")] HomeTown, [EnumMember(Value = "id")] Id, [EnumMember(Value = "interests")] Interests, [EnumMember(Value = "is_admin")] IsAdmin, [EnumMember(Value = "is_closed")] IsClosed, [EnumMember(Value = "is_favorite")] IsFavorite, [EnumMember(Value = "is_friend")] IsFriend, [EnumMember(Value = "is_hidden_from_feed")] IsHiddenFromFeed, [EnumMember(Value = "is_member")] IsMember, [EnumMember(Value = "is_messages_blocked")] IsMessagesBlocked, [EnumMember(Value = "can_send_notify")] CanSendNotify, [EnumMember(Value = "is_subscribed")] IsSubscribed, [EnumMember(Value = "last_seen")] LastSeen, [EnumMember(Value = "links")] Links, [EnumMember(Value = "lists")] Lists, [EnumMember(Value = "maiden_name")] MaidenName, [EnumMember(Value = "main_album_id")] MainAlbumId, [EnumMember(Value = "main_section")] MainSection, [EnumMember(Value = "market")] Market, [EnumMember(Value = "member_status")] MemberStatus, [EnumMember(Value = "members_count")] MembersCount, [EnumMember(Value = "military")] Military, [EnumMember(Value = "movies")] Movies, [EnumMember(Value = "music")] Music, [EnumMember(Value = "name")] Name, [EnumMember(Value = "nickname")] Nickname, [EnumMember(Value = "occupation")] Occupation, [EnumMember(Value = "online")] Online, [EnumMember(Value = "online_status")] OnlineStatus, [EnumMember(Value = "personal")] Personal, [EnumMember(Value = "phone")] Phone, [EnumMember(Value = "photo_100")] Photo100, [EnumMember(Value = "photo_200")] Photo200, [EnumMember(Value = "photo_200_orig")] Photo200Orig, [EnumMember(Value = "photo_400_orig")] Photo400Orig, [EnumMember(Value = "photo_50")] Photo50, [EnumMember(Value = "photo_id")] PhotoId, [EnumMember(Value = "photo_max")] PhotoMax, [EnumMember(Value = "photo_max_orig")] PhotoMaxOrig, [EnumMember(Value = "quotes")] Quotes, [EnumMember(Value = "relation")] Relation, [EnumMember(Value = "relatives")] Relatives, [EnumMember(Value = "schools")] Schools, [EnumMember(Value = "screen_name")] ScreenName, [EnumMember(Value = "sex")] Sex, [EnumMember(Value = "site")] Site, [EnumMember(Value = "start_date")] StartDate, [EnumMember(Value = "status")] Status, [EnumMember(Value = "timezone")] Timezone, [EnumMember(Value = "trending")] Trending, [EnumMember(Value = "tv")] Tv, [EnumMember(Value = "type")] Type, [EnumMember(Value = "universities")] Universities, [EnumMember(Value = "verified")] Verified, [EnumMember(Value = "wall_comments")] WallComments, [EnumMember(Value = "wiki_page")] WikiPage, [EnumMember(Value = "vk_admin_status")] VkAdminStatus } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors #if DECODER && !NO_EVEX using System; namespace Iced.Intel.DecoderInternal { sealed class EvexOpCodeHandlerReader : OpCodeHandlerReader { public override int ReadHandlers(ref TableDeserializer deserializer, OpCodeHandler?[] result, int resultIndex) { ref var elem = ref result[resultIndex]; Code code; switch (deserializer.ReadEvexOpCodeHandlerKind()) { case EvexOpCodeHandlerKind.Invalid: elem = OpCodeHandler_Invalid.Instance; return 1; case EvexOpCodeHandlerKind.Invalid2: result[resultIndex] = OpCodeHandler_Invalid.Instance; result[resultIndex + 1] = OpCodeHandler_Invalid.Instance; return 2; case EvexOpCodeHandlerKind.Dup: int count = deserializer.ReadInt32(); var handler = deserializer.ReadHandler(); for (int i = 0; i < count; i++) result[resultIndex + i] = handler; return count; case EvexOpCodeHandlerKind.HandlerReference: elem = deserializer.ReadHandlerReference(); return 1; case EvexOpCodeHandlerKind.ArrayReference: throw new InvalidOperationException(); case EvexOpCodeHandlerKind.RM: elem = new OpCodeHandler_RM(deserializer.ReadHandler(), deserializer.ReadHandler()); return 1; case EvexOpCodeHandlerKind.Group: elem = new OpCodeHandler_Group(deserializer.ReadArrayReference((uint)EvexOpCodeHandlerKind.ArrayReference)); return 1; case EvexOpCodeHandlerKind.W: elem = new OpCodeHandler_W(deserializer.ReadHandler(), deserializer.ReadHandler()); return 1; case EvexOpCodeHandlerKind.MandatoryPrefix2: elem = new OpCodeHandler_MandatoryPrefix2(deserializer.ReadHandler(), deserializer.ReadHandler(), deserializer.ReadHandler(), deserializer.ReadHandler()); return 1; case EvexOpCodeHandlerKind.VectorLength: elem = new OpCodeHandler_VectorLength_EVEX(deserializer.ReadHandler(), deserializer.ReadHandler(), deserializer.ReadHandler()); return 1; case EvexOpCodeHandlerKind.VectorLength_er: elem = new OpCodeHandler_VectorLength_EVEX_er(deserializer.ReadHandler(), deserializer.ReadHandler(), deserializer.ReadHandler()); return 1; case EvexOpCodeHandlerKind.Ed_V_Ib: elem = new OpCodeHandler_EVEX_Ed_V_Ib(deserializer.ReadRegister(), code = deserializer.ReadCode(), code + 1, deserializer.ReadTupleType(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.Ev_VX: code = deserializer.ReadCode(); elem = new OpCodeHandler_EVEX_Ev_VX(code, code + 1, deserializer.ReadTupleType(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.Ev_VX_Ib: elem = new OpCodeHandler_EVEX_Ev_VX_Ib(deserializer.ReadRegister(), code = deserializer.ReadCode(), code + 1); return 1; case EvexOpCodeHandlerKind.Gv_W_er: elem = new OpCodeHandler_EVEX_Gv_W_er(deserializer.ReadRegister(), code = deserializer.ReadCode(), code + 1, deserializer.ReadTupleType(), deserializer.ReadBoolean()); return 1; case EvexOpCodeHandlerKind.GvM_VX_Ib: elem = new OpCodeHandler_EVEX_GvM_VX_Ib(deserializer.ReadRegister(), code = deserializer.ReadCode(), code + 1, deserializer.ReadTupleType(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.HkWIb_3: elem = new OpCodeHandler_EVEX_HkWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.HkWIb_3b: elem = new OpCodeHandler_EVEX_HkWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.HWIb: elem = new OpCodeHandler_EVEX_HWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.KkHW_3: elem = new OpCodeHandler_EVEX_KkHW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.KkHW_3b: elem = new OpCodeHandler_EVEX_KkHW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.KkHWIb_sae_3: elem = new OpCodeHandler_EVEX_KkHWIb_sae(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.KkHWIb_sae_3b: elem = new OpCodeHandler_EVEX_KkHWIb_sae(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.KkHWIb_3: elem = new OpCodeHandler_EVEX_KkHWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.KkHWIb_3b: elem = new OpCodeHandler_EVEX_KkHWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.KkWIb_3: elem = new OpCodeHandler_EVEX_KkWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.KkWIb_3b: elem = new OpCodeHandler_EVEX_KkWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.KP1HW: elem = new OpCodeHandler_EVEX_KP1HW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.KR: elem = new OpCodeHandler_EVEX_KR(deserializer.ReadRegister(), deserializer.ReadCode()); return 1; case EvexOpCodeHandlerKind.MV: elem = new OpCodeHandler_EVEX_MV(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.V_H_Ev_er: elem = new OpCodeHandler_EVEX_V_H_Ev_er(deserializer.ReadRegister(), code = deserializer.ReadCode(), code + 1, deserializer.ReadTupleType(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.V_H_Ev_Ib: elem = new OpCodeHandler_EVEX_V_H_Ev_Ib(deserializer.ReadRegister(), code = deserializer.ReadCode(), code + 1, deserializer.ReadTupleType(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VHM: elem = new OpCodeHandler_EVEX_VHM(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VHW_3: elem = new OpCodeHandler_EVEX_VHW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VHW_4: elem = new OpCodeHandler_EVEX_VHW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VHWIb: elem = new OpCodeHandler_EVEX_VHWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VK: elem = new OpCodeHandler_EVEX_VK(deserializer.ReadRegister(), deserializer.ReadCode()); return 1; case EvexOpCodeHandlerKind.Vk_VSIB: elem = new OpCodeHandler_EVEX_Vk_VSIB(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VkEv_REXW_2: elem = new OpCodeHandler_EVEX_VkEv_REXW(deserializer.ReadRegister(), deserializer.ReadCode()); return 1; case EvexOpCodeHandlerKind.VkEv_REXW_3: elem = new OpCodeHandler_EVEX_VkEv_REXW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadCode()); return 1; case EvexOpCodeHandlerKind.VkHM: elem = new OpCodeHandler_EVEX_VkHM(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VkHW_3: elem = new OpCodeHandler_EVEX_VkHW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.VkHW_3b: elem = new OpCodeHandler_EVEX_VkHW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.VkHW_5: elem = new OpCodeHandler_EVEX_VkHW(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.VkHW_er_4: elem = new OpCodeHandler_EVEX_VkHW_er(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), deserializer.ReadBoolean(), false); return 1; case EvexOpCodeHandlerKind.VkHW_er_4b: elem = new OpCodeHandler_EVEX_VkHW_er(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), deserializer.ReadBoolean(), true); return 1; case EvexOpCodeHandlerKind.VkHWIb_3: elem = new OpCodeHandler_EVEX_VkHWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.VkHWIb_3b: elem = new OpCodeHandler_EVEX_VkHWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.VkHWIb_5: elem = new OpCodeHandler_EVEX_VkHWIb(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.VkHWIb_er_4: elem = new OpCodeHandler_EVEX_VkHWIb_er(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.VkHWIb_er_4b: elem = new OpCodeHandler_EVEX_VkHWIb_er(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.VkM: elem = new OpCodeHandler_EVEX_VkM(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VkW_3: elem = new OpCodeHandler_EVEX_VkW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.VkW_3b: elem = new OpCodeHandler_EVEX_VkW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.VkW_4: elem = new OpCodeHandler_EVEX_VkW(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.VkW_4b: elem = new OpCodeHandler_EVEX_VkW(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.VkW_er_4: elem = new OpCodeHandler_EVEX_VkW_er(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), deserializer.ReadBoolean()); return 1; case EvexOpCodeHandlerKind.VkW_er_5: elem = new OpCodeHandler_EVEX_VkW_er(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), deserializer.ReadBoolean()); return 1; case EvexOpCodeHandlerKind.VkW_er_6: elem = new OpCodeHandler_EVEX_VkW_er(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), deserializer.ReadBoolean(), deserializer.ReadBoolean()); return 1; case EvexOpCodeHandlerKind.VkWIb_3: elem = new OpCodeHandler_EVEX_VkWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), false); return 1; case EvexOpCodeHandlerKind.VkWIb_3b: elem = new OpCodeHandler_EVEX_VkWIb(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), true); return 1; case EvexOpCodeHandlerKind.VkWIb_er: elem = new OpCodeHandler_EVEX_VkWIb_er(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VM: elem = new OpCodeHandler_EVEX_VM(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VSIB_k1: elem = new OpCodeHandler_EVEX_VSIB_k1(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VSIB_k1_VX: elem = new OpCodeHandler_EVEX_VSIB_k1_VX(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VW: elem = new OpCodeHandler_EVEX_VW(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VW_er: elem = new OpCodeHandler_EVEX_VW_er(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.VX_Ev: code = deserializer.ReadCode(); elem = new OpCodeHandler_EVEX_VX_Ev(code, code + 1, deserializer.ReadTupleType(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.WkHV: elem = new OpCodeHandler_EVEX_WkHV(deserializer.ReadRegister(), deserializer.ReadCode()); return 1; case EvexOpCodeHandlerKind.WkV_3: elem = new OpCodeHandler_EVEX_WkV(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.WkV_4a: elem = new OpCodeHandler_EVEX_WkV(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.WkV_4b: elem = new OpCodeHandler_EVEX_WkV(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType(), deserializer.ReadBoolean()); return 1; case EvexOpCodeHandlerKind.WkVIb: elem = new OpCodeHandler_EVEX_WkVIb(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.WkVIb_er: elem = new OpCodeHandler_EVEX_WkVIb_er(deserializer.ReadRegister(), deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; case EvexOpCodeHandlerKind.WV: elem = new OpCodeHandler_EVEX_WV(deserializer.ReadRegister(), deserializer.ReadCode(), deserializer.ReadTupleType()); return 1; default: throw new InvalidOperationException(); } } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SWP.Backend.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public static class UKGameObjectExtension { /// <summary> /// Checks if an object has a given object as parent. /// </summary> /// <returns><c>true</c> if parent is child's parent or if both are equal. /// <param name="child">Child.</param> /// <param name="parent">Parent.</param> public static bool IsChildOfParent(this GameObject child, GameObject parent) { if (child == parent) { return true; } else if (child.transform.parent != null) { return IsChildOfParent(child.transform.parent.gameObject, parent); } else { return false; } } /// <summary> /// Finds the first child object with a given name (depth first). /// </summary> /// <returns>The child with the name or null.</returns> /// <param name="root">Root.</param> /// <param name="name">Name.</param> public static GameObject FindChildByNameDeep(this GameObject root, string name){ if (root.name == name){ return root; } else { int count = root.transform.childCount; for (int i = 0; i < count; ++i){ GameObject child = root.transform.GetChild(i).gameObject; GameObject searchResult = FindChildByNameDeep(child, name); if (searchResult != null){ return searchResult; } } } return null; } /// <summary> /// Finds the first child with a given substring in its name. /// </summary> /// <returns>The first child or null.</returns> /// <param name="root">Root.</param> /// <param name="substring">Substring.</param> public static GameObject FindChildBySubstringInName(this GameObject root, string substring){ if (root.name.IndexOf(substring) != -1){ return root; } else { int count = root.transform.childCount; for (int i = 0; i < count; ++i){ GameObject child = root.transform.GetChild(i).gameObject; GameObject searchResult = FindChildBySubstringInName(child, substring); if (searchResult != null){ return searchResult; } } } return null; } public static void VisitComponentsInDirectChildren<T>(this GameObject root, Action<T> callback) where T : Component { int count = root.transform.childCount; for (int i = 0; i < count; ++i){ GameObject child = root.transform.GetChild(i).gameObject; T t = child.GetComponent<T>(); if (t) callback(t); } } public static IEnumerable<GameObject> EnumGameObjectsDeep(this GameObject root) { yield return root; int count = root.transform.childCount; for (int i = 0; i < count; ++i){ GameObject child = root.transform.GetChild(i).gameObject; foreach (var x in child.EnumGameObjectsDeep()) { yield return x; } } } public static IEnumerable<GameObject> EnumChilds(this GameObject gameObject) { int count = gameObject.transform.childCount; for (int i = 0; i < count; ++i){ GameObject child = gameObject.transform.GetChild(i).gameObject; yield return child; } } public static IEnumerable<T> EnumComponentsDeep<T>(this GameObject root) where T : Component { T t = root.GetComponent<T>(); if (t) yield return t; int count = root.transform.childCount; for (int i = 0; i < count; ++i){ GameObject child = root.transform.GetChild(i).gameObject; foreach (var x in child.EnumComponentsDeep<T>()) { yield return x; } } } /** * recursive and expensive */ public static void VisitComponentsDeep<T>(this GameObject root, Action<T> callback) where T : Component { foreach(var c in root.EnumComponentsDeep<T>()) { callback(c); } } public static void VisitGameObjectsDeep(this GameObject root, Action<GameObject> callback) { callback(root); int count = root.transform.childCount; for (int i = 0; i < count; ++i){ GameObject child = root.transform.GetChild(i).gameObject; VisitGameObjectsDeep(child, callback); } } public static void RemoveAllComponentsOfType<T>(this GameObject root) where T : Component { T[] ts = root.GetComponentsInChildren<T>(); foreach(T t in ts) { Component.Destroy(t); } } public static bool HasParentWithName(this GameObject child, String parentName) { if (child.name == parentName) { return true; } if (child.transform.parent != null) { return HasParentWithName(child.transform.parent.gameObject, parentName); } else { return false; } } public static String PrintPathToRoot(this GameObject o) { if (o) { String name = "?"; if (o.name.Length > 0) { name = o.name; } if (o.transform.parent) { return PrintPathToRoot(o.transform.parent.gameObject) + "." + name; } else { return name; } } else { return ""; } } public static Vector3 GetAABBMeshCenter(this GameObject o) { MeshFilter mf = o.GetComponent<MeshFilter>(); if (mf != null) { return o.transform.TransformPoint(mf.mesh.bounds.center); } throw new Exception("there is no mesh to calculate center"); } public static void RemoveComponent<T>(this GameObject gameObject) where T : Component { T t = gameObject.GetComponent<T>(); if (t != null) { GameObject.Destroy(t); } } public static T EnsureComponent<T>(this GameObject gameObject) where T : Component { T t = gameObject.GetComponent<T>(); if (t == null) { t = gameObject.AddComponent<T>(); } return t; } public static T FindComponentDeep<T>(this GameObject gameObject) where T : Component { foreach(var c in gameObject.EnumComponentsDeep<T>()) { return c; } return null; } public static T FindComponentUpwards<T>(this GameObject gameObject) where T : Component { Transform t = gameObject.transform; while (t) { var c = t.GetComponent<T>(); if (c != null) return c; t = t.transform.parent; } return null; } public static void RemoveAllChildren(this GameObject gameObject) { int counter = gameObject.transform.childCount; while( counter > 0 ) { counter--; GameObject.Destroy( gameObject.transform.GetChild(counter).gameObject ); } } public static void ResetTransformLocal(this GameObject gameObject) { gameObject.transform.localPosition = Vector3.zero; gameObject.transform.localScale = Vector3.one; gameObject.transform.localRotation = Quaternion.identity; } }
// 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.Linq; using System.Reflection; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Diagnostics { internal static class AnalyzerHelper { private const string CSharpCompilerAnalyzerTypeName = "Microsoft.CodeAnalysis.Diagnostics.CSharp.CSharpCompilerDiagnosticAnalyzer"; private const string VisualBasicCompilerAnalyzerTypeName = "Microsoft.CodeAnalysis.Diagnostics.VisualBasic.VisualBasicCompilerDiagnosticAnalyzer"; // These are the error codes of the compiler warnings. // Keep the ids the same so that de-duplication against compiler errors // works in the error list (after a build). internal const string WRN_AnalyzerCannotBeCreatedIdCS = "CS8032"; internal const string WRN_AnalyzerCannotBeCreatedIdVB = "BC42376"; internal const string WRN_NoAnalyzerInAssemblyIdCS = "CS8033"; internal const string WRN_NoAnalyzerInAssemblyIdVB = "BC42377"; internal const string WRN_UnableToLoadAnalyzerIdCS = "CS8034"; internal const string WRN_UnableToLoadAnalyzerIdVB = "BC42378"; // Shared with Compiler internal const string AnalyzerExceptionDiagnosticId = "AD0001"; internal const string AnalyzerDriverExceptionDiagnosticId = "AD0002"; // IDE only errors internal const string WRN_AnalyzerCannotBeCreatedId = "AD1000"; internal const string WRN_NoAnalyzerInAssemblyId = "AD1001"; internal const string WRN_UnableToLoadAnalyzerId = "AD1002"; private const string AnalyzerExceptionDiagnosticCategory = "Intellisense"; public static bool IsWorkspaceDiagnosticAnalyzer(this DiagnosticAnalyzer analyzer) { return analyzer is DocumentDiagnosticAnalyzer || analyzer is ProjectDiagnosticAnalyzer; } public static bool IsBuiltInAnalyzer(this DiagnosticAnalyzer analyzer) { return analyzer is IBuiltInAnalyzer || analyzer.IsWorkspaceDiagnosticAnalyzer() || analyzer.IsCompilerAnalyzer(); } public static bool ShouldRunForFullProject(this DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer, Project project) { var builtInAnalyzer = analyzer as IBuiltInAnalyzer; if (builtInAnalyzer != null) { return !builtInAnalyzer.OpenFileOnly(project.Solution.Workspace); } if (analyzer.IsWorkspaceDiagnosticAnalyzer()) { return true; } // most of analyzers, number of descriptor is quite small, so this should be cheap. return service.GetDiagnosticDescriptors(analyzer).Any(d => d.GetEffectiveSeverity(project.CompilationOptions) != ReportDiagnostic.Hidden); } public static ReportDiagnostic GetEffectiveSeverity(this DiagnosticDescriptor descriptor, CompilationOptions options) { return options == null ? descriptor.DefaultSeverity.MapSeverityToReport() : descriptor.GetEffectiveSeverity(options); } public static ReportDiagnostic MapSeverityToReport(this DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Hidden: return ReportDiagnostic.Hidden; case DiagnosticSeverity.Info: return ReportDiagnostic.Info; case DiagnosticSeverity.Warning: return ReportDiagnostic.Warn; case DiagnosticSeverity.Error: return ReportDiagnostic.Error; default: throw ExceptionUtilities.Unreachable; } } public static bool IsCompilerAnalyzer(this DiagnosticAnalyzer analyzer) { // TODO: find better way. var typeString = analyzer.GetType().ToString(); if (typeString == CSharpCompilerAnalyzerTypeName) { return true; } if (typeString == VisualBasicCompilerAnalyzerTypeName) { return true; } return false; } public static ValueTuple<string, VersionStamp> GetAnalyzerIdAndVersion(this DiagnosticAnalyzer analyzer) { // Get the unique ID for given diagnostic analyzer. // note that we also put version stamp so that we can detect changed analyzer. var typeInfo = analyzer.GetType().GetTypeInfo(); return ValueTuple.Create(analyzer.GetAnalyzerId(), GetAnalyzerVersion(CorLightup.Desktop.GetAssemblyLocation(typeInfo.Assembly))); } public static string GetAnalyzerAssemblyName(this DiagnosticAnalyzer analyzer) { var typeInfo = analyzer.GetType().GetTypeInfo(); return typeInfo.Assembly.GetName().Name; } public static async Task<OptionSet> GetDocumentOptionSetAsync(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var workspace = (analyzerOptions as WorkspaceAnalyzerOptions)?.Workspace; if (workspace == null) { return null; } var documentId = workspace.CurrentSolution.GetDocumentId(syntaxTree); if (documentId == null) { return workspace.Options; } var document = workspace.CurrentSolution.GetDocument(documentId); if (document == null) { return workspace.Options; } var documentOptionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); return documentOptionSet ?? workspace.Options; } internal static void OnAnalyzerException_NoTelemetryLogging( Exception ex, DiagnosticAnalyzer analyzer, Diagnostic diagnostic, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource, ProjectId projectIdOpt) { if (diagnostic != null) { hostDiagnosticUpdateSource?.ReportAnalyzerDiagnostic(analyzer, diagnostic, hostDiagnosticUpdateSource?.Workspace, projectIdOpt); } if (IsBuiltInAnalyzer(analyzer)) { FatalError.ReportWithoutCrashUnlessCanceled(ex); } } internal static void OnAnalyzerExceptionForSupportedDiagnostics(DiagnosticAnalyzer analyzer, Exception exception, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource) { if (exception is OperationCanceledException) { return; } var diagnostic = CreateAnalyzerExceptionDiagnostic(analyzer, exception); OnAnalyzerException_NoTelemetryLogging(exception, analyzer, diagnostic, hostDiagnosticUpdateSource, projectIdOpt: null); } /// <summary> /// Create a diagnostic for exception thrown by the given analyzer. /// </summary> /// <remarks> /// Keep this method in sync with "AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic". /// </remarks> internal static Diagnostic CreateAnalyzerExceptionDiagnostic(DiagnosticAnalyzer analyzer, Exception e) { var analyzerName = analyzer.ToString(); // TODO: It is not ideal to create a new descriptor per analyzer exception diagnostic instance. // However, until we add a LongMessage field to the Diagnostic, we are forced to park the instance specific description onto the Descriptor's Description field. // This requires us to create a new DiagnosticDescriptor instance per diagnostic instance. var descriptor = new DiagnosticDescriptor(AnalyzerExceptionDiagnosticId, title: FeaturesResources.User_Diagnostic_Analyzer_Failure, messageFormat: FeaturesResources.Analyzer_0_threw_an_exception_of_type_1_with_message_2, description: string.Format(FeaturesResources.Analyzer_0_threw_the_following_exception_colon_1, analyzerName, e.CreateDiagnosticDescription()), category: AnalyzerExceptionDiagnosticCategory, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); return Diagnostic.Create(descriptor, Location.None, analyzerName, e.GetType(), e.Message); } private static VersionStamp GetAnalyzerVersion(string path) { if (path == null || !File.Exists(path)) { return VersionStamp.Default; } return VersionStamp.Create(File.GetLastWriteTimeUtc(path)); } public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic(string fullPath, AnalyzerLoadFailureEventArgs e) { return CreateAnalyzerLoadFailureDiagnostic(null, null, null, fullPath, e); } public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic( Workspace workspace, ProjectId projectId, string language, string fullPath, AnalyzerLoadFailureEventArgs e) { if (!TryGetErrorMessage(language, fullPath, e, out var id, out var message, out var messageFormat, out var description)) { return null; } return new DiagnosticData( id, FeaturesResources.Roslyn_HostError, message, messageFormat, severity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description, warningLevel: 0, workspace: workspace, projectId: projectId); } private static bool TryGetErrorMessage( string language, string fullPath, AnalyzerLoadFailureEventArgs e, out string id, out string message, out string messageFormat, out string description) { switch (e.ErrorCode) { case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer: id = Choose(language, WRN_UnableToLoadAnalyzerId, WRN_UnableToLoadAnalyzerIdCS, WRN_UnableToLoadAnalyzerIdVB); messageFormat = FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1; message = string.Format(FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1, fullPath, e.Message); description = e.Exception.CreateDiagnosticDescription(); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer: id = Choose(language, WRN_AnalyzerCannotBeCreatedId, WRN_AnalyzerCannotBeCreatedIdCS, WRN_AnalyzerCannotBeCreatedIdVB); messageFormat = FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2; message = string.Format(FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2, e.TypeName, fullPath, e.Message); description = e.Exception.CreateDiagnosticDescription(); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers: id = Choose(language, WRN_NoAnalyzerInAssemblyId, WRN_NoAnalyzerInAssemblyIdCS, WRN_NoAnalyzerInAssemblyIdVB); messageFormat = FeaturesResources.The_assembly_0_does_not_contain_any_analyzers; message = string.Format(FeaturesResources.The_assembly_0_does_not_contain_any_analyzers, fullPath); description = e.Exception.CreateDiagnosticDescription(); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.None: default: id = string.Empty; message = string.Empty; messageFormat = string.Empty; description = string.Empty; return false; } return true; } private static string Choose(string language, string noLanguageMessage, string csharpMessage, string vbMessage) { if (language == null) { return noLanguageMessage; } return language == LanguageNames.CSharp ? csharpMessage : vbMessage; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Magecrawl.Interfaces; using Magecrawl.Maps.MapObjects; using Magecrawl.Utilities; namespace Magecrawl.Maps.Generator.Stitch { // The idea of this clsas is that we read from file(s) a set of // building blocks that we can stitch togeather to get a good map. // There are Entrances, hallways (horizontal and vertical), Main Rooms // Treausre Rooms, and side rooms public sealed class StitchtogeatherMapGenerator : MapGeneratorBase { private const int Width = 250; private const int Height = 250; private static List<MapChunk> m_entrances; private static List<MapChunk> m_halls; private static List<MapChunk> m_mainRooms; private static List<MapChunk> m_treasureRooms; private static List<MapChunk> m_sideRooms; private static bool m_chunksLoaded = false; private StitchtogeatherMapGraphGenerator m_graphGenerator; private Queue<MapNode> m_unplacedDueToSpace; private int m_smallestX; private int m_smallestY; private int m_largestX; private int m_largestY; private int m_placed; private int m_level; public StitchtogeatherMapGenerator(Random random) : base(random) { m_unplacedDueToSpace = new Queue<MapNode>(); m_graphGenerator = new StitchtogeatherMapGraphGenerator(); m_smallestX = Int32.MaxValue; m_smallestY = Int32.MaxValue; m_largestX = Int32.MinValue; m_largestY = Int32.MinValue; m_placed = 0; LoadChunksFromFile("Map" + Path.DirectorySeparatorChar + "DungeonChunks.dat"); } // So we don't have to walk the entire map to find the lower left and trim // as we generate the map, keep track private void PossiblyUpdateLargestSmallestPoint(Point upperLeft, MapChunk chunk) { m_placed++; Point lowerRight = upperLeft + new Point(chunk.Width, chunk.Height); m_smallestX = Math.Min(m_smallestX, upperLeft.X); m_smallestY = Math.Min(m_smallestY, upperLeft.Y); m_largestX = Math.Max(m_largestX, lowerRight.X); m_largestY = Math.Max(m_largestY, lowerRight.Y); if (m_smallestX < 0) throw new ArgumentException("Width too small"); if (m_smallestY < 0) throw new ArgumentException("Height too small"); if (m_largestX >= Width) throw new ArgumentException("Width too large"); if (m_largestY >= Height) throw new ArgumentException("Height too large"); } public override Map GenerateMap(Stairs incommingStairs, int level) { for (int i = 0; i < 5; ++i) { m_level = level; Map map = new Map(Width, Height); MapNode graphHead = m_graphGenerator.GenerateMapGraph(); ParenthoodChain parentChain = new ParenthoodChain(); GenerateMapFromGraph(graphHead, map, Point.Invalid, parentChain); Point upperLeft = new Point(m_smallestX, m_smallestY); Point lowerRight = new Point(m_largestX, m_largestY); map.TrimToSubset(upperLeft, lowerRight); if (!CheckConnectivity(map)) continue; if (m_placed < 30) continue; GenerateUpDownStairs(map, incommingStairs); StripImpossibleDoors(map); return map; } throw new MapGenerationFailureException("Unable to generate Stitch map with multiple attempts."); } private void StripImpossibleDoors(Map map) { foreach (MapDoor door in map.MapObjects.OfType<MapDoor>().ToList()) { if (!map.IsPointOnMap(door.Position) || map.GetTerrainAt(door.Position) == TerrainType.Wall || !WallsOnOneSetOfSides(map, door)) { map.RemoveMapItem(door); } } List<Point> doorPositions = map.MapObjects.OfType<MapDoor>().Select(x => x.Position).ToList(); foreach (MapDoor door in map.MapObjects.OfType<MapDoor>().ToList()) { if (doorPositions.Exists(x => x != door.Position && PointDirectionUtils.NormalDistance(x, door.Position) < 2)) { map.RemoveMapItem(door); doorPositions.Remove(door.Position); } } } private bool WallsOnOneSetOfSides(Map map, MapDoor door) { return (map.GetTerrainAt(door.Position + new Point(1, 0)) == TerrainType.Wall && map.GetTerrainAt(door.Position + new Point(-1, 0)) == TerrainType.Wall) || (map.GetTerrainAt(door.Position + new Point(0, 1)) == TerrainType.Wall && map.GetTerrainAt(door.Position + new Point(0, -1)) == TerrainType.Wall); } private MapChunk GetRandomChunkFromList(List<MapChunk> chunk) { MapChunk newChunk = new MapChunk(chunk[m_random.getInt(0, chunk.Count - 1)]); newChunk.Prepare(); return newChunk; } private void GenerateMapFromGraph(MapNode current, Map map, Point seam, ParenthoodChain parentChain) { if (current.Generated) return; current.Generated = true; bool placed = false; switch (current.Type) { case MapNodeType.Entrance: { placed = true; MapChunk entranceChunk = GetRandomChunkFromList(m_entrances); // We need to place entrace so it's at our expected location Point randomCenter = new Point(m_random.getInt(100, 150), m_random.getInt(100, 150)); Point entraceUpperLeftCorner = randomCenter - entranceChunk.PlayerPosition; parentChain.Push(entranceChunk, entraceUpperLeftCorner, Point.Invalid); entranceChunk.PlaceChunkOnMapAtPosition(map, entraceUpperLeftCorner, m_random); PossiblyUpdateLargestSmallestPoint(entraceUpperLeftCorner, entranceChunk); map.AddMapItem(MapObjectFactory.Instance.CreateMapObject("StairsUp", entranceChunk.PlayerPosition + entraceUpperLeftCorner)); if (current.Neighbors.Count != entranceChunk.Seams.Count) throw new InvalidOperationException("Number of neighbors should equal number of seams."); WalkNeighbors(current, entranceChunk, map, entraceUpperLeftCorner, parentChain); parentChain.Pop(); break; } case MapNodeType.Hall: { for (int i = 0; i < 10; i++) { placed = PlaceMapNode(current, GetRandomChunkFromList(m_halls), map, seam, parentChain); if (placed) break; } break; } case MapNodeType.None: { // If we have nothing, see if we have any orphan nodes to try to place if (m_unplacedDueToSpace.Count > 0) { // Grab the first unplaced node, and try again. MapNode treeToGraphOn = m_unplacedDueToSpace.Dequeue(); treeToGraphOn.Generated = false; GenerateMapFromGraph(treeToGraphOn, map, seam, parentChain); } else { map.SetTerrainAt(seam, TerrainType.Wall); if (current.Neighbors.Count != 0) throw new InvalidOperationException("None Node types should only have no neighbors"); } placed = true; break; } case MapNodeType.MainRoom: { placed = PlaceMapNode(current, GetRandomChunkFromList(m_mainRooms), map, seam, parentChain); break; } case MapNodeType.TreasureRoom: { placed = PlaceMapNode(current, GetRandomChunkFromList(m_treasureRooms), map, seam, parentChain); break; } case MapNodeType.SideRoom: { placed = PlaceMapNode(current, GetRandomChunkFromList(m_sideRooms), map, seam, parentChain); break; } case MapNodeType.NoneGivenYet: default: throw new InvalidOperationException("Trying to generate MapNode from invalid node."); } if (!placed) { UnplacePossibleHallwayToNowhere(map, parentChain); m_unplacedDueToSpace.Enqueue(current); } } private void UnplacePossibleHallwayToNowhere(Map map, ParenthoodChain parentChain) { ParenthoodChain localChain = new ParenthoodChain(parentChain); ParenthoodElement top = localChain.Pop(); Point seamToFill = Point.Invalid; if (top.Chunk.Type == MapNodeType.Hall) { do { if (top.Chunk.Type == MapNodeType.Hall) { m_placed--; top.Chunk.UnplaceChunkOnMapAtPosition(map, top.UpperLeft); seamToFill = top.Seam; top = localChain.Pop(); } else { if (seamToFill == Point.Invalid) throw new MapGenerationFailureException("Trying to fill in invalid seam"); map.SetTerrainAt(seamToFill, TerrainType.Wall); break; } } while (true); } } // Returns true if placed, false if we walled off seam private bool PlaceMapNode(MapNode current, MapChunk mapChunk, Map map, Point seam, ParenthoodChain parentChain) { Point placedUpperLeftCorner = mapChunk.PlaceChunkOnMap(map, seam, m_level); if (placedUpperLeftCorner == Point.Invalid) { map.SetTerrainAt(seam, TerrainType.Wall); return false; } else { PossiblyUpdateLargestSmallestPoint(placedUpperLeftCorner, mapChunk); map.SetTerrainAt(seam, TerrainType.Floor); parentChain.Push(mapChunk, placedUpperLeftCorner, seam); WalkNeighbors(current, mapChunk, map, placedUpperLeftCorner, parentChain); parentChain.Pop(); return true; } } private void WalkNeighbors(MapNode currentNode, MapChunk currentChunk, Map map, Point upperLeft, ParenthoodChain parentChain) { while (currentNode.Neighbors.Count > 0) { MapNode nextNode = currentNode.Neighbors[0]; nextNode.RemoveNeighbor(currentNode); currentNode.RemoveNeighbor(nextNode); Point seam = currentChunk.Seams[0]; currentChunk.Seams.Remove(seam); GenerateMapFromGraph(nextNode, map, seam + upperLeft, parentChain); } } private static void LoadChunksFromFile(string fileName) { if (!m_chunksLoaded) { m_chunksLoaded = true; m_entrances = new List<MapChunk>(); m_halls = new List<MapChunk>(); m_mainRooms = new List<MapChunk>(); m_treasureRooms = new List<MapChunk>(); m_sideRooms = new List<MapChunk>(); using (StreamReader inputFile = XMLResourceReaderBase.GetFileStream(fileName)) { while (!inputFile.EndOfStream) { string definationLine = inputFile.ReadLine(); string[] definationParts = definationLine.Split(' '); int width = int.Parse(definationParts[0], CultureInfo.InvariantCulture); int height = int.Parse(definationParts[1], CultureInfo.InvariantCulture); string chunkType = definationParts[2]; MapChunk newChunk = new MapChunk(width, height, chunkType); newChunk.ReadSegmentFromFile(inputFile); if (chunkType != "Hall") newChunk.Doors.AddRange(newChunk.Seams); switch (chunkType) { case "Entrance": m_entrances.Add(newChunk); break; case "Hall": m_halls.Add(newChunk); break; case "MainRoom": m_mainRooms.Add(newChunk); break; case "TreasureRoom": m_treasureRooms.Add(newChunk); break; case "SideRoom": m_sideRooms.Add(newChunk); break; default: throw new ArgumentOutOfRangeException("Unknown Chunk Type Read From File"); } inputFile.ReadLine(); } } } } } }
//Copyright 2016 Malooba Ltd //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Linq; using System.Runtime.InteropServices; using DeckLinkAPI; namespace MaloobaFingerprint.FingerprintAnalyser { /// <summary> /// Callback object for Decklink Monitor card /// </summary> internal class Callback : IDeckLinkInputCallback { private readonly AnalyserConfig config; public event EventHandler<FingerprintEventArgs> FingerprintCreated; private readonly Channel[] channelData; // Three slot triangular window private readonly double[] window0; private readonly double[] window1; private readonly double[] window2; /// <summary> /// Hadamard masks /// </summary> private readonly int[,] masks = { { 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1}, { 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1}, { 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1}, { 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1}, { 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1}, { 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1}, { 1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1}, { 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1}, { 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1}, { 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1}, { 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1}, { 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1}, { 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1}, { 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1}, { 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1} }; /// <summary> /// Construct with configuration and output stream writer /// </summary> /// <param name="config"></param> public Callback(AnalyserConfig config) { this.config = config; // sps is assumed to be even var sps = config.SamplesPerSlot; channelData = new Channel[Analyser.CHANNELS]; for(var c = 0; c < Analyser.CHANNELS; c++) channelData[c] = new Channel(config); window0 = new double[sps]; window1 = new double[sps]; window2 = new double[sps]; // Build a triangular window across 3 slots var half = sps * 3 >> 1; var end = (sps << 1) - 1; var step = 1.0 / (half - 1); for(var i = 0; i < sps; i++) window0[i] = window2[sps - 1 - i] = i * step; for(var i = sps; i < half; i++) window1[i - sps] = window1[end - i] = i * step; } /// <summary> /// Calback function for input format change (unused) /// </summary> /// <param name="notificationEvents"></param> /// <param name="newDisplayMode"></param> /// <param name="detectedSignalFlags"></param> public void VideoInputFormatChanged(_BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode newDisplayMode, _BMDDetectedVideoInputFormatFlags detectedSignalFlags) { } /// <summary> /// Calback function for new frame /// </summary> /// <param name="videoFrame"></param> /// <param name="audioPacket"></param> public void VideoInputFrameArrived(IDeckLinkVideoInputFrame videoFrame, IDeckLinkAudioInputPacket audioPacket) { // The conditions under which either of these cases occur are unclear but an overstreched processor doesn't help if(videoFrame == null || audioPacket == null) return; IDeckLinkTimecode timecode; videoFrame.GetTimecode(config.TimecodeFormat, out timecode); if(audioPacket.GetSampleFrameCount() != config.SamplesPerSlot * config.SlotsPerFrame) throw new ApplicationException("Wrong buffer size"); IntPtr buffer; audioPacket.GetBytes(out buffer); var audioFingerprints = GetAudioFingerprints(buffer, config); var timecodeBcd = timecode?.GetBCD() ?? 0; FingerprintCreated?.Invoke(this, new FingerprintEventArgs(timecodeBcd, (byte)config.SlotsPerFrame, 0, audioFingerprints)); // The documentation suggests that neither of these are necessary // BM's own code does the former // Including these doesn't make anything go bang so, in for a penny... Marshal.ReleaseComObject(videoFrame); Marshal.ReleaseComObject(audioPacket); } /// <summary> /// Generate a 15-bit video fingerprint from the input YUV244 buffer /// This is currently unused but could be used to regenerate timecode on the destination video /// if this has been lost in the trancode process. There are many other potential uses for this fingerprint data. /// /// The algorithm divides the frame into 16 blocks (4x4) and applies the Hadamard masks to divide these blocks /// into two sets in 15 different and orthogonal ways. The relative brightness of each pair of sets yields one /// bit of the fingerprint. The entire fingerprint is comprised of 15 bits; one from each Hadamard mask. /// The whole algorithm is resilient to changes of resolution, aspect, brightness, contrast and gamma that might occur in the /// transcode process. It would be a simple matter to automatically detect letterboxing/pillarboxing and to only analyse the /// active video area if this were required. /// Testing with transcoded broadcast video has shown the fingerprint to be robust and reliable. /// </summary> /// <param name="videoFrame"></param> /// <param name="sums"></param> /// <returns></returns> private unsafe int VideoFingerprint(IDeckLinkVideoInputFrame videoFrame, int[] sums) { var qheight = videoFrame.GetHeight() >> 2; var qwidth = videoFrame.GetWidth() >> 2; IntPtr buffer; videoFrame.GetBytes(out buffer); var ptr = (byte*)buffer + 1; // Skip over first U byte for(var r = 0; r < qheight; r++) { for(var c = 0; c < qwidth; c++) { sums[0] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[1] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[2] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[3] += *ptr; ptr += 2; } } for(var r = 0; r < qheight; r++) { for(var c = 0; c < qwidth; c++) { sums[4] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[5] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[6] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[7] += *ptr; ptr += 2; } } for(var r = 0; r < qheight; r++) { for(var c = 0; c < qwidth; c++) { sums[8] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[9] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[10] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[11] += *ptr; ptr += 2; } } for(var r = 0; r < qheight; r++) { for(var c = 0; c < qwidth; c++) { sums[12] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[13] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[14] += *ptr; ptr += 2; } for(var c = 0; c < qwidth; c++) { sums[15] += *ptr; ptr += 2; } } for(var i = 0; i < 16; i++) { sums[i] /= qwidth * qheight; } var videoFingerprint = 0; var bit = 1; for(var i = 0; i < 15; i++) { var sum = 0; for(var j = 0; j < 16; j++) sum += sums[j] * masks[i, j]; if(sum > 0) videoFingerprint |= bit; bit <<= 1; } return videoFingerprint; } /// <summary> /// Generate an audio fingerprint for each selected input audio channel in the buffer /// </summary> /// <param name="buffer"></param> /// <returns></returns> internal unsafe ulong[] GetAudioFingerprints(IntPtr buffer, AnalyserConfig config) { var signatures = new ulong[Analyser.CHANNELS]; // window support var support = config.SamplesPerSlot * 3; for(var channel = 0; channel < Analyser.CHANNELS; channel++) { var signature = 0UL; var signalPresent = false; var cd = channelData[channel]; // Initialise sptr to the first sample for the channel var sptr = (short*)(buffer) + channel; var bit = 1UL << config.SlotsPerFrame; for(var slot = 0; slot < config.SlotsPerFrame; slot++) { // Sum of squares of windowed samples var ssqr = 0.0; for(var i = 0; i < config.SamplesPerSlot; i++) { var sample = *sptr; // Step to the same channel in the next sample sptr += Analyser.CHANNELS; var fsample = cd.Filter.Filter(sample); cd.Slot2[i] = fsample * fsample; ssqr += window0[i] * cd.Slot0[i] + window1[i] * cd.Slot1[i] + window2[i] * cd.Slot2[i]; } signalPresent = signalPresent || (ssqr > 0); // Convert to logarithmic RMS // The log scaling ensures that we are working with perceived loudness var rms = signalPresent ? Math.Log10(ssqr / support) : 0.0; // Rotate the slot buffers var tmp = cd.Slot0; cd.Slot0 = cd.Slot1; cd.Slot1 = cd.Slot2; cd.Slot2 = tmp; bit >>= 1; var rmsa = cd.RmsBuffer.Average(); if(rms > rmsa) signature |= bit; Buffer.BlockCopy(cd.RmsBuffer, sizeof(double), cd.RmsBuffer, 0, (config.FirLength - 1) * sizeof(double)); cd.RmsBuffer[config.FirLength - 1] = rms; } // MSB is a signal present flag if(signalPresent) signature |= 0x8000000000000000UL; signatures[channel] = signature; } return signatures; } } }
namespace microForum.Migrations { using System; using System.Data.Entity.Migrations; public partial class intial : DbMigration { public override void Up() { CreateTable( "dbo.Answers", c => new { AnswerId = c.Int(nullable: false), AnwserText = c.String(), QuestionId = c.Int(nullable: false), Question_QuestionId = c.Int(nullable: false), }) .PrimaryKey(t => t.AnswerId) .ForeignKey("dbo.Questions", t => t.AnswerId) .ForeignKey("dbo.Questions", t => t.Question_QuestionId, cascadeDelete: true) .Index(t => t.AnswerId) .Index(t => t.Question_QuestionId); CreateTable( "dbo.Questions", c => new { QuestionId = c.Int(nullable: false, identity: true), Content = c.String(), CorrectAnwserId = c.Int(nullable: false), Quiz_QuizId = c.Int(), }) .PrimaryKey(t => t.QuestionId) .ForeignKey("dbo.Quizs", t => t.Quiz_QuizId) .Index(t => t.Quiz_QuizId); CreateTable( "dbo.Codes", c => new { CodeId = c.Int(nullable: false, identity: true), Body = c.String(), CodeOrdering = c.Int(nullable: false), LanguageId = c.Int(nullable: false), CodeSampleId = c.Int(nullable: false), }) .PrimaryKey(t => t.CodeId) .ForeignKey("dbo.CodeSamples", t => t.CodeSampleId, cascadeDelete: true) .ForeignKey("dbo.Languages", t => t.LanguageId, cascadeDelete: true) .Index(t => t.LanguageId) .Index(t => t.CodeSampleId); CreateTable( "dbo.CodeSamples", c => new { CodeSampleId = c.Int(nullable: false, identity: true), Name = c.String(), Description = c.String(), Language_LanguageId = c.Int(), }) .PrimaryKey(t => t.CodeSampleId) .ForeignKey("dbo.Languages", t => t.Language_LanguageId) .Index(t => t.Language_LanguageId); CreateTable( "dbo.Tags", c => new { TagId = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.TagId); CreateTable( "dbo.Languages", c => new { LanguageId = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.LanguageId); CreateTable( "dbo.Images", c => new { ImageId = c.Int(nullable: false, identity: true), Description = c.String(), Url = c.String(), UserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.ImageId) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.Posts", c => new { PostId = c.Int(nullable: false, identity: true), Headline = c.String(nullable: false), Body = c.String(nullable: false), DateCreated = c.DateTime(nullable: false), UserId = c.String(maxLength: 128), ThreadId = c.Int(nullable: false), }) .PrimaryKey(t => t.PostId) .ForeignKey("dbo.Threads", t => t.ThreadId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId) .Index(t => t.ThreadId); CreateTable( "dbo.Threads", c => new { ThreadId = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), Body = c.String(nullable: false), DateCreated = c.DateTime(nullable: false), TopicId = c.Int(nullable: false), VideoUrl = c.String(), UserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.ThreadId) .ForeignKey("dbo.Topics", t => t.TopicId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.TopicId) .Index(t => t.UserId); CreateTable( "dbo.Topics", c => new { TopicId = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), SortOrder = c.Int(nullable: false), TopicParentId = c.Int(), }) .PrimaryKey(t => t.TopicId) .ForeignKey("dbo.Topics", t => t.TopicParentId) .Index(t => t.TopicParentId); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.Quizs", c => new { QuizId = c.Int(nullable: false, identity: true), Title = c.String(), Description = c.String(), CreatedByUserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.QuizId) .ForeignKey("dbo.AspNetUsers", t => t.CreatedByUserId) .Index(t => t.CreatedByUserId); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); CreateTable( "dbo.TagCodeSamples", c => new { Tag_TagId = c.Int(nullable: false), CodeSample_CodeSampleId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.Tag_TagId, t.CodeSample_CodeSampleId }) .ForeignKey("dbo.Tags", t => t.Tag_TagId, cascadeDelete: true) .ForeignKey("dbo.CodeSamples", t => t.CodeSample_CodeSampleId, cascadeDelete: true) .Index(t => t.Tag_TagId) .Index(t => t.CodeSample_CodeSampleId); CreateTable( "dbo.QuizmicroUsers", c => new { Quiz_QuizId = c.Int(nullable: false), microUser_Id = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.Quiz_QuizId, t.microUser_Id }) .ForeignKey("dbo.Quizs", t => t.Quiz_QuizId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.microUser_Id, cascadeDelete: true) .Index(t => t.Quiz_QuizId) .Index(t => t.microUser_Id); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.QuizmicroUsers", "microUser_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.QuizmicroUsers", "Quiz_QuizId", "dbo.Quizs"); DropForeignKey("dbo.Questions", "Quiz_QuizId", "dbo.Quizs"); DropForeignKey("dbo.Quizs", "CreatedByUserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Posts", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Threads", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Threads", "TopicId", "dbo.Topics"); DropForeignKey("dbo.Topics", "TopicParentId", "dbo.Topics"); DropForeignKey("dbo.Posts", "ThreadId", "dbo.Threads"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Images", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.CodeSamples", "Language_LanguageId", "dbo.Languages"); DropForeignKey("dbo.Codes", "LanguageId", "dbo.Languages"); DropForeignKey("dbo.TagCodeSamples", "CodeSample_CodeSampleId", "dbo.CodeSamples"); DropForeignKey("dbo.TagCodeSamples", "Tag_TagId", "dbo.Tags"); DropForeignKey("dbo.Codes", "CodeSampleId", "dbo.CodeSamples"); DropForeignKey("dbo.Answers", "Question_QuestionId", "dbo.Questions"); DropForeignKey("dbo.Answers", "AnswerId", "dbo.Questions"); DropIndex("dbo.QuizmicroUsers", new[] { "microUser_Id" }); DropIndex("dbo.QuizmicroUsers", new[] { "Quiz_QuizId" }); DropIndex("dbo.TagCodeSamples", new[] { "CodeSample_CodeSampleId" }); DropIndex("dbo.TagCodeSamples", new[] { "Tag_TagId" }); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.Quizs", new[] { "CreatedByUserId" }); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.Topics", new[] { "TopicParentId" }); DropIndex("dbo.Threads", new[] { "UserId" }); DropIndex("dbo.Threads", new[] { "TopicId" }); DropIndex("dbo.Posts", new[] { "ThreadId" }); DropIndex("dbo.Posts", new[] { "UserId" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.Images", new[] { "UserId" }); DropIndex("dbo.CodeSamples", new[] { "Language_LanguageId" }); DropIndex("dbo.Codes", new[] { "CodeSampleId" }); DropIndex("dbo.Codes", new[] { "LanguageId" }); DropIndex("dbo.Questions", new[] { "Quiz_QuizId" }); DropIndex("dbo.Answers", new[] { "Question_QuestionId" }); DropIndex("dbo.Answers", new[] { "AnswerId" }); DropTable("dbo.QuizmicroUsers"); DropTable("dbo.TagCodeSamples"); DropTable("dbo.AspNetRoles"); DropTable("dbo.Quizs"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.Topics"); DropTable("dbo.Threads"); DropTable("dbo.Posts"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.Images"); DropTable("dbo.Languages"); DropTable("dbo.Tags"); DropTable("dbo.CodeSamples"); DropTable("dbo.Codes"); DropTable("dbo.Questions"); DropTable("dbo.Answers"); } } }
/* * Qa full api * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: all * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HostMe.Sdk.Model { /// <summary> /// PaymentPlan /// </summary> [DataContract] public partial class PaymentPlan : IEquatable<PaymentPlan>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PaymentPlan" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="Name">Name.</param> /// <param name="Currency">Currency.</param> /// <param name="Created">Created.</param> /// <param name="Amount">Amount.</param> /// <param name="Interval">Interval.</param> /// <param name="IntervalCount">IntervalCount.</param> /// <param name="LiveMode">LiveMode.</param> /// <param name="StatementDescriptor">StatementDescriptor.</param> /// <param name="TrialPeriodDays">TrialPeriodDays.</param> /// <param name="Metadata">Metadata.</param> public PaymentPlan(string Id = null, string Name = null, string Currency = null, DateTimeOffset? Created = null, int? Amount = null, string Interval = null, int? IntervalCount = null, bool? LiveMode = null, string StatementDescriptor = null, int? TrialPeriodDays = null, Dictionary<string, string> Metadata = null) { this.Id = Id; this.Name = Name; this.Currency = Currency; this.Created = Created; this.Amount = Amount; this.Interval = Interval; this.IntervalCount = IntervalCount; this.LiveMode = LiveMode; this.StatementDescriptor = StatementDescriptor; this.TrialPeriodDays = TrialPeriodDays; this.Metadata = Metadata; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=true)] public string Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=true)] public string Name { get; set; } /// <summary> /// Gets or Sets Currency /// </summary> [DataMember(Name="currency", EmitDefaultValue=true)] public string Currency { get; set; } /// <summary> /// Gets or Sets Created /// </summary> [DataMember(Name="created", EmitDefaultValue=true)] public DateTimeOffset? Created { get; set; } /// <summary> /// Gets or Sets Amount /// </summary> [DataMember(Name="amount", EmitDefaultValue=true)] public int? Amount { get; set; } /// <summary> /// Gets or Sets Interval /// </summary> [DataMember(Name="interval", EmitDefaultValue=true)] public string Interval { get; set; } /// <summary> /// Gets or Sets IntervalCount /// </summary> [DataMember(Name="intervalCount", EmitDefaultValue=true)] public int? IntervalCount { get; set; } /// <summary> /// Gets or Sets LiveMode /// </summary> [DataMember(Name="liveMode", EmitDefaultValue=true)] public bool? LiveMode { get; set; } /// <summary> /// Gets or Sets StatementDescriptor /// </summary> [DataMember(Name="statementDescriptor", EmitDefaultValue=true)] public string StatementDescriptor { get; set; } /// <summary> /// Gets or Sets TrialPeriodDays /// </summary> [DataMember(Name="trialPeriodDays", EmitDefaultValue=true)] public int? TrialPeriodDays { get; set; } /// <summary> /// Gets or Sets Metadata /// </summary> [DataMember(Name="metadata", EmitDefaultValue=true)] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PaymentPlan {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Currency: ").Append(Currency).Append("\n"); sb.Append(" Created: ").Append(Created).Append("\n"); sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" Interval: ").Append(Interval).Append("\n"); sb.Append(" IntervalCount: ").Append(IntervalCount).Append("\n"); sb.Append(" LiveMode: ").Append(LiveMode).Append("\n"); sb.Append(" StatementDescriptor: ").Append(StatementDescriptor).Append("\n"); sb.Append(" TrialPeriodDays: ").Append(TrialPeriodDays).Append("\n"); sb.Append(" Metadata: ").Append(Metadata).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as PaymentPlan); } /// <summary> /// Returns true if PaymentPlan instances are equal /// </summary> /// <param name="other">Instance of PaymentPlan to be compared</param> /// <returns>Boolean</returns> public bool Equals(PaymentPlan other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Currency == other.Currency || this.Currency != null && this.Currency.Equals(other.Currency) ) && ( this.Created == other.Created || this.Created != null && this.Created.Equals(other.Created) ) && ( this.Amount == other.Amount || this.Amount != null && this.Amount.Equals(other.Amount) ) && ( this.Interval == other.Interval || this.Interval != null && this.Interval.Equals(other.Interval) ) && ( this.IntervalCount == other.IntervalCount || this.IntervalCount != null && this.IntervalCount.Equals(other.IntervalCount) ) && ( this.LiveMode == other.LiveMode || this.LiveMode != null && this.LiveMode.Equals(other.LiveMode) ) && ( this.StatementDescriptor == other.StatementDescriptor || this.StatementDescriptor != null && this.StatementDescriptor.Equals(other.StatementDescriptor) ) && ( this.TrialPeriodDays == other.TrialPeriodDays || this.TrialPeriodDays != null && this.TrialPeriodDays.Equals(other.TrialPeriodDays) ) && ( this.Metadata == other.Metadata || this.Metadata != null && this.Metadata.SequenceEqual(other.Metadata) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.Currency != null) hash = hash * 59 + this.Currency.GetHashCode(); if (this.Created != null) hash = hash * 59 + this.Created.GetHashCode(); if (this.Amount != null) hash = hash * 59 + this.Amount.GetHashCode(); if (this.Interval != null) hash = hash * 59 + this.Interval.GetHashCode(); if (this.IntervalCount != null) hash = hash * 59 + this.IntervalCount.GetHashCode(); if (this.LiveMode != null) hash = hash * 59 + this.LiveMode.GetHashCode(); if (this.StatementDescriptor != null) hash = hash * 59 + this.StatementDescriptor.GetHashCode(); if (this.TrialPeriodDays != null) hash = hash * 59 + this.TrialPeriodDays.GetHashCode(); if (this.Metadata != null) hash = hash * 59 + this.Metadata.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Reflection; using System.Collections; using System.Collections.Generic; namespace Manos.Routing { public class ParameterizedActionTarget : IManosTarget { private object target; private ParameterizedAction action; private ParameterInfo [] parameters; public ParameterizedActionTarget (object target, MethodInfo method, ParameterizedAction action) { if (method == null) throw new ArgumentNullException ("method"); if (action == null) throw new ArgumentNullException ("action"); this.target = target; Action = action; parameters = method.GetParameters (); } public Object Target { get { return target; } } public Delegate Action { get { return action; } set { if (value == null) throw new ArgumentNullException ("action"); ParameterizedAction pa = value as ParameterizedAction; if (pa == null) throw new InvalidOperationException ("ParameterizedActionTarget Action property can only be set to a ParameterizedAction."); action = pa; } } public void Invoke (ManosApp app, IManosContext ctx) { object [] data; if (!TryGetDataForParamList (parameters, app, ctx, out data)) { // TODO: More graceful way of handling this? ctx.Transaction.Abort (400, "Can not convert parameters to match Action argument list."); return; } action (target, data); } private ParameterInfo [] GetParamList () { MethodInfo method = action.Method; return method.GetParameters (); } public static bool TryGetDataForParamList (ParameterInfo [] parameters, ManosApp app, IManosContext ctx, out object [] data) { data = new object [parameters.Length]; int param_start = 1; data [0] = ctx; if (typeof (ManosApp).IsAssignableFrom (parameters [1].ParameterType)) { data [1] = app; ++param_start; } for (int i = param_start; i < data.Length; i++) { string name = parameters [i].Name; if (!TryConvertType (ctx, name, parameters [i], out data [i])) return false; } return true; } public static bool TryConvertType (IManosContext ctx, string name, ParameterInfo param, out object data) { Type dest = param.ParameterType; if (dest.IsArray) { var list = ctx.Request.Data.GetList (name); if (list != null) { Type element = dest.GetElementType (); IList arr = Array.CreateInstance (element, list.Count); for (int i = 0; i < list.Count; i++) { object elem_data; if (!TryConvertUnsafeString (ctx, element, param, list [i], out elem_data)) { data = null; return false; } arr [i] = elem_data; } data = arr; return true; } } if (dest.GetInterface ("IDictionary") != null) { var dict = ctx.Request.Data.GetDict (name); if (dict != null) { Type eltype = typeof (UnsafeString); IDictionary dd = (IDictionary) Activator.CreateInstance (dest); if (dest.IsGenericType) { Type [] args = dest.GetGenericArguments (); if (args.Length != 2) throw new Exception ("Generic Dictionaries must contain two generic type arguments."); if (args [0] != typeof (string)) throw new Exception ("Generic Dictionaries must use strings for their keys."); eltype = args [1]; // ie the TValue in Dictionary<TKey,TValue> } foreach (string key in dict.Keys) { object elem_data; if (!TryConvertUnsafeString (ctx, eltype, param, dict [key], out elem_data)) { data = null; return false; } dd.Add (key, elem_data); } data = dd; return true; } } UnsafeString strd = ctx.Request.Data.Get (name); return TryConvertUnsafeString (ctx, dest, param, strd, out data); } public static bool TryConvertUnsafeString (IManosContext ctx, Type type, ParameterInfo param, UnsafeString unsafe_str_value, out object data) { if (type == typeof (UnsafeString)) { data = unsafe_str_value; return true; } string str_value = unsafe_str_value == null ? null : unsafe_str_value.SafeValue; if (TryConvertFormData (type, str_value, out data)) return true; if (str_value == null && param.DefaultValue != DBNull.Value) { data = param.DefaultValue; return true; } try { data = Convert.ChangeType (str_value, type); } catch { Console.Error.WriteLine ("Error while converting '{0}' to '{1}'.", str_value, type); data = null; return false; } return true; } public static bool TryConvertFormData (Type type, string str_value, out object data) { var converter = new HtmlFormDataTypeConverter (type); data = converter.ConvertFrom (str_value); return data != null; } } }
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography.ECC; using Neo.IO; using Neo.IO.Json; using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.VM; using Neo.Wallets; using System; using System.IO; using System.Linq; using System.Numerics; namespace Neo.UnitTests.Network.P2P.Payloads { [TestClass] public class UT_Transaction { Transaction uut; [TestInitialize] public void TestSetup() { uut = new Transaction(); } [TestMethod] public void Script_Get() { uut.Script.Should().BeNull(); } [TestMethod] public void FromStackItem() { Assert.ThrowsException<NotSupportedException>(() => ((IInteroperable)uut).FromStackItem(VM.Types.StackItem.Null)); } [TestMethod] public void TestEquals() { Assert.IsTrue(uut.Equals(uut)); Assert.IsFalse(uut.Equals(null)); } [TestMethod] public void InventoryType_Get() { ((IInventory)uut).InventoryType.Should().Be(InventoryType.TX); } [TestMethod] public void Script_Set() { byte[] val = TestUtils.GetByteArray(32, 0x42); uut.Script = val; uut.Script.Length.Should().Be(32); for (int i = 0; i < val.Length; i++) { uut.Script[i].Should().Be(val[i]); } } [TestMethod] public void Gas_Get() { uut.SystemFee.Should().Be(0); } [TestMethod] public void Gas_Set() { long val = 4200000000; uut.SystemFee = val; uut.SystemFee.Should().Be(val); } [TestMethod] public void Size_Get() { uut.Script = TestUtils.GetByteArray(32, 0x42); uut.Signers = Array.Empty<Signer>(); uut.Attributes = Array.Empty<TransactionAttribute>(); uut.Witnesses = new[] { new Witness { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() } }; uut.Version.Should().Be(0); uut.Script.Length.Should().Be(32); uut.Script.GetVarSize().Should().Be(33); uut.Size.Should().Be(63); } [TestMethod] public void FeeIsMultiSigContract() { var walletA = TestUtils.GenerateTestWallet(); var walletB = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); using var unlockA = walletA.Unlock("123"); using var unlockB = walletB.Unlock("123"); var a = walletA.CreateAccount(); var b = walletB.CreateAccount(); var multiSignContract = Contract.CreateMultiSigContract(2, new ECPoint[] { a.GetKey().PublicKey, b.GetKey().PublicKey }); walletA.CreateAccount(multiSignContract, a.GetKey()); var acc = walletB.CreateAccount(multiSignContract, b.GetKey()); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction var tx = walletA.MakeTransaction(snapshot, new TransferOutput[] { new TransferOutput() { AssetId = NativeContract.GAS.Hash, ScriptHash = acc.ScriptHash, Value = new BigDecimal(BigInteger.One,8) } }, acc.ScriptHash); Assert.IsNotNull(tx); // Sign var wrongData = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network + 1); Assert.IsFalse(walletA.Sign(wrongData)); var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); Assert.IsTrue(walletA.Sign(data)); Assert.IsTrue(walletB.Sign(data)); Assert.IsTrue(data.Completed); tx.Witnesses = data.GetWitnesses(); // Fast check Assert.IsTrue(tx.VerifyWitnesses(ProtocolSettings.Default, snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot, settings: TestBlockchain.TheNeoSystem.Settings, gas: tx.NetworkFee); engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().GetBoolean()); verificationGas += engine.GasConsumed; } var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); Assert.AreEqual(1967100, verificationGas); Assert.AreEqual(348000, sizeGas); Assert.AreEqual(2315100, tx.NetworkFee); } [TestMethod] public void FeeIsSignatureContractDetailed() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); using var unlock = wallet.Unlock("123"); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction // self-transfer of 1e-8 GAS var tx = wallet.MakeTransaction(snapshot, new TransferOutput[] { new TransferOutput() { AssetId = NativeContract.GAS.Hash, ScriptHash = acc.ScriptHash, Value = new BigDecimal(BigInteger.One,8) } }, acc.ScriptHash); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // check pre-computed network fee (already guessing signature sizes) tx.NetworkFee.Should().Be(1228520L); // ---- // Sign // ---- var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); // 'from' is always required as witness // if not included on cosigner with a scope, its scope should be considered 'CalledByEntry' data.ScriptHashes.Count.Should().Be(1); data.ScriptHashes[0].Should().BeEquivalentTo(acc.ScriptHash); // will sign tx bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(ProtocolSettings.Default, snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot, settings: TestBlockchain.TheNeoSystem.Settings, gas: tx.NetworkFee); engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().GetBoolean()); verificationGas += engine.GasConsumed; } // ------------------ // check tx_size cost // ------------------ Assert.AreEqual(245, tx.Size); // will verify tx size, step by step // Part I Assert.AreEqual(25, Transaction.HeaderSize); // Part II Assert.AreEqual(1, tx.Attributes.GetVarSize()); Assert.AreEqual(0, tx.Attributes.Length); Assert.AreEqual(1, tx.Signers.Length); // Note that Data size and Usage size are different (because of first byte on GetVarSize()) Assert.AreEqual(22, tx.Signers.GetVarSize()); // Part III Assert.AreEqual(88, tx.Script.GetVarSize()); // Part IV Assert.AreEqual(109, tx.Witnesses.GetVarSize()); // I + II + III + IV Assert.AreEqual(25 + 22 + 1 + 88 + 109, tx.Size); Assert.AreEqual(1000, NativeContract.Policy.GetFeePerByte(snapshot)); var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check: verification_cost and tx_size Assert.AreEqual(245000, sizeGas); Assert.AreEqual(983520, verificationGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } [TestMethod] public void FeeIsSignatureContract_TestScope_Global() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); // no password on this wallet using var unlock = wallet.Unlock(""); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new()) { // self-transfer of 1e-8 GAS BigInteger value = new BigDecimal(BigInteger.One, 8).Value; sb.EmitDynamicCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value, null); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying global scope var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.Global } }; // using this... var tx = wallet.MakeTransaction(snapshot, script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(ProtocolSettings.Default, snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot, settings: TestBlockchain.TheNeoSystem.Settings, gas: tx.NetworkFee); engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().GetBoolean()); verificationGas += engine.GasConsumed; } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(1228520, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } [TestMethod] public void FeeIsSignatureContract_TestScope_CurrentHash_GAS() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); // no password on this wallet using var unlock = wallet.Unlock(""); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new()) { // self-transfer of 1e-8 GAS BigInteger value = new BigDecimal(BigInteger.One, 8).Value; sb.EmitDynamicCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value, null); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying global scope var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { NativeContract.GAS.Hash } } }; // using this... var tx = wallet.MakeTransaction(snapshot, script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(ProtocolSettings.Default, snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot, settings: TestBlockchain.TheNeoSystem.Settings, gas: tx.NetworkFee); engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().GetBoolean()); verificationGas += engine.GasConsumed; } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(1249520, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } [TestMethod] public void FeeIsSignatureContract_TestScope_CalledByEntry_Plus_GAS() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); // no password on this wallet using var unlock = wallet.Unlock(""); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new()) { // self-transfer of 1e-8 GAS BigInteger value = new BigDecimal(BigInteger.One, 8).Value; sb.EmitDynamicCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value, null); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying CalledByEntry together with GAS var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, // This combination is supposed to actually be an OR, // where it's valid in both Entry and also for Custom hash provided (in any execution level) // it would be better to test this in the future including situations where a deeper call level uses this custom witness successfully Scopes = WitnessScope.CustomContracts | WitnessScope.CalledByEntry, AllowedContracts = new[] { NativeContract.GAS.Hash } } }; // using this... var tx = wallet.MakeTransaction(snapshot, script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(ProtocolSettings.Default, snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot, settings: TestBlockchain.TheNeoSystem.Settings, gas: tx.NetworkFee); engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().GetBoolean()); verificationGas += engine.GasConsumed; } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(1249520, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } [TestMethod] public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_FAULT() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); // no password on this wallet using var unlock = wallet.Unlock(""); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new()) { // self-transfer of 1e-8 GAS BigInteger value = new BigDecimal(BigInteger.One, 8).Value; sb.EmitDynamicCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying global scope var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { NativeContract.NEO.Hash } } }; // using this... // expects FAULT on execution of 'transfer' Application script // due to lack of a valid witness validation Transaction tx = null; Assert.ThrowsException<InvalidOperationException>(() => tx = wallet.MakeTransaction(snapshot, script, acc.ScriptHash, signers)); Assert.IsNull(tx); } [TestMethod] public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_GAS() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); // no password on this wallet using var unlock = wallet.Unlock(""); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new()) { // self-transfer of 1e-8 GAS BigInteger value = new BigDecimal(BigInteger.One, 8).Value; sb.EmitDynamicCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value, null); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying two custom hashes, for same target account var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { NativeContract.NEO.Hash, NativeContract.GAS.Hash } } }; // using this... var tx = wallet.MakeTransaction(snapshot, script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); // only a single witness should exist tx.Witnesses.Length.Should().Be(1); // no attributes must exist tx.Attributes.Length.Should().Be(0); // one cosigner must exist tx.Signers.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(ProtocolSettings.Default, snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot, settings: TestBlockchain.TheNeoSystem.Settings, gas: tx.NetworkFee); engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().GetBoolean()); verificationGas += engine.GasConsumed; } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(1269520, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } [TestMethod] public void FeeIsSignatureContract_TestScope_NoScopeFAULT() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); // no password on this wallet using var unlock = wallet.Unlock(""); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new()) { // self-transfer of 1e-8 GAS BigInteger value = new BigDecimal(BigInteger.One, 8).Value; sb.EmitDynamicCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying with no scope var attributes = Array.Empty<TransactionAttribute>(); var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { NativeContract.NEO.Hash, NativeContract.GAS.Hash } } }; // using this... // expects FAULT on execution of 'transfer' Application script // due to lack of a valid witness validation Transaction tx = null; Assert.ThrowsException<InvalidOperationException>(() => tx = wallet.MakeTransaction(snapshot, script, acc.ScriptHash, signers, attributes)); Assert.IsNull(tx); } [TestMethod] public void FeeIsSignatureContract_UnexistingVerificationContractFAULT() { var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); // no password on this wallet using var unlock = wallet.Unlock(""); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new()) { // self-transfer of 1e-8 GAS BigInteger value = new BigDecimal(BigInteger.One, 8).Value; sb.EmitDynamicCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value, null); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying global scope var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.Global } }; // creating new wallet with missing account for test var walletWithoutAcc = TestUtils.GenerateTestWallet(); // using this... Transaction tx = null; // expects ArgumentException on execution of 'CalculateNetworkFee' due to // null witness_script (no account in the wallet, no corresponding witness // and no verification contract for the signer) Assert.ThrowsException<ArgumentException>(() => walletWithoutAcc.MakeTransaction(snapshot, script, acc.ScriptHash, signers)); Assert.IsNull(tx); } [TestMethod] public void Transaction_Reverify_Hashes_Length_Unequal_To_Witnesses_Length() { var snapshot = TestBlockchain.GetTestSnapshot(); Transaction txSimple = new() { Version = 0x00, Nonce = 0x01020304, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = Array.Empty<TransactionAttribute>(), Signers = new[]{ new Signer { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), Scopes = WitnessScope.Global } }, Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = Array.Empty<Witness>() }; UInt160[] hashes = txSimple.GetScriptHashesForVerifying(snapshot); Assert.AreEqual(1, hashes.Length); Assert.AreNotEqual(VerifyResult.Succeed, txSimple.VerifyStateDependent(ProtocolSettings.Default, snapshot, new TransactionVerificationContext())); } [TestMethod] public void Transaction_Serialize_Deserialize_Simple() { // good and simple transaction Transaction txSimple = new() { Version = 0x00, Nonce = 0x01020304, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, Attributes = Array.Empty<TransactionAttribute>(), Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[] { new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() } } }; byte[] sTx = txSimple.ToArray(); // detailed hexstring info (basic checking) sTx.ToHexString().Should().Be( "00" + // version "04030201" + // nonce "00e1f50500000000" + // system fee (1 GAS) "0100000000000000" + // network fee (1 satoshi) "04030201" + // timelimit "01000000000000000000000000000000000000000000" + // empty signer "00" + // no attributes "0111" + // push1 script "010000"); // empty witnesses // try to deserialize Transaction tx2 = Neo.IO.Helper.AsSerializable<Transaction>(sTx); tx2.Version.Should().Be(0x00); tx2.Nonce.Should().Be(0x01020304); tx2.Sender.Should().Be(UInt160.Zero); tx2.SystemFee.Should().Be(0x0000000005f5e100); // 1 GAS (long)BigInteger.Pow(10, 8) tx2.NetworkFee.Should().Be(0x0000000000000001); tx2.ValidUntilBlock.Should().Be(0x01020304); tx2.Attributes.Should().BeEquivalentTo(Array.Empty<TransactionAttribute>()); tx2.Signers.Should().BeEquivalentTo(new[] { new Signer { Account = UInt160.Zero, AllowedContracts = Array.Empty<UInt160>(), AllowedGroups = Array.Empty<ECPoint>(), Rules = Array.Empty<WitnessRule>() } }); tx2.Script.Should().BeEquivalentTo(new byte[] { (byte)OpCode.PUSH1 }); tx2.Witnesses.Should().BeEquivalentTo(new Witness[] { new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() } }); } [TestMethod] public void Transaction_Serialize_Deserialize_DistinctCosigners() { // cosigners must be distinct (regarding account) Transaction txDoubleCosigners = new() { Version = 0x00, Nonce = 0x01020304, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = Array.Empty<TransactionAttribute>(), Signers = new Signer[] { new Signer() { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), Scopes = WitnessScope.Global }, new Signer() { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), // same account as above Scopes = WitnessScope.CalledByEntry // different scope, but still, same account (cannot do that) } }, Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[] { new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() } } }; byte[] sTx = txDoubleCosigners.ToArray(); // no need for detailed hexstring here (see basic tests for it) sTx.ToHexString().Should().Be("000403020100e1f5050000000001000000000000000403020102090807060504030201000908070605040302010080090807060504030201000908070605040302010001000111010000"); // back to transaction (should fail, due to non-distinct cosigners) Transaction tx2 = null; Assert.ThrowsException<FormatException>(() => tx2 = Neo.IO.Helper.AsSerializable<Transaction>(sTx) ); Assert.IsNull(tx2); } [TestMethod] public void Transaction_Serialize_Deserialize_MaxSizeCosigners() { // cosigners must respect count int maxCosigners = 16; // -------------------------------------- // this should pass (respecting max size) var cosigners1 = new Signer[maxCosigners]; for (int i = 0; i < cosigners1.Length; i++) { string hex = i.ToString("X4"); while (hex.Length < 40) hex = hex.Insert(0, "0"); cosigners1[i] = new Signer { Account = UInt160.Parse(hex), Scopes = WitnessScope.CalledByEntry }; } Transaction txCosigners1 = new() { Version = 0x00, Nonce = 0x01020304, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = Array.Empty<TransactionAttribute>(), Signers = cosigners1, // max + 1 (should fail) Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[] { new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() } } }; byte[] sTx1 = txCosigners1.ToArray(); // back to transaction (should fail, due to non-distinct cosigners) Assert.ThrowsException<FormatException>(() => Neo.IO.Helper.AsSerializable<Transaction>(sTx1)); // ---------------------------- // this should fail (max + 1) var cosigners = new Signer[maxCosigners + 1]; for (var i = 0; i < maxCosigners + 1; i++) { string hex = i.ToString("X4"); while (hex.Length < 40) hex = hex.Insert(0, "0"); cosigners[i] = new Signer { Account = UInt160.Parse(hex) }; } Transaction txCosigners = new() { Version = 0x00, Nonce = 0x01020304, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, Attributes = Array.Empty<TransactionAttribute>(), Signers = cosigners, // max + 1 (should fail) Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[] { new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() } } }; byte[] sTx2 = txCosigners.ToArray(); // back to transaction (should fail, due to non-distinct cosigners) Transaction tx2 = null; Assert.ThrowsException<FormatException>(() => tx2 = Neo.IO.Helper.AsSerializable<Transaction>(sTx2) ); Assert.IsNull(tx2); } [TestMethod] public void FeeIsSignatureContract_TestScope_FeeOnly_Default() { // Global is supposed to be default Signer cosigner = new(); cosigner.Scopes.Should().Be(WitnessScope.None); var wallet = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); // no password on this wallet using var unlock = wallet.Unlock(""); var acc = wallet.CreateAccount(); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction // Manually creating script byte[] script; using (ScriptBuilder sb = new()) { // self-transfer of 1e-8 GAS BigInteger value = new BigDecimal(BigInteger.One, 8).Value; sb.EmitDynamicCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value, null); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // try to use fee only inside the smart contract var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.None } }; Assert.ThrowsException<InvalidOperationException>(() => wallet.MakeTransaction(snapshot, script, acc.ScriptHash, signers)); // change to global scope signers[0].Scopes = WitnessScope.Global; var tx = wallet.MakeTransaction(snapshot, script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); // ---- // Sign // ---- var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); bool signed = wallet.Sign(data); Assert.IsTrue(signed); // get witnesses from signed 'data' tx.Witnesses = data.GetWitnesses(); tx.Witnesses.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(ProtocolSettings.Default, snapshot, tx.NetworkFee)); // Check long verificationGas = 0; foreach (var witness in tx.Witnesses) { using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot, settings: TestBlockchain.TheNeoSystem.Settings, gas: tx.NetworkFee); engine.LoadScript(witness.VerificationScript); engine.LoadScript(witness.InvocationScript); Assert.AreEqual(VMState.HALT, engine.Execute()); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Pop().GetBoolean()); verificationGas += engine.GasConsumed; } // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size Assert.AreEqual(1228520, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } [TestMethod] public void ToJson() { uut.Script = TestUtils.GetByteArray(32, 0x42); uut.SystemFee = 4200000000; uut.Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }; uut.Attributes = Array.Empty<TransactionAttribute>(); uut.Witnesses = new[] { new Witness { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() } }; JObject jObj = uut.ToJson(ProtocolSettings.Default); jObj.Should().NotBeNull(); jObj["hash"].AsString().Should().Be("0x0ab073429086d9e48fc87386122917989705d1c81fe4a60bf90e2fc228de3146"); jObj["size"].AsNumber().Should().Be(84); jObj["version"].AsNumber().Should().Be(0); ((JArray)jObj["attributes"]).Count.Should().Be(0); jObj["netfee"].AsString().Should().Be("0"); jObj["script"].AsString().Should().Be("QiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA="); jObj["sysfee"].AsString().Should().Be("4200000000"); } [TestMethod] public void Test_GetAttribute() { var tx = new Transaction() { Attributes = Array.Empty<TransactionAttribute>(), NetworkFee = 0, Nonce = (uint)Environment.TickCount, Script = new byte[Transaction.MaxTransactionSize], Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, SystemFee = 0, ValidUntilBlock = 0, Version = 0, Witnesses = Array.Empty<Witness>(), }; Assert.IsNull(tx.GetAttribute<OracleResponse>()); Assert.IsNull(tx.GetAttribute<HighPriorityAttribute>()); tx.Attributes = new TransactionAttribute[] { new HighPriorityAttribute() }; Assert.IsNull(tx.GetAttribute<OracleResponse>()); Assert.IsNotNull(tx.GetAttribute<HighPriorityAttribute>()); } [TestMethod] public void Test_VerifyStateIndependent() { var tx = new Transaction() { Attributes = Array.Empty<TransactionAttribute>(), NetworkFee = 0, Nonce = (uint)Environment.TickCount, Script = new byte[Transaction.MaxTransactionSize], Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, SystemFee = 0, ValidUntilBlock = 0, Version = 0, Witnesses = new[] { new Witness { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() } } }; tx.VerifyStateIndependent(ProtocolSettings.Default).Should().Be(VerifyResult.OverSize); tx.Script = Array.Empty<byte>(); tx.VerifyStateIndependent(ProtocolSettings.Default).Should().Be(VerifyResult.Succeed); var walletA = TestUtils.GenerateTestWallet(); var walletB = TestUtils.GenerateTestWallet(); var snapshot = TestBlockchain.GetTestSnapshot(); using var unlockA = walletA.Unlock("123"); using var unlockB = walletB.Unlock("123"); var a = walletA.CreateAccount(); var b = walletB.CreateAccount(); var multiSignContract = Contract.CreateMultiSigContract(2, new ECPoint[] { a.GetKey().PublicKey, b.GetKey().PublicKey }); walletA.CreateAccount(multiSignContract, a.GetKey()); var acc = walletB.CreateAccount(multiSignContract, b.GetKey()); // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); var entry = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); entry.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; snapshot.Commit(); // Make transaction tx = walletA.MakeTransaction(snapshot, new TransferOutput[] { new TransferOutput() { AssetId = NativeContract.GAS.Hash, ScriptHash = acc.ScriptHash, Value = new BigDecimal(BigInteger.One,8) } }, acc.ScriptHash); // Sign var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); Assert.IsTrue(walletA.Sign(data)); Assert.IsTrue(walletB.Sign(data)); Assert.IsTrue(data.Completed); tx.Witnesses = data.GetWitnesses(); tx.VerifyStateIndependent(ProtocolSettings.Default).Should().Be(VerifyResult.Succeed); // Different hash tx.Witnesses[0] = new Witness() { VerificationScript = walletB.GetAccounts().First().Contract.Script, InvocationScript = tx.Witnesses[0].InvocationScript.ToArray() }; tx.VerifyStateIndependent(ProtocolSettings.Default).Should().Be(VerifyResult.Invalid); } [TestMethod] public void Test_VerifyStateDependent() { var snapshot = TestBlockchain.GetTestSnapshot(); var height = NativeContract.Ledger.CurrentIndex(snapshot); var tx = new Transaction() { Attributes = Array.Empty<TransactionAttribute>(), NetworkFee = 55000, Nonce = (uint)Environment.TickCount, Script = Array.Empty<byte>(), Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, SystemFee = 0, ValidUntilBlock = height + 1, Version = 0, Witnesses = new Witness[] { new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() }, new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = new byte[1] } } }; // Fake balance var key = NativeContract.GAS.CreateStorageKey(20, tx.Sender); var balance = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); balance.GetInteroperable<AccountState>().Balance = tx.NetworkFee; tx.VerifyStateDependent(ProtocolSettings.Default, snapshot, new TransactionVerificationContext()).Should().Be(VerifyResult.Invalid); balance.GetInteroperable<AccountState>().Balance = 0; tx.SystemFee = 10; tx.VerifyStateDependent(ProtocolSettings.Default, snapshot, new TransactionVerificationContext()).Should().Be(VerifyResult.InsufficientFunds); var walletA = TestUtils.GenerateTestWallet(); var walletB = TestUtils.GenerateTestWallet(); using var unlockA = walletA.Unlock("123"); using var unlockB = walletB.Unlock("123"); var a = walletA.CreateAccount(); var b = walletB.CreateAccount(); var multiSignContract = Contract.CreateMultiSigContract(2, new ECPoint[] { a.GetKey().PublicKey, b.GetKey().PublicKey }); walletA.CreateAccount(multiSignContract, a.GetKey()); var acc = walletB.CreateAccount(multiSignContract, b.GetKey()); // Fake balance snapshot = TestBlockchain.GetTestSnapshot(); key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); balance = snapshot.GetAndChange(key, () => new StorageItem(new AccountState())); balance.GetInteroperable<AccountState>().Balance = 10000 * NativeContract.GAS.Factor; // Make transaction snapshot.Commit(); tx = walletA.MakeTransaction(snapshot, new TransferOutput[] { new TransferOutput() { AssetId = NativeContract.GAS.Hash, ScriptHash = acc.ScriptHash, Value = new BigDecimal(BigInteger.One,8) } }, acc.ScriptHash); // Sign var data = new ContractParametersContext(snapshot, tx, ProtocolSettings.Default.Network); Assert.IsTrue(walletA.Sign(data)); Assert.IsTrue(walletB.Sign(data)); Assert.IsTrue(data.Completed); tx.Witnesses = data.GetWitnesses(); tx.VerifyStateDependent(ProtocolSettings.Default, snapshot, new TransactionVerificationContext()).Should().Be(VerifyResult.Succeed); } [TestMethod] public void Test_VerifyStateInDependent_Multi() { var txData = Convert.FromBase64String( "AHXd31W0NlsAAAAAAJRGawAAAAAA3g8CAAGSs5x3qmDym1fBc87ZF/F/0yGm6wEAXwsDAOQLVAIAAAAMFLqZBJj+L0XZPXNHHM9MBfCza5HnDBSSs5x3qmDym1fBc87ZF/F/0yGm6xTAHwwIdHJhbnNmZXIMFM924ovQBixKR47jVWEBExnzz6TSQWJ9W1I5Af1KAQxAnZvOQOCdkM+j22dS5SdEncZVYVVi1F26MhheNzNImTD4Ekw5kFR6Fojs7gD57Bdeuo8tLS1UXpzflmKcQ3pniAxAYvGgxtokrk6PVdduxCBwVbdfie+ZxiaDsjK0FYregl24cDr2v5cTLHrURVfJJ1is+4G6Jaer7nB1JrDrw+Qt6QxATA5GdR4rKFPPPQQ24+42OP2tz0HylG1LlANiOtIdag3ZPkUfZiBfEGoOteRD1O0UnMdJP4Su7PFhDuCdHu4MlwxAuGFEk2m/rdruleBGYz8DIzExJtwb/TsFxZdHxo4VV8ktv2Nh71Fwhg2bhW2tq8hV6RK2GFXNAU72KAgf/Qv6BQxA0j3srkwY333KvGNtw7ZvSG8X36Tqu000CEtDx4SMOt8qhVYGMr9PClsUVcYFHdrJaodilx8ewXDHNIq+OnS7SfwVDCEDAJt1QOEPJWLl/Y+snq7CUWaliybkEjSP9ahpJ7+sIqIMIQMCBenO+upaHfxYCvIMjVqiRouwFI8aXkYF/GIsgOYEugwhAhS68M7qOmbxfn4eg56iX9i+1s2C5rtuaCUBiQZfRP8BDCECPpsy6om5TQZuZJsST9UOOW7pE2no4qauGxHBcNAiJW0MIQNAjc1BY5b2R4OsWH6h4Vk8V9n+qIDIpqGSDpKiWUd4BgwhAqeDS+mzLimB0VfLW706y0LP0R6lw7ECJNekTpjFkQ8bDCECuixw9ZlvNXpDGYcFhZ+uLP6hPhFyligAdys9WIqdSr0XQZ7Q3Do="); var tx = new Transaction(); ((ISerializable)tx).Deserialize(new BinaryReader(new MemoryStream(txData))); var settings = new ProtocolSettings() { Network = 844378958 }; var result = tx.VerifyStateIndependent(settings); Assert.AreEqual(VerifyResult.Succeed, result); } } }
// SharpMath - C# Mathematical Library // Copyright (c) 2016 Morten Bakkedal // This code is published under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace SharpMath.Optimization.DualNumbers { [Serializable] [DebuggerStepThrough] [DebuggerDisplay("{ToString(),nq}")] public sealed class DualMatrix { private DualNumber[,] entries; //hashCode public DualMatrix(DualNumber[,] entries) { if (entries == null) { throw new ArgumentNullException(); } for (int i = 0; i < entries.GetLength(0); i++) { for (int j = 0; j < entries.GetLength(1); j++) { if (entries[i, j] == null) { throw new ArgumentNullException(); } } } this.entries = (DualNumber[,])entries.Clone(); } // more overloads public DualMatrix(int rows, int columns) : this(rows, columns, 0.0) { // Dependence is the other way around here to ensure non-null initialization values. } public DualMatrix(int rows, int columns, DualNumber value) { if (rows < 0 || columns < 0) { throw new ArgumentOutOfRangeException(); } entries = new DualNumber[rows, columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { entries[i, j] = value; } } } public DualMatrix(Matrix values) : this(values, null) { } public DualMatrix(Matrix values, Matrix[] gradients) : this(values, gradients, null) { } public DualMatrix(Matrix values, Matrix[] gradients, Matrix[,] hessians) { if (values == null || gradients == null || hessians == null) { throw new ArgumentNullException(); } int rows = values.Rows; int columns = values.Columns; entries = new DualNumber[rows, columns]; int n = 0; if (gradients != null) { n = gradients.Length; for (int i = 0; i < n; i++) { if (gradients[i] == null) { throw new ArgumentNullException("gradients", "The gradients must be fully specified."); } if (gradients[i].Rows != rows || gradients[i].Columns != columns) { throw new ArgumentException("Inconsistent matrix sizes."); } } } if (hessians != null) { if (gradients == null) { throw new ArgumentException("The gradients must be specified if the Hessians are specified."); } if (hessians.GetLength(0) != n || hessians.GetLength(1) != n) { throw new ArgumentException("Inconsistent number of derivatives."); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (hessians[i, j] == null) { throw new ArgumentNullException("hessians", "The Hessians must be fully specified."); } if (hessians[i, j].Rows != rows || hessians[i, j].Columns != columns) { throw new ArgumentException("Inconsistent matrix sizes."); } } } } for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { double value = values[i, j]; Vector gradient = null; if (gradients != null) { double[] a = new double[n]; for (int k = 0; k < n; k++) { a[k] = gradients[k][i, j]; } gradient = new Vector(a); } Matrix hessian = null; if (hessians != null) { double[,] a = new double[n, n]; for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { a[k, l] = hessians[k, l][i, j]; } } hessian = new Matrix(a); } entries[i, j] = new DualNumber(value, gradient, hessian); } } } public DualMatrix SetEntry(int row, int column, DualNumber value) { if (row < 0 || row >= Rows || column < 0 || column >= Columns) { throw new ArgumentOutOfRangeException(); } DualMatrix a = new DualMatrix(entries); a[row, column] = value; return a; } public DualMatrix SetMatrix(int row, int column, DualMatrix subMatrix) { if (row < 0 || row + subMatrix.Rows > Rows || column < 0 || column + subMatrix.Columns > Columns) { throw new ArgumentOutOfRangeException(); } int n = subMatrix.Rows; int m = subMatrix.Columns; DualMatrix b = new DualMatrix(entries); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b[row + i, column + j] = subMatrix[i, j]; } } return b; } public DualMatrix GetMatrix(int row, int column, int rows, int columns) { if (rows < 0 || row < 0 || row + rows > Rows || columns < 0 || column < 0 || column + columns > Columns) { throw new ArgumentOutOfRangeException(); } int n = rows; int m = columns; DualMatrix a = new DualMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i, j] = this[row + i, column + j]; } } return a; } public DualVector GetRow(int row) { int n = Columns; // Use conversion operator defined in DualVector. return (DualVector)GetMatrix(row, 0, 1, n); } public DualVector GetColumn(int column) { int n = Rows; // Use conversion operator defined in DualVector. return (DualVector)GetMatrix(0, column, n, 1); } public Matrix GetValues() { int n = Rows; int m = Columns; double[,] a = new double[n, m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i, j] = this[i, j].Value; } } return new Matrix(a); } public Matrix GetGradients(int index) { int n = Rows; int m = Columns; double[,] a = new double[n, m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Vector gradient = this[i, j].Gradient; if (gradient != null) { a[i, j] = gradient[index]; } } } return new Matrix(a); } public Matrix GetHessians(int index1, int index2) { int n = Rows; int m = Columns; double[,] a = new double[n, m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Matrix hessian = this[i, j].Hessian; if (hessian != null) { a[i, j] = hessian[index1, index2]; } } } return new Matrix(a); } public DualNumber[,] ToArray() { return (DualNumber[,])entries.Clone(); } public DualNumber[][] ToJaggedArray() { DualNumber[][] entries = new DualNumber[Rows][]; for (int i = 0; i < Rows; i++) { entries[i] = new DualNumber[Columns]; for (int j = 0; j < Columns; j++) { entries[i][j] = this[i, j]; } } return entries; } public override string ToString() { return ToString(null); } public string ToString(string format) { return GetValues().ToString(format); } public static DualMatrix Zero(int rows, int columns) { return new DualMatrix(rows, columns); } public static DualMatrix Identity(int rows, int columns) { if (rows < 0 || columns < 0) { throw new ArgumentOutOfRangeException(); } int n = Math.Min(rows, columns); DualMatrix a = new DualMatrix(rows, columns); for (int i = 0; i < n; i++) { a[i, i] = 1.0; } return a; } public static DualMatrix Diagonal(params DualNumber[] values) { if (values == null) { throw new ArgumentNullException(); } int n = values.Length; DualMatrix a = new DualMatrix(n, n); for (int i = 0; i < n; i++) { a[i, i] = values[i]; } return a; } public static DualMatrix Diagonal(IEnumerable<DualNumber> values) { if (values == null) { throw new ArgumentNullException(); } return Diagonal(values.ToArray()); } public static DualMatrix Basis(int rows, int columns, int row, int column) { if (rows < 0 || row < 0 || row >= rows || columns < 0 || column < 0 || column >= columns) { throw new ArgumentOutOfRangeException(); } DualMatrix a = new DualMatrix(rows, columns); a[row, column] = 1.0; return a; } public static DualMatrix Transpose(DualMatrix matrix) { if (matrix == null) { throw new ArgumentNullException(); } int n = matrix.Columns; int m = matrix.Rows; DualMatrix b = new DualMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b[i, j] = matrix[j, i]; } } return b; } public static DualNumber Trace(DualMatrix matrix) { if (matrix == null) { throw new ArgumentNullException(); } int n = matrix.Rows; if (matrix.Columns != n) { throw new ArgumentException("Non-square matrix."); } DualNumber s = 0.0; for (int i = 0; i < n; i++) { s += matrix[i, i]; } return s; } public static DualMatrix Inverse(DualMatrix matrix) { // Use direct computation for low dimenstions; LU decomposition otherwise. return DualLUDecomposition.Inverse(matrix); } public static DualNumber Determinant(DualMatrix matrix) { // Use direct computation for low dimenstions; LU decomposition otherwise. return DualLUDecomposition.Determinant(matrix); } public static implicit operator DualMatrix(Matrix matrix) { return new DualMatrix(matrix); } public static DualMatrix operator +(DualMatrix a, DualMatrix b) { // hertil!!!!!!!!!!!!! int n = a.Rows; int m = a.Columns; if (b.Rows != n || b.Columns != m) { throw new ArgumentException("The matrix dimensions don't match."); } DualMatrix c = new DualMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { c[i, j] = a[i, j] + b[i, j]; } } return c; } public static DualMatrix operator +(DualMatrix a, DualNumber t) { int n = a.Rows; int m = a.Columns; DualMatrix b = new DualMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b[i, j] = a[i, j] + t; } } return b; } public static DualMatrix operator +(DualNumber t, DualMatrix a) { return a + t; } public static DualMatrix operator -(DualMatrix a) { return a * -1.0; } public static DualMatrix operator -(DualMatrix a, DualMatrix b) { int n = a.Rows; int m = a.Columns; if (b.Rows != n || b.Columns != m) { throw new ArgumentException("The matrix dimensions don't match."); } DualMatrix c = new DualMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { c[i, j] = a[i, j] - b[i, j]; } } return c; } public static DualMatrix operator -(DualMatrix a, DualNumber t) { return a + (-t); } public static DualMatrix operator -(DualNumber t, DualMatrix a) { int n = a.Rows; int m = a.Columns; DualMatrix b = new DualMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b[i, j] = t - a[i, j]; } } return b; } public static DualMatrix operator *(DualMatrix a, DualMatrix b) { int n = a.Rows; int m = b.Columns; int l = a.Columns; if (b.Rows != l) { throw new ArgumentException("The matrix dimensions don't match."); } DualMatrix c = new DualMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { DualNumber s = 0.0; for (int k = 0; k < l; k++) { s += a[i, k] * b[k, j]; } c[i, j] = s; } } return c; } public static DualMatrix operator *(DualMatrix a, DualNumber t) { int n = a.Rows; int m = a.Columns; DualMatrix b = new DualMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b[i, j] = a[i, j] * t; } } return b; } public static DualMatrix operator *(DualNumber t, DualMatrix a) { return a * t; } public static DualMatrix operator /(DualMatrix a, DualNumber t) { return a * (1.0 / t); } public DualNumber this[int row, int column] { get { return entries[row, column]; } private set { // This property is kept private. The class is immutable by design. entries[row, column] = value; } } public int Rows { get { return entries.GetLength(0); } } public int Columns { get { return entries.GetLength(1); } } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kodestruct.Analysis.BeamForces.SimpleWithOverhang { public class DistributedLoadOverhang : ISingleLoadCaseBeam, ISingleLoadCaseDeflectionBeam { BeamSimpleWithOverhang beam; const string CASE = "C2C_2"; double w, a, L, X1; bool X1Calculated; //note for overhang beam a is the overhang with //1 exception of concentrated load between supports public DistributedLoadOverhang(BeamSimpleWithOverhang beam, double w) { this.beam = beam; L = beam.Length; this.w = w; this.a = beam.OverhangLength; X1Calculated = false; } public double Moment(double X) { beam.EvaluateX(X); double M; if (X <= L) { M = (w * a * a * X) / (2 * L); BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 1, new Dictionary<string, double>() { {"L",L }, {"X",X }, {"a",a }, {"w",w } }, CASE, beam); return M; } else { if (X1Calculated == false) { CalculateX1(X); } M = w / 2.0 * Math.Pow(a - X1, 2); BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 2, new Dictionary<string, double>() { {"X1",X1 }, {"a",a }, {"w",w } }, CASE, beam); return M; } } public ForceDataPoint MomentMax() { double M; if (w>0.0) { M = w * a * a / 2.0; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"X",L }, {"w",w }, {"a",a }, }, CASE, beam, true); } else { BeamEntryFactory.CreateEntry("Mx", 0.0, BeamTemplateType.M_zero, 0, null, CASE, beam, true); M = 0.0; } return new ForceDataPoint(L, M); } public ForceDataPoint MomentMin() { double M; if (w < 0.0) { M = w * a * a / 2.0; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"X",L }, {"w",w }, {"a",a }, }, CASE, beam, false, true); } else { BeamEntryFactory.CreateEntry("Mx", 0.0, BeamTemplateType.M_zero, 0, null, CASE, beam, false, true); M = 0.0; } return new ForceDataPoint(L, M); } public double Shear(double X) { beam.EvaluateX(X); double V1 = CalculateV1(); double V2 = CalculateV2(); if (X<L) { BeamEntryFactory.CreateEntry("Vx", V1, BeamTemplateType.Vx, 1, new Dictionary<string, double>() { {"L",L }, {"X",X }, {"w",w }, {"a",a }, }, CASE, beam); return V1; } else if (X>L) { if (X1Calculated==false) { CalculateX1(X); } double V = w * (a - X1); BeamEntryFactory.CreateEntry("Vx", V, BeamTemplateType.Vx, 2, new Dictionary<string, double>() { {"X1",X1 }, {"w",w }, {"a",a }, }, CASE, beam); return V; } else //right at the support { if (V1 > V2) { BeamEntryFactory.CreateEntry("Vx", V1, BeamTemplateType.Vx, 1, new Dictionary<string, double>() { {"L",L }, {"X",X }, {"w",w }, {"a",a }, }, CASE, beam); return V1; } else { BeamEntryFactory.CreateEntry("Vx", V2, BeamTemplateType.Vx, 2, new Dictionary<string, double>() { {"X",X }, {"w",w }, {"a",a }, }, CASE, beam); return V2; } } } public ForceDataPoint ShearMax() { double V1 = Math.Abs(CalculateV1()); double V2 = Math.Abs(CalculateV2()); if (V1 > V2) { BeamEntryFactory.CreateEntry("Vx", V1, BeamTemplateType.Vmax, 1, new Dictionary<string, double>() { {"L",L }, {"X",L }, {"w",w }, {"a",a }, }, CASE, beam, true); return new ForceDataPoint(L, V1); } else { BeamEntryFactory.CreateEntry("Vx", V2, BeamTemplateType.Vmax, 2, new Dictionary<string, double>() { {"X",L }, {"w",w }, {"a",a }, }, CASE, beam, true); return new ForceDataPoint(L,V2); } } private void CalculateX1(double X) { X1 = X - L; BeamEntryFactory.CreateEntry("X1", X1, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"L",L }, {"X1",X1 }, }, CASE, beam, true); X1Calculated = true; } private double CalculateV1() { double V = w * a * a / (2.0 * L); return V; } private double CalculateV2() { double V = w * a; return V; } public double MaximumDeflection() { double E = beam.ModulusOfElasticity; double I = beam.MomentOfInertia; double delta_Maximum = ((w * Math.Pow(a, 3)) / (24.0 * E * I)) * (4.0 * L + 3.0 * a); return delta_Maximum; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Demo.Domain.Service.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); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.Util { using System; using NPOI.HSSF.UserModel; using NPOI.SS.Util; /// <summary> /// Various utility functions that make working with a region of cells easier. /// @author Eric Pugh epugh@upstate.com /// </summary> internal class HSSFRegionUtil { private HSSFRegionUtil() { // no instances of this class } /// <summary> /// For setting the same property on many cells to the same value /// </summary> private class CellPropertySetter { private HSSFWorkbook _workbook; private String _propertyName; private short _propertyValue; public CellPropertySetter(HSSFWorkbook workbook, String propertyName, int value) { _workbook = workbook; _propertyName = propertyName; _propertyValue = (short)value; } public void SetProperty(NPOI.SS.UserModel.IRow row, int column) { NPOI.SS.UserModel.ICell cell = HSSFCellUtil.GetCell(row, column); HSSFCellUtil.SetCellStyleProperty(cell, _workbook, _propertyName, _propertyValue); } } [Obsolete] private static CellRangeAddress toCRA(Region region) { return Region.ConvertToCellRangeAddress(region); } //[Obsolete] //public static void SetBorderLeft(NPOI.SS.UserModel.CellBorderType border, Region region, HSSFSheet sheet, // HSSFWorkbook workbook) //{ // SetBorderLeft(border, toCRA(region), sheet, workbook); //} /// <summary> /// Sets the left border for a region of cells by manipulating the cell style /// of the individual cells on the left /// </summary> /// <param name="border">The new border</param> /// <param name="region">The region that should have the border</param> /// <param name="sheet">The sheet that the region is on.</param> /// <param name="workbook">The workbook that the region is on.</param> public static void SetBorderLeft(NPOI.SS.UserModel.BorderStyle border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook workbook) { int rowStart = region.FirstRow; int rowEnd = region.LastRow; int column = region.FirstColumn; CellPropertySetter cps = new CellPropertySetter(workbook, HSSFCellUtil.BORDER_LEFT, (int)border); for (int i = rowStart; i <= rowEnd; i++) { cps.SetProperty(HSSFCellUtil.GetRow(i, sheet), column); } } //[Obsolete] //public static void SetLeftBorderColor(short color, Region region, HSSFSheet sheet, // HSSFWorkbook workbook) //{ // SetLeftBorderColor(color, toCRA(region), sheet, workbook); //} /// <summary> /// Sets the leftBorderColor attribute of the HSSFRegionUtil object /// </summary> /// <param name="color">The color of the border</param> /// <param name="region">The region that should have the border</param> /// <param name="sheet">The sheet that the region is on.</param> /// <param name="workbook">The workbook that the region is on.</param> public static void SetLeftBorderColor(int color, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook workbook) { int rowStart = region.FirstRow; int rowEnd = region.LastRow; int column = region.FirstColumn; CellPropertySetter cps = new CellPropertySetter(workbook, HSSFCellUtil.LEFT_BORDER_COLOR, color); for (int i = rowStart; i <= rowEnd; i++) { cps.SetProperty(HSSFCellUtil.GetRow(i, sheet), column); } } //[Obsolete] //public static void SetBorderRight(NPOI.SS.UserModel.CellBorderType border, Region region, HSSFSheet sheet, // HSSFWorkbook workbook) //{ // SetBorderRight(border, toCRA(region), sheet, workbook); //} /// <summary> /// Sets the borderRight attribute of the HSSFRegionUtil object /// </summary> /// <param name="border">The new border</param> /// <param name="region">The region that should have the border</param> /// <param name="sheet">The sheet that the region is on.</param> /// <param name="workbook">The workbook that the region is on.</param> public static void SetBorderRight(NPOI.SS.UserModel.BorderStyle border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook workbook) { int rowStart = region.FirstRow; int rowEnd = region.LastRow; int column = region.LastColumn; CellPropertySetter cps = new CellPropertySetter(workbook, HSSFCellUtil.BORDER_RIGHT, (int)border); for (int i = rowStart; i <= rowEnd; i++) { cps.SetProperty(HSSFCellUtil.GetRow(i, sheet), column); } } //[Obsolete] //public static void SetRightBorderColor(short color, Region region, HSSFSheet sheet, // HSSFWorkbook workbook) //{ // SetRightBorderColor(color, toCRA(region), sheet, workbook); //} /// <summary> /// Sets the rightBorderColor attribute of the HSSFRegionUtil object /// </summary> /// <param name="color">The color of the border</param> /// <param name="region">The region that should have the border</param> /// <param name="sheet">The workbook that the region is on.</param> /// <param name="workbook">The sheet that the region is on.</param> public static void SetRightBorderColor(int color, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook workbook) { int rowStart = region.FirstRow; int rowEnd = region.LastRow; int column = region.LastColumn; CellPropertySetter cps = new CellPropertySetter(workbook, HSSFCellUtil.RIGHT_BORDER_COLOR, color); for (int i = rowStart; i <= rowEnd; i++) { cps.SetProperty(HSSFCellUtil.GetRow(i, sheet), column); } } //[Obsolete] //public static void SetBorderBottom(NPOI.SS.UserModel.CellBorderType border, Region region, HSSFSheet sheet, // HSSFWorkbook workbook) //{ // SetBorderBottom(border, toCRA(region), sheet, workbook); //} /// <summary> /// Sets the borderBottom attribute of the HSSFRegionUtil object /// </summary> /// <param name="border">The new border</param> /// <param name="region">The region that should have the border</param> /// <param name="sheet">The sheet that the region is on.</param> /// <param name="workbook">The workbook that the region is on.</param> public static void SetBorderBottom(NPOI.SS.UserModel.BorderStyle border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook workbook) { int colStart = region.FirstColumn; int colEnd = region.LastColumn; int rowIndex = region.LastRow; CellPropertySetter cps = new CellPropertySetter(workbook, HSSFCellUtil.BORDER_BOTTOM, (int)border); NPOI.SS.UserModel.IRow row = HSSFCellUtil.GetRow(rowIndex, sheet); for (int i = colStart; i <= colEnd; i++) { cps.SetProperty(row, i); } } //[Obsolete] //public static void SetBottomBorderColor(short color, Region region, HSSFSheet sheet, // HSSFWorkbook workbook) //{ // SetBottomBorderColor(color, toCRA(region), sheet, workbook); //} /// <summary> /// Sets the bottomBorderColor attribute of the HSSFRegionUtil object /// </summary> /// <param name="color">The color of the border</param> /// <param name="region">The region that should have the border</param> /// <param name="sheet">The sheet that the region is on.</param> /// <param name="workbook">The workbook that the region is on.</param> public static void SetBottomBorderColor(int color, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook workbook) { int colStart = region.FirstColumn; int colEnd = region.LastColumn; int rowIndex = region.LastRow; CellPropertySetter cps = new CellPropertySetter(workbook, HSSFCellUtil.BOTTOM_BORDER_COLOR, color); NPOI.SS.UserModel.IRow row = HSSFCellUtil.GetRow(rowIndex, sheet); for (int i = colStart; i <= colEnd; i++) { cps.SetProperty(row, i); } } //[Obsolete] //public static void SetBorderTop(NPOI.SS.UserModel.CellBorderType border, Region region, HSSFSheet sheet, // HSSFWorkbook workbook) //{ // SetBorderTop(border, toCRA(region), sheet, workbook); //} /// <summary> /// Sets the borderBottom attribute of the HSSFRegionUtil object /// </summary> /// <param name="border">The new border</param> /// <param name="region">The region that should have the border</param> /// <param name="sheet">The sheet that the region is on.</param> /// <param name="workbook">The workbook that the region is on.</param> public static void SetBorderTop(NPOI.SS.UserModel.BorderStyle border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook workbook) { int colStart = region.FirstColumn; int colEnd = region.LastColumn; int rowIndex = region.FirstRow; CellPropertySetter cps = new CellPropertySetter(workbook, HSSFCellUtil.BORDER_TOP, (int)border); NPOI.SS.UserModel.IRow row = HSSFCellUtil.GetRow(rowIndex, sheet); for (int i = colStart; i <= colEnd; i++) { cps.SetProperty(row, i); } } /// <summary> /// Sets the topBorderColor attribute of the HSSFRegionUtil object /// </summary> /// <param name="color">The color of the border</param> /// <param name="region">The region that should have the border</param> /// <param name="sheet">The sheet that the region is on.</param> /// <param name="workbook">The workbook that the region is on.</param> public static void SetTopBorderColor(int color, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook workbook) { int colStart = region.FirstColumn; int colEnd = region.LastColumn; int rowIndex = region.FirstRow; CellPropertySetter cps = new CellPropertySetter(workbook, HSSFCellUtil.TOP_BORDER_COLOR, color); NPOI.SS.UserModel.IRow row = HSSFCellUtil.GetRow(rowIndex, sheet); for (int i = colStart; i <= colEnd; i++) { cps.SetProperty(row, i); } } } }
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 Falling { enum GameState { title, playing, gameover, victory} /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; FrameImageManager frameImageManager; TurnString turnString; int gameTurns = C.gameTurns; List<LevelLibrary.Level> levels = new List<LevelLibrary.Level>(); GameState state; MouseState oldMouse; KeyboardState oldKeyboard; Grid grid; Camera2D camera; Vector2 cameraDirection = Vector2.Zero; int currentLevel; Player currentPlayer; Texture2D currentBackground; Texture2D currentFrame; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = 1280; // set this value to the desired width of your window graphics.PreferredBackBufferHeight = 720; // set this value to the desired height of your window graphics.ApplyChanges(); this.Window.Title = "Falling World - GGJ12 - Finland - Oulu - Stage gamedev"; } /// <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() { // TODO: Add your initialization logic here this.IsMouseVisible = true; state = GameState.title; currentPlayer = new Player(); frameImageManager = new FrameImageManager(); base.Initialize(); camera = new Camera2D(spriteBatch); grid = new Grid(C.xMarginLeft, C.yMargin, C.tileWidth, C.tileHeight, camera); grid.setCurrentPlayer(currentPlayer); grid.initJewels(frameImageManager); turnString = new TurnString(TextureRefs.turnsTexture, 0, C.turnsX, C.turnsY); } /// <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); levels.Add(Content.Load<LevelLibrary.Level>("level2")); levels.Add(Content.Load<LevelLibrary.Level>("level3")); levels.Add(Content.Load<LevelLibrary.Level>("level4")); TextureRefs.tileLevel0 = this.Content.Load<Texture2D>("Textures/Tiles/1"); TextureRefs.tileLevel1 = this.Content.Load<Texture2D>("Textures/Tiles/laatta4"); TextureRefs.tileLevel2 = this.Content.Load<Texture2D>("Textures/Tiles/laatta3"); TextureRefs.tileLevel3 = this.Content.Load<Texture2D>("Textures/Tiles/laatta2"); TextureRefs.tileLevel4 = this.Content.Load<Texture2D>("Textures/Tiles/laatta1"); TextureRefs.tileLevel5 = this.Content.Load<Texture2D>("Textures/Tiles/laatta1"); TextureRefs.turnsTexture = this.Content.Load<Texture2D>("Textures/atlas_score"); TextureRefs.jewel1 = this.Content.Load<Texture2D>("Textures/Jewels/jkeltainen"); TextureRefs.jewel2 = this.Content.Load<Texture2D>("Textures/Jewels/joranssi"); TextureRefs.jewel3 = this.Content.Load<Texture2D>("Textures/Jewels/jpunainen"); TextureRefs.jewel4 = this.Content.Load<Texture2D>("Textures/Jewels/jturkoosi"); TextureRefs.jewel5 = this.Content.Load<Texture2D>("Textures/Jewels/jvihrea"); TextureRefs.jewel6 = this.Content.Load<Texture2D>("Textures/Jewels/jvioletti"); TextureRefs.jewel7 = this.Content.Load<Texture2D>("Textures/Jewels/jpinkki"); TextureRefs.player = this.Content.Load<Texture2D>("Textures/hahmo"); TextureRefs.playerWings = this.Content.Load<Texture2D>("Textures/hahmo"); TextureRefs.playerBridge = this.Content.Load<Texture2D>("Textures/silta"); TextureRefs.bird = this.Content.Load<Texture2D>("7"); TextureRefs.background = this.Content.Load<Texture2D>("Textures/bg1"); TextureRefs.frame = this.Content.Load<Texture2D>("Textures/frame1"); TextureRefs.backgroundGood = this.Content.Load<Texture2D>("Textures/bg2"); TextureRefs.frameGood = this.Content.Load<Texture2D>("Textures/frame2"); TextureRefs.introPage = this.Content.Load<Texture2D>("Textures/bg1"); TextureRefs.gameOver = this.Content.Load<Texture2D>("Textures/bg1"); TextureRefs.victoryScreen = this.Content.Load<Texture2D>("Textures/bg2"); TextureRefs.turnTextBackground = this.Content.Load<Texture2D>("textBG"); TextureRefs.selector = this.Content.Load<Texture2D>("selector"); TextureRefs.frameImage1 = this.Content.Load<Texture2D>("Textures/Animals/kettu1"); TextureRefs.frameImage11 = this.Content.Load<Texture2D>("Textures/Animals/kettu2"); TextureRefs.frameImage2 = this.Content.Load<Texture2D>("Textures/Animals/kukka1"); TextureRefs.frameImage22 = this.Content.Load<Texture2D>("Textures/Animals/kukka2"); TextureRefs.frameImage3 = this.Content.Load<Texture2D>("Textures/Animals/lintu1"); TextureRefs.frameImage33 = this.Content.Load<Texture2D>("Textures/Animals/lintu2"); TextureRefs.frameImage4 = this.Content.Load<Texture2D>("Textures/Animals/pilvi1a"); TextureRefs.frameImage44 = this.Content.Load<Texture2D>("Textures/Animals/pilvi1b"); TextureRefs.frameImage5 = this.Content.Load<Texture2D>("Textures/Animals/aurinko1"); TextureRefs.frameImage55 = this.Content.Load<Texture2D>("Textures/Animals/aurinko2"); TextureRefs.frameImage6 = this.Content.Load<Texture2D>("Textures/Animals/pupu1"); TextureRefs.frameImage66 = this.Content.Load<Texture2D>("Textures/Animals/pupu2"); TextureRefs.frameImage7 = this.Content.Load<Texture2D>("Textures/Animals/puu1"); TextureRefs.frameImage77 = this.Content.Load<Texture2D>("Textures/Animals/puu2"); //Need 7 of these frameImageManager.addFrameImage(TextureRefs.frameImage5, TextureRefs.frameImage55, new Vector2(1000, 30)); //aurinko frameImageManager.addFrameImage(TextureRefs.frameImage4, TextureRefs.frameImage44, new Vector2(1000, 10)); //pilvi frameImageManager.addFrameImage(TextureRefs.frameImage7, TextureRefs.frameImage77, new Vector2(1000, 200)); //puu frameImageManager.addFrameImage(TextureRefs.frameImage3, TextureRefs.frameImage33, new Vector2(100, 50)); //lintu frameImageManager.addFrameImage(TextureRefs.frameImage1, TextureRefs.frameImage11, new Vector2(30, 550)); //Kettu frameImageManager.addFrameImage(TextureRefs.frameImage6, TextureRefs.frameImage66, new Vector2(1000, 500)); // pupu frameImageManager.addFrameImage(TextureRefs.frameImage2, TextureRefs.frameImage22, new Vector2(200,600)); //kukka } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); MouseState mouse = Mouse.GetState(); KeyboardState keyboard = Keyboard.GetState(); switch (state) { case GameState.title: titleScreen(mouse); break; case GameState.playing: PlayingGame(gameTime, mouse, keyboard); break; case GameState.gameover: gameOver(mouse); break; case GameState.victory: victory(mouse); break; } oldMouse = mouse; oldKeyboard = keyboard; 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.CornflowerBlue); spriteBatch.Begin(); switch (state) { case GameState.title: spriteBatch.Draw(TextureRefs.introPage, new Vector2(0.0f, 0.0f), Color.White); break; case GameState.playing: spriteBatch.Draw(currentBackground, new Vector2(0.0f, 0.0f), Color.White); grid.Draw(spriteBatch); spriteBatch.Draw(currentFrame, new Vector2(0.0f, 0.0f), Color.White); frameImageManager.Draw(spriteBatch); spriteBatch.Draw(TextureRefs.turnTextBackground, new Vector2(100, 50), Color.White); turnString.Draw(spriteBatch); break; case GameState.gameover: spriteBatch.Draw(TextureRefs.gameOver, new Vector2(0.0f, 0.0f), Color.White); break; case GameState.victory: spriteBatch.Draw(TextureRefs.victoryScreen, new Vector2(0.0f, 0.0f), Color.White); break; } spriteBatch.End(); base.Draw(gameTime); } protected void PlayingGame(GameTime gametime, MouseState mouse, KeyboardState keyboard) { turnString.SetValue(currentPlayer.getTurnsLeft()); cameraDirection = Vector2.Zero; if (keyboard.IsKeyDown(Keys.Left) == true) { cameraDirection.X = -1; } else if (keyboard.IsKeyDown(Keys.Right) == true) { cameraDirection.X = 1; } if (keyboard.IsKeyDown(Keys.Up) == true) { cameraDirection.Y = -1; } else if (keyboard.IsKeyDown(Keys.Down) == true) { cameraDirection.Y = 1; } camera.Translate(cameraDirection, gametime, grid.getLevelRows(), grid.getLevelCols()); if (mouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released) { //if is a valid tile if (grid.mouseClicked(camera.TransformMouse(new Vector2( mouse.X, mouse.Y)))) { if (currentPlayer.isBridge()) { currentPlayer = new Player(); currentPlayer.Position = grid.getSpawnPoint(); currentPlayer.setPosition(grid.getSpawnRow(), grid.getSpawnCol()); camera.Position = grid.getCameraCenter(); grid.setCurrentPlayer(currentPlayer); grid.decreaseTileLevels(); gameTurns--; if (gameTurns <= 0) state = GameState.gameover; } else { currentPlayer.decrementTurnsLeft(); if (currentPlayer.getTurnsLeft() <= 0) { grid.addDeadPlayer(currentPlayer); currentPlayer = new Player(); currentPlayer.Position = grid.getSpawnPoint(); currentPlayer.setPosition(grid.getSpawnRow(), grid.getSpawnCol()); camera.Position = grid.getCameraCenter(); grid.setCurrentPlayer(currentPlayer); grid.decreaseTileLevels(); gameTurns--; if (gameTurns <= 0) state = GameState.gameover; } } } } else if (keyboard.IsKeyDown(Keys.Space) && oldKeyboard.IsKeyUp(Keys.Space)) { grid.addDeadPlayer(currentPlayer); int passedTurns = currentPlayer.getTurnsLeft(); currentPlayer = new Player(); currentPlayer.Position=grid.getSpawnPoint(); currentPlayer.setPosition(grid.getSpawnRow(), grid.getSpawnCol()); camera.Position = grid.getCameraCenter(); grid.setCurrentPlayer(currentPlayer); grid.decreaseTileLevels(); currentPlayer.addTurnsLeft(passedTurns); gameTurns--; if (gameTurns <= 0) state = GameState.gameover; } if (grid.isWin()) { currentLevel++; if (currentLevel < levels.Count) { gameTurns = C.gameTurns; grid.unloadLevel(); grid.initJewels(frameImageManager); grid.LoadLevel(levels[currentLevel]); frameImageManager.resetFrameImages(); currentBackground = TextureRefs.background; currentFrame = TextureRefs.frame; } else { state = GameState.victory; } } else if (grid.isCloseWin()) { currentBackground = TextureRefs.backgroundGood; currentFrame = TextureRefs.frameGood; } } private void titleScreen(MouseState mouse) { currentLevel = 0; if (mouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released) { grid.LoadLevel(levels[currentLevel]); state = GameState.playing; currentBackground = TextureRefs.background; currentFrame = TextureRefs.frame; } } private void gameOver(MouseState mouse) { if (mouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released) { this.Exit(); } } private void victory(MouseState mouse) { if (mouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released) { this.Exit(); } } } }
/* * Copyright (c) 2006, Clever Age * 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 Clever Age 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 REGENTS 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 REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Xml; using System.Xml.Schema; using System.Reflection; using System.Collections; using System.IO.Packaging; using Daisy.SaveAsDAISY.Conversion; namespace Daisy.SaveAsDAISY.CommandLineTool { /// <summary>Exception thrown when the file is not valid</summary> public class OoxValidatorException : Exception { public OoxValidatorException(String msg) : base(msg) { } } /// <summary>Check the validity of a docx file. Throw an OoxValidatorException if errors occurs</summary> public class OoxValidator { // namespaces private static string OOX_DOC_REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; // OOX special files private static string OOX_RELATIONSHIP_FILE = "_rels/.rels"; // OOX relationship private static string OOX_DOCUMENT_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; private XmlReaderSettings settings = null; // global settings to open the xml files private Report report; private Package reader; PackagePart relationshipPart = null; Stream str = null; String target = null; /// <summary> /// Initialize the validator /// </summary> public OoxValidator(Report report) { this.settings = new XmlReaderSettings(); this.report = report; } /// <summary> /// Check the validity of an Office Open XML file. /// </summary> /// <param name="fileName">The path of the docx file.</param> public void validate(String fileName) { // 0. The file must exist and be a valid Package try { reader = Package.Open(fileName); } catch (Exception e) { throw new OoxValidatorException("Problem opening the docx file : " + e.Message); } // 1. _rels/.rels must be present and valid Stream relationShips = null; try { relationShips = GetEntry(reader, OOX_RELATIONSHIP_FILE); } catch (Exception) { throw new OoxValidatorException("The docx package must have a \"/_rels/.rels\" file"); } this.validateXml(relationShips); // 2. _rel/.rels must contain a relationship of document.xml relationShips = GetEntry(reader, OOX_RELATIONSHIP_FILE); XmlReader r = XmlReader.Create(relationShips); String docTarget = null; while (r.Read() && docTarget == null) { if (r.NodeType == XmlNodeType.Element && r.GetAttribute("Type") == OOX_DOCUMENT_RELATIONSHIP_TYPE) { docTarget = r.GetAttribute("Target"); } } if (docTarget == null) { throw new OoxValidatorException(" document.xml relation not found in \"/_rels/.rels\""); } // 3. For each item in _rels/.rels relationShips = GetEntry(reader, OOX_RELATIONSHIP_FILE); r = XmlReader.Create(relationShips); while (r.Read()) { if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship") { String target = r.GetAttribute("Target"); // 3.1. The target item must exist in the package Stream item = null; try { item = GetEntry(reader, target); } catch (Exception) { throw new OoxValidatorException("The file \"" + target + "\" is described in the \"/_rels/.rels\" file but does not exist in the package."); } // 3.2. A content type can be found in [Content_Types].xml file String ct = this.FindContentType(reader, "/" + target); //// 3.3. If it's an xml file, it has to be valid if (ct.EndsWith("+xml")) { this.validateXml(item); } } } // Does a part relationship exist ? Stream partRel = null; String partDir = docTarget.Substring(0, docTarget.LastIndexOf("/")); String partRelPath = partDir + "/_rels/" + docTarget.Substring(docTarget.LastIndexOf("/") + 1) + ".rels"; bool partRelExists = true; try { partRel = GetEntry(reader, partRelPath); } catch (Exception) { partRelExists = false; } if (partRelExists) { this.validateXml(partRel); // 4. For each item in /word/_rels/document.xml.rels partRel = GetEntry(reader, partRelPath); r = XmlReader.Create(partRel); target = null; while (r.Read()) { if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship") { if (r.GetAttribute("Type") == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml") { //target = r.GetAttribute("Target").Replace("../", ""); } else if (r.GetAttribute("Type") == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") { //target = r.GetAttribute("Target").Replace("../", ""); } else if (r.GetAttribute("Type") == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" && r.GetAttribute("TargetMode") == "External") { //target = r.GetAttribute("Target").Replace("../", ""); } else if (r.GetAttribute("Type") == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/subDocument" && r.GetAttribute("TargetMode") == "External") { //target = r.GetAttribute("Target").Replace("../", ""); } else { target = partDir + "/" + r.GetAttribute("Target"); } // Is the target item exist in the package ? Stream item = null; bool fileExists = true; try { if (target != null) { item = GetEntry(reader, target); } else fileExists = false; } catch (Exception) { fileExists = false; } if (fileExists) { // 4.1. A content type can be found in [Content_Types].xml file String ct = this.FindContentType(reader, "/" + target); // 4.2. If it's an xml file, it has to be valid if (ct.EndsWith("+xml")) { this.validateXml(item); } } } } } // 5. are all referenced relationships exist in the part relationship file // retrieve all ids referenced in the document Stream doc = GetEntry(reader, docTarget); r = XmlReader.Create(doc); ArrayList ids = new ArrayList(); while (r.Read()) { if (r.NodeType == XmlNodeType.Element && r.GetAttribute("id", OOX_DOC_REL_NS) != null) { if (!ids.Contains(r.GetAttribute("id", OOX_DOC_REL_NS))) ids.Add(r.GetAttribute("id", OOX_DOC_REL_NS)); } } // check if each id exists in the partRel file if (ids.Count != 0) { if (!partRelExists) { throw new OoxValidatorException("Referenced id exist but no part relationship file found"); } relationShips = GetEntry(reader, partRelPath); r = XmlReader.Create(relationShips); while (r.Read()) { if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship") { if (ids.Contains(r.GetAttribute("Id"))) { ids.Remove(r.GetAttribute("Id")); } } } if (ids.Count != 0) { throw new OoxValidatorException("One or more relationship id have not been found in the partRelationship file : " + ids[0]); } } reader.Close(); } // validate xml stream private void validateXml(Stream xmlStream) { XmlReader r = XmlReader.Create(xmlStream, this.settings); while (r.Read()) ; } // find the content type of a part in the package private String FindContentType(Package reader, String target) { String extension = null; String contentType = null; if (target.IndexOf(".") != -1) { extension = target.Substring(target.IndexOf(".") + 1); } foreach (PackagePart searchRelation in reader.GetParts()) { relationshipPart = searchRelation; if (target == relationshipPart.Uri.ToString()) contentType = relationshipPart.ContentType.ToString(); } if (contentType == null) { throw new OoxValidatorException("Content type not found for " + target); } return contentType; } public void ValidationHandler(object sender, ValidationEventArgs args) { throw new OoxValidatorException("XML Schema Validation error : " + args.Message); } public Stream GetEntry(Package pack, String name) { foreach (PackagePart searchRelation in pack.GetParts()) { String com = "/" + name; relationshipPart = searchRelation; if (com == relationshipPart.Uri.ToString()) str = relationshipPart.GetStream(); } return str; } } }
#region Using directives using System; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Collections.Generic; using log4net; #endregion namespace Commanigy.Iquomi.Data { /// <summary> /// Summary description for DbUtility. /// </summary> public class DbUtility : IDisposable { private static readonly ILog log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType ); private IDbConnection connection; private IDbCommand command; public DbUtility() : this(null) { } public DbUtility(string commandText) { connection = DataStore.Instance.GetConnection(); if (commandText != null) { Cmd(commandText, CommandType.StoredProcedure); } } public void Cmd(string commandText, CommandType commandType) { command = connection.CreateCommand(); command.CommandText = commandText; command.CommandType = commandType; } public void In(string name, DbType type, object v) { IDbDataParameter prm = command.CreateParameter(); prm.ParameterName = name; prm.DbType = type; prm.Value = (v != null) ? v : DBNull.Value; command.Parameters.Add(prm); } #region Helper methods for commonly used types public void In(string name, int v) { this.In(name, DbType.Int32, v); } public void In(string name, string v) { this.In(name, DbType.String, v); } public void In(string name, float v) { this.In(name, DbType.Single, v); } public void In(string name, double v) { this.In(name, DbType.Double, v); } public void In(string name, DateTime v) { this.In(name, DbType.DateTime, v); } public void In(string name, Guid v) { this.In(name, DbType.Guid, v); } #endregion public void Out(string name, DbType type) { IDbDataParameter prm = command.CreateParameter(); prm.ParameterName = name; prm.Direction = ParameterDirection.Output; prm.DbType = type; command.Parameters.Add(prm); } public object ExecuteScalar() { object o = null; try { Open(); o = command.ExecuteScalar(); } finally { Close(); } return o; } public int ExecuteNonQuery() { int r = 0; try { Open(); r = command.ExecuteNonQuery(); } finally { Close(); } return r; } /* public object ExecuteOut() { Open(); command.ExecuteScalar(); object o = ((IDbDataParameter)command.Parameters["@id"]).Value; Close(); return o; } */ public object Fill(object obj) { try { Open(); IDataReader rdr = command.ExecuteReader(); if (rdr.Read()) { new DbColumnAdapter(obj).Load(rdr); } } finally { Close(); } return obj; } public T Fill<T>(T obj) { try { Open(); IDataReader rdr = command.ExecuteReader(); if (rdr.Read()) { new DbColumnAdapter(obj).Load(rdr); } } finally { Close(); } return obj; } public Array FillAll(System.Type t) { ArrayList list = new ArrayList(); try { Open(); IDataReader rdr = command.ExecuteReader(); while (rdr.Read()) { object obj = Activator.CreateInstance(t); list.Add(new DbColumnAdapter(obj).Load(rdr)); } } finally { Close(); } return list.ToArray(t); } public List<object> GetList(System.Type t) { List<object> list = new List<object>(); try { Open(); IDataReader rdr = command.ExecuteReader(); while (rdr.Read()) { object obj = Activator.CreateInstance(t); list.Add(new DbColumnAdapter(obj).Load(rdr)); } } finally { Close(); } return list; } public DataTable GetDataTable() { DataTable dt = new DataTable(); try { Open(); IDataReader rdr = command.ExecuteReader(); DataTable schemaTable = rdr.GetSchemaTable(); foreach (DataRow myRow in schemaTable.Rows) { // dt.Columns.Add(myRow["ColumnName"].ToString()); dt.Columns.Add((string)myRow["ColumnName"], (Type)myRow["DataType"]); } while (rdr.Read()) { object[] v = new object[rdr.FieldCount]; rdr.GetValues(v); dt.Rows.Add(v); } } finally { Close(); } return dt; } private void Open() { connection.Open(); } private void Close() { connection.Close(); } #region IDisposable Members public void Dispose() { if (connection.State == ConnectionState.Open) { this.Close(); connection.Dispose(); connection = null; } } #endregion } }
// // PlaybackControllerService.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Hyena; using Hyena.Collections; using Banshee.Base; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.MediaEngine; namespace Banshee.PlaybackController { [NDesk.DBus.IgnoreMarshalByRefObjectBaseClass] public class PlaybackControllerService : MarshalByRefObject, IRequiredService, ICanonicalPlaybackController, IPlaybackController, IPlaybackControllerService { private enum Direction { Next, Previous } private IStackProvider<TrackInfo> previous_stack; private IStackProvider<TrackInfo> next_stack; private TrackInfo current_track; private TrackInfo prior_track; private TrackInfo changing_to_track; private bool raise_started_after_transition = false; private bool transition_track_started = false; private bool last_was_skipped = true; private int consecutive_errors; private uint error_transition_id; private DateTime source_auto_set_at = DateTime.MinValue; private string shuffle_mode; private PlaybackRepeatMode repeat_mode; private bool stop_when_finished = false; private PlayerEngineService player_engine; private ITrackModelSource source; private ITrackModelSource next_source; private event PlaybackControllerStoppedHandler dbus_stopped; event PlaybackControllerStoppedHandler IPlaybackControllerService.Stopped { add { dbus_stopped += value; } remove { dbus_stopped -= value; } } public event EventHandler Stopped; public event EventHandler SourceChanged; public event EventHandler NextSourceChanged; public event EventHandler TrackStarted; public event EventHandler Transition; public event EventHandler<EventArgs<string>> ShuffleModeChanged; public event EventHandler<EventArgs<PlaybackRepeatMode>> RepeatModeChanged; public PlaybackControllerService () { InstantiateStacks (); player_engine = ServiceManager.PlayerEngine; player_engine.PlayWhenIdleRequest += OnPlayerEnginePlayWhenIdleRequest; player_engine.ConnectEvent (OnPlayerEvent, PlayerEvent.RequestNextTrack | PlayerEvent.EndOfStream | PlayerEvent.StartOfStream | PlayerEvent.StateChange | PlayerEvent.Error, true); ServiceManager.SourceManager.ActiveSourceChanged += delegate { ITrackModelSource active_source = ServiceManager.SourceManager.ActiveSource as ITrackModelSource; if (active_source != null && source_auto_set_at == source_set_at && !player_engine.IsPlaying ()) { Source = active_source; source_auto_set_at = source_set_at; } }; } protected virtual void InstantiateStacks () { previous_stack = new PlaybackControllerDatabaseStack (); next_stack = new PlaybackControllerDatabaseStack (); } private void OnPlayerEnginePlayWhenIdleRequest (object o, EventArgs args) { ITrackModelSource next_source = NextSource; if (next_source != null && next_source.TrackModel.Selection.Count > 0) { Source = NextSource; CancelErrorTransition (); CurrentTrack = next_source.TrackModel[next_source.TrackModel.Selection.FirstIndex]; QueuePlayTrack (); } else { Next (); } } private void OnPlayerEvent (PlayerEventArgs args) { switch (args.Event) { case PlayerEvent.StartOfStream: CurrentTrack = player_engine.CurrentTrack; consecutive_errors = 0; break; case PlayerEvent.EndOfStream: EosTransition (); break; case PlayerEvent.Error: if (++consecutive_errors >= 5) { consecutive_errors = 0; player_engine.Close (false); OnStopped (); break; } CancelErrorTransition (); // TODO why is this so long? any reason not to be instantaneous? error_transition_id = Application.RunTimeout (250, delegate { EosTransition (); RequestTrackHandler (); return true; }); break; case PlayerEvent.StateChange: if (((PlayerEventStateChangeArgs)args).Current != PlayerState.Loading) { break; } TrackInfo track = player_engine.CurrentTrack; if (changing_to_track != track && track != null) { CurrentTrack = track; } changing_to_track = null; if (!raise_started_after_transition) { transition_track_started = false; OnTrackStarted (); } else { transition_track_started = true; } break; case PlayerEvent.RequestNextTrack: RequestTrackHandler (); break; } } private void CancelErrorTransition () { if (error_transition_id > 0) { Application.IdleTimeoutRemove (error_transition_id); error_transition_id = 0; } } private bool EosTransition () { player_engine.IncrementLastPlayed (); return true; } private bool RequestTrackHandler () { if (!StopWhenFinished) { if (RepeatMode == PlaybackRepeatMode.RepeatSingle) { QueuePlayTrack (); } else { last_was_skipped = false; Next (RepeatMode == PlaybackRepeatMode.RepeatAll, false); } } else { OnStopped (); } StopWhenFinished = false; return false; } public void First () { CancelErrorTransition (); Source = NextSource; // This and OnTransition() below commented out b/c of BGO #524556 //raise_started_after_transition = true; if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).First ()) { } else { ((IBasicPlaybackController)this).First (); } //OnTransition (); } public void Next () { Next (RepeatMode == PlaybackRepeatMode.RepeatAll, true); } public void Next (bool restart) { Next (restart, true); } public void Next (bool restart, bool changeImmediately) { CancelErrorTransition (); Source = NextSource; raise_started_after_transition = true; if (changeImmediately) { player_engine.IncrementLastPlayed (); } if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).Next (restart, changeImmediately)) { } else { ((IBasicPlaybackController)this).Next (restart, changeImmediately); } OnTransition (); } public void Previous () { Previous (RepeatMode == PlaybackRepeatMode.RepeatAll); } public void Previous (bool restart) { CancelErrorTransition (); Source = NextSource; raise_started_after_transition = true; player_engine.IncrementLastPlayed (); if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).Previous (restart)) { } else { ((IBasicPlaybackController)this).Previous (restart); } OnTransition (); } public void RestartOrPrevious () { RestartOrPrevious (RepeatMode == PlaybackRepeatMode.RepeatAll); } public void RestartOrPrevious (bool restart) { const int delay = 4000; // ms if (player_engine.Position < delay) { Previous (); } else { var track = player_engine.CurrentTrack; if (track != null) { player_engine.Close (); player_engine.OpenPlay (track); } } } bool IBasicPlaybackController.First () { if (Source.Count > 0) { if (ShuffleMode == "off") { CurrentTrack = Source.TrackModel[0]; player_engine.OpenPlay (CurrentTrack); } else { ((IBasicPlaybackController)this).Next (false, true); } } return true; } bool IBasicPlaybackController.Next (bool restart, bool changeImmediately) { if (CurrentTrack != null) { previous_stack.Push (CurrentTrack); } CurrentTrack = CalcNextTrack (Direction.Next, restart); if (!changeImmediately) { // A RequestNextTrack event should always result in SetNextTrack being called. null is acceptable. player_engine.SetNextTrack (CurrentTrack); } else if (CurrentTrack != null) { QueuePlayTrack (); } return true; } bool IBasicPlaybackController.Previous (bool restart) { if (CurrentTrack != null && previous_stack.Count > 0) { next_stack.Push (current_track); } CurrentTrack = CalcNextTrack (Direction.Previous, restart); if (CurrentTrack != null) { QueuePlayTrack (); } return true; } private TrackInfo CalcNextTrack (Direction direction, bool restart) { if (direction == Direction.Previous) { if (previous_stack.Count > 0) { return previous_stack.Pop (); } } else if (direction == Direction.Next) { if (next_stack.Count > 0) { return next_stack.Pop (); } } return QueryTrack (direction, restart); } private TrackInfo QueryTrack (Direction direction, bool restart) { Log.DebugFormat ("Querying model for track to play in {0}:{1} mode", ShuffleMode, direction); return ShuffleMode == "off" ? QueryTrackLinear (direction, restart) : QueryTrackRandom (ShuffleMode, restart); } private TrackInfo QueryTrackLinear (Direction direction, bool restart) { if (Source.TrackModel.Count == 0) return null; int index = Source.TrackModel.IndexOf (PriorTrack); // Clear the PriorTrack after using it, it's only meant to be used for a single Query PriorTrack = null; if (index == -1) { return Source.TrackModel[0]; } else { index += (direction == Direction.Next ? 1 : -1); if (index >= 0 && index < Source.TrackModel.Count) { return Source.TrackModel[index]; } else if (!restart) { return null; } else if (index < 0) { return Source.TrackModel[Source.TrackModel.Count - 1]; } else { return Source.TrackModel[0]; } } } private TrackInfo QueryTrackRandom (string shuffle_mode, bool restart) { var track_shuffler = Source.TrackModel as Banshee.Collection.Database.DatabaseTrackListModel; TrackInfo track = track_shuffler == null ? Source.TrackModel.GetRandom (source_set_at) : track_shuffler.GetRandom (source_set_at, shuffle_mode, restart, last_was_skipped, Banshee.Collection.Database.Shuffler.Playback); // Reset to default of true, only ever set to false by EosTransition last_was_skipped = true; return track; } private void QueuePlayTrack () { changing_to_track = CurrentTrack; player_engine.OpenPlay (CurrentTrack); } protected virtual void OnStopped () { player_engine.IncrementLastPlayed (); EventHandler handler = Stopped; if (handler != null) { handler (this, EventArgs.Empty); } PlaybackControllerStoppedHandler dbus_handler = dbus_stopped; if (dbus_handler != null) { dbus_handler (); } } protected virtual void OnTransition () { EventHandler handler = Transition; if (handler != null) { handler (this, EventArgs.Empty); } if (raise_started_after_transition && transition_track_started) { OnTrackStarted (); } raise_started_after_transition = false; transition_track_started = false; } protected virtual void OnSourceChanged () { EventHandler handler = SourceChanged; if (handler != null) { handler (this, EventArgs.Empty); } } protected void OnNextSourceChanged () { EventHandler handler = NextSourceChanged; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnTrackStarted () { EventHandler handler = TrackStarted; if (handler != null) { handler (this, EventArgs.Empty); } } public TrackInfo CurrentTrack { get { return current_track; } protected set { current_track = value; } } public TrackInfo PriorTrack { get { return prior_track ?? CurrentTrack; } set { prior_track = value; } } protected DateTime source_set_at = DateTime.MinValue; public ITrackModelSource Source { get { if (source == null && ServiceManager.SourceManager.DefaultSource is ITrackModelSource) { return (ITrackModelSource)ServiceManager.SourceManager.DefaultSource; } return source; } set { if (source != value) { NextSource = value; source = value; source_set_at = DateTime.Now; OnSourceChanged (); } } } public ITrackModelSource NextSource { get { return next_source ?? Source; } set { if (next_source != value) { next_source = value; OnNextSourceChanged (); if (!player_engine.IsPlaying ()) { Source = next_source; } } } } public string ShuffleMode { get { return shuffle_mode; } set { shuffle_mode = value; // If the user changes the shuffle mode, she expects the "Next" // button to behave according to the new selection. See bgo#528809 next_stack.Clear (); var handler = ShuffleModeChanged; if (handler != null) { handler (this, new EventArgs<string> (shuffle_mode)); } } } public PlaybackRepeatMode RepeatMode { get { return repeat_mode; } set { repeat_mode = value; EventHandler<EventArgs<PlaybackRepeatMode>> handler = RepeatModeChanged; if (handler != null) { handler (this, new EventArgs<PlaybackRepeatMode> (repeat_mode)); } } } public bool StopWhenFinished { get { return stop_when_finished; } set { stop_when_finished = value; } } string IService.ServiceName { get { return "PlaybackController"; } } IRemoteExportable IRemoteExportable.Parent { get { return null; } } } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // Copyright (c) 2020 Upendo Ventures, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY daOF 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.Globalization; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using Hotcakes.Commerce; using Hotcakes.Commerce.Catalog; using Hotcakes.Commerce.Globalization; using Hotcakes.Commerce.Membership; using Hotcakes.Modules.Core.Admin.AppCode; namespace Hotcakes.Modules.Core.Admin.Catalog { partial class ProductTypePropertiesEdit : BaseAdminPage { public long? _productPropertyId; private const string DATEFORMAT = "MM/dd/yyyy"; public long? ProductPropertyId { get { var propertyId = Request.QueryString["id"]; long productPropertyId; if (long.TryParse(propertyId, out productPropertyId)) _productPropertyId = productPropertyId; return _productPropertyId; } } private long ProductPropertyChoiceId { get { return (long) ViewState["ProductPropertyChoiceId"]; } set { ViewState["ProductPropertyChoiceId"] = value; } } protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); PageTitle = Localization.GetString("PageTitle"); CurrentTab = AdminTabType.Catalog; ValidateCurrentUserHasPermission(SystemPermissions.CatalogView); } protected override void OnInit(EventArgs e) { base.OnInit(e); rgChoices.RowDataBound += rgChoices_RowDataBound; rgChoices.RowDeleting += rgChoices_RowDeleting; rgChoices.RowEditing += rgChoices_RowEditing; btnUpdateChoice.Click += btnUpdateChoice_Click; btnCancelUpdateChoice.Click += btnCancelUpdateChoice_Click; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { var property = HccApp.CatalogServices.ProductProperties.Find(ProductPropertyId.Value); if (property == null) { Response.Redirect("ProductTypeProperties.aspx"); } LocalizeView(); PopulateCultureCodeList(); LoadProperty(property); } } private void LocalizeView() { var localization = Factory.Instance.CreateLocalizationHelper(LocalResourceFile); LocalizationUtils.LocalizeGridView(rgChoices, localization); } private void PopulateCultureCodeList() { var allCountries = HccApp.GlobalizationServices.Countries.FindAllForCurrency(); lstCultureCode.DataSource = allCountries; lstCultureCode.DataValueField = "CultureCode"; lstCultureCode.DataTextField = "SampleNameAndCurrency"; lstCultureCode.DataBind(); } private void LoadProperty(ProductProperty prop) { txtPropertyName.Text = prop.PropertyName; txtDisplayName.Text = prop.DisplayName; chkDisplayOnSite.Checked = prop.DisplayOnSite; chkDisplayToDropShipper.Checked = prop.DisplayToDropShipper; chkDisplayOnSearch.Checked = prop.DisplayOnSearch; InitSpecificSettings(prop); } private void InitSpecificSettings(ProductProperty property) { switch (property.TypeCode) { case ProductPropertyType.CurrencyField: mvTypeSettings.SetActiveView(vCurrency); var liCultureCode = lstCultureCode.Items.FindByValue(property.CultureCode); if (liCultureCode != null) liCultureCode.Selected = true; txtDefaultCurrencyValue.Text = property.DefaultValue; break; case ProductPropertyType.DateField: mvTypeSettings.SetActiveView(vDate); if (!string.IsNullOrEmpty(property.DefaultValue)) { DateTime selectedDate; if ( !DateTime.TryParse(property.DefaultValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out selectedDate)) { selectedDate = DateTime.UtcNow; } radDefaultDate.Text = selectedDate.ToString(DATEFORMAT); } break; case ProductPropertyType.MultipleChoiceField: mvTypeSettings.SetActiveView(vMultipleChoice); PopulateMultipleChoice(property); break; case ProductPropertyType.TextField: mvTypeSettings.SetActiveView(vText); chkIsLocalizable.Checked = property.IsLocalizable; var realValue = property.IsLocalizable ? property.DefaultLocalizableValue : property.DefaultValue; txtDefaultTextValue.Text = realValue; break; } } private void PopulateMultipleChoice(ProductProperty property) { BindGridView(); foreach (GridViewRow row in rgChoices.Rows) { var chbDefault = row.FindControl("chbDefault") as CheckBox; var choiceId = rgChoices.DataKeys[row.RowIndex]["Id"].ToString(); if (choiceId == property.DefaultValue) { chbDefault.Checked = true; break; } } } private void BindGridView() { var property = HccApp.CatalogServices.ProductProperties.Find(ProductPropertyId.Value); if (property != null && property.Choices != null && property.Choices.Count > 0) { property.Choices = property.Choices.OrderBy(y => y.SortOrder).ToList(); rgChoices.DataSource = property.Choices; rgChoices.DataBind(); } } private void rgChoices_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var productPropertyChoice = e.Row.DataItem as ProductPropertyChoice; e.Row.Attributes["productPropertyChoiceId"] = productPropertyChoice.Id.ToString(); } } private void rgChoices_RowEditing(object sender, GridViewEditEventArgs e) { e.Cancel = true; var ProductPropertyChoiceId = long.Parse(rgChoices.DataKeys[e.NewEditIndex]["Id"].ToString()); var prop = HccApp.CatalogServices.ProductProperties.Find(ProductPropertyId.Value); var choice = prop.Choices.FirstOrDefault(y => y.Id == ProductPropertyChoiceId); txtChoiceName.Text = choice.ChoiceName; txtChoiceDisplayName.Text = choice.DisplayName; ShowEditor(true); } private void rgChoices_RowDeleting(object sender, GridViewDeleteEventArgs e) { var choiceId = long.Parse(rgChoices.DataKeys[e.RowIndex]["Id"].ToString()); var prop = HccApp.CatalogServices.ProductProperties.Find(ProductPropertyId.Value); var c = prop.Choices.FirstOrDefault(y => y.Id == choiceId); if (c != null) { prop.Choices.Remove(c); HccApp.CatalogServices.ProductProperties.Update(prop); } BindGridView(); ShowEditor(false); } private void btnUpdateChoice_Click(object sender, EventArgs e) { if (Page.IsValid) { var prop = HccApp.CatalogServices.ProductProperties.Find(ProductPropertyId.Value); var choice = prop.Choices.FirstOrDefault(y => y.Id == ProductPropertyChoiceId); choice.ChoiceName = txtChoiceName.Text.Trim(); choice.DisplayName = txtChoiceDisplayName.Text.Trim(); if (HccApp.CatalogServices.ProductProperties.Update(prop)) { BindGridView(); } else { msg.ShowError(Localization.GetString("AddChoiceFailure")); } BindGridView(); ShowEditor(false); } } private void btnCancelUpdateChoice_Click(object sender, EventArgs e) { BindGridView(); ShowEditor(false); } protected void btnCancel_Click(object sender, EventArgs e) { Response.Redirect("ProductTypeProperties.aspx"); } protected void btnSave_Click(object sender, EventArgs e) { if (Page.IsValid) { var prop = HccApp.CatalogServices.ProductProperties.Find(ProductPropertyId.Value); prop.PropertyName = txtPropertyName.Text; prop.DisplayName = txtDisplayName.Text; prop.DisplayOnSite = chkDisplayOnSite.Checked; prop.DisplayToDropShipper = chkDisplayToDropShipper.Checked; prop.DisplayOnSearch = chkDisplayOnSearch.Checked; switch (prop.TypeCode) { case ProductPropertyType.CurrencyField: prop.CultureCode = lstCultureCode.SelectedValue; prop.DefaultValue = txtDefaultCurrencyValue.Text.Trim(); break; case ProductPropertyType.MultipleChoiceField: var selectedValue = string.Empty; foreach (GridViewRow row in rgChoices.Rows) { var chbDefault = row.FindControl("chbDefault") as CheckBox; if (chbDefault != null && chbDefault.Checked) { selectedValue = rgChoices.DataKeys[row.RowIndex]["Id"].ToString(); break; } } prop.DefaultValue = selectedValue; break; case ProductPropertyType.DateField: prop.DefaultValue = string.Format("{0:d}", radDefaultDate.Text.Trim(), CultureInfo.InvariantCulture); break; case ProductPropertyType.TextField: prop.IsLocalizable = chkIsLocalizable.Checked; if (prop.IsLocalizable) prop.DefaultLocalizableValue = txtDefaultTextValue.Text.Trim(); else prop.DefaultValue = txtDefaultTextValue.Text.Trim(); break; } var success = HccApp.CatalogServices.ProductProperties.Update(prop); if (success) { Response.Redirect("ProductTypeProperties.aspx"); } else { msg.ShowError(Localization.GetString("SavePropertyFailure")); } } } protected void btnNewChoice_Click(object sender, EventArgs e) { if (Page.IsValid) { var prop = HccApp.CatalogServices.ProductProperties.Find(ProductPropertyId.Value); var maxSortOrder = prop.Choices.Max(c => (int?) c.SortOrder) ?? 0; var ppc = new ProductPropertyChoice(); ppc.ChoiceName = txtNewChoice.Text.Trim(); ppc.DisplayName = txtNewChoice.Text.Trim(); ppc.PropertyId = ProductPropertyId.Value; ppc.SortOrder = maxSortOrder + 1; prop.Choices.Add(ppc); if (HccApp.CatalogServices.ProductProperties.Update(prop)) { BindGridView(); } else { msg.ShowError(Localization.GetString("AddChoiceFailure")); } txtNewChoice.Text = string.Empty; ProductPropertyChoiceId = ppc.Id; txtChoiceName.Text = ppc.ChoiceName; txtChoiceDisplayName.Text = ppc.DisplayName; ShowEditor(true); } } #region Private private void ShowEditor(bool show) { pnlEditChoice.Visible = show; if (show) { ScriptManager.RegisterStartupScript(Page, GetType(), "hcEditChoiceDialog", "hcEditChoiceDialog();", true); } } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- /// Returns true if the current quality settings equal /// this graphics quality level. function GraphicsQualityLevel::isCurrent( %this ) { // Test each pref to see if the current value // equals our stored value. for ( %i=0; %i < %this.count(); %i++ ) { %pref = %this.getKey( %i ); %value = %this.getValue( %i ); if ( getVariable( %pref ) !$= %value ) return false; } return true; } /// Applies the graphics quality settings and calls /// 'onApply' on itself or its parent group if its /// been overloaded. function GraphicsQualityLevel::apply( %this ) { for ( %i=0; %i < %this.count(); %i++ ) { %pref = %this.getKey( %i ); %value = %this.getValue( %i ); setVariable( %pref, %value ); } // If we have an overloaded onApply method then // call it now to finalize the changes. if ( %this.isMethod( "onApply" ) ) %this.onApply(); else { %group = %this.getGroup(); if ( isObject( %group ) && %group.isMethod( "onApply" ) ) %group.onApply( %this ); } } function GraphicsQualityPopup::init( %this, %qualityGroup ) { assert( isObject( %this ) ); assert( isObject( %qualityGroup ) ); // Clear the existing content first. %this.clear(); // Fill it. %select = -1; for ( %i=0; %i < %qualityGroup.getCount(); %i++ ) { %level = %qualityGroup.getObject( %i ); if ( %level.isCurrent() ) %select = %i; %this.add( %level.getInternalName(), %i ); } // Setup a default selection. if ( %select == -1 ) %this.setText( "Custom" ); else %this.setSelected( %select ); } function GraphicsQualityPopup::apply( %this, %qualityGroup, %testNeedApply ) { assert( isObject( %this ) ); assert( isObject( %qualityGroup ) ); %quality = %this.getText(); %index = %this.findText( %quality ); if ( %index == -1 ) return false; %level = %qualityGroup.getObject( %index ); if ( isObject( %level ) && !%level.isCurrent() ) { if ( %testNeedApply ) return true; %level.apply(); } return false; } function OptionsDlg::setPane(%this, %pane) { %this-->OptAudioPane.setVisible(false); %this-->OptGraphicsPane.setVisible(false); %this-->OptNetworkPane.setVisible(false); %this-->OptControlsPane.setVisible(false); %this.findObjectByInternalName( "Opt" @ %pane @ "Pane", true ).setVisible(true); %this.fillRemapList(); // Update the state of the apply button. %this._updateApplyState(); } function OptionsDlg::onWake(%this) { if ( isFunction("getWebDeployment") && getWebDeployment() ) { // Cannot enable full screen under web deployment %this-->OptGraphicsFullscreenToggle.setStateOn( false ); %this-->OptGraphicsFullscreenToggle.setVisible( false ); } else { %this-->OptGraphicsFullscreenToggle.setStateOn( Canvas.isFullScreen() ); } %this-->OptGraphicsVSyncToggle.setStateOn( !$pref::Video::disableVerticalSync ); OptionsDlg.initResMenu(); %resSelId = OptionsDlg-->OptGraphicsResolutionMenu.findText( _makePrettyResString( $pref::Video::mode ) ); if( %resSelId != -1 ) OptionsDlg-->OptGraphicsResolutionMenu.setSelected( %resSelId ); OptGraphicsDriverMenu.clear(); %buffer = getDisplayDeviceList(); %count = getFieldCount( %buffer ); for(%i = 0; %i < %count; %i++) OptGraphicsDriverMenu.add(getField(%buffer, %i), %i); %selId = OptGraphicsDriverMenu.findText( getDisplayDeviceInformation() ); if ( %selId == -1 ) OptGraphicsDriverMenu.setFirstSelected(); else OptGraphicsDriverMenu.setSelected( %selId ); // Setup the graphics quality dropdown menus. %this-->OptMeshQualityPopup.init( MeshQualityGroup ); %this-->OptTextureQualityPopup.init( TextureQualityGroup ); %this-->OptLightingQualityPopup.init( LightingQualityGroup ); %this-->OptShaderQualityPopup.init( ShaderQualityGroup ); // Setup the anisotropic filtering menu. %ansioCtrl = %this-->OptAnisotropicPopup; %ansioCtrl.clear(); %ansioCtrl.add( "Off", 0 ); %ansioCtrl.add( "4X", 4 ); %ansioCtrl.add( "8X", 8 ); %ansioCtrl.add( "16X", 16 ); %ansioCtrl.setSelected( $pref::Video::defaultAnisotropy, false ); // set up the Refresh Rate menu. %refreshMenu = %this-->OptRefreshSelectMenu; %refreshMenu.clear(); // %refreshMenu.add("Auto", 60); %refreshMenu.add("60", 60); %refreshMenu.add("75", 75); %refreshMenu.setSelected( getWord( $pref::Video::mode, $WORD::REFRESH ) ); // Audio //OptAudioHardwareToggle.setStateOn($pref::SFX::useHardware); //OptAudioHardwareToggle.setActive( true ); %this-->OptAudioVolumeMaster.setValue( $pref::SFX::masterVolume ); %this-->OptAudioVolumeShell.setValue( $pref::SFX::channelVolume[ $GuiAudioType] ); %this-->OptAudioVolumeSim.setValue( $pref::SFX::channelVolume[ $SimAudioType ] ); %this-->OptAudioVolumeMusic.setValue( $pref::SFX::channelVolume[ $MusicAudioType ] ); OptAudioProviderList.clear(); %buffer = sfxGetAvailableDevices(); %count = getRecordCount( %buffer ); for(%i = 0; %i < %count; %i++) { %record = getRecord(%buffer, %i); %provider = getField(%record, 0); if ( OptAudioProviderList.findText( %provider ) == -1 ) OptAudioProviderList.add( %provider, %i ); } OptAudioProviderList.sort(); %selId = OptAudioProviderList.findText($pref::SFX::provider); if ( %selId == -1 ) OptAudioProviderList.setFirstSelected(); else OptAudioProviderList.setSelected( %selId ); // Populate the Anti-aliasing popup. %aaMenu = %this-->OptAAQualityPopup; %aaMenu.clear(); %aaMenu.Add( "Off", 0 ); %aaMenu.Add( "1x", 1 ); %aaMenu.Add( "2x", 2 ); %aaMenu.Add( "4x", 4 ); %aaMenu.setSelected( getWord( $pref::Video::mode, $WORD::AA ) ); OptMouseSensitivity.value = $pref::Input::LinkMouseSensitivity; // Set the graphics pane to start. %this-->OptGraphicsButton.performClick(); } function OptionsDlg::onSleep(%this) { // write out the control config into the rw/config.cs file moveMap.save( "scripts/client/config.cs" ); } function OptGraphicsDriverMenu::onSelect( %this, %id, %text ) { // Attempt to keep the same resolution settings: %resMenu = OptionsDlg-->OptGraphicsResolutionMenu; %currRes = %resMenu.getText(); // If its empty the use the current. if ( %currRes $= "" ) %currRes = _makePrettyResString( Canvas.getVideoMode() ); // Fill the resolution list. optionsDlg.initResMenu(); // Try to select the previous settings: %selId = %resMenu.findText( %currRes ); if ( %selId == -1 ) %selId = 0; %resMenu.setSelected( %selId ); OptionsDlg._updateApplyState(); } function _makePrettyResString( %resString ) { %width = getWord( %resString, $WORD::RES_X ); %height = getWord( %resString, $WORD::RES_Y ); %aspect = %width / %height; %aspect = mRound( %aspect * 100 ) * 0.01; switch$( %aspect ) { case "1.33": %aspect = "4:3"; case "1.78": %aspect = "16:9"; default: %aspect = ""; } %outRes = %width @ " x " @ %height; if ( %aspect !$= "" ) %outRes = %outRes @ " (" @ %aspect @ ")"; return %outRes; } function OptionsDlg::initResMenu( %this ) { // Clear out previous values %resMenu = %this-->OptGraphicsResolutionMenu; %resMenu.clear(); // If we are in a browser then we can't change our resolution through // the options dialog if (getWebDeployment()) { %count = 0; %currRes = getWords(Canvas.getVideoMode(), $WORD::RES_X, $WORD::RES_Y); %resMenu.add(%currRes, %count); %count++; return; } // Loop through all and add all valid resolutions %count = 0; %resCount = Canvas.getModeCount(); for (%i = 0; %i < %resCount; %i++) { %testResString = Canvas.getMode( %i ); %testRes = _makePrettyResString( %testResString ); // Only add to list if it isn't there already. if (%resMenu.findText(%testRes) == -1) { %resMenu.add(%testRes, %i); %count++; } } %resMenu.sort(); } function OptionsDlg::applyGraphics( %this, %testNeedApply ) { %newAdapter = OptGraphicsDriverMenu.getText(); %numAdapters = GFXInit::getAdapterCount(); %newDevice = $pref::Video::displayDevice; for( %i = 0; %i < %numAdapters; %i ++ ) if( GFXInit::getAdapterName( %i ) $= %newAdapter ) { %newDevice = GFXInit::getAdapterType( %i ); break; } // Change the device. if ( %newDevice !$= $pref::Video::displayDevice ) { if ( %testNeedApply ) return true; $pref::Video::displayDevice = %newDevice; if( %newAdapter !$= getDisplayDeviceInformation() ) MessageBoxOK( "Change requires restart", "Please restart the game for a display device change to take effect." ); } // Gather the new video mode. if ( isFunction("getWebDeployment") && getWebDeployment() ) { // Under web deployment, we use the custom resolution rather than a Canvas // defined one. %newRes = %this-->OptGraphicsResolutionMenu.getText(); } else { %newRes = getWords( Canvas.getMode( %this-->OptGraphicsResolutionMenu.getSelected() ), $WORD::RES_X, $WORD::RES_Y ); } %newBpp = 32; // ... its not 1997 anymore. %newFullScreen = %this-->OptGraphicsFullscreenToggle.getValue() ? "true" : "false"; %newRefresh = %this-->OptRefreshSelectMenu.getSelected(); %newVsync = !%this-->OptGraphicsVSyncToggle.getValue(); %newFSAA = %this-->OptAAQualityPopup.getSelected(); // Under web deployment we can't be full screen. if ( isFunction("getWebDeployment") && getWebDeployment() ) { %newFullScreen = false; } else if ( %newFullScreen $= "false" ) { // If we're in windowed mode switch the fullscreen check // if the resolution is bigger than the desktop. %deskRes = getDesktopResolution(); %deskResX = getWord(%deskRes, $WORD::RES_X); %deskResY = getWord(%deskRes, $WORD::RES_Y); if ( getWord( %newRes, $WORD::RES_X ) > %deskResX || getWord( %newRes, $WORD::RES_Y ) > %deskResY ) { %newFullScreen = "true"; %this-->OptGraphicsFullscreenToggle.setStateOn( true ); } } // Build the final mode string. %newMode = %newRes SPC %newFullScreen SPC %newBpp SPC %newRefresh SPC %newFSAA; // Change the video mode. if ( %newMode !$= $pref::Video::mode || %newVsync != $pref::Video::disableVerticalSync ) { if ( %testNeedApply ) return true; $pref::Video::mode = %newMode; $pref::Video::disableVerticalSync = %newVsync; configureCanvas(); } // Test and apply the graphics settings. if ( %this-->OptMeshQualityPopup.apply( MeshQualityGroup, %testNeedApply ) ) return true; if ( %this-->OptTextureQualityPopup.apply( TextureQualityGroup, %testNeedApply ) ) return true; if ( %this-->OptLightingQualityPopup.apply( LightingQualityGroup, %testNeedApply ) ) return true; if ( %this-->OptShaderQualityPopup.apply( ShaderQualityGroup, %testNeedApply ) ) return true; // Check the anisotropic filtering. %level = %this-->OptAnisotropicPopup.getSelected(); if ( %level != $pref::Video::defaultAnisotropy ) { if ( %testNeedApply ) return true; $pref::Video::defaultAnisotropy = %level; } // If we're applying the state then recheck the // state to update the apply button. if ( !%testNeedApply ) %this._updateApplyState(); return false; } function OptionsDlg::_updateApplyState( %this ) { %applyCtrl = %this-->Apply; %graphicsPane = %this-->OptGraphicsPane; assert( isObject( %applyCtrl ) ); assert( isObject( %graphicsPane ) ); %applyCtrl.active = %graphicsPane.isVisible() && %this.applyGraphics( true ); } function OptionsDlg::_autoDetectQuality( %this ) { %msg = GraphicsQualityAutodetect(); %this.onWake(); if ( %msg !$= "" ) { MessageBoxOK( "Notice", %msg ); } } $RemapCount = 0; $RemapName[$RemapCount] = "Forward"; $RemapCmd[$RemapCount] = "moveforward"; $RemapCount++; $RemapName[$RemapCount] = "Backward"; $RemapCmd[$RemapCount] = "movebackward"; $RemapCount++; $RemapName[$RemapCount] = "Strafe Left"; $RemapCmd[$RemapCount] = "moveleft"; $RemapCount++; $RemapName[$RemapCount] = "Strafe Right"; $RemapCmd[$RemapCount] = "moveright"; $RemapCount++; $RemapName[$RemapCount] = "Turn Left"; $RemapCmd[$RemapCount] = "turnLeft"; $RemapCount++; $RemapName[$RemapCount] = "Turn Right"; $RemapCmd[$RemapCount] = "turnRight"; $RemapCount++; $RemapName[$RemapCount] = "Look Up"; $RemapCmd[$RemapCount] = "panUp"; $RemapCount++; $RemapName[$RemapCount] = "Look Down"; $RemapCmd[$RemapCount] = "panDown"; $RemapCount++; $RemapName[$RemapCount] = "Jump"; $RemapCmd[$RemapCount] = "jump"; $RemapCount++; $RemapName[$RemapCount] = "Fire Weapon"; $RemapCmd[$RemapCount] = "mouseFire"; $RemapCount++; $RemapName[$RemapCount] = "Adjust Zoom"; $RemapCmd[$RemapCount] = "setZoomFov"; $RemapCount++; $RemapName[$RemapCount] = "Toggle Zoom"; $RemapCmd[$RemapCount] = "toggleZoom"; $RemapCount++; $RemapName[$RemapCount] = "Free Look"; $RemapCmd[$RemapCount] = "toggleFreeLook"; $RemapCount++; $RemapName[$RemapCount] = "Switch 1st/3rd"; $RemapCmd[$RemapCount] = "toggleFirstPerson"; $RemapCount++; $RemapName[$RemapCount] = "Chat to Everyone"; $RemapCmd[$RemapCount] = "toggleMessageHud"; $RemapCount++; $RemapName[$RemapCount] = "Message Hud PageUp"; $RemapCmd[$RemapCount] = "pageMessageHudUp"; $RemapCount++; $RemapName[$RemapCount] = "Message Hud PageDown"; $RemapCmd[$RemapCount] = "pageMessageHudDown"; $RemapCount++; $RemapName[$RemapCount] = "Resize Message Hud"; $RemapCmd[$RemapCount] = "resizeMessageHud"; $RemapCount++; $RemapName[$RemapCount] = "Show Scores"; $RemapCmd[$RemapCount] = "showPlayerList"; $RemapCount++; $RemapName[$RemapCount] = "Animation - Wave"; $RemapCmd[$RemapCount] = "celebrationWave"; $RemapCount++; $RemapName[$RemapCount] = "Animation - Salute"; $RemapCmd[$RemapCount] = "celebrationSalute"; $RemapCount++; $RemapName[$RemapCount] = "Suicide"; $RemapCmd[$RemapCount] = "suicide"; $RemapCount++; $RemapName[$RemapCount] = "Toggle Camera"; $RemapCmd[$RemapCount] = "toggleCamera"; $RemapCount++; $RemapName[$RemapCount] = "Drop Camera at Player"; $RemapCmd[$RemapCount] = "dropCameraAtPlayer"; $RemapCount++; $RemapName[$RemapCount] = "Drop Player at Camera"; $RemapCmd[$RemapCount] = "dropPlayerAtCamera"; $RemapCount++; $RemapName[$RemapCount] = "Bring up Options Dialog"; $RemapCmd[$RemapCount] = "bringUpOptions"; $RemapCount++; function restoreDefaultMappings() { moveMap.delete(); exec( "scripts/client/default.bind.cs" ); optionsDlg.fillRemapList(); } function getMapDisplayName( %device, %action ) { if ( %device $= "keyboard" ) return( %action ); else if ( strstr( %device, "mouse" ) != -1 ) { // Substitute "mouse" for "button" in the action string: %pos = strstr( %action, "button" ); if ( %pos != -1 ) { %mods = getSubStr( %action, 0, %pos ); %object = getSubStr( %action, %pos, 1000 ); %instance = getSubStr( %object, strlen( "button" ), 1000 ); return( %mods @ "mouse" @ ( %instance + 1 ) ); } else error( "Mouse input object other than button passed to getDisplayMapName!" ); } else if ( strstr( %device, "joystick" ) != -1 ) { // Substitute "joystick" for "button" in the action string: %pos = strstr( %action, "button" ); if ( %pos != -1 ) { %mods = getSubStr( %action, 0, %pos ); %object = getSubStr( %action, %pos, 1000 ); %instance = getSubStr( %object, strlen( "button" ), 1000 ); return( %mods @ "joystick" @ ( %instance + 1 ) ); } else { %pos = strstr( %action, "pov" ); if ( %pos != -1 ) { %wordCount = getWordCount( %action ); %mods = %wordCount > 1 ? getWords( %action, 0, %wordCount - 2 ) @ " " : ""; %object = getWord( %action, %wordCount - 1 ); switch$ ( %object ) { case "upov": %object = "POV1 up"; case "dpov": %object = "POV1 down"; case "lpov": %object = "POV1 left"; case "rpov": %object = "POV1 right"; case "upov2": %object = "POV2 up"; case "dpov2": %object = "POV2 down"; case "lpov2": %object = "POV2 left"; case "rpov2": %object = "POV2 right"; default: %object = "??"; } return( %mods @ %object ); } else error( "Unsupported Joystick input object passed to getDisplayMapName!" ); } } return( "??" ); } function buildFullMapString( %index ) { %name = $RemapName[%index]; %cmd = $RemapCmd[%index]; %temp = moveMap.getBinding( %cmd ); if ( %temp $= "" ) return %name TAB ""; %mapString = ""; %count = getFieldCount( %temp ); for ( %i = 0; %i < %count; %i += 2 ) { if ( %mapString !$= "" ) %mapString = %mapString @ ", "; %device = getField( %temp, %i + 0 ); %object = getField( %temp, %i + 1 ); %mapString = %mapString @ getMapDisplayName( %device, %object ); } return %name TAB %mapString; } function OptionsDlg::fillRemapList( %this ) { %remapList = %this-->OptRemapList; %remapList.clear(); for ( %i = 0; %i < $RemapCount; %i++ ) %remapList.addRow( %i, buildFullMapString( %i ) ); } function OptionsDlg::doRemap( %this ) { %remapList = %this-->OptRemapList; %selId = %remapList.getSelectedId(); %name = $RemapName[%selId]; RemapDlg-->OptRemapText.setValue( "Re-bind \"" @ %name @ "\" to..." ); OptRemapInputCtrl.index = %selId; Canvas.pushDialog( RemapDlg ); } function redoMapping( %device, %action, %cmd, %oldIndex, %newIndex ) { //%actionMap.bind( %device, %action, $RemapCmd[%newIndex] ); moveMap.bind( %device, %action, %cmd ); %remapList = %this-->OptRemapList; %remapList.setRowById( %oldIndex, buildFullMapString( %oldIndex ) ); %remapList.setRowById( %newIndex, buildFullMapString( %newIndex ) ); } function findRemapCmdIndex( %command ) { for ( %i = 0; %i < $RemapCount; %i++ ) { if ( %command $= $RemapCmd[%i] ) return( %i ); } return( -1 ); } /// This unbinds actions beyond %count associated to the /// particular moveMap %commmand. function unbindExtraActions( %command, %count ) { %temp = moveMap.getBinding( %command ); if ( %temp $= "" ) return; %count = getFieldCount( %temp ) - ( %count * 2 ); for ( %i = 0; %i < %count; %i += 2 ) { %device = getField( %temp, %i + 0 ); %action = getField( %temp, %i + 1 ); moveMap.unbind( %device, %action ); } } function OptRemapInputCtrl::onInputEvent( %this, %device, %action ) { //error( "** onInputEvent called - device = " @ %device @ ", action = " @ %action @ " **" ); Canvas.popDialog( RemapDlg ); // Test for the reserved keystrokes: if ( %device $= "keyboard" ) { // Cancel... if ( %action $= "escape" ) { // Do nothing... return; } } %cmd = $RemapCmd[%this.index]; %name = $RemapName[%this.index]; // Grab the friendly display name for this action // which we'll use when prompting the user below. %mapName = getMapDisplayName( %device, %action ); // Get the current command this action is mapped to. %prevMap = moveMap.getCommand( %device, %action ); // If nothing was mapped to the previous command // mapping then it's easy... just bind it. if ( %prevMap $= "" ) { unbindExtraActions( %cmd, 1 ); moveMap.bind( %device, %action, %cmd ); optionsDlg-->OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) ); return; } // If the previous command is the same as the // current then they hit the same input as what // was already assigned. if ( %prevMap $= %cmd ) { unbindExtraActions( %cmd, 0 ); moveMap.bind( %device, %action, %cmd ); optionsDlg-->OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) ); return; } // Look for the index of the previous mapping. %prevMapIndex = findRemapCmdIndex( %prevMap ); // If we get a negative index then the previous // mapping was to an item that isn't included in // the mapping list... so we cannot unmap it. if ( %prevMapIndex == -1 ) { MessageBoxOK( "Remap Failed", "\"" @ %mapName @ "\" is already bound to a non-remappable command!" ); return; } // Setup the forced remapping callback command. %callback = "redoMapping(" @ %device @ ", \"" @ %action @ "\", \"" @ %cmd @ "\", " @ %prevMapIndex @ ", " @ %this.index @ ");"; // Warn that we're about to remove the old mapping and // replace it with another. %prevCmdName = $RemapName[%prevMapIndex]; MessageBoxYesNo( "Warning", "\"" @ %mapName @ "\" is already bound to \"" @ %prevCmdName @ "\"!\nDo you wish to replace this mapping?", %callback, "" ); } $AudioTestHandle = 0; // Description to use for playing the volume test sound. This isn't // played with the description of the channel that has its volume changed // because we know nothing about the playback state of the channel. If it // is paused or stopped, the test sound would not play then. $AudioTestDescription = new SFXDescription() { sourceGroup = AudioChannelMaster; }; function OptAudioUpdateMasterVolume( %volume ) { if( %volume == $pref::SFX::masterVolume ) return; sfxSetMasterVolume( %volume ); $pref::SFX::masterVolume = %volume; if( !isObject( $AudioTestHandle ) ) $AudioTestHandle = sfxPlayOnce( AudioChannel, "art/sound/ui/volumeTest.wav" ); } function OptAudioUpdateChannelVolume( %description, %volume ) { %channel = sfxGroupToOldChannel( %description.sourceGroup ); if( %volume == $pref::SFX::channelVolume[ %channel ] ) return; sfxSetChannelVolume( %channel, %volume ); $pref::SFX::channelVolume[ %channel ] = %volume; if( !isObject( $AudioTestHandle ) ) { $AudioTestDescription.volume = %volume; $AudioTestHandle = sfxPlayOnce( $AudioTestDescription, "art/sound/ui/volumeTest.wav" ); } } function OptAudioProviderList::onSelect( %this, %id, %text ) { // Skip empty provider selections. if ( %text $= "" ) return; $pref::SFX::provider = %text; OptAudioDeviceList.clear(); %buffer = sfxGetAvailableDevices(); %count = getRecordCount( %buffer ); for(%i = 0; %i < %count; %i++) { %record = getRecord(%buffer, %i); %provider = getField(%record, 0); %device = getField(%record, 1); if (%provider !$= %text) continue; if ( OptAudioDeviceList.findText( %device ) == -1 ) OptAudioDeviceList.add( %device, %i ); } // Find the previous selected device. %selId = OptAudioDeviceList.findText($pref::SFX::device); if ( %selId == -1 ) OptAudioDeviceList.setFirstSelected(); else OptAudioDeviceList.setSelected( %selId ); } function OptAudioDeviceList::onSelect( %this, %id, %text ) { // Skip empty selections. if ( %text $= "" ) return; $pref::SFX::device = %text; if ( !sfxCreateDevice( $pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, -1 ) ) error( "Unable to create SFX device: " @ $pref::SFX::provider SPC $pref::SFX::device SPC $pref::SFX::useHardware ); } function OptMouseSetSensitivity(%value) { $pref::Input::LinkMouseSensitivity = %value; } /* function OptAudioHardwareToggle::onClick(%this) { if (!sfxCreateDevice($pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, -1)) error("Unable to create SFX device: " @ $pref::SFX::provider SPC $pref::SFX::device SPC $pref::SFX::useHardware); } */
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows.Forms; using bv.common.Core; using bv.winclient.Core; using DevExpress.XtraBars; using DevExpress.XtraPrinting; using DevExpress.XtraPrinting.Preview; using DevExpress.XtraReports.UI; using eidss.model.Core; using eidss.model.Enums; using EIDSS.Reports.BaseControls.Report; using HScrollBar = DevExpress.XtraEditors.HScrollBar; using VScrollBar = DevExpress.XtraEditors.VScrollBar; namespace EIDSS.Reports.BaseControls { public partial class ReportView : BvXtraUserControl { private const float ZoomLandscape = 0.75f; private const float ZoomDefault = 1f; private readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (ReportView)); private bool m_IsBarcode; private bool m_ReportInitializing; private XtraReport m_Report; public event EventHandler OnReportEdit; public event EventHandler OnReportLoadDefault; public ReportView() { InitializeComponent(); printControlReport.VScrollBar.Visible = false; printControlReport.HScrollBar.Visible = false; timerScroll.Start(); biPage.Caption = string.Empty; } [DefaultValue(false)] [Browsable(true)] public bool IsBarcode { get { return m_IsBarcode; } set { m_IsBarcode = value; AjustToolbar(); } } [Browsable(false)] internal float Zoom { get { return printControlReport.Zoom; } set { printControlReport.Zoom = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public XtraReport Report { get { return m_Report; } } public void SetReport(XtraReport value, bool buildReportInBackground) { if (m_Report == value) { return; } try { m_ReportInitializing = true; if (m_Report != null) { m_Report.Dispose(); } m_Report = value; if (m_Report != null) { printControlReport.PrintingSystem = m_Report.PrintingSystem; m_Report.PrintingSystem.ClearContent(); Invalidate(); Update(); var baseReport = m_Report as BaseReport; if (baseReport != null && baseReport.ChildReport != null) { baseReport.CreateDocument(); baseReport.ChildReport.CreateDocument(); baseReport.Pages.AddRange(baseReport.ChildReport.Pages); baseReport.PrintingSystem.ContinuousPageNumbering = true; } else { m_Report.CreateDocument(buildReportInBackground); } m_Report.PrintingSystem.PageSettings.Landscape = m_Report.Landscape; printControlReport.Zoom = m_Report.Landscape ? ZoomLandscape : ZoomDefault; printControlReport.ExecCommand(PrintingSystemCommand.ZoomToPageWidth); if (printControlReport.Zoom > 1) { printControlReport.Zoom = 1; } AjustToolbar(); biLoadDefault.Enabled = true; biEdit.Enabled = true; } } finally { m_ReportInitializing = false; } } private void AjustToolbar() { if (WinUtils.IsComponentInDesignMode(this)) { return; } // todo: Ivan: unhide bytton when barcode designer will be implemented //BarItemVisibility visibility = (IsBarcode) ? BarItemVisibility.Always : BarItemVisibility.Never; //biEdit.Visibility = visibility; //biLoadDefault.Visibility = visibility; biEdit.Visibility = BarItemVisibility.Never; biLoadDefault.Visibility = BarItemVisibility.Never; var itemsToRemove = new List<BarItem>(); itemsToRemove.AddRange(new BarItem[] {biExportHtm, biExportMht}); var allItems = printBarManager.Items.Cast<BarItem>(); itemsToRemove.AddRange(allItems.Where(item => (item is PrintPreviewBarItem) && string.IsNullOrEmpty(item.Name))); if (IsBarcode) { itemsToRemove.AddRange(new BarItem[] { biFind, biPageSetup, biScale, biMagnifier, biMultiplePages, biMultiplePages, biFillBackground, biExportFile }); } if ( !EidssUserContext.User.HasPermission( PermissionHelper.ExecutePermission(EIDSSPermissionObject.CanImportExportData))) { itemsToRemove.Add(biExportFile); } RemoveFromToolbar(itemsToRemove, printBarManager, previewBar1); } private void timerScroll_Tick(object sender, EventArgs e) { if (m_ReportInitializing && m_Report.PrintingSystem.Document.IsCreating) { return; } VScrollBar vScrollBar = printControlReport.VScrollBar; bool verticalVisible = (vScrollBar.Maximum > vScrollBar.Bounds.Height - vScrollBar.Bounds.Y + 2 * SystemInformation.HorizontalScrollBarHeight); if (vScrollBar.Visible != verticalVisible) { vScrollBar.Visible = verticalVisible; } HScrollBar hScrollBar = printControlReport.HScrollBar; bool horisontalVisible = (hScrollBar.Maximum > hScrollBar.ClientSize.Width + SystemInformation.VerticalScrollBarWidth); if (hScrollBar.Visible != horisontalVisible) { hScrollBar.Visible = horisontalVisible; } } public static void RemoveFromToolbar (ICollection<BarItem> itemsToRemove, PrintBarManager barManager, PreviewBar previewBar) { foreach (BarItem item in itemsToRemove) { barManager.Items.Remove(item); } var allLinks = previewBar.LinksPersistInfo.Cast<LinkPersistInfo>(); var linksToRemove = allLinks.Where(linksInfo => itemsToRemove.Contains(linksInfo.Item)).ToList(); foreach (LinkPersistInfo linksInfo in linksToRemove) { previewBar.LinksPersistInfo.Remove(linksInfo); } } private void biEdit_ItemClick(object sender, ItemClickEventArgs e) { EventHandler handler = OnReportEdit; if (handler != null) { handler(sender, e); } } private void biLoadDefault_ItemClick(object sender, ItemClickEventArgs e) { EventHandler handler = OnReportLoadDefault; if (handler != null) { handler(sender, e); } } internal void ApplyResources() { m_Resources.ApplyResources(printControlReport, "printControlReport"); m_Resources.ApplyResources(previewBar1, "previewBar1"); m_Resources.ApplyResources(biFind, "biFind"); m_Resources.ApplyResources(biPrint, "biPrint"); m_Resources.ApplyResources(biPrintDirect, "biPrintDirect"); m_Resources.ApplyResources(biPageSetup, "biPageSetup"); m_Resources.ApplyResources(biScale, "biScale"); m_Resources.ApplyResources(biHandTool, "biHandTool"); m_Resources.ApplyResources(biMagnifier, "biMagnifier"); m_Resources.ApplyResources(biZoomOut, "biZoomOut"); m_Resources.ApplyResources(biZoom, "biZoom"); m_Resources.ApplyResources(ZoomIn, "ZoomIn"); m_Resources.ApplyResources(biShowFirstPage, "biShowFirstPage"); m_Resources.ApplyResources(biShowPrevPage, "biShowPrevPage"); m_Resources.ApplyResources(biShowNextPage, "biShowNextPage"); m_Resources.ApplyResources(biShowLastPage, "biShowLastPage"); m_Resources.ApplyResources(biMultiplePages, "biMultiplePages"); m_Resources.ApplyResources(biExportFile, "biExportFile"); m_Resources.ApplyResources(barStatus, "previewBar2"); m_Resources.ApplyResources(biPage, "printPreviewStaticItem1"); m_Resources.ApplyResources(biProgressBar, "progressBarEditItem1"); m_Resources.ApplyResources(biStatusStatus, "printPreviewBarItem1"); m_Resources.ApplyResources(biStatusZoom, "printPreviewStaticItem2"); m_Resources.ApplyResources(barMainMenu, "previewBar3"); m_Resources.ApplyResources(printPreviewSubItem4, "printPreviewSubItem4"); m_Resources.ApplyResources(printPreviewBarItem27, "printPreviewBarItem27"); m_Resources.ApplyResources(printPreviewBarItem28, "printPreviewBarItem28"); m_Resources.ApplyResources(barToolbarsListItem1, "barToolbarsListItem1"); m_Resources.ApplyResources(biExportPdf, "biExportPdf"); m_Resources.ApplyResources(biExportHtm, "biExportHtm"); m_Resources.ApplyResources(biExportMht, "biExportMht"); m_Resources.ApplyResources(biExportRtf, "biExportRtf"); m_Resources.ApplyResources(biExportXls, "biExportXls"); m_Resources.ApplyResources(biExportCsv, "biExportCsv"); m_Resources.ApplyResources(biExportTxt, "biExportTxt"); m_Resources.ApplyResources(biExportGraphic, "biExportGraphic"); m_Resources.ApplyResources(biFillBackground, "biFillBackground"); m_Resources.ApplyResources(printPreviewBarItem2, "printPreviewBarItem2"); // m_Resources.ApplyResources(this, "$this"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Sep.Git.Tfs.Commands; using Sep.Git.Tfs.Core.TfsInterop; using Sep.Git.Tfs.Util; using StructureMap; using LibGit2Sharp; using Branch = LibGit2Sharp.Branch; namespace Sep.Git.Tfs.Core { public class GitRepository : GitHelpers, IGitRepository { private readonly IContainer _container; private readonly Globals _globals; private static readonly Regex configLineRegex = new Regex("^tfs-remote\\.(?<id>.+)\\.(?<key>[^.=]+)=(?<value>.*)$"); private IDictionary<string, IGitTfsRemote> _cachedRemotes; private Repository _repository; private RemoteConfigConverter _remoteConfigReader; public GitRepository(TextWriter stdout, string gitDir, IContainer container, Globals globals, RemoteConfigConverter remoteConfigReader) : base(stdout, container) { _container = container; _globals = globals; GitDir = gitDir; _repository = new LibGit2Sharp.Repository(GitDir); _remoteConfigReader = remoteConfigReader; } ~GitRepository() { if (_repository != null) _repository.Dispose(); } public void UpdateRef(string gitRefName, string shaCommit, string message = null) { _repository.Refs.Add(gitRefName, shaCommit, allowOverwrite: true, logMessage: message); } public static string ShortToLocalName(string branchName) { return "refs/heads/" + branchName; } public string GitDir { get; set; } public string WorkingCopyPath { get; set; } public string WorkingCopySubdir { get; set; } protected override Process Start(string[] command, Action<ProcessStartInfo> initialize) { return base.Start(command, initialize.And(SetUpPaths)); } private void SetUpPaths(ProcessStartInfo gitCommand) { if (GitDir != null) gitCommand.EnvironmentVariables["GIT_DIR"] = GitDir; if (WorkingCopyPath != null) gitCommand.WorkingDirectory = WorkingCopyPath; if (WorkingCopySubdir != null) gitCommand.WorkingDirectory = Path.Combine(gitCommand.WorkingDirectory, WorkingCopySubdir); } public string GetConfig(string key) { var entry = _repository.Config.Get<string>(key); return entry == null ? null : entry.Value; } public void SetConfig(string key, string value) { _repository.Config.Set<string>(key, value, ConfigurationLevel.Local); } public IEnumerable<IGitTfsRemote> ReadAllTfsRemotes() { var remotes = GetTfsRemotes().Values; foreach (var remote in remotes) remote.EnsureTfsAuthenticated(); return remotes; } public IGitTfsRemote ReadTfsRemote(string remoteId) { if (!HasRemote(remoteId)) throw new GitTfsException("Unable to locate git-tfs remote with id = " + remoteId) .WithRecommendation("Try using `git tfs bootstrap` to auto-init TFS remotes."); var remote = GetTfsRemotes()[remoteId]; remote.EnsureTfsAuthenticated(); return remote; } private IGitTfsRemote ReadTfsRemote(string tfsUrl, string tfsRepositoryPath, bool includeStubRemotes) { var allRemotes = GetTfsRemotes(); var matchingRemotes = allRemotes.Values.Where( remote => remote.MatchesUrlAndRepositoryPath(tfsUrl, tfsRepositoryPath)); switch (matchingRemotes.Count()) { case 0: if (!includeStubRemotes) throw new GitTfsException("Unable to locate a remote for <" + tfsUrl + ">" + tfsRepositoryPath) .WithRecommendation("Try using `git tfs bootstrap` to auto-init TFS remotes.") .WithRecommendation("Try setting a legacy-url for an existing remote."); return new DerivedGitTfsRemote(tfsUrl, tfsRepositoryPath); case 1: var remote = matchingRemotes.First(); return remote; default: Trace.WriteLine("More than one remote matched!"); goto case 1; } } private IDictionary<string, IGitTfsRemote> GetTfsRemotes() { return _cachedRemotes ?? (_cachedRemotes = ReadTfsRemotes()); } public IGitTfsRemote CreateTfsRemote(RemoteInfo remote, string autocrlf = null, string ignorecase = null) { if (HasRemote(remote.Id)) throw new GitTfsException("A remote with id \"" + remote.Id + "\" already exists."); // The autocrlf default (as indicated by a null) is false and is set to override the system-wide setting. // When creating branches we use the empty string to indicate that we do not want to set the value at all. if (autocrlf == null) autocrlf = "false"; if (autocrlf != String.Empty) _repository.Config.Set("core.autocrlf", autocrlf); if (ignorecase != null) _repository.Config.Set("core.ignorecase", ignorecase); foreach (var entry in _remoteConfigReader.Dump(remote)) { if (entry.Value != null) { _repository.Config.Set(entry.Key, entry.Value); } else { _repository.Config.Unset(entry.Key); } } var gitTfsRemote = BuildRemote(remote); gitTfsRemote.EnsureTfsAuthenticated(); return _cachedRemotes[remote.Id] = gitTfsRemote; } public void DeleteTfsRemote(IGitTfsRemote remote) { if (remote == null) throw new GitTfsException("error: the name of the remote to delete is invalid!"); UnsetTfsRemoteConfig(remote.Id); _repository.Refs.Remove(remote.RemoteRef); } private void UnsetTfsRemoteConfig(string remoteId) { foreach (var entry in _remoteConfigReader.Delete(remoteId)) { _repository.Config.Unset(entry.Key); } _cachedRemotes = null; } public void MoveRemote(string oldRemoteName, string newRemoteName) { if (!_repository.Refs.IsValidName(ShortToLocalName(oldRemoteName))) throw new GitTfsException("error: the name of the remote to move is invalid!"); if (!_repository.Refs.IsValidName(ShortToLocalName(newRemoteName))) throw new GitTfsException("error: the new name of the remote is invalid!"); if (HasRemote(newRemoteName)) throw new GitTfsException(string.Format("error: this remote name \"{0}\" is already used!", newRemoteName)); var oldRemote = ReadTfsRemote(oldRemoteName); if(oldRemote == null) throw new GitTfsException(string.Format("error: the remote \"{0}\" doesn't exist!", oldRemoteName)); var remoteInfo = oldRemote.RemoteInfo; remoteInfo.Id = newRemoteName; CreateTfsRemote(remoteInfo); var newRemote = ReadTfsRemote(newRemoteName); _repository.Refs.Move(oldRemote.RemoteRef, newRemote.RemoteRef); UnsetTfsRemoteConfig(oldRemoteName); } public Branch RenameBranch(string oldName, string newName) { var branch = _repository.Branches[oldName]; if (branch == null) return null; return _repository.Branches.Move(branch, newName); } private IDictionary<string, IGitTfsRemote> ReadTfsRemotes() { // does this need to ensuretfsauthenticated? _repository.Config.Set("tfs.touch", "1"); // reload configuration, because `git tfs init` and `git tfs clone` use Process.Start to update the config, so _repository's copy is out of date. return _remoteConfigReader.Load(_repository.Config).Select(x => BuildRemote(x)).ToDictionary(x => x.Id); } private IGitTfsRemote BuildRemote(RemoteInfo remoteInfo) { return _container.With(remoteInfo).With<IGitRepository>(this).GetInstance<IGitTfsRemote>(); } public bool HasRemote(string remoteId) { return GetTfsRemotes().ContainsKey(remoteId); } public bool HasRef(string gitRef) { return _repository.Refs[gitRef] != null; } public void MoveTfsRefForwardIfNeeded(IGitTfsRemote remote) { long currentMaxChangesetId = remote.MaxChangesetId; var untrackedTfsChangesets = from cs in GetParentTfsCommits("refs/remotes/tfs/" + remote.Id + "..HEAD", false) where cs.Remote.Id == remote.Id && cs.ChangesetId > currentMaxChangesetId orderby cs.ChangesetId select cs; foreach (var cs in untrackedTfsChangesets) { // UpdateTfsHead sets tag with TFS changeset id on each commit so we can't just update to latest remote.UpdateTfsHead(cs.GitCommit, cs.ChangesetId); } } public GitCommit GetCommit(string commitish) { return new GitCommit(_repository.Lookup<Commit>(commitish)); } public String GetCurrentCommit() { return _repository.Head.Commits.First().Sha; } public IEnumerable<TfsChangesetInfo> GetLastParentTfsCommits(string head) { return GetLastParentTfsCommits(head, false); } public IEnumerable<TfsChangesetInfo> GetLastParentTfsCommits(string head, bool includeStubRemotes) { List<TfsChangesetInfo> tfsCommits = GetParentTfsCommits(head, includeStubRemotes); return from commit in tfsCommits group commit by commit.Remote into remotes select remotes.OrderBy(commit => -commit.ChangesetId).First(); } public IEnumerable<TfsChangesetInfo> FilterParentTfsCommits(string head, bool includeStubRemotes, Predicate<TfsChangesetInfo> pred) { return from commit in GetParentTfsCommits(head, includeStubRemotes) where pred(commit) select commit; } private List<TfsChangesetInfo> GetParentTfsCommits(string head, bool includeStubRemotes) { var tfsCommits = new List<TfsChangesetInfo>(); try { CommandOutputPipe(stdout => FindTfsCommits(stdout, tfsCommits, includeStubRemotes), "log", "--no-color", "--pretty=medium", head, "--"); } catch (GitCommandException e) { Trace.WriteLine("An error occurred while loading head " + head + " (maybe it doesn't exist?): " + e); } return tfsCommits; } public TfsChangesetInfo GetCurrentTfsCommit() { var currentCommit = _repository.Head.Commits.First(); return TryParseChangesetInfo(currentCommit.Message, currentCommit.Sha, false); } public TfsChangesetInfo GetTfsCommit(string sha) { return TryParseChangesetInfo(GetCommit(sha).Message, sha, false); } private void FindTfsCommits(TextReader stdout, ICollection<TfsChangesetInfo> tfsCommits, bool includeStubRemotes) { string currentCommit = null; TfsChangesetInfo lastChangesetInfo = null; string line; while (null != (line = stdout.ReadLine())) { var match = GitTfsConstants.CommitRegex.Match(line); if (match.Success) { if (lastChangesetInfo != null) { tfsCommits.Add(lastChangesetInfo); lastChangesetInfo = null; } currentCommit = match.Groups[1].Value; continue; } var changesetInfo = TryParseChangesetInfo(line, currentCommit, includeStubRemotes); if (changesetInfo != null) { lastChangesetInfo = changesetInfo; } } // Add the final changesetinfo object; it won't be handled in the loop // if it was part of the last commit message. if (lastChangesetInfo != null) tfsCommits.Add(lastChangesetInfo); //stdout.Close(); } private TfsChangesetInfo TryParseChangesetInfo(string gitTfsMetaInfo, string commit, bool includeStubRemotes) { var match = GitTfsConstants.TfsCommitInfoRegex.Match(gitTfsMetaInfo); if (match.Success) { var commitInfo = _container.GetInstance<TfsChangesetInfo>(); commitInfo.Remote = ReadTfsRemote(match.Groups["url"].Value, match.Groups["repository"].Success ? match.Groups["repository"].Value : null, includeStubRemotes); commitInfo.ChangesetId = Convert.ToInt32(match.Groups["changeset"].Value); commitInfo.GitCommit = commit; return commitInfo; } return null; } public IDictionary<string, GitObject> GetObjects(string commit) { var entries = GetObjects(); if (commit != null) { ParseEntries(entries, _repository.Lookup<Commit>(commit).Tree, commit); } return entries; } public Dictionary<string, GitObject> GetObjects() { return new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase); } public string GetCommitMessage(string head, string parentCommitish) { var message = new System.Text.StringBuilder(); foreach (Commit comm in _repository.Commits.QueryBy(new CommitFilter { Since = head, Until = parentCommitish })) { // Normalize commit message line endings to CR+LF style, so that message // would be correctly shown in TFS commit dialog. message.AppendLine(NormalizeLineEndings(comm.Message)); } return GitTfsConstants.TfsCommitInfoRegex.Replace(message.ToString(), "").Trim(' ', '\r', '\n'); } public string GetCommitMessage(string commitish) { return GetCommitMessage(commitish, commitish + "^"); } private static string NormalizeLineEndings(string input) { return string.IsNullOrEmpty(input) ? input : input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"); } private void ParseEntries(IDictionary<string, GitObject> entries, Tree treeInfo, string commit) { var treesToDescend = new Queue<Tree>(new[] {treeInfo}); while (treesToDescend.Any()) { var currentTree = treesToDescend.Dequeue(); foreach (var item in currentTree) { if (item.TargetType == TreeEntryTargetType.Tree) { treesToDescend.Enqueue((Tree)item.Target); } var path = item.Path.Replace('\\', '/'); entries[path] = new GitObject { Mode = item.Mode.ToModeString(), Sha = item.Target.Sha, ObjectType = item.TargetType.ToString().ToLower(), Path = path, Commit = commit }; } } } public IEnumerable<IGitChangedFile> GetChangedFiles(string from, string to) { using (var diffOutput = CommandOutputPipe("diff-tree", "-r", "-M", "-z", from, to)) { var changes = GitChangeInfo.GetChangedFiles(diffOutput); foreach (var change in changes) { yield return BuildGitChangedFile(change); } } } private IGitChangedFile BuildGitChangedFile(GitChangeInfo change) { return change.ToGitChangedFile(_container.With((IGitRepository) this)); } public bool WorkingCopyHasUnstagedOrUncommitedChanges { get { if (IsBare) return false; return (from entry in _repository.Index.RetrieveStatus() where entry.State != FileStatus.Ignored && entry.State != FileStatus.Untracked select entry).Any(); } } public void CopyBlob(string sha, string outputFile) { Blob blob; var destination = new FileInfo(outputFile); if (!destination.Directory.Exists) destination.Directory.Create(); if ((blob = _repository.Lookup<Blob>(sha)) != null) using (Stream stream = blob.ContentStream) using (var outstream = File.Create(destination.FullName)) stream.CopyTo(outstream); } public string HashAndInsertObject(string filename) { if (_repository.Info.IsBare) { filename = Path.GetFullPath(filename); } return _repository.ObjectDatabase.CreateBlob(filename).Id.Sha; } public string AssertValidBranchName(string gitBranchName) { if (!_repository.Refs.IsValidName(ShortToLocalName(gitBranchName))) throw new GitTfsException("The name specified for the new git branch is not allowed. Choose another one!"); return gitBranchName; } public bool CreateBranch(string gitBranchName, string target) { Reference reference; try { reference = _repository.Refs.Add(gitBranchName, target); } catch (Exception) { return false; } return reference != null; } public string FindCommitHashByChangesetId(long changesetId) { Trace.WriteLine("Looking for changeset " + changesetId + " in git repository..."); var patternToFind = "git-tfs-id: .*;C" + changesetId + "[^0-9]"; var regex = new Regex(patternToFind); foreach (var branch in _repository.Branches.Where(p => p.IsRemote).ToList()) { var commit = branch.Commits.FirstOrDefault(c => regex.IsMatch(c.Message)); if (commit != null) { Trace.WriteLine(" => Commit found! hash: " + commit.Sha); return commit.Sha; } } Trace.WriteLine(" => Commit not found!"); return null; } public void CreateTag(string name, string sha, string comment, string Owner, string emailOwner, System.DateTime creationDate) { if (_repository.Tags[name] == null) _repository.ApplyTag(name, sha, new Signature(Owner, emailOwner, new DateTimeOffset(creationDate)), comment); } public void CreateNote(string sha, string content, string owner, string emailOwner, DateTime creationDate) { Signature author = new Signature(owner, emailOwner, creationDate); _repository.Notes.Add(new ObjectId(sha), content, author, author, "commits"); } public void Reset(string sha, ResetOptions resetOptions) { _repository.Reset(resetOptions, sha); } public bool IsBare { get { return _repository.Info.IsBare; } } /// <summary> /// Gets all configured "subtree" remotes which point to the same Tfs URL as the given remote. /// If the given remote is itself a subtree, an empty enumerable is returned. /// </summary> public IEnumerable<IGitTfsRemote> GetSubtrees(IGitTfsRemote owner) { //a subtree remote cannot have subtrees itself. if (owner.IsSubtree) return Enumerable.Empty<IGitTfsRemote>(); return ReadAllTfsRemotes().Where(x => x.IsSubtree && string.Equals(x.OwningRemoteId, owner.Id, StringComparison.InvariantCultureIgnoreCase)); } public void ResetRemote(IGitTfsRemote remoteToReset, string target) { _repository.Refs.UpdateTarget(remoteToReset.RemoteRef, target); } } }
/***************************************************************************\ * * File: BamlCollectionHolder.cs * * Copyright (C) 2003 by Microsoft Corporation. All rights reserved. * \***************************************************************************/ using System; using System.Collections; using System.Reflection; namespace System.Windows.Markup { // Helper class that holds a collection for a property. This class // replaces the old BamlDictionaryHolder and BamlArrayHolder classes internal class BamlCollectionHolder { internal BamlCollectionHolder() { } internal BamlCollectionHolder(BamlRecordReader reader, object parent, short attributeId) : this(reader, parent, attributeId, true) { } internal BamlCollectionHolder(BamlRecordReader reader, object parent, short attributeId, bool needDefault) { _reader = reader; _parent = parent; _propDef = new WpfPropertyDefinition(reader, attributeId, parent is DependencyObject); _attributeId = attributeId; if (needDefault) { InitDefaultValue(); } CheckReadOnly(); } // the collection stored for a given property internal object Collection { get { return _collection; } set { _collection = value; } } // helper that casts the collection as an IList internal IList List { get { return _collection as IList; } } // helper that casts the collection as an IDictionary internal IDictionary Dictionary { get { return _collection as IDictionary; } } // helper that casts the collection as an ArrayExtension internal ArrayExtension ArrayExt { get { return _collection as ArrayExtension; } } // the default collection to be used in case the property does not have an explicit tag internal object DefaultCollection { get { return _defaultCollection; } } // the PropertyDefinition associated with the BamlCollectionHolder's property internal WpfPropertyDefinition PropertyDefinition { get { return _propDef; } } // the return type of the BamlCollectionHolder's property's getter internal Type PropertyType { get { return _resourcesParent != null ? typeof(ResourceDictionary) : PropertyDefinition.PropertyType; } } // the parent object of this collection holder internal object Parent { get { return _parent; } } // returns true if the property cannot be set internal bool ReadOnly { get { return _readonly; } set { _readonly = value; } } // returns true if the property has an explicit tag, so items should not be added to it directly internal bool IsClosed { get { return _isClosed; } set { _isClosed = value; } } internal string AttributeName { get { return _reader.GetPropertyNameFromAttributeId(_attributeId); } } // set the property associated with the collection holder to the value of the holder's collection internal void SetPropertyValue() { // Do if the property value has not been set before this if (!_isPropertyValueSet) { _isPropertyValueSet = true; // the order of precedence is the fast-tracked Resources property, then DP, then the attached property // setter, then the property info if (_resourcesParent != null) { _resourcesParent.Resources = (ResourceDictionary)Collection; } else if (PropertyDefinition.DependencyProperty != null) { DependencyObject dpParent = Parent as DependencyObject; if (dpParent == null) { _reader.ThrowException(SRID.ParserParentDO, Parent.ToString()); } _reader.SetDependencyValue(dpParent, PropertyDefinition.DependencyProperty, Collection); } else if (PropertyDefinition.AttachedPropertySetter != null) { PropertyDefinition.AttachedPropertySetter.Invoke(null, new object[] { Parent, Collection }); } else if (PropertyDefinition.PropertyInfo != null) { PropertyDefinition.PropertyInfo.SetValue(Parent, Collection, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy, null, null, TypeConverterHelper.InvariantEnglishUS); } else { _reader.ThrowException(SRID.ParserCantGetDPOrPi, AttributeName); } } } // Initialize the collection holder, by setting its property definition and default value (retrieved // from the property definition). internal void InitDefaultValue() { if (AttributeName == "Resources" && Parent is IHaveResources) { // "Fast Path" handling of Resources non-DP property _resourcesParent = ((IHaveResources)Parent); _defaultCollection = _resourcesParent.Resources; } // the order of precedence according to the spec is DP, then attached property, then PropertyInfo else if (PropertyDefinition.DependencyProperty != null) { _defaultCollection = ((DependencyObject)Parent).GetValue(PropertyDefinition.DependencyProperty); } else if (PropertyDefinition.AttachedPropertyGetter != null) { _defaultCollection = PropertyDefinition.AttachedPropertyGetter.Invoke(null, new object[] { Parent }); } else if (PropertyDefinition.PropertyInfo != null) { if (PropertyDefinition.IsInternal) { _defaultCollection = XamlTypeMapper.GetInternalPropertyValue(_reader.ParserContext, _reader.ParserContext.RootElement, PropertyDefinition.PropertyInfo, Parent); if (_defaultCollection == null) { _reader.ThrowException(SRID.ParserCantGetProperty, PropertyDefinition.Name); } } else { _defaultCollection = PropertyDefinition.PropertyInfo.GetValue( Parent, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy, null, null, TypeConverterHelper.InvariantEnglishUS); } } else { _reader.ThrowException(SRID.ParserCantGetDPOrPi, AttributeName); } } private void CheckReadOnly() { if (_resourcesParent == null && (PropertyDefinition.DependencyProperty == null || PropertyDefinition.DependencyProperty.ReadOnly) && (PropertyDefinition.PropertyInfo == null || !PropertyDefinition.PropertyInfo.CanWrite) && PropertyDefinition.AttachedPropertySetter == null) { if (DefaultCollection == null) { // if the property is read-only and has a null default value, throw an exception _reader.ThrowException(SRID.ParserReadOnlyNullProperty, PropertyDefinition.Name); } // the property is read-only, so we have to use its default value as the dictionary ReadOnly = true; Collection = DefaultCollection; } } private object _collection; private object _defaultCollection; private short _attributeId; private WpfPropertyDefinition _propDef; private object _parent; private BamlRecordReader _reader; private IHaveResources _resourcesParent; // for fast-tracking Resources properties private bool _readonly; private bool _isClosed; private bool _isPropertyValueSet; } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Google.ProtocolBuffers { /// <summary> /// Immutable array of bytes. /// TODO(jonskeet): Implement the common collection interfaces? /// </summary> public sealed class ByteString : IEnumerable<byte>, IEquatable<ByteString> { private static readonly ByteString empty = new ByteString(new byte[0]); private readonly byte[] bytes; /// <summary> /// Constructs a new ByteString from the given byte array. The array is /// *not* copied, and must not be modified after this constructor is called. /// </summary> private ByteString(byte[] bytes) { this.bytes = bytes; } /// <summary> /// Returns an empty ByteString. /// </summary> public static ByteString Empty { get { return empty; } } /// <summary> /// Returns the length of this ByteString in bytes. /// </summary> public int Length { get { return bytes.Length; } } public bool IsEmpty { get { return Length == 0; } } public byte[] ToByteArray() { return (byte[])bytes.Clone(); } /// <summary> /// Constructs a ByteString from the Base64 Encoded String. /// </summary> public static ByteString FromBase64(string bytes) { return new ByteString(System.Convert.FromBase64String(bytes)); } /// <summary> /// Constructs a ByteString from the given array. The contents /// are copied, so further modifications to the array will not /// be reflected in the returned ByteString. /// </summary> public static ByteString CopyFrom(byte[] bytes) { return new ByteString((byte[]) bytes.Clone()); } /// <summary> /// Constructs a ByteString from a portion of a byte array. /// </summary> public static ByteString CopyFrom(byte[] bytes, int offset, int count) { byte[] portion = new byte[count]; Array.Copy(bytes, offset, portion, 0, count); return new ByteString(portion); } /// <summary> /// Creates a new ByteString by encoding the specified text with /// the given encoding. /// </summary> public static ByteString CopyFrom(string text, Encoding encoding) { return new ByteString(encoding.GetBytes(text)); } /// <summary> /// Creates a new ByteString by encoding the specified text in UTF-8. /// </summary> public static ByteString CopyFromUtf8(string text) { return CopyFrom(text, Encoding.UTF8); } /// <summary> /// Retuns the byte at the given index. /// </summary> public byte this[int index] { get { return bytes[index]; } } public string ToString(Encoding encoding) { return encoding.GetString(bytes, 0, bytes.Length); } public string ToStringUtf8() { return ToString(Encoding.UTF8); } public IEnumerator<byte> GetEnumerator() { return ((IEnumerable<byte>) bytes).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Creates a CodedInputStream from this ByteString's data. /// </summary> public CodedInputStream CreateCodedInput() { // We trust CodedInputStream not to reveal the provided byte array or modify it return CodedInputStream.CreateInstance(bytes); } // TODO(jonskeet): CopyTo if it turns out to be required public override bool Equals(object obj) { ByteString other = obj as ByteString; if (obj == null) { return false; } return Equals(other); } public override int GetHashCode() { int ret = 23; foreach (byte b in bytes) { ret = (ret << 8) | b; } return ret; } public bool Equals(ByteString other) { if (other.bytes.Length != bytes.Length) { return false; } for (int i = 0; i < bytes.Length; i++) { if (other.bytes[i] != bytes[i]) { return false; } } return true; } /// <summary> /// Builder for ByteStrings which allows them to be created without extra /// copying being involved. This has to be a nested type in order to have access /// to the private ByteString constructor. /// </summary> internal sealed class CodedBuilder { private readonly CodedOutputStream output; private readonly byte[] buffer; internal CodedBuilder(int size) { buffer = new byte[size]; output = CodedOutputStream.CreateInstance(buffer); } internal ByteString Build() { output.CheckNoSpaceLeft(); // We can be confident that the CodedOutputStream will not modify the // underlying bytes anymore because it already wrote all of them. So, // no need to make a copy. return new ByteString(buffer); } internal CodedOutputStream CodedOutput { get { return output; } } } } }
namespace ScreenCapture { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this._txtOutputFile = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this._numWidth = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this._numHeight = new System.Windows.Forms.NumericUpDown(); this.label4 = new System.Windows.Forms.Label(); this._numFramerate = new System.Windows.Forms.NumericUpDown(); this._cmbQuality = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this._lblBitrate = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this._numEncodingThreads = new System.Windows.Forms.NumericUpDown(); this._btnScreenCapture = new System.Windows.Forms.Button(); this._btnPauseScreenCapture = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this._numWidth)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._numHeight)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._numFramerate)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._numEncodingThreads)).BeginInit(); this.SuspendLayout(); // // _txtOutputFile // this._txtOutputFile.Location = new System.Drawing.Point(16, 31); this._txtOutputFile.Margin = new System.Windows.Forms.Padding(4); this._txtOutputFile.Name = "_txtOutputFile"; this._txtOutputFile.Size = new System.Drawing.Size(300, 22); this._txtOutputFile.TabIndex = 0; this._txtOutputFile.Text = "output.wmv"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(17, 7); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(73, 17); this.label1.TabIndex = 1; this.label1.Text = "Output file"; // // _numWidth // this._numWidth.Increment = new decimal(new int[] { 2, 0, 0, 0}); this._numWidth.Location = new System.Drawing.Point(16, 96); this._numWidth.Margin = new System.Windows.Forms.Padding(4); this._numWidth.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this._numWidth.Name = "_numWidth"; this._numWidth.Size = new System.Drawing.Size(160, 22); this._numWidth.TabIndex = 2; this._numWidth.Value = new decimal(new int[] { 1024, 0, 0, 0}); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(16, 76); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(44, 17); this.label2.TabIndex = 3; this.label2.Text = "Width"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(184, 76); this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(49, 17); this.label3.TabIndex = 5; this.label3.Text = "Height"; // // _numHeight // this._numHeight.Increment = new decimal(new int[] { 2, 0, 0, 0}); this._numHeight.Location = new System.Drawing.Point(184, 96); this._numHeight.Margin = new System.Windows.Forms.Padding(4); this._numHeight.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this._numHeight.Name = "_numHeight"; this._numHeight.Size = new System.Drawing.Size(160, 22); this._numHeight.TabIndex = 4; this._numHeight.Value = new decimal(new int[] { 768, 0, 0, 0}); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(352, 76); this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(73, 17); this.label4.TabIndex = 7; this.label4.Text = "Framerate"; // // _numFramerate // this._numFramerate.DecimalPlaces = 2; this._numFramerate.Increment = new decimal(new int[] { 2, 0, 0, 0}); this._numFramerate.Location = new System.Drawing.Point(352, 96); this._numFramerate.Margin = new System.Windows.Forms.Padding(4); this._numFramerate.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this._numFramerate.Name = "_numFramerate"; this._numFramerate.Size = new System.Drawing.Size(160, 22); this._numFramerate.TabIndex = 6; this._numFramerate.ThousandsSeparator = true; this._numFramerate.Value = new decimal(new int[] { 20, 0, 0, 0}); // // _cmbQuality // this._cmbQuality.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._cmbQuality.FormattingEnabled = true; this._cmbQuality.Location = new System.Drawing.Point(520, 96); this._cmbQuality.Margin = new System.Windows.Forms.Padding(4); this._cmbQuality.Name = "_cmbQuality"; this._cmbQuality.Size = new System.Drawing.Size(240, 24); this._cmbQuality.TabIndex = 8; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(516, 76); this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(52, 17); this.label5.TabIndex = 9; this.label5.Text = "Quality"; // // _lblBitrate // this._lblBitrate.Location = new System.Drawing.Point(352, 145); this._lblBitrate.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this._lblBitrate.Name = "_lblBitrate"; this._lblBitrate.Size = new System.Drawing.Size(408, 51); this._lblBitrate.TabIndex = 11; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(17, 145); this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(192, 17); this.label6.TabIndex = 15; this.label6.Text = "Number of encoding threads:"; // // _numEncodingThreads // this._numEncodingThreads.Increment = new decimal(new int[] { 2, 0, 0, 0}); this._numEncodingThreads.Location = new System.Drawing.Point(217, 142); this._numEncodingThreads.Margin = new System.Windows.Forms.Padding(4); this._numEncodingThreads.Maximum = new decimal(new int[] { 16, 0, 0, 0}); this._numEncodingThreads.Name = "_numEncodingThreads"; this._numEncodingThreads.Size = new System.Drawing.Size(127, 22); this._numEncodingThreads.TabIndex = 14; this._numEncodingThreads.Value = new decimal(new int[] { 3, 0, 0, 0}); // // _btnScreenCapture // this._btnScreenCapture.Location = new System.Drawing.Point(19, 200); this._btnScreenCapture.Margin = new System.Windows.Forms.Padding(4); this._btnScreenCapture.Name = "_btnScreenCapture"; this._btnScreenCapture.Size = new System.Drawing.Size(163, 28); this._btnScreenCapture.TabIndex = 16; this._btnScreenCapture.Text = "Screen capture video"; this._btnScreenCapture.UseVisualStyleBackColor = true; this._btnScreenCapture.Click += new System.EventHandler(this._btnScreenCapture_Click); // // _btnPauseScreenCapture // this._btnPauseScreenCapture.Location = new System.Drawing.Point(205, 200); this._btnPauseScreenCapture.Margin = new System.Windows.Forms.Padding(4); this._btnPauseScreenCapture.Name = "_btnPauseScreenCapture"; this._btnPauseScreenCapture.Size = new System.Drawing.Size(163, 28); this._btnPauseScreenCapture.TabIndex = 19; this._btnPauseScreenCapture.Text = "Pause Screen Capture"; this._btnPauseScreenCapture.UseVisualStyleBackColor = true; this._btnPauseScreenCapture.Visible = false; this._btnPauseScreenCapture.Click += new System.EventHandler(this._btnPauseScreenCapture_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(779, 241); this.Controls.Add(this._btnPauseScreenCapture); this.Controls.Add(this._btnScreenCapture); this.Controls.Add(this.label6); this.Controls.Add(this._numEncodingThreads); this.Controls.Add(this._lblBitrate); this.Controls.Add(this.label5); this.Controls.Add(this._cmbQuality); this.Controls.Add(this.label4); this.Controls.Add(this._numFramerate); this.Controls.Add(this.label3); this.Controls.Add(this._numHeight); this.Controls.Add(this.label2); this.Controls.Add(this._numWidth); this.Controls.Add(this.label1); this.Controls.Add(this._txtOutputFile); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Margin = new System.Windows.Forms.Padding(4); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Form1"; this.Text = "Screen Capture Video"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this._numWidth)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._numHeight)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._numFramerate)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._numEncodingThreads)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox _txtOutputFile; private System.Windows.Forms.Label label1; private System.Windows.Forms.NumericUpDown _numWidth; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.NumericUpDown _numHeight; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown _numFramerate; private System.Windows.Forms.ComboBox _cmbQuality; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label _lblBitrate; private System.Windows.Forms.Label label6; private System.Windows.Forms.NumericUpDown _numEncodingThreads; private System.Windows.Forms.Button _btnScreenCapture; private System.Windows.Forms.Button _btnPauseScreenCapture; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Services.Connectors; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteGridServicesConnector")] public class RemoteGridServicesConnector : ISharedRegionModule, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private bool m_Enabled = false; private IGridService m_LocalGridService; private IGridService m_RemoteGridService; private RegionInfoCache m_RegionInfoCache = new RegionInfoCache(); public RemoteGridServicesConnector() { } public RemoteGridServicesConnector(IConfigSource source) { InitialiseServices(source); } #region ISharedRegionmodule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "RemoteGridServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("GridServices", ""); if (name == Name) { InitialiseServices(source); m_Enabled = true; m_log.Info("[REMOTE GRID CONNECTOR]: Remote grid enabled"); } } } private void InitialiseServices(IConfigSource source) { IConfig gridConfig = source.Configs["GridService"]; if (gridConfig == null) { m_log.Error("[REMOTE GRID CONNECTOR]: GridService missing from OpenSim.ini"); return; } string networkConnector = gridConfig.GetString("NetworkConnector", string.Empty); if (networkConnector == string.Empty) { m_log.Error("[REMOTE GRID CONNECTOR]: Please specify a network connector under [GridService]"); return; } Object[] args = new Object[] { source }; m_RemoteGridService = ServerUtils.LoadPlugin<IGridService>(networkConnector, args); m_LocalGridService = new LocalGridServicesConnector(source); } public void PostInitialise() { if (m_LocalGridService != null) ((ISharedRegionModule)m_LocalGridService).PostInitialise(); } public void Close() { } public void AddRegion(Scene scene) { if (m_Enabled) scene.RegisterModuleInterface<IGridService>(this); if (m_LocalGridService != null) ((ISharedRegionModule)m_LocalGridService).AddRegion(scene); } public void RemoveRegion(Scene scene) { if (m_LocalGridService != null) ((ISharedRegionModule)m_LocalGridService).RemoveRegion(scene); } public void RegionLoaded(Scene scene) { } #endregion #region IGridService public string RegisterRegion(UUID scopeID, GridRegion regionInfo) { string msg = m_LocalGridService.RegisterRegion(scopeID, regionInfo); if (msg == String.Empty) return m_RemoteGridService.RegisterRegion(scopeID, regionInfo); return msg; } public bool DeregisterRegion(UUID regionID) { if (m_LocalGridService.DeregisterRegion(regionID)) return m_RemoteGridService.DeregisterRegion(regionID); return false; } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { return m_RemoteGridService.GetNeighbours(scopeID, regionID); } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { bool inCache = false; GridRegion rinfo = m_RegionInfoCache.Get(scopeID,regionID,out inCache); if (inCache) return rinfo; rinfo = m_LocalGridService.GetRegionByUUID(scopeID, regionID); if (rinfo == null) rinfo = m_RemoteGridService.GetRegionByUUID(scopeID, regionID); m_RegionInfoCache.Cache(scopeID,regionID,rinfo); return rinfo; } public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { bool inCache = false; GridRegion rinfo = m_RegionInfoCache.Get(scopeID, Util.UIntsToLong((uint)x, (uint)y), out inCache); if (inCache) return rinfo; rinfo = m_LocalGridService.GetRegionByPosition(scopeID, x, y); if (rinfo == null) rinfo = m_RemoteGridService.GetRegionByPosition(scopeID, x, y); m_RegionInfoCache.Cache(rinfo); return rinfo; } public GridRegion GetRegionByName(UUID scopeID, string regionName) { bool inCache = false; GridRegion rinfo = m_RegionInfoCache.Get(scopeID,regionName, out inCache); if (inCache) return rinfo; rinfo = m_LocalGridService.GetRegionByName(scopeID, regionName); if (rinfo == null) rinfo = m_RemoteGridService.GetRegionByName(scopeID, regionName); // can't cache negative results for name lookups m_RegionInfoCache.Cache(rinfo); return rinfo; } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { List<GridRegion> rinfo = m_LocalGridService.GetRegionsByName(scopeID, name, maxNumber); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionsByName {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetRegionsByName(scopeID, name, maxNumber); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionsByName {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public virtual List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { List<GridRegion> rinfo = m_LocalGridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionRange {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionRange {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public List<GridRegion> GetDefaultRegions(UUID scopeID) { List<GridRegion> rinfo = m_LocalGridService.GetDefaultRegions(scopeID); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetDefaultRegions {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetDefaultRegions(scopeID); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetDefaultRegions {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { List<GridRegion> rinfo = m_LocalGridService.GetFallbackRegions(scopeID, x, y); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetFallbackRegions {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetFallbackRegions(scopeID, x, y); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetFallbackRegions {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public List<GridRegion> GetHyperlinks(UUID scopeID) { List<GridRegion> rinfo = m_LocalGridService.GetHyperlinks(scopeID); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetHyperlinks {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetHyperlinks(scopeID); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetHyperlinks {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public int GetRegionFlags(UUID scopeID, UUID regionID) { int flags = m_LocalGridService.GetRegionFlags(scopeID, regionID); if (flags == -1) flags = m_RemoteGridService.GetRegionFlags(scopeID, regionID); return flags; } #endregion } }
using GitHub.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using UnityEditor; using UnityEngine; using Application = UnityEngine.Application; namespace GitHub.Unity { sealed class ApplicationCache : ScriptObjectSingleton<ApplicationCache> { [SerializeField] private bool firstRun = true; [SerializeField] public string firstRunAtString; [SerializeField] public string instanceIdString; [SerializeField] private bool initialized = false; [NonSerialized] private Guid? instanceId; [NonSerialized] private bool? firstRunValue; [NonSerialized] public DateTimeOffset? firstRunAtValue; public bool FirstRun { get { EnsureFirstRun(); return firstRunValue.Value; } } public DateTimeOffset FirstRunAt { get { EnsureFirstRun(); if (!firstRunAtValue.HasValue) { DateTimeOffset dt; if (!DateTimeOffset.TryParseExact(firstRunAtString.ToEmptyIfNull(), Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { dt = DateTimeOffset.Now; } FirstRunAt = dt; } return firstRunAtValue.Value; } private set { firstRunAtString = value.ToString(Constants.Iso8601Format); firstRunAtValue = value; } } private void EnsureFirstRun() { if (!firstRunValue.HasValue) { firstRunValue = firstRun; } } public Guid InstanceId { get { EnsureInstanceId(); return instanceId.Value; } } private void EnsureInstanceId() { if (instanceId.HasValue) { return; } if (string.IsNullOrEmpty(instanceIdString)) { instanceId = Guid.NewGuid(); instanceIdString = instanceId.ToString(); } else { instanceId = new Guid(instanceIdString); } } public bool Initialized { get { return initialized; } set { initialized = value; if (initialized && firstRun) { firstRun = false; FirstRunAt = DateTimeOffset.Now; } Save(true); } } } sealed class EnvironmentCache : ScriptObjectSingleton<EnvironmentCache> { [NonSerialized] private IEnvironment environment; [SerializeField] private string extensionInstallPath; [SerializeField] private string repositoryPath; [SerializeField] private string unityApplication; [SerializeField] private string unityApplicationContents; [SerializeField] private string unityAssetsPath; [SerializeField] private string unityVersion; public void Flush() { repositoryPath = Environment.RepositoryPath; unityApplication = Environment.UnityApplication; unityApplicationContents = Environment.UnityApplicationContents; unityAssetsPath = Environment.UnityAssetsPath; extensionInstallPath = Environment.ExtensionInstallPath; Save(true); } private NPath DetermineInstallationPath() { // Juggling to find out where we got installed var shim = CreateInstance<RunLocationShim>(); var script = MonoScript.FromScriptableObject(shim); var scriptPath = Application.dataPath.ToNPath().Parent.Combine(AssetDatabase.GetAssetPath(script).ToNPath()); DestroyImmediate(shim); return scriptPath.Parent; } public IEnvironment Environment { get { if (environment == null) { var cacheContainer = new CacheContainer(); cacheContainer.SetCacheInitializer(CacheType.Branches, () => BranchesCache.Instance); cacheContainer.SetCacheInitializer(CacheType.GitAheadBehind, () => GitAheadBehindCache.Instance); cacheContainer.SetCacheInitializer(CacheType.GitLocks, () => GitLocksCache.Instance); cacheContainer.SetCacheInitializer(CacheType.GitLog, () => GitLogCache.Instance); cacheContainer.SetCacheInitializer(CacheType.GitFileLog, () => GitFileLogCache.Instance); cacheContainer.SetCacheInitializer(CacheType.GitStatus, () => GitStatusCache.Instance); cacheContainer.SetCacheInitializer(CacheType.GitUser, () => GitUserCache.Instance); cacheContainer.SetCacheInitializer(CacheType.RepositoryInfo, () => RepositoryInfoCache.Instance); environment = new DefaultEnvironment(cacheContainer); if (unityApplication == null) { unityAssetsPath = Application.dataPath; unityApplication = EditorApplication.applicationPath; unityApplicationContents = EditorApplication.applicationContentsPath; extensionInstallPath = DetermineInstallationPath(); unityVersion = Application.unityVersion; } environment.Initialize(unityVersion, extensionInstallPath.ToNPath(), unityApplication.ToNPath(), unityApplicationContents.ToNPath(), unityAssetsPath.ToNPath()); NPath? path = null; if (!String.IsNullOrEmpty(repositoryPath)) path = repositoryPath.ToNPath(); environment.InitializeRepository(path); Flush(); } return environment; } } } abstract class ManagedCacheBase<T> : ScriptObjectSingleton<T> where T : ScriptableObject, IManagedCache { [SerializeField] private CacheType cacheType; [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(Constants.Iso8601Format); [SerializeField] private string initializedAtString = DateTimeOffset.MinValue.ToString(Constants.Iso8601Format); [NonSerialized] private DateTimeOffset? lastUpdatedAtValue; [NonSerialized] private DateTimeOffset? initializedAtValue; [NonSerialized] private bool isInvalidating; [NonSerialized] protected bool forcedInvalidation; public event Action<CacheType> CacheInvalidated; public event Action<CacheType, DateTimeOffset> CacheUpdated; protected ManagedCacheBase(CacheType type) { Logger = LogHelper.GetLogger(GetType()); CacheType = type; } public bool ValidateData() { var isInitialized = IsInitialized; var timedOut = DateTimeOffset.Now - LastUpdatedAt > DataTimeout; var needsInvalidation = !isInitialized || timedOut; if (needsInvalidation && !isInvalidating) { Logger.Trace("needsInvalidation isInitialized:{0} timedOut:{1}", isInitialized, timedOut); Invalidate(); } return !needsInvalidation; } public void InvalidateData() { forcedInvalidation = true; Invalidate(); } private void Invalidate() { isInvalidating = true; LastUpdatedAt = DateTimeOffset.MinValue; CacheInvalidated.SafeInvoke(CacheType); } public void ResetInvalidation() { isInvalidating = false; } protected void SaveData(DateTimeOffset now, bool isChanged) { var isInitialized = IsInitialized; isChanged = isChanged || !isInitialized; InitializedAt = !isInitialized || InitializedAt == DateTimeOffset.MinValue ? now : InitializedAt; LastUpdatedAt = isChanged || LastUpdatedAt == DateTimeOffset.MinValue ? now : LastUpdatedAt; Save(true); isInvalidating = false; if (isChanged) { CacheUpdated.SafeInvoke(CacheType, now); } } public abstract TimeSpan DataTimeout { get; } public string LastUpdatedAtString { get { return lastUpdatedAtString; } private set { lastUpdatedAtString = value; } } public string InitializedAtString { get { return initializedAtString; } private set { initializedAtString = value; } } public bool IsInitialized { get { return ApplicationCache.Instance.FirstRunAt <= InitializedAt; } } public DateTimeOffset LastUpdatedAt { get { if (!lastUpdatedAtValue.HasValue) { DateTimeOffset result; if (DateTimeOffset.TryParseExact(LastUpdatedAtString.ToEmptyIfNull(), Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) { lastUpdatedAtValue = result; } else { LastUpdatedAt = DateTimeOffset.MinValue; } } return lastUpdatedAtValue.Value; } set { LastUpdatedAtString = value.ToString(Constants.Iso8601Format); lastUpdatedAtValue = value; } } public DateTimeOffset InitializedAt { get { if (!initializedAtValue.HasValue) { DateTimeOffset result; if (DateTimeOffset.TryParseExact(InitializedAtString.ToEmptyIfNull(), Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) { initializedAtValue = result; } else { InitializedAt = DateTimeOffset.MinValue; } } return initializedAtValue.Value; } set { InitializedAtString = value.ToString(Constants.Iso8601Format); initializedAtValue = value; } } public CacheType CacheType { get { return cacheType; } private set { cacheType = value; } } protected ILogging Logger { get; private set; } } [Serializable] class LocalConfigBranchDictionary : SerializableDictionary<string, ConfigBranch>, ILocalConfigBranchDictionary { public LocalConfigBranchDictionary() { } public LocalConfigBranchDictionary(IDictionary<string, ConfigBranch> dictionary) : base() { foreach (var pair in dictionary) { this.Add(pair.Key, pair.Value); } } } [Serializable] public class ArrayContainer<T> { [SerializeField] public T[] Values = new T[0]; } [Serializable] public class StringArrayContainer : ArrayContainer<string> {} [Serializable] public class ConfigBranchArrayContainer : ArrayContainer<ConfigBranch> {} [Serializable] class RemoteConfigBranchDictionary : Dictionary<string, Dictionary<string, ConfigBranch>>, ISerializationCallbackReceiver, IRemoteConfigBranchDictionary { [SerializeField] private string[] keys = new string[0]; [SerializeField] private StringArrayContainer[] subKeys = new StringArrayContainer[0]; [SerializeField] private ConfigBranchArrayContainer[] subKeyValues = new ConfigBranchArrayContainer[0]; public RemoteConfigBranchDictionary() { } public RemoteConfigBranchDictionary(Dictionary<string, Dictionary<string, ConfigBranch>> dictionary) { foreach (var pair in dictionary) { Add(pair.Key, pair.Value.ToDictionary(valuePair => valuePair.Key, valuePair => valuePair.Value)); } } // save the dictionary to lists public void OnBeforeSerialize() { var keyList = new List<string>(); var subKeysList = new List<StringArrayContainer>(); var subKeysValuesList = new List<ConfigBranchArrayContainer>(); foreach (var pair in this) { var pairKey = pair.Key; keyList.Add(pairKey); var serializeSubKeys = new List<string>(); var serializeSubKeyValues = new List<ConfigBranch>(); var subDictionary = pair.Value; foreach (var subPair in subDictionary) { serializeSubKeys.Add(subPair.Key); serializeSubKeyValues.Add(subPair.Value); } subKeysList.Add(new StringArrayContainer { Values = serializeSubKeys.ToArray() }); subKeysValuesList.Add(new ConfigBranchArrayContainer { Values = serializeSubKeyValues.ToArray() }); } keys = keyList.ToArray(); subKeys = subKeysList.ToArray(); subKeyValues = subKeysValuesList.ToArray(); } // load dictionary from lists public void OnAfterDeserialize() { Clear(); if (keys.Length != subKeys.Length || subKeys.Length != subKeyValues.Length) { throw new SerializationException("Deserialization length mismatch"); } for (var remoteIndex = 0; remoteIndex < keys.Length; remoteIndex++) { var remote = keys[remoteIndex]; var subKeyContainer = subKeys[remoteIndex]; var subKeyValueContainer = subKeyValues[remoteIndex]; if (subKeyContainer.Values.Length != subKeyValueContainer.Values.Length) { throw new SerializationException("Deserialization length mismatch"); } var branchesDictionary = new Dictionary<string, ConfigBranch>(); for (var branchIndex = 0; branchIndex < subKeyContainer.Values.Length; branchIndex++) { var remoteBranchKey = subKeyContainer.Values[branchIndex]; var remoteBranch = subKeyValueContainer.Values[branchIndex]; branchesDictionary.Add(remoteBranchKey, remoteBranch); } Add(remote, branchesDictionary); } } } [Serializable] class ConfigRemoteDictionary : SerializableDictionary<string, ConfigRemote>, IConfigRemoteDictionary { public ConfigRemoteDictionary() { } public ConfigRemoteDictionary(IDictionary<string, ConfigRemote> dictionary) { foreach (var pair in dictionary) { this.Add(pair.Key, pair.Value); } } } [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)] sealed class RepositoryInfoCache : ManagedCacheBase<RepositoryInfoCache>, IRepositoryInfoCache { [SerializeField] private GitRemote currentGitRemote; [SerializeField] private GitBranch currentGitBranch; [SerializeField] private ConfigBranch currentConfigBranch; [SerializeField] private ConfigRemote currentConfigRemote; [SerializeField] private string currentHead; public RepositoryInfoCache() : base(CacheType.RepositoryInfo) { } public void UpdateData(IRepositoryInfoCacheData data) { var now = DateTimeOffset.Now; var isUpdated = false; if (forcedInvalidation || !Nullable.Equals(currentGitRemote, data.CurrentGitRemote)) { currentGitRemote = data.CurrentGitRemote ?? GitRemote.Default; isUpdated = true; } if (forcedInvalidation || !Nullable.Equals(currentGitBranch, data.CurrentGitBranch)) { currentGitBranch = data.CurrentGitBranch ?? GitBranch.Default; isUpdated = true; } if (forcedInvalidation || !Nullable.Equals(currentConfigRemote, data.CurrentConfigRemote)) { currentConfigRemote = data.CurrentConfigRemote ?? ConfigRemote.Default; isUpdated = true; } if (forcedInvalidation || !Nullable.Equals(currentConfigBranch, data.CurrentConfigBranch)) { currentConfigBranch = data.CurrentConfigBranch ?? ConfigBranch.Default; isUpdated = true; } if (forcedInvalidation || !String.Equals(currentHead, data.CurrentHead)) { currentHead = data.CurrentHead; isUpdated = true; } SaveData(now, isUpdated); } public GitRemote? CurrentGitRemote { get { ValidateData(); return currentGitRemote.Equals(GitRemote.Default) ? (GitRemote?)null : currentGitRemote; } } public GitBranch? CurrentGitBranch { get { ValidateData(); return currentGitBranch.Equals(GitBranch.Default) ? (GitBranch?)null : currentGitBranch; } } public ConfigRemote? CurrentConfigRemote { get { ValidateData(); return currentConfigRemote.Equals(ConfigRemote.Default) ? (ConfigRemote?)null : currentConfigRemote; } } public ConfigBranch? CurrentConfigBranch { get { ValidateData(); return currentConfigBranch.Equals(ConfigBranch.Default) ? (ConfigBranch?)null : currentConfigBranch; } } public string CurrentHead { get { ValidateData(); return currentHead; } } public override TimeSpan DataTimeout { get { return TimeSpan.FromDays(1); } } } [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] sealed class BranchesCache : ManagedCacheBase<BranchesCache>, IBranchCache { [SerializeField] private GitBranch[] localBranches = new GitBranch[0]; [SerializeField] private GitBranch[] remoteBranches = new GitBranch[0]; [SerializeField] private GitRemote[] remotes = new GitRemote[0]; [SerializeField] private LocalConfigBranchDictionary localConfigBranches = new LocalConfigBranchDictionary(); [SerializeField] private RemoteConfigBranchDictionary remoteConfigBranches = new RemoteConfigBranchDictionary(); [SerializeField] private ConfigRemoteDictionary configRemotes = new ConfigRemoteDictionary(); public BranchesCache() : base(CacheType.Branches) { } public void SetRemotes(Dictionary<string, ConfigRemote> remoteConfigs, Dictionary<string, Dictionary<string, ConfigBranch>> configBranches, GitRemote[] gitRemotes, GitBranch[] gitBranches) { var now = DateTimeOffset.Now; configRemotes = new ConfigRemoteDictionary(remoteConfigs); remoteConfigBranches = new RemoteConfigBranchDictionary(configBranches); remotes = gitRemotes; remoteBranches = gitBranches; SaveData(now, true); } public void SetLocals(Dictionary<string, ConfigBranch> configBranches, GitBranch[] gitBranches) { var now = DateTimeOffset.Now; localConfigBranches = new LocalConfigBranchDictionary(configBranches); localBranches = gitBranches; SaveData(now, true); } public ILocalConfigBranchDictionary LocalConfigBranches { get { return localConfigBranches; } } public IRemoteConfigBranchDictionary RemoteConfigBranches { get { return remoteConfigBranches; } } public IConfigRemoteDictionary ConfigRemotes { get { return configRemotes; } } public GitBranch[] LocalBranches { get { return localBranches; } } public GitBranch[] RemoteBranches { get { return remoteBranches; } } public GitRemote[] Remotes { get { return remotes; } } public override TimeSpan DataTimeout { get { return TimeSpan.FromDays(1); } } } [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitLogCache : ManagedCacheBase<GitLogCache>, IGitLogCache { [SerializeField] private List<GitLogEntry> log = new List<GitLogEntry>(); public GitLogCache() : base(CacheType.GitLog) { } public List<GitLogEntry> Log { get { ValidateData(); return log; } set { var now = DateTimeOffset.Now; var isUpdated = false; if (value == null) { if (forcedInvalidation || log.Count > 0) { log.Clear(); isUpdated = true; } } else if (forcedInvalidation || !log.SequenceEqual(value)) { log = value; isUpdated = true; } SaveData(now, isUpdated); } } public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } } } [Location("cache/gitfilelog.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitFileLogCache : ManagedCacheBase<GitFileLogCache>, IGitFileLogCache { [SerializeField] private GitFileLog fileLog = GitFileLog.Default; public GitFileLogCache() : base(CacheType.GitFileLog) { } public GitFileLog FileLog { get { ValidateData(); return fileLog; } set { var now = DateTimeOffset.Now; var isUpdated = false; var shouldUpdate = forcedInvalidation; if (!shouldUpdate) { shouldUpdate = true; } if (shouldUpdate) { fileLog = value; isUpdated = true; } SaveData(now, isUpdated); } } public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } } } [Location("cache/gittrackingstatus.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitAheadBehindCache : ManagedCacheBase<GitAheadBehindCache>, IGitAheadBehindCache { [SerializeField] private int ahead; [SerializeField] private int behind; public GitAheadBehindCache() : base(CacheType.GitAheadBehind) { } public int Ahead { get { ValidateData(); return ahead; } set { var now = DateTimeOffset.Now; var isUpdated = false; if (forcedInvalidation || ahead != value) { ahead = value; isUpdated = true; } SaveData(now, isUpdated); } } public int Behind { get { ValidateData(); return behind; } set { var now = DateTimeOffset.Now; var isUpdated = false; if (forcedInvalidation || behind != value) { behind = value; isUpdated = true; } SaveData(now, isUpdated); } } public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } } } [Location("cache/gitstatusentries.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitStatusCache : ManagedCacheBase<GitStatusCache>, IGitStatusCache { [SerializeField] private List<GitStatusEntry> entries = new List<GitStatusEntry>(); public GitStatusCache() : base(CacheType.GitStatus) { } public List<GitStatusEntry> Entries { get { ValidateData(); return entries; } set { var now = DateTimeOffset.Now; var isUpdated = false; if (value == null) { if (forcedInvalidation || entries.Count > 0) { entries.Clear(); isUpdated = true; } } else if (forcedInvalidation || !entries.SequenceEqual(value)) { entries = value; isUpdated = true; } SaveData(now, isUpdated); } } public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } } } [Location("cache/gitlocks.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitLocksCache : ManagedCacheBase<GitLocksCache>, IGitLocksCache { [SerializeField] private List<GitLock> gitLocks = new List<GitLock>(); public GitLocksCache() : base(CacheType.GitLocks) { } public List<GitLock> GitLocks { get { ValidateData(); return gitLocks; } set { var now = DateTimeOffset.Now; var isUpdated = false; if (value == null) { if (forcedInvalidation || gitLocks.Count > 0) { gitLocks.Clear(); isUpdated = true; } } else if (forcedInvalidation || !gitLocks.SequenceEqual(value)) { gitLocks = value; isUpdated = true; } SaveData(now, isUpdated); } } public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } } } [Location("cache/gituser.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitUserCache : ManagedCacheBase<GitUserCache>, IGitUserCache { [SerializeField] private string gitName; [SerializeField] private string gitEmail; public GitUserCache() : base(CacheType.GitUser) {} public string Name { get { ValidateData(); return gitName; } set { var now = DateTimeOffset.Now; var isUpdated = false; if (forcedInvalidation || gitName != value) { gitName = value; isUpdated = true; } SaveData(now, isUpdated); } } public string Email { get { ValidateData(); return gitEmail; } set { var now = DateTimeOffset.Now; var isUpdated = false; if (forcedInvalidation || gitEmail != value) { gitEmail = value; isUpdated = true; } SaveData(now, isUpdated); } } public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(10); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Globalization; #if __UNIFIED__ using UIKit; using Foundation; using WebView = UIKit.UIWebView; using Class = ObjCRuntime.Class; // Mappings Unified CoreGraphic classes to MonoTouch classes using CGRect = global::System.Drawing.RectangleF; using CGSize = global::System.Drawing.SizeF; using CGPoint = global::System.Drawing.PointF; // Mappings Unified types to MonoTouch types using nfloat = global::System.Single; using nint = global::System.Int32; using nuint = global::System.UInt32; #elif MONOMAC using MonoMac.Foundation; using MonoMac.WebKit; using WebView = MonoMac.WebKit.WebView; using Class = MonoMac.ObjCRuntime.Class; #else using MonoTouch.UIKit; using MonoTouch.Foundation; using WebView = MonoTouch.UIKit.UIWebView; using Class = MonoTouch.ObjCRuntime.Class; #endif namespace cdeutsch { public static class JsBridge { // most of this library is borrowed from Titanium, Copyright 2008-2012 Appcelerator, Inc. under the Apache License Version 2 http://www.apache.org/licenses/LICENSE-2.0 //I haven't implemented all the features they have. #region MT_JAVASCRIPT private static string MT_JAVASCRIPT = @" // jXHR library (function (global) { var SETTIMEOUT = global.setTimeout, // for better compression doc = global.document, callback_counter = 0; global.jXHR = function () { var script_url, script_loaded, jsonp_callback, scriptElem, publicAPI = null; function removeScript() { try { scriptElem.parentNode.removeChild(scriptElem); } catch (err) { } } function reset() { script_loaded = false; script_url = ''; removeScript(); scriptElem = null; fireReadyStateChange(0); } function ThrowError(msg) { try { publicAPI.onerror.call(publicAPI, msg, script_url); } catch (err) { throw new Error(msg); } } function handleScriptLoad() { if ((this.readyState && this.readyState !== 'complete' && this.readyState !== 'loaded') || script_loaded) { return; } this.onload = this.onreadystatechange = null; // prevent memory leak script_loaded = true; if (publicAPI.readyState !== 4) ThrowError('Script failed to load [' + script_url + '].'); removeScript(); } function fireReadyStateChange(rs, args) { args = args || []; publicAPI.readyState = rs; if (typeof publicAPI.onreadystatechange === 'function') publicAPI.onreadystatechange.apply(publicAPI, args); } publicAPI = { onerror: null, onreadystatechange: null, readyState: 0, open: function (method, url) { reset(); internal_callback = 'cb' + (callback_counter++); (function (icb) { global.jXHR[icb] = function () { try { fireReadyStateChange.call(publicAPI, 4, arguments); } catch (err) { publicAPI.readyState = -1; ThrowError('Script failed to run [' + script_url + '].'); } global.jXHR[icb] = null; }; })(internal_callback); script_url = url.replace(/=\?/, '=jXHR.' + internal_callback); fireReadyStateChange(1); }, send: function () { SETTIMEOUT(function () { scriptElem = doc.createElement('script'); scriptElem.setAttribute('type', 'text/javascript'); scriptElem.onload = scriptElem.onreadystatechange = function () { handleScriptLoad.call(scriptElem); }; scriptElem.setAttribute('src', script_url); doc.getElementsByTagName('head')[0].appendChild(scriptElem); }, 0); fireReadyStateChange(2); }, setRequestHeader: function () { }, // noop getResponseHeader: function () { return ''; }, // basically noop getAllResponseHeaders: function () { return []; } // ditto }; reset(); return publicAPI; }; })(window); // most of this library is borrowed from Titanium, Copyright 2008-2012 Appcelerator, Inc. under the Apache License Version 2 http://www.apache.org/licenses/LICENSE-2.0 //I haven't implemented all the features they have. Mt = {}; Mt.appId = 'jsbridge'; Mt.pageToken = 'index'; Mt.App = {}; Mt.API = {}; Mt.App._listeners = {}; Mt.App._listener_id = 1; Mt.App.id = Mt.appId; Mt.App._xhr = jXHR; Mt._broker = function (module, method, data) { var x1 = new Mt.App._xhr(); x1.onerror = function (e) { console.log('XHR error:' + JSON.stringify(e)); }; var url = 'app://' + module + '/' + method + '?callback=?&data=' + encodeURIComponent(JSON.stringify(data)) + '&_=' + Math.random(); x1.open('GET', url); x1.send(); }; Mt._hexish = function (a) { var r = ''; var e = a.length; var c = 0; var h; while (c < e) { h = a.charCodeAt(c++).toString(16); r += '\\\\u'; var l = 4 - h.length; while (l-- > 0) { r += '0' } ; r += h } return r }; Mt._bridgeEnc = function (o) { return'<' + Mt._hexish(o) + '>' }; Mt.App._JSON = function (object, bridge) { var type = typeof object; switch (type) { case'undefined': case'function': case'unknown': return undefined; case'number': case'boolean': return object; case'string': if (bridge === 1)return Mt._bridgeEnc(object); return '""""' + object.replace(/""""/g, '\\\\""""').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r') + '""""' } if ((object === null) || (object.nodeType == 1))return'null'; if (object.constructor.toString().indexOf('Date') != -1) { return'new Date(' + object.getTime() + ')' } if (object.constructor.toString().indexOf('Array') != -1) { var res = '['; var pre = ''; var len = object.length; for (var i = 0; i < len; i++) { var value = object[i]; if (value !== undefined)value = Mt.App._JSON(value, bridge); if (value !== undefined) { res += pre + value; pre = ', ' } } return res + ']' } var objects = []; for (var prop in object) { var value = object[prop]; if (value !== undefined) { value = Mt.App._JSON(value, bridge) } if (value !== undefined) { objects.push(Mt.App._JSON(prop, bridge) + ': ' + value) } } return'{' + objects.join(',') + '}' }; //CDeutsch: removing evtid param //Mt.App._dispatchEvent = function (type, evtid, evt) { Mt.App._dispatchEvent = function (type, evt) { var listeners = Mt.App._listeners[type]; if (listeners) { for (var c = 0; c < listeners.length; c++) { var entry = listeners[c]; //CDeutsch: changing to look for type so we only have to call once. //if (entry.id == evtid) { entry.callback.call(entry.callback, evt) //} } } }; Mt.App.fireEvent = function (name, evt) { Mt._broker('App', 'fireEvent', {name:name, event:evt}) }; Mt.API.log = function (a, b) { Mt._broker('API', 'log', {level:a, message:b}) }; Mt.API.debug = function (e) { Mt._broker('API', 'log', {level:'debug', message:e}) }; Mt.API.error = function (e) { Mt._broker('API', 'log', {level:'error', message:e}) }; Mt.API.info = function (e) { Mt._broker('API', 'log', {level:'info', message:e}) }; Mt.API.fatal = function (e) { Mt._broker('API', 'log', {level:'fatal', message:e}) }; Mt.API.warn = function (e) { Mt._broker('API', 'log', {level:'warn', message:e}) }; Mt.App.addEventListener = function (name, fn) { var listeners = Mt.App._listeners[name]; if (typeof(listeners) == 'undefined') { listeners = []; Mt.App._listeners[name] = listeners } var newid = Mt.pageToken + Mt.App._listener_id++; listeners.push({callback:fn, id:newid}); //CDeutsch: not going to do this (don't see the advatange right now //Mt._broker('App', 'addEventListener', {name:name, id:newid}) }; Mt.App.removeEventListener = function (name, fn) { var listeners = Mt.App._listeners[name]; if (listeners) { for (var c = 0; c < listeners.length; c++) { var entry = listeners[c]; if (entry.callback == fn) { listeners.splice(c, 1); //CDeutsch: not going to do this (don't see the advatange right now //Mt._broker('App', 'removeEventListener', {name:name, id:entry.id}); break } } } };"; #endregion static bool protocolRegistered = false; public static void EnableJsBridge() { if (!protocolRegistered) { NSUrlProtocol.RegisterClass (new Class (typeof (AppProtocolHandler))); protocolRegistered = true; } } public static void InjectMtJavascript(this WebView webView) { #if MONOMAC InjectMtJavascript(webView, MT_JAVASCRIPT); #else webView.EvaluateJavascript(MT_JAVASCRIPT); #endif } public static void InjectMtJavascript(this WebView webView, string script) { #if MONOMAC var document = webView.MainFrame.DomDocument; document.EvaluateWebScript(script); #else webView.EvaluateJavascript(script); #endif } private static List<EventListener> EventListeners = new List<EventListener>(); public static void AddEventListener (this WebView source, string EventName, Action<FireEventData> Event) { EventListeners.Add( new EventListener(source, EventName, Event) ); } public static void RemoveEventListener (this WebView source, string EventName, Action<FireEventData> Event) { for(int xx = 0; xx < EventListeners.Count; xx++) { var ee = EventListeners[xx]; if (source == ee.WebView && string.Compare(EventName, ee.EventName, StringComparison.InvariantCultureIgnoreCase) == 0 && ee.Event == Event) { EventListeners.RemoveAt(xx); break; } } } public static void FireEvent (this WebView source, string EventName, Object Data) { // call javascript event hanlder code string json = SimpleJson.SerializeObject(Data); source.BeginInvokeOnMainThread ( delegate{ source.InjectMtJavascript(string.Format("Mt.App._dispatchEvent('{0}', {1});", EventName, json)); }); } public static void JsEventFired (FireEventData feData) { foreach(var ee in EventListeners.Where(oo => string.Compare(oo.EventName, feData.Name, StringComparison.InvariantCultureIgnoreCase) == 0)) { ee.Event(feData); } } } public class AppProtocolHandler : NSUrlProtocol { [Export ("canInitWithRequest:")] public static bool canInitWithRequest (NSUrlRequest request) { return request.Url.Scheme == "app"; } [Export ("canonicalRequestForRequest:")] public static new NSUrlRequest GetCanonicalRequest (NSUrlRequest forRequest) { return forRequest; } public AppProtocolHandler(IntPtr ptr) : base(ptr) { } #if __UNIFIED__ public AppProtocolHandler (NSUrlRequest request, NSCachedUrlResponse cachedResponse, INSUrlProtocolClient client) : base (request, cachedResponse, client) { } #else #if !MONOMAC [Export ("initWithRequest:cachedResponse:client:")] #endif public AppProtocolHandler (NSUrlRequest request, NSCachedUrlResponse cachedResponse, NSUrlProtocolClient client) : base (request, cachedResponse, client) { } #endif public override void StartLoading () { // parse callback function name. // EX: callback=jXHR.cb0&data=%7B%22hello%22%3A%22world%22%7D&_=0.3452287893742323 var parameters = Request.Url.Query.Split('&'); if (parameters.Length > 2) { var callbackToks = parameters[0].Split('='); var dataToks = parameters[1].Split('='); if (callbackToks.Length > 1 && dataToks.Length > 1) { // Determine what to do here based on the url var appUrl = new AppUrl() { Module = Request.Url.Host, Method = Request.Url.RelativePath.Substring(1), JsonData = System.Web.HttpUtility.UrlDecode(dataToks[1]) }; // this is a request from mt.js so handle it. switch (appUrl.Module.ToLower()) { case "app": if (string.Equals(appUrl.Method, "fireEvent", StringComparison.InvariantCultureIgnoreCase)) { // fire this event. var feData = appUrl.DeserializeFireEvent(); // find event listeners for this event and trigger it. JsBridge.JsEventFired(feData); } break; case "api": if (string.Equals(appUrl.Method, "log", StringComparison.InvariantCultureIgnoreCase)) { // log output. var lData = appUrl.DeserializeLog(); #if DEBUG Console.WriteLine("BROWSER:[" + lData.Level + "]: " + lData.Message); #endif } break; } // indicate success. var data = NSData.FromString(callbackToks[1] + "({'success' : '1'});"); using (var response = new NSUrlResponse (Request.Url, "text/javascript", Convert.ToInt32(data.Length), "utf-8")) { Client.ReceivedResponse (this, response, NSUrlCacheStoragePolicy.NotAllowed); Client.DataLoaded (this, data); Client.FinishedLoading (this); } return; } } Client.FailedWithError(this, NSError.FromDomain(new NSString("AppProtocolHandler"), Convert.ToInt32(NSUrlError.ResourceUnavailable))); Client.FinishedLoading(this); } public override void StopLoading () { } } public class EventListener { public WebView WebView { get; set; } public string EventName { get; set; } public Action<FireEventData> Event { get; set; } public EventListener() { } public EventListener(WebView WebView, string EventName, Action<FireEventData> Event) { this.WebView = WebView; this.EventName = EventName; this.Event = Event; } } public class AppUrl { public string Module { get; set; } public string Method { get; set; } public string JsonData { get; set; } public Object Deserialize() { return SimpleJson.DeserializeObject(JsonData); } public T Deserialize<T>() { return SimpleJson.DeserializeObject<T>(JsonData); } public FireEventData DeserializeFireEvent() { if (string.Equals(Method, "fireEvent", StringComparison.InvariantCultureIgnoreCase)) { return new FireEventData(JsonData); } else { return null; } } public LogData DeserializeLog() { if (string.Equals(Method, "log", StringComparison.InvariantCultureIgnoreCase)) { return new LogData(JsonData); } else { return null; } } } public class FireEventData { public string Name { get; set; } public JsonObject Data { get; set; } public string JsonData { get; set; } public FireEventData() { } public FireEventData(string Json) { JsonObject feData = (JsonObject)SimpleJson.DeserializeObject(Json); this.Name = feData["name"].ToString(); this.Data = (JsonObject)feData["event"]; // save json of data so user can desiralize in a typed object. this.JsonData = SimpleJson.SerializeObject(this.Data); } } public class LogData { public string Level { get; set; } public string Message { get; set; } public LogData() { } public LogData(string Json) { JsonObject lData = (JsonObject)SimpleJson.DeserializeObject(Json); this.Level = lData["level"].ToString(); if (lData["message"] != null) { this.Message = lData["message"].ToString(); } } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Gui; using FlatRedBall; using System.IO; using FlatRedBall.Graphics; using FlatRedBall.IO; using FlatRedBall.Graphics.Animation; using FlatRedBall.ManagedSpriteGroups; using FlatRedBall.Content; using EditorObjects.Gui; using SpriteGrid = FlatRedBall.ManagedSpriteGroups.SpriteGrid; using EditorObjects; using Microsoft.DirectX; using FlatRedBall.Content.Model; using EditorObjects.Savers; using FlatRedBall.Content.Scene; using FlatRedBall.Content.SpriteRig; using EditorObjects.EditorSettings; using FlatRedBall.Content.SpriteGrid; using FlatRedBall.Math; namespace SpriteEditor.Gui { public class MenuStrip : FlatRedBall.Gui.MenuStrip { #region Fields private string mLastFileName; private string mLastFileTypeLoaded; private SpriteList namesToChange; private List<Texture2D> mTexturesNotRelative = new List<Texture2D>(); private List<AnimationChainList> mAnimationChainListsNotRelative = new List<AnimationChainList>(); private List<string> mFntFilesNotRelative = new List<string>(); #endregion #region Properties public string LastFileTypeLoaded { get { return mLastFileTypeLoaded; } set { mLastFileTypeLoaded = value; } } #endregion #region Event Methods #region File events #region New public static void NewSceneClick(Window callingWindow) { OkCancelWindow tempWindow = GuiManager.AddOkCancelWindow(); tempWindow.Name = "New Scene"; tempWindow.ScaleX = 12f; tempWindow.ScaleY = 6f; tempWindow.Message = "Creating a new scene will delete the current scene. Continue?"; tempWindow.OkClick += new GuiMessage(newSceneOk); tempWindow.HasMoveBar = true; GuiManager.AddDominantWindow(tempWindow); } static void newSceneOk(Window callingWindow) { GameData.MakeNewScene(); } #endregion #region Save private void SaveSceneClick(Window callingWindow) { SaveSceneClick(GameData.FileName); } void SaveSceneAs_Click(Window callingWindow) { SaveSceneClick(""); } public void SaveSceneClick(string fileName) { if (!string.IsNullOrEmpty(fileName)) { mLastFileName = fileName; } List<string> stringArray = new List<string>(); namesToChange = new SpriteList(); foreach (Sprite s in GameData.Scene.Sprites) { if (stringArray.Contains(s.Name)) { namesToChange.AddOneWay(s); } else { stringArray.Add(s.Name); } } if (AskQuestionsAndDelaySaveIfNecessary(SaveSceneClick)) { if (namesToChange.Count != 0) { MultiButtonMessageBox mbmb = GuiManager.AddMultiButtonMessageBox(); mbmb.Name = "Duplicate Sprite names found"; mbmb.Text = "Duplicate names found in scene. Duplicate names can alter attachment information. What would you like to do?"; mbmb.AddButton("Leave names as they are and save.", new GuiMessage(OpenFileWindowSaveScene)); mbmb.AddButton("Automatically change Sprite names and save.", new GuiMessage(ChangeNamesAndSave)); mbmb.AddButton("Cancel save.", null); } else { if (string.IsNullOrEmpty(fileName)) { OpenFileWindowSaveScene(null); } else { SaveSceneFileWindowOk(null); } } ShowWarningsAndMessagesBeforeSaving(); } } private void SaveSceneFileWindowOk(Window callingWindow) { string fileName; if (callingWindow != null && callingWindow is FileWindow) fileName = ((FileWindow)callingWindow).Results[0]; else fileName = mLastFileName; mLastFileName = fileName; SceneSaver.MakeSceneRelativeAndSave(GameData.Scene, fileName, GameData.SceneContentManager, GameData.SpriteEditorSceneProperties.FilesToMakeDotDotSlashRelative, GameData.ReplaceTexture, SaveScene); } public event EventHandler SavedSuccess; public bool SaveScene(string name, bool areAssetsRelativeToScene) { string oldRelativeDirectory = FileManager.RelativeDirectory; if (areAssetsRelativeToScene) { FileManager.RelativeDirectory = FileManager.GetDirectory(name); } // This will reduce the file size if we use a lot of SpriteGrids for (int i = 0; i < GameData.Scene.SpriteGrids.Count; i++) { GameData.Scene.SpriteGrids[i].TrimGrid(); } SpriteEditorScene ses = SpriteEditorScene.FromScene(GameData.Scene); ses.AssetsRelativeToSceneFile = areAssetsRelativeToScene; ses.Save(name); // TODO: Need to check if file saving worked properly. bool wasSceneSaved = true; if (wasSceneSaved) { #region create the SpriteEditorSceneProperties GameData.SpriteEditorSceneProperties.SetFromRuntime( GameData.Camera, GameData.BoundsCamera, GameData.EditorProperties.PixelSize, GuiData.CameraBoundsPropertyGrid.Visible ); GameData.SpriteEditorSceneProperties.WorldAxesVisible = GameData.EditorProperties.WorldAxesDisplayVisible; GameData.SpriteEditorSceneProperties.TextureDisplayRegionsList.Clear(); for (int k = 0; k < GuiData.ListWindow.TextureListBox.Count; k++) { TextureDisplayRegionsSave tdrs = new TextureDisplayRegionsSave(); CollapseItem item = GuiData.ListWindow.TextureListBox[k]; // The FileManager's relative directory has been set, so we just have to call MakeRelative and it should work fine tdrs.TextureName = FileManager.MakeRelative(((Texture2D)item.ReferenceObject).SourceFile()); tdrs.DisplayRegions = GuiData.ListWindow.CreateTextureReferences(item); GameData.SpriteEditorSceneProperties.TextureDisplayRegionsList.Add(tdrs); } GameData.SpriteEditorSceneProperties.Save(FileManager.RemoveExtension(name) + ".sep"); #endregion FlatRedBallServices.Owner.Text = "SpriteEditor - Currently editing " + name; // As mentioned in the othe area where GameData.Filename is set, I'm not // sure why we were removing the extension. I've commented out the extension // removal since it causes problems with CTRL+S // name = FileManager.RemoveExtension(name); GameData.FileName = name; if (SavedSuccess != null) SavedSuccess(this, null); } FileManager.RelativeDirectory = oldRelativeDirectory; if (! wasSceneSaved) GuiManager.ShowMessageBox("Could not save " + GameData.FileName + ". Is the file readonly?", "Error Saving"); return wasSceneSaved; } #endregion #region Load public void LoadSceneClick(Window callingWindow) { FileWindow tempFileWindow = GuiManager.AddFileWindow(); tempFileWindow.Filter = "SpriteEditor Binary Scene (*.scn)|*.scn|SpriteEditor XML Scene (*.scnx)|*.scnx"; tempFileWindow.CurrentFileType = "scnx"; tempFileWindow.OkClick += new GuiMessage(LoadSceneOk); } private void LoadSceneInsertClick(Window callingWindow) { PerformLoadScn(callingWindow.Name, false); } private void LoadSceneOk(Window callingWindow) { AskToReplaceOrInsertNewScene(((FileWindow)callingWindow).Results[0]); } private void LoadSceneReplaceClick(Window callingWindow) { PerformLoadScn(callingWindow.Name, true); } private void LoadShapeCollectionClick(Window callingWindow) { FileWindow tempFileWindow = GuiManager.AddFileWindow(); tempFileWindow.Filter = "ShapeCollection XML File(*.shcx)|*.shcx"; tempFileWindow.CurrentFileType = "shcx"; tempFileWindow.OkClick += new GuiMessage(LoadShapeCollectionOk); } private void LoadShapeCollectionOk(Window callingWindow) { string fileName = ((FileWindow)callingWindow).Results[0]; GameData.AddShapeCollection(fileName); } public static void LoadSpriteRigClick(Window callingWindow) { OkCancelWindow tempWindow = GuiManager.AddOkCancelWindow(); tempWindow.ScaleX = 22f; tempWindow.ScaleY = 19f; tempWindow.Message = "The SpriteEditor does not fully support SpriteRig editing. Currently, the SpriteEditor can only remember animations for one SpriteRig at a time. Therefore, you should not load more than one SpriteRig per SpriteEditor session unless you do not plan on saving the SpriteRigs. \n\nAlso, do not add or remove any Sprites from the SpriteRig as the animation data depends on having the same number of joints and body sprites when saving the SpriteRig.\n\nIf you attempt to save a SpriteRig which does not match the animation information, the SpriteEditor will warn you.\n\nLoad SpriteRig?"; tempWindow.OkText = "Yes"; tempWindow.CancelText = "No"; tempWindow.OkClick += new GuiMessage(OpenFileWindowLoadSpriteRig); } public static void LoadSpriteRigOk(Window callingWindow) { #region Load the SpriteRig EditorSprite es; string fileName = ((FileWindow)callingWindow).Results[0]; SpriteRigSave srs = SpriteRigSave.FromFile(fileName); SpriteList loadedSprites = new SpriteList(); SpriteRig spriteRig = srs.ToSpriteRig(GameData.SceneContentManager); #endregion #region Play some Pose so that the SpriteRig has a proper pose and texture coordinates // Play and stop an animation to get the texture coordinates set up in case // the SpriteRig has texture coords defined in its AnimationChains if (spriteRig.PoseChains.Count != 0) { spriteRig.SetPoseChain(spriteRig.PoseChains[0]); spriteRig.Animate = true; spriteRig.SetPositionAtTimeFromAnimationStart(0); spriteRig.Animate = false; } #endregion GuiData.srSaveOptions.joints = new SpriteList(); GuiData.srSaveOptions.bodySprites = new SpriteList(); GuiData.srSaveOptions.joints.Clear(); GuiData.srSaveOptions.bodySprites.Clear(); string oldRelativeDirectory = FileManager.RelativeDirectory; FileManager.RelativeDirectory = FileManager.GetDirectory(fileName); foreach (Sprite regularSprite in spriteRig.Joints) { es = new EditorSprite(); es.SetFromRegularSprite(regularSprite); GameData.Scene.Sprites.Add(es); SpriteManager.AddSprite(es); loadedSprites.AddOneWay(es); GuiData.srSaveOptions.joints.Add(es); } foreach (Sprite regularSprite in spriteRig.BodySprites) { es = new EditorSprite(); es.SetFromRegularSprite(regularSprite); GameData.Scene.Sprites.Add(es); SpriteManager.AddSprite(es); loadedSprites.AddOneWay(es); GuiData.srSaveOptions.bodySprites.Add(es); } // The root is not part of the body Sprites, but it should be if (spriteRig.Root != null && GameData.Scene.Sprites.Contains(spriteRig.Root) == false) { es = new EditorSprite(); es.SetFromRegularSprite(spriteRig.Root); GameData.Scene.Sprites.Add(es); SpriteManager.AddSprite(es); loadedSprites.AddOneWay(es); GuiData.srSaveOptions.bodySprites.Add(es); } if (spriteRig.Root != null) { GuiData.srSaveOptions.root = GuiData.srSaveOptions.bodySprites.FindByName(spriteRig.Root.Name); GuiData.srSaveOptions.bodySprites.Remove(GuiData.srSaveOptions.root); } GuiData.srSaveOptions.poseChains = spriteRig.PoseChains; if (srs.JointsVisible) { GuiData.srSaveOptions.jointsVisible.Press(); } else { GuiData.srSaveOptions.jointsVisible.Unpress(); } if (srs.RootVisible) { GuiData.srSaveOptions.rootVisible.Press(); } else { GuiData.srSaveOptions.rootVisible.Unpress(); } FileManager.RelativeDirectory = oldRelativeDirectory; string oldRelative = FileManager.RelativeDirectory; if (srs.AssetsRelativeToFile) { FileManager.RelativeDirectory = FileManager.GetDirectory(fileName); } FileManager.RelativeDirectory = oldRelative; foreach (SpriteSave ss in srs.Joints) { srs.BodySprites.Add(ss); } for (int i = 0; i < loadedSprites.Count; i++) { if (loadedSprites[i].PixelSize > 0f) { ((EditorSprite)loadedSprites[i]).ConstantPixelSizeExempt = false; } else { ((EditorSprite)loadedSprites[i]).ConstantPixelSizeExempt = true; } if (loadedSprites[i].Texture.texture != null) { GuiData.ListWindow.Add(loadedSprites[i].Texture); } string parentName = ""; Sprite matchingSprite = spriteRig.BodySprites.FindByName(loadedSprites[i].Name); if (matchingSprite == null) { matchingSprite = spriteRig.Joints.FindByName(loadedSprites[i].Name); } // parent may be null if there is no root if (matchingSprite != null && matchingSprite.Parent != null) { parentName = matchingSprite.Parent.Name; loadedSprites[i].AttachTo(loadedSprites.FindByName(parentName), false); } } GameData.Scene.Sprites.SortZInsertionDescending(); AskToSearchForReplacements(((FileWindow)callingWindow).Results[0]); } public void AskToReplaceOrInsertNewScene(string fileName) { if (FileManager.FileExists(fileName)) { OkCancelWindow tempWindow = GuiManager.AddOkCancelWindow(); tempWindow.Message = "Would you like to replace the current scene or insert " + fileName + " into the current scene?"; tempWindow.ScaleX = 16f; tempWindow.ScaleY = 10f; tempWindow.Name = fileName; tempWindow.OkText = "Replace"; tempWindow.OkClick += new GuiMessage(LoadSceneReplaceClick); tempWindow.CancelText = "Insert"; tempWindow.CancelClick += new GuiMessage(LoadSceneInsertClick); } else { MessageBox messageBox = GuiManager.ShowMessageBox("Could not find the file " + fileName, "Error loading .scnx"); } } public void PerformLoadScn(string fileName, bool replace) { // This method is public because this method is called if the user drags a // .scnx onto the SpriteEditor #region Mark how many objects before loading in case there is an insertion. // If there is an insertion, only the newly-added objects should have post load // logic performed on them int numSpritesBefore = GameData.Scene.Sprites.Count; int numOfSGsBefore = GameData.Scene.SpriteGrids.Count; int numOfSpriteFramesBefore = GameData.Scene.SpriteFrames.Count; int numberOfPositionedModels = GameData.Scene.PositionedModels.Count; #endregion SpriteEditorScene tempSES = SpriteEditorScene.FromFile(fileName); #region See if there are any Models that reference files that aren't on disk string sceneDirectory = FileManager.GetDirectory(fileName); for (int i = 0; i < tempSES.PositionedModelSaveList.Count; i++) { PositionedModelSave modelSave = tempSES.PositionedModelSaveList[i]; if (!FileManager.FileExists(modelSave.ModelFileName)) { // See if there's a .x with that name if (FileManager.FileExists(sceneDirectory + modelSave.ModelFileName + ".x")) { modelSave.ModelFileName = modelSave.ModelFileName + ".x"; } } } #endregion #region Now, see if there are any other files that haven't been found and create the error window List<string> texturesNotFound = tempSES.GetMissingFiles(); if (texturesNotFound.Count != 0) { OkListWindow okListWindow = new OkListWindow( "There are files that the .scnx references which cannot be located.", "Error loading .scnx"); foreach (string file in texturesNotFound) { okListWindow.AddItem(file); } return; } #endregion #region if replacing, clear the old scene out if (replace) { SpriteManager.RemoveScene(GameData.Scene, true); FlatRedBallServices.Unload(GameData.SceneContentManager); tempSES.SetCamera(GameData.Camera); #if FRB_MDX if (tempSES.CoordinateSystem == FlatRedBall.Math.CoordinateSystem.RightHanded) { GameData.Camera.Z *= -1; } #endif GameData.EditorProperties.PixelSize = tempSES.PixelSize; GuiData.EditorPropertiesGrid.Refresh(); // 4/16/2011: The following line of code // was causing errors when saving the .scnx // file through CTRL+S. Taking it out because // I don't see why we need this anyway. // GameData.FileName = FileManager.RemoveExtension(fileName); GameData.FileName = fileName; FlatRedBallServices.Owner.Text = "SpriteEditor - Currently editing " + GameData.FileName; GuiData.MenuStrip.LastFileTypeLoaded = FileManager.GetExtension(fileName); } #endregion Scene newlyLoadedScene = tempSES.ToScene<EditorSprite>(GameData.SceneContentManager); GameData.Scene.AddToThis(newlyLoadedScene); // This caused // a double-add. // Not sure why we're // adding GameData.Scene. //GameData.Scene.AddToManagers(); newlyLoadedScene.AddToManagers(); GuiData.ListWindow.RefreshListsShown(); #region Add the used Textures to the texture ListBox for (int i = numSpritesBefore; i < GameData.Scene.Sprites.Count; i++) { GuiData.ListWindow.Add(GameData.Scene.Sprites[i].Texture); GuiData.ListWindow.Add(GameData.Scene.Sprites[i].AnimationChains); } for (int i = numOfSpriteFramesBefore; i < GameData.Scene.SpriteFrames.Count; i++) { GuiData.ListWindow.Add(GameData.Scene.SpriteFrames[i].Texture); GuiData.ListWindow.Add(GameData.Scene.SpriteFrames[i].AnimationChains); } for (int i = numOfSGsBefore; i < GameData.Scene.SpriteGrids.Count; i++) { SpriteGrid sg = GameData.Scene.SpriteGrids[i]; sg.PopulateGrid(GameData.Camera.X, GameData.Camera.Y, 0f); sg.RefreshPaint(); List<Texture2D> texturesToAdd = sg.GetUsedTextures(); foreach (Texture2D tex in texturesToAdd) { GuiData.ListWindow.Add(tex); } } #endregion CheckForExtraFiles(FileManager.RemoveExtension(fileName)); GameData.Scene.Sprites.SortZInsertionDescending(); if (tempSES.AssetsRelativeToSceneFile) { FileManager.ResetRelativeToCurrentDirectory(); } } #endregion private static void AskToSearchForReplacements(string fileName) { //throw new NotImplementedException("Not implemented"); /* if (SpriteManager.texturesNotFound.Count != 0) { MultiButtonMessageBox mbmb = GuiManager.AddMultiButtonMessageBox(); mbmb.Text = SpriteManager.texturesNotFound.Count + " textures not found."; mbmb.AddButton("Search in folders relative to SpriteEditor.", new GuiMessage(this.SpriteEditorRelativeSearch)); mbmb.AddButton("Search in folders relative to file.", new GuiMessage(this.FileRelativeSearch)); mbmb.AddButton("Don't search for replacements.", null); this.mSpriteRigFileName = fileName; } */ } private void ChangeNamesAndSave(Window callingWindow) { foreach (Sprite s in namesToChange) { s.Name = GameData.GetUniqueNameForObject<Sprite>(s.Name, s); } OpenFileWindowSaveScene(null); } private void CopyAssetsToFileFolder(Window callingWindow) { string directory = FileManager.GetDirectory(mLastFileName); #region Copy Texture2Ds and replace references foreach (Texture2D texture in mTexturesNotRelative) { if (!System.IO.File.Exists(directory + FileManager.RemovePath(texture.Name))) { System.IO.File.Copy(texture.Name, directory + FileManager.RemovePath(texture.Name)); } GameData.ReplaceTexture(texture, FlatRedBallServices.Load<Texture2D>(directory + FileManager.RemovePath(texture.Name), GameData.SceneContentManager)); } #endregion #region Copy AnimationChainLists and replace references foreach (AnimationChainList animationChainList in mAnimationChainListsNotRelative) { if (!System.IO.File.Exists(directory + FileManager.RemovePath(animationChainList.Name))) { System.IO.File.Copy(animationChainList.Name, directory + FileManager.RemovePath(animationChainList.Name)); } animationChainList.Name = directory + FileManager.RemovePath(animationChainList.Name); } #endregion #region Copy Fnt Files and replace references foreach (string oldFnt in mFntFilesNotRelative) { if (!System.IO.File.Exists(directory + FileManager.RemovePath(oldFnt))) { System.IO.File.Copy( oldFnt, directory + FileManager.RemovePath(oldFnt)); foreach (Text text in GameData.Scene.Texts) { if (text.Font.FontFile == oldFnt) { // A little inefficient because it hits the file for the same information. // Revisit this if it's a performance problem. text.Font.SetFontPatternFromFile(directory + FileManager.RemovePath(oldFnt)); } } } } #endregion SaveSceneFileWindowOk(callingWindow); } public static void OpenFileWindowLoadSpriteRig(Window callingWindow) { FileWindow tempFileWindow = GuiManager.AddFileWindow(); tempFileWindow.SetFileType("srgx"); tempFileWindow.OkClick += new GuiMessage(LoadSpriteRigOk); } public void OpenFileWindowSaveScene(Window callingWindow) { FileWindow tempFileWindow = GuiManager.AddFileWindow(); //tempFileWindow.activityToExecute = "loadScene"; tempFileWindow.SetToSave(); tempFileWindow.Filter = "SpriteEditor XML Scene (*.scnx)|*.scnx"; tempFileWindow.CurrentFileType = "scnx"; tempFileWindow.saveNameText = FileManager.RemoveExtension(FileManager.RemovePath(GameData.FileName)); tempFileWindow.OkClick += new GuiMessage(SaveSceneFileWindowOk); } public static bool AskQuestionsAndDelaySaveIfNecessary(GuiMessage guiMessage) { if (SESpriteGridManager.CurrentSpriteGrid != null && SESpriteGridManager.HasBlueprintChanged()) { SESpriteGridManager.AskIfChangesShouldBeApplied(guiMessage); return false; } else { return true; } } public static void ShowWarningsAndMessagesBeforeSaving() { SESpriteGridManager.ShowMessageBoxIfBoundsAreInvalid(); } #endregion #region Edit events private void ShiftSceneClick(Window callingWindow) { Vector3OkWindow v3ok = new Vector3OkWindow(GuiManager.Cursor); GuiManager.AddWindow(v3ok); v3ok.OkClick += ShiftSceneOk; } private void ShiftSceneOk(Window callingWindow) { Vector3OkWindow v3ok = callingWindow as Vector3OkWindow; Vector3 amountToShiftBy = v3ok.Vector3Value; GameData.Scene.Shift(amountToShiftBy); GuiManager.RemoveWindow(v3ok); } private void DeleteSelected(Window callingWindow) { GameData.EditorLogic.DeleteSelectedObject(); } void ScalePositionOnly(Window callingWindow) { Vector3OkWindow v3ok = new Vector3OkWindow(GuiManager.Cursor); GuiManager.AddWindow(v3ok); v3ok.Vector3Value = new Vector3(1, 1, 1); v3ok.OkClick += ScalePositionsOnlyOk; } void ScalePositionAndScaleOnly(Window callingWindow) { TextInputWindow tiw = GuiManager.ShowTextInputWindow( "Enter scale amount. Scale will be applied on X, Y, and Z", "Scale Scene"); tiw.Text = "1.0"; tiw.Format = TextBox.FormatTypes.Decimal; tiw.OkClick += ScalePositionsAndScaleOk; } void ScalePositionsAndScaleOk(Window callingWindow) { TextInputWindow window = callingWindow as TextInputWindow; float value = float.Parse(window.Text); Vector3 amountToShiftBy = new Vector3(value, value, value); Scene scene = GameData.Scene; for (int i = 0; i < scene.PositionedModels.Count; i++) { scene.PositionedModels[i].X *= amountToShiftBy.X; scene.PositionedModels[i].Y *= amountToShiftBy.Y; scene.PositionedModels[i].Z *= amountToShiftBy.Z; scene.PositionedModels[i].ScaleX *= amountToShiftBy.X; scene.PositionedModels[i].ScaleY *= amountToShiftBy.Y; scene.PositionedModels[i].ScaleZ *= amountToShiftBy.Z; } for (int i = 0; i < scene.SpriteFrames.Count; i++) { scene.SpriteFrames[i].X *= amountToShiftBy.X; scene.SpriteFrames[i].Y *= amountToShiftBy.Y; scene.SpriteFrames[i].Z *= amountToShiftBy.Z; scene.SpriteFrames[i].ScaleX *= amountToShiftBy.X; scene.SpriteFrames[i].ScaleY *= amountToShiftBy.Y; } for (int i = 0; i < scene.Sprites.Count; i++) { scene.Sprites[i].X *= amountToShiftBy.X; scene.Sprites[i].Y *= amountToShiftBy.Y; scene.Sprites[i].Z *= amountToShiftBy.Z; scene.Sprites[i].ScaleX *= amountToShiftBy.X; scene.Sprites[i].ScaleY *= amountToShiftBy.Y; } for (int i = 0; i < scene.Texts.Count; i++) { scene.Texts[i].X *= amountToShiftBy.X; scene.Texts[i].Y *= amountToShiftBy.Y; scene.Texts[i].Z *= amountToShiftBy.Z; scene.Texts[i].Scale *= amountToShiftBy.X; scene.Texts[i].Spacing *= amountToShiftBy.X; scene.Texts[i].NewLineDistance *= amountToShiftBy.X; } GuiManager.RemoveWindow(window); } void ScalePositionsOnlyOk(Window callingWindow) { Vector3OkWindow v3ok = callingWindow as Vector3OkWindow; Vector3 amountToShiftBy = v3ok.Vector3Value; Scene scene = GameData.Scene; for (int i = 0; i < scene.PositionedModels.Count; i++) { scene.PositionedModels[i].X *= amountToShiftBy.X; scene.PositionedModels[i].Y *= amountToShiftBy.Y; scene.PositionedModels[i].Z *= amountToShiftBy.Z; } for (int i = 0; i < scene.SpriteFrames.Count; i++) { scene.SpriteFrames[i].X *= amountToShiftBy.X; scene.SpriteFrames[i].Y *= amountToShiftBy.Y; scene.SpriteFrames[i].Z *= amountToShiftBy.Z; } for (int i = 0; i < scene.Sprites.Count; i++) { scene.Sprites[i].X *= amountToShiftBy.X; scene.Sprites[i].Y *= amountToShiftBy.Y; scene.Sprites[i].Z *= amountToShiftBy.Z; } for (int i = 0; i < scene.Texts.Count; i++) { scene.Texts[i].X *= amountToShiftBy.X; scene.Texts[i].Y *= amountToShiftBy.Y; scene.Texts[i].Z *= amountToShiftBy.Z; } GuiManager.RemoveWindow(v3ok); } #endregion #region Add events //private void AddAnimationChainClick(Window callingWindow) //{ // FileWindow fileWindow = GuiManager.AddFileWindow(); // fileWindow.SetFileType("achx"); // fileWindow.SetToLoad(); // fileWindow.OkClick += AddAnimationChainOk; //} private void AddAnimationChainOk(Window callingWindow) { string fileName = ((FileWindow)callingWindow).Results[0]; AnimationChainList acl = GameData.AddAnimationChainList(fileName); foreach (AnimationChain animationChain in acl) { foreach (AnimationFrame animationFrame in animationChain) { WarnAboutNonPowerOfTwoTexture(animationFrame.Texture); } } } private void AddSpriteClick(Window callingWindow) { FileWindow tempFileWindow = GuiManager.AddFileWindow(); tempFileWindow.SetFileType("graphic and animation"); tempFileWindow.ShowLoadDirButton(); tempFileWindow.betweenLoadFolder += new BetweenLoadFolder(MoveCameraToTheRight); tempFileWindow.OkClick += new GuiMessage(this.AddSpriteOk); } private void AddSpriteOk(Window callingWindow) { SpriteEditorSettings.EditingSprites = true; Sprite tempSprite = null; try { tempSprite = GameData.AddSprite(((FileWindow)callingWindow).Results[0], ""); WarnAboutNonPowerOfTwoTexture(tempSprite.Texture); } catch (InvalidDataException) { GuiManager.ShowMessageBox("Could not read " + ((FileWindow)callingWindow).Results[0] + ". Sprite not created.", "Error Creating Sprite"); return; } GuiData.ToolsWindow.paintButton.Unpress(); GameData.Cursor.ClickSprite(tempSprite); } public static void WarnAboutNonPowerOfTwoTexture(Texture2D texture) { if (texture != null && (!MathFunctions.IsPowerOfTwo(texture.Width) || !MathFunctions.IsPowerOfTwo(texture.Height))) { GuiManager.ShowMessageBox("The texture " + texture.Name + " has dimensions that are not a " + "power of two. They are " + texture.Width + " x " + texture.Height, "Texture not power of two"); } } private void AddUntexturedSprite(Window callingWindow) { Sprite tempSprite = GameData.AddSprite(null, "UntexturedSprite"); GuiData.ToolsWindow.paintButton.Unpress(); GameData.Cursor.ClickSprite(tempSprite); } private void MoveCameraToTheRight(string fileNameOfSpriteLoaded) { GameData.Camera.X += 2f; } private void AddSpriteFrameClick(Window callingWindow) { FileWindow tempFileWindow = GuiManager.AddFileWindow(); tempFileWindow.SetFileType("graphic and animation"); tempFileWindow.ShowLoadDirButton(); tempFileWindow.betweenLoadFolder += new BetweenLoadFolder(MoveCameraToTheRight); tempFileWindow.OkClick += new GuiMessage(this.AddSpriteFrameOk); } private void AddSpriteFrameOk(Window callingWindow) { string texture = ((FileWindow)callingWindow).Results[0]; SpriteFrame spriteFrame = GameData.AddSpriteFrame(texture); WarnAboutNonPowerOfTwoTexture(spriteFrame.Texture); } private void AddSpriteGridClick(Window callingWindow) { FileWindow tempFileWindow = GuiManager.AddFileWindow(); tempFileWindow.SetFileType("graphic"); //tempFileWindow.ShowAddButton(); //tempFileWindow.ShowLoadDirButton(); //tempFileWindow.betweenLoadFolder += new BetweenLoadFolder(MoveCameraToTheRight); tempFileWindow.OkClick += new GuiMessage(this.AddSpriteGridOk); } private void AddSpriteGridOk(Window callingWindow) { string textureFileName = ((FileWindow)callingWindow).Results[0]; GameData.AddSpriteGrid(textureFileName); } private void AddTextClick(Window callingWindow) { SpriteEditorSettings.EditingTexts = true; Text newText = GameData.CreateText(); } #endregion #region Performance void MakeAllSpriteGridsCreateParticleSpriteClick(Window callingWindow) { int numberConverted = 0; for (int i = 0; i < GameData.Scene.SpriteGrids.Count; i++) { SpriteGrid spriteGrid = GameData.Scene.SpriteGrids[i]; if (!spriteGrid.CreatesParticleSprites) { spriteGrid.CreatesParticleSprites = true; numberConverted++; } } GuiManager.ShowMessageBox("Converted " + numberConverted + " SpriteGrids", "Conversion Complete"); } #endregion #region Window events private void ShowCameraBounds(Window callingWindow) { GuiData.CameraBoundsPropertyGrid.Visible = true; GuiManager.BringToFront(GuiData.CameraBoundsPropertyGrid); GuiData.CameraBoundsPropertyGrid.UpdateDisplayedProperties(); } private void toggleCameraPropertiesVisibility(Window callingWindow) { GuiData.CameraPropertyGrid.Visible = true; GuiManager.BringToFront(GuiData.CameraPropertyGrid); } private void toggleEditorPropertiesVisibility(Window callingWindow) { GuiData.EditorPropertiesGrid.Visible = true; GuiManager.BringToFront(GuiData.EditorPropertiesGrid); } private void toggleSceneColorOperationVisibility(Window callingWindow) { /* GameData.guiData.sceneColorOperationWindow.Visible = GameData.guiData.sceneColorOperationWindowVisibility.IsPressed; GuiManager.BringToFront(GameData.guiData.sceneColorOperationWindow); */ } private void toggleSpriteListVisibility(Window callingWindow) { GuiData.ListWindow.Visible = true; GuiManager.BringToFront(GuiData.ListWindow); } private void toggleToolsVisibility(Window callingWindow) { GuiData.ToolsWindow.Visible = true; GuiManager.BringToFront(GuiData.ToolsWindow); } //private void ToggleAttributesVisibility(Window callingWindow) //{ // GuiData.AttributesWindow.Visible = true; //} #endregion #endregion #region Methods #region Constructor public MenuStrip() : base(GuiManager.Cursor) { GuiManager.AddWindow(this); MenuItem menuItem = null; MenuItem subMenuItem = null; #region File menuItem = AddItem("File"); menuItem.AddItem("New Scene").Click += NewSceneClick; menuItem.AddItem("---------------------"); menuItem.AddItem("Load Scene").Click += LoadSceneClick; menuItem.AddItem("Load SpriteRig").Click += LoadSpriteRigClick; menuItem.AddItem("Load Shape Collection").Click += LoadShapeCollectionClick; menuItem.AddItem("---------------------"); menuItem.AddItem("Save Scene Ctrl+S").Click += SaveSceneClick; menuItem.AddItem("Save Scene As...").Click += SaveSceneAs_Click; menuItem.AddItem("Save SpriteRig").Click += FileButtonWindow.SaveSpriteRigClick; #endregion #region Edit menuItem = AddItem("Edit"); menuItem.AddItem("Delete Selected").Click += DeleteSelected; menuItem.AddItem("---------------"); menuItem.AddItem("Shift Scene").Click += ShiftSceneClick; MenuItem scaleScene = menuItem.AddItem("Scale Scene->"); scaleScene.AddItem("Position Only").Click += new GuiMessage(ScalePositionOnly); scaleScene.AddItem("Position and Scale").Click += new GuiMessage(ScalePositionAndScaleOnly); #endregion #region Add menuItem = AddItem("Add"); subMenuItem = menuItem.AddItem("Sprite ->"); subMenuItem.AddItem("From File...").Click += AddSpriteClick; subMenuItem.AddItem("Untextured").Click += AddUntexturedSprite; menuItem.AddItem("SpriteGrid").Click += AddSpriteGridClick; menuItem.AddItem("SpriteFrame").Click += AddSpriteFrameClick; menuItem.AddItem("Text").Click += AddTextClick; menuItem.AddItem("Texture").Click += FileButtonWindow.openFileWindowLoadTexture; // We no longer support adding raw AnimationChains - this was confusing // to users and not really useful // menuItem.AddItem("Animation Chains").Click += AddAnimationChainClick; #endregion #region Performance menuItem = AddItem("Performance"); menuItem.AddItem("Make all SpriteGrids CreateParticleSprite").Click += MakeAllSpriteGridsCreateParticleSpriteClick; #endregion #region Window menuItem = AddItem("Window"); menuItem.AddItem("Tools").Click += toggleToolsVisibility; menuItem.AddItem("List Box").Click += toggleSpriteListVisibility; menuItem.AddItem("Camera Properties").Click += toggleCameraPropertiesVisibility; menuItem.AddItem("Camera Bounds").Click += ShowCameraBounds; menuItem.AddItem("Editor Properties").Click += toggleEditorPropertiesVisibility; menuItem.AddItem("Show Undos").Click += UndoManager.ShowListDisplayWindow; //menuItem.AddItem("Attributes").Click += ToggleAttributesVisibility; #endregion } #endregion #region Private Methods private void CheckForExtraFiles(string fileLoaded) { #region Try loading the .sep file try { if (System.IO.File.Exists(FileManager.RemoveExtension(fileLoaded) + ".sep")) { GameData.SpriteEditorSceneProperties = SpriteEditorSceneProperties.Load(FileManager.RemoveExtension(fileLoaded) + ".sep"); SpriteEditorSceneProperties sesp = GameData.SpriteEditorSceneProperties; if (sesp != null) { string directory = FileManager.GetDirectory(fileLoaded); sesp.SetCameras(GameData.Camera, GameData.BoundsCamera); GameData.EditorProperties.WorldAxesDisplayVisible = sesp.WorldAxesVisible; GameData.EditorProperties.PixelSize = sesp.PixelSize; if (sesp.BoundsVisible) { GuiData.CameraBoundsPropertyGrid.Visible = true; } // add the textures from the SpriteEditorSceneProperties if (sesp.TextureDisplayRegionsList != null) { foreach (TextureDisplayRegionsSave textureReference in sesp.TextureDisplayRegionsList) { string fileName = directory + textureReference.TextureName; if (System.IO.File.Exists(fileName)) { Texture2D texture = FlatRedBallServices.Load<Texture2D>(fileName, GameData.SceneContentManager); foreach (DisplayRegion displayRegion in textureReference.DisplayRegions) { GuiData.ListWindow.AddDisplayRegion(displayRegion, texture); } } } } } } } catch { // do nothing, it's ok. } #endregion } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Waypoint = System.Collections.Generic.KeyValuePair<HalmaShared.HexCoord, HalmaShared.GameBoard.WaypointInfo>; namespace HalmaShared { public static class GameBoardEnumExtensions { public static bool IsStar(this GameBoard.Configuration config) { return true; } public static int NumPlayers(this GameBoard.Configuration config) { switch (config) { case GameBoard.Configuration.STAR_2: return 2; case GameBoard.Configuration.STAR_3: return 3; case GameBoard.Configuration.STAR_4: return 4; case GameBoard.Configuration.STAR_6: return 6; default: throw new NotImplementedException(); } } public static GameBoard.Configuration ConfigFromPlayerCount(int numPlayers) { switch (numPlayers) { case 2: return GameBoard.Configuration.STAR_2; case 3: return GameBoard.Configuration.STAR_3; case 4: return GameBoard.Configuration.STAR_4; case 6: return GameBoard.Configuration.STAR_6; default: throw new NotImplementedException(); } } /// <summary> /// Returns for which player the given FieldType is a goal. /// </summary> /// <param name="fieldType"></param> /// <returns></returns> public static int GetPlayerGoal(this GameBoard.FieldType fieldType) { return (int)fieldType - (int)GameBoard.FieldType.PlayerGoal0; } } public class GameBoard { public enum Configuration { /// <summary> /// Classic chinese checkers with 2 players. /// </summary> STAR_2, /// <summary> /// Classic chinese checkers with 3 players. /// </summary> STAR_3, /// <summary> /// Classic chinese checkers with 4 players. Two players paired /// </summary> STAR_4, /// <summary> /// Classic chinese checkers with all 6 players. /// </summary> STAR_6, } /// <summary> /// Map configuration. May be used for specific/optimized drawing and AI. /// </summary> public Configuration Config { get; private set; } public enum FieldType { Invalid = -2, Normal = -1, PlayerGoal0, PlayerGoal1, PlayerGoal2, PlayerGoal3, PlayerGoal4, PlayerGoal5, } public struct Field { /// <summary> /// Index of the player who has a piece on the field. /// </summary> public int PlayerPiece; /// <summary> /// Type of the field. /// </summary> public FieldType Type; } private readonly Dictionary<HexCoord, Field> fields = new Dictionary<HexCoord, Field>(); public TurnHistory TurnHistory { get; private set; } public GameBoard(Configuration config) { Config = config; TurnHistory = new TurnHistory(this); // Config determines fields per direction. int coreSize = 4; Field[] dirField; switch (Config) { case Configuration.STAR_2: dirField = new Field[6] { new Field {Type = FieldType.Normal, PlayerPiece = -1}, new Field {Type = FieldType.PlayerGoal1, PlayerPiece = 0}, // Top new Field {Type = FieldType.Normal, PlayerPiece = -1}, new Field {Type = FieldType.Normal, PlayerPiece = -1}, new Field {Type = FieldType.PlayerGoal0, PlayerPiece = 1}, // Bottom new Field {Type = FieldType.Normal, PlayerPiece = -1} }; break; case Configuration.STAR_3: dirField = new Field[6] { new Field {Type = FieldType.Normal, PlayerPiece = 2}, new Field {Type = FieldType.PlayerGoal0, PlayerPiece = -1}, new Field {Type = FieldType.Normal, PlayerPiece = 1}, new Field {Type = FieldType.PlayerGoal2, PlayerPiece = -1}, new Field {Type = FieldType.Normal, PlayerPiece = 0}, new Field {Type = FieldType.PlayerGoal1, PlayerPiece = -1} }; break; case Configuration.STAR_4: dirField = new Field[6] { new Field {Type = FieldType.Normal, PlayerPiece = -1}, new Field {Type = FieldType.PlayerGoal0, PlayerPiece = 2}, new Field {Type = FieldType.PlayerGoal1, PlayerPiece = 3}, new Field {Type = FieldType.Normal, PlayerPiece = -1}, new Field {Type = FieldType.PlayerGoal2, PlayerPiece = 0}, new Field {Type = FieldType.PlayerGoal3, PlayerPiece = 1} }; break; case Configuration.STAR_6: dirField = new Field[6] { new Field {Type = FieldType.PlayerGoal4, PlayerPiece = 1}, new Field {Type = FieldType.PlayerGoal5, PlayerPiece = 2}, new Field {Type = FieldType.PlayerGoal0, PlayerPiece = 3}, new Field {Type = FieldType.PlayerGoal1, PlayerPiece = 4}, new Field {Type = FieldType.PlayerGoal2, PlayerPiece = 5}, new Field {Type = FieldType.PlayerGoal3, PlayerPiece = 0} }; break; default: throw new NotImplementedException(); } // Mostly empty hexagon core. for (int r = -coreSize; r <= coreSize; ++r) { int endQ = coreSize - Math.Max(r, 0); int startQ = -coreSize - Math.Min(r, 0); for (int q = startQ; q <= endQ; ++q) { var coord = new HexCoord(q, r); var field = new Field { Type = FieldType.Normal, PlayerPiece = -1 }; // Extra players in the core vary. // (Code not optimal, but readability is more important for this piece of init code!) if (coord.Length == coreSize) { switch (Config) { case Configuration.STAR_2: if (coord.Z == -coreSize) field = dirField[(int)HexCoord.Direction.NorthEast]; else if (coord.Z == coreSize) field = dirField[(int)HexCoord.Direction.SouthWest]; break; case Configuration.STAR_3: if (coord.Z == coreSize) field.PlayerPiece = dirField[(int)HexCoord.Direction.SouthWest].PlayerPiece; if (coord.Z == -coreSize) field.Type = dirField[(int)HexCoord.Direction.NorthEast].Type; if (coord.X == coreSize) field.PlayerPiece = dirField[(int)HexCoord.Direction.East].PlayerPiece; if (coord.X == -coreSize) field.Type = dirField[(int)HexCoord.Direction.West].Type; if (coord.Y == coreSize) field.PlayerPiece = dirField[(int)HexCoord.Direction.NorthWest].PlayerPiece; if (coord.Y == -coreSize) field.Type = dirField[(int)HexCoord.Direction.SouthEast].Type; break; case Configuration.STAR_4: if (coord.Y != -coord.Z) { if (coord.Z == -coreSize) field = dirField[(int)HexCoord.Direction.NorthEast]; else if (coord.Z == coreSize) field = dirField[(int)HexCoord.Direction.SouthWest]; else if (coord.Y == -coreSize) field = dirField[(int)HexCoord.Direction.SouthEast]; else if (coord.Y == coreSize) field = dirField[(int)HexCoord.Direction.NorthWest]; } break; case Configuration.STAR_6: break; default: throw new NotImplementedException(); } } fields.Add(coord, field); } } // Pikes for (int dir = 0; dir < 6; ++dir) { HexCoord dirA = HexCoord.Directions[dir]; HexCoord dirB = HexCoord.Directions[(dir + 2) % 6]; HexCoord current = dirA * (coreSize + 1); for (int a = 0; a <= coreSize; ++a) { HexCoord backup = current; for (int b = 0; b < coreSize - a; ++b) { current += dirB; fields.Add(current, dirField[dir]); } current = backup + dirA + dirB; } } // Sanity check for board setup. #if DEBUG int[] playerPieceCount = new int[6]; int[] playerGoalCount = new int[6]; foreach (Field f in fields.Values) { System.Diagnostics.Debug.Assert(f.PlayerPiece < 6); if (f.PlayerPiece >= 0) ++playerPieceCount[f.PlayerPiece]; if (f.Type.GetPlayerGoal() >= 0) ++playerGoalCount[f.Type.GetPlayerGoal()]; } for(int i=0; i<6; ++i) { System.Diagnostics.Debug.Assert(playerGoalCount[i] == playerPieceCount[i]); } #endif } /// <summary> /// Check weather a given player has won. /// </summary> /// <returns>True if the current player has won.</returns> public bool HasPlayerWon(int currentPlayer) { foreach (Field field in fields.Values) { if (field.PlayerPiece == currentPlayer) { int playerGoal = field.Type.GetPlayerGoal(); if (playerGoal < 0 || playerGoal != currentPlayer) { return false; } } } return true; } /// <summary> /// Executes a given turn. Attention: Will execute even if the turn is illegal or meaningless.1 /// </summary> public void ExecuteTurn(Turn turn) { System.Diagnostics.Debug.Assert(turn.ValidateAndUpdateTurnSequence(this)); var fromBefore = this[turn.From]; var toBefore = this[turn.To]; this[turn.From] = new Field() { Type = fromBefore.Type, PlayerPiece = toBefore.PlayerPiece }; this[turn.To] = new Field() { Type = toBefore.Type, PlayerPiece = fromBefore.PlayerPiece }; TurnHistory.RecordTurn(turn); } /// <summary> /// FieldType access. /// </summary> /// <returns>Get: If coord does not exist, FieldType.Invalid is returned.</returns> public Field this[HexCoord hexcoord] { get { Field outField = new Field() {Type = FieldType.Invalid, PlayerPiece = -1}; fields.TryGetValue(hexcoord, out outField); return outField; } private set { System.Diagnostics.Debug.Assert(fields.ContainsKey(hexcoord), "There is no FieldType at given coordinate!"); fields[hexcoord] = value; } } public IEnumerable<KeyValuePair<HexCoord, Field>> GetFields() { return fields; } public IEnumerable<KeyValuePair<HexCoord, Field>> GetGoalFields() { return fields; } #region Path Finding public class WaypointInfo { public WaypointInfo(HexCoord position, WaypointInfo predecessor, int distanceToStart) { Position = position; Predecessor = predecessor; DistanceToStart = distanceToStart; } public void TryUpdatePredecessor(WaypointInfo predecessorCandidate) { if(predecessorCandidate.DistanceToStart < (Predecessor == null ? Predecessor.DistanceToStart : 0)) { Predecessor = predecessorCandidate; DistanceToStart = predecessorCandidate.DistanceToStart + 1; } } public HexCoord Position { get; set; } public WaypointInfo Predecessor { get; private set; } public int DistanceToStart { get; private set; } } /// <summary> /// Lists all fields that would be reachable for a piece starting from given coord. /// </summary> /// <returns></returns> public IEnumerable<HexCoord> GetReachableFields(HexCoord from) { return GetPossiblePaths(from).Select(x => x.Key); } public Dictionary<HexCoord, WaypointInfo> GetPossiblePaths(HexCoord from) { var visited = new Dictionary<HexCoord, WaypointInfo>(); // Technically not reachable, but we don't want to walk in circles during the search that comes next. var startWaypoint = new Waypoint(from, new WaypointInfo(from, null, 0)); visited.Add(startWaypoint.Key, startWaypoint.Value); // Add direct neighbors. for (int i = 0; i < 6; ++i) { HexCoord targetCoord = from + HexCoord.Directions[i]; Field targetField = this[targetCoord]; if (targetField.Type != FieldType.Invalid && targetField.PlayerPiece < 0) visited.Add(targetCoord, new WaypointInfo(targetCoord, startWaypoint.Value, 1)); } // Breath first search. var searchQueue = new Queue<Waypoint>(); searchQueue.Enqueue(startWaypoint); while (searchQueue.Count > 0) { Waypoint current = searchQueue.Dequeue(); // Check neighborhood. for (int i = 0; i < 6; ++i) { HexCoord targetCoord = current.Key + HexCoord.Directions[i]; Field targetField = this[targetCoord]; // Existing field with piece? if (targetField.Type != FieldType.Invalid && targetField.PlayerPiece >= 0) { targetCoord += HexCoord.Directions[i]; // Jump! targetField = this[targetCoord]; if (targetField.Type != FieldType.Invalid && targetField.PlayerPiece < 0) { WaypointInfo oldWaypoint = null; if (visited.TryGetValue(targetCoord, out oldWaypoint)) oldWaypoint.TryUpdatePredecessor(current.Value); else { Waypoint newWaypoint = new Waypoint(targetCoord, new WaypointInfo(targetCoord, current.Value, current.Value.DistanceToStart + 1)); visited.Add(newWaypoint.Key, newWaypoint.Value); searchQueue.Enqueue(newWaypoint); } } } } } return visited; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace ForumSystem.Services.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.IO; namespace ICSharpCode.SharpZipLib.Zip { // TODO: Sort out wether tagged data is useful and what a good implementation might look like. // Its just a sketch of an idea at the moment. /// <summary> /// ExtraData tagged value interface. /// </summary> public interface ITaggedData { /// <summary> /// Get the ID for this tagged data value. /// </summary> short TagID { get; } /// <summary> /// Set the contents of this instance from the data passed. /// </summary> /// <param name="data">The data to extract contents from.</param> /// <param name="offset">The offset to begin extracting data from.</param> /// <param name="count">The number of bytes to extract.</param> void SetData(byte[] data, int offset, int count); /// <summary> /// Get the data representing this instance. /// </summary> /// <returns>Returns the data for this instance.</returns> byte[] GetData(); } /// <summary> /// A raw binary tagged value /// </summary> public class RawTaggedData : ITaggedData { /// <summary> /// Initialise a new instance. /// </summary> /// <param name="tag">The tag ID.</param> public RawTaggedData(short tag) { _tag = tag; } #region ITaggedData Members /// <summary> /// Get the ID for this tagged data value. /// </summary> public short TagID { get { return _tag; } set { _tag = value; } } /// <summary> /// Set the data from the raw values provided. /// </summary> /// <param name="data">The raw data to extract values from.</param> /// <param name="offset">The index to start extracting values from.</param> /// <param name="count">The number of bytes available.</param> public void SetData(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException(nameof(data)); } _data = new byte[count]; Array.Copy(data, offset, _data, 0, count); } /// <summary> /// Get the binary data representing this instance. /// </summary> /// <returns>The raw binary data representing this instance.</returns> public byte[] GetData() { return _data; } #endregion /// <summary> /// Get /set the binary data representing this instance. /// </summary> /// <returns>The raw binary data representing this instance.</returns> public byte[] Data { get { return _data; } set { _data = value; } } #region Instance Fields /// <summary> /// The tag ID for this instance. /// </summary> short _tag; byte[] _data; #endregion } /// <summary> /// Class representing extended unix date time values. /// </summary> public class ExtendedUnixData : ITaggedData { /// <summary> /// Flags indicate which values are included in this instance. /// </summary> [Flags] public enum Flags : byte { /// <summary> /// The modification time is included /// </summary> ModificationTime = 0x01, /// <summary> /// The access time is included /// </summary> AccessTime = 0x02, /// <summary> /// The create time is included. /// </summary> CreateTime = 0x04, } #region ITaggedData Members /// <summary> /// Get the ID /// </summary> public short TagID { get { return 0x5455; } } /// <summary> /// Set the data from the raw values provided. /// </summary> /// <param name="data">The raw data to extract values from.</param> /// <param name="index">The index to start extracting values from.</param> /// <param name="count">The number of bytes available.</param> public void SetData(byte[] data, int index, int count) { using (MemoryStream ms = new MemoryStream(data, index, count, false)) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { // bit 0 if set, modification time is present // bit 1 if set, access time is present // bit 2 if set, creation time is present _flags = (Flags)helperStream.ReadByte(); if (((_flags & Flags.ModificationTime) != 0)) { int iTime = helperStream.ReadLEInt(); _modificationTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); // Central-header version is truncated after modification time if (count <= 5) return; } if ((_flags & Flags.AccessTime) != 0) { int iTime = helperStream.ReadLEInt(); _lastAccessTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); } if ((_flags & Flags.CreateTime) != 0) { int iTime = helperStream.ReadLEInt(); _createTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); } } } /// <summary> /// Get the binary data representing this instance. /// </summary> /// <returns>The raw binary data representing this instance.</returns> public byte[] GetData() { using (MemoryStream ms = new MemoryStream()) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.IsStreamOwner = false; helperStream.WriteByte((byte)_flags); // Flags if ((_flags & Flags.ModificationTime) != 0) { TimeSpan span = _modificationTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } if ((_flags & Flags.AccessTime) != 0) { TimeSpan span = _lastAccessTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } if ((_flags & Flags.CreateTime) != 0) { TimeSpan span = _createTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } return ms.ToArray(); } } #endregion /// <summary> /// Test a <see cref="DateTime"> value to see if is valid and can be represented here.</see> /// </summary> /// <param name="value">The <see cref="DateTime">value</see> to test.</param> /// <returns>Returns true if the value is valid and can be represented; false if not.</returns> /// <remarks>The standard Unix time is a signed integer data type, directly encoding the Unix time number, /// which is the number of seconds since 1970-01-01. /// Being 32 bits means the values here cover a range of about 136 years. /// The minimum representable time is 1901-12-13 20:45:52, /// and the maximum representable time is 2038-01-19 03:14:07. /// </remarks> public static bool IsValidValue(DateTime value) { return ((value >= new DateTime(1901, 12, 13, 20, 45, 52)) || (value <= new DateTime(2038, 1, 19, 03, 14, 07))); } /// <summary> /// Get /set the Modification Time /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <seealso cref="IsValidValue"></seealso> public DateTime ModificationTime { get { return _modificationTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException(nameof(value)); } _flags |= Flags.ModificationTime; _modificationTime = value; } } /// <summary> /// Get / set the Access Time /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <seealso cref="IsValidValue"></seealso> public DateTime AccessTime { get { return _lastAccessTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException(nameof(value)); } _flags |= Flags.AccessTime; _lastAccessTime = value; } } /// <summary> /// Get / Set the Create Time /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <seealso cref="IsValidValue"></seealso> public DateTime CreateTime { get { return _createTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException(nameof(value)); } _flags |= Flags.CreateTime; _createTime = value; } } /// <summary> /// Get/set the <see cref="Flags">values</see> to include. /// </summary> public Flags Include { get { return _flags; } set { _flags = value; } } #region Instance Fields Flags _flags; DateTime _modificationTime = new DateTime(1970, 1, 1); DateTime _lastAccessTime = new DateTime(1970, 1, 1); DateTime _createTime = new DateTime(1970, 1, 1); #endregion } /// <summary> /// Class handling NT date time values. /// </summary> public class NTTaggedData : ITaggedData { /// <summary> /// Get the ID for this tagged data value. /// </summary> public short TagID { get { return 10; } } /// <summary> /// Set the data from the raw values provided. /// </summary> /// <param name="data">The raw data to extract values from.</param> /// <param name="index">The index to start extracting values from.</param> /// <param name="count">The number of bytes available.</param> public void SetData(byte[] data, int index, int count) { using (MemoryStream ms = new MemoryStream(data, index, count, false)) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.ReadLEInt(); // Reserved while (helperStream.Position < helperStream.Length) { int ntfsTag = helperStream.ReadLEShort(); int ntfsLength = helperStream.ReadLEShort(); if (ntfsTag == 1) { if (ntfsLength >= 24) { long lastModificationTicks = helperStream.ReadLELong(); _lastModificationTime = DateTime.FromFileTimeUtc(lastModificationTicks); long lastAccessTicks = helperStream.ReadLELong(); _lastAccessTime = DateTime.FromFileTimeUtc(lastAccessTicks); long createTimeTicks = helperStream.ReadLELong(); _createTime = DateTime.FromFileTimeUtc(createTimeTicks); } break; } else { // An unknown NTFS tag so simply skip it. helperStream.Seek(ntfsLength, SeekOrigin.Current); } } } } /// <summary> /// Get the binary data representing this instance. /// </summary> /// <returns>The raw binary data representing this instance.</returns> public byte[] GetData() { using (MemoryStream ms = new MemoryStream()) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.IsStreamOwner = false; helperStream.WriteLEInt(0); // Reserved helperStream.WriteLEShort(1); // Tag helperStream.WriteLEShort(24); // Length = 3 x 8. helperStream.WriteLELong(_lastModificationTime.ToFileTimeUtc()); helperStream.WriteLELong(_lastAccessTime.ToFileTimeUtc()); helperStream.WriteLELong(_createTime.ToFileTimeUtc()); return ms.ToArray(); } } /// <summary> /// Test a <see cref="DateTime"> valuie to see if is valid and can be represented here.</see> /// </summary> /// <param name="value">The <see cref="DateTime">value</see> to test.</param> /// <returns>Returns true if the value is valid and can be represented; false if not.</returns> /// <remarks> /// NTFS filetimes are 64-bit unsigned integers, stored in Intel /// (least significant byte first) byte order. They determine the /// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch", /// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit /// </remarks> public static bool IsValidValue(DateTime value) { bool result = true; try { value.ToFileTimeUtc(); } catch { result = false; } return result; } /// <summary> /// Get/set the <see cref="DateTime">last modification time</see>. /// </summary> public DateTime LastModificationTime { get { return _lastModificationTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException(nameof(value)); } _lastModificationTime = value; } } /// <summary> /// Get /set the <see cref="DateTime">create time</see> /// </summary> public DateTime CreateTime { get { return _createTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException(nameof(value)); } _createTime = value; } } /// <summary> /// Get /set the <see cref="DateTime">last access time</see>. /// </summary> public DateTime LastAccessTime { get { return _lastAccessTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException(nameof(value)); } _lastAccessTime = value; } } #region Instance Fields DateTime _lastAccessTime = DateTime.FromFileTimeUtc(0); DateTime _lastModificationTime = DateTime.FromFileTimeUtc(0); DateTime _createTime = DateTime.FromFileTimeUtc(0); #endregion } /// <summary> /// A factory that creates <see cref="ITaggedData">tagged data</see> instances. /// </summary> interface ITaggedDataFactory { /// <summary> /// Get data for a specific tag value. /// </summary> /// <param name="tag">The tag ID to find.</param> /// <param name="data">The data to search.</param> /// <param name="offset">The offset to begin extracting data from.</param> /// <param name="count">The number of bytes to extract.</param> /// <returns>The located <see cref="ITaggedData">value found</see>, or null if not found.</returns> ITaggedData Create(short tag, byte[] data, int offset, int count); } /// /// <summary> /// A class to handle the extra data field for Zip entries /// </summary> /// <remarks> /// Extra data contains 0 or more values each prefixed by a header tag and length. /// They contain zero or more bytes of actual data. /// The data is held internally using a copy on write strategy. This is more efficient but /// means that for extra data created by passing in data can have the values modified by the caller /// in some circumstances. /// </remarks> sealed public class ZipExtraData : IDisposable { #region Constructors /// <summary> /// Initialise a default instance. /// </summary> public ZipExtraData() { Clear(); } /// <summary> /// Initialise with known extra data. /// </summary> /// <param name="data">The extra data.</param> public ZipExtraData(byte[] data) { if (data == null) { _data = new byte[0]; } else { _data = data; } } #endregion /// <summary> /// Get the raw extra data value /// </summary> /// <returns>Returns the raw byte[] extra data this instance represents.</returns> public byte[] GetEntryData() { if (Length > ushort.MaxValue) { throw new ZipException("Data exceeds maximum length"); } return (byte[])_data.Clone(); } /// <summary> /// Clear the stored data. /// </summary> public void Clear() { if ((_data == null) || (_data.Length != 0)) { _data = new byte[0]; } } /// <summary> /// Gets the current extra data length. /// </summary> public int Length { get { return _data.Length; } } /// <summary> /// Get a read-only <see cref="Stream"/> for the associated tag. /// </summary> /// <param name="tag">The tag to locate data for.</param> /// <returns>Returns a <see cref="Stream"/> containing tag data or null if no tag was found.</returns> public Stream GetStreamForTag(int tag) { Stream result = null; if (Find(tag)) { result = new MemoryStream(_data, _index, _readValueLength, false); } return result; } /// <summary> /// Get the <see cref="ITaggedData">tagged data</see> for a tag. /// </summary> /// <typeparam name="T">The tag to search for.</typeparam> /// <returns>Returns a <see cref="ITaggedData">tagged value</see> or null if none found.</returns> public T GetData<T>() where T : class, ITaggedData, new() { T result = new T(); if (Find(result.TagID)) { result.SetData(_data, _readValueStart, _readValueLength); return result; } else return null; } /// <summary> /// Get the length of the last value found by <see cref="Find"/> /// </summary> /// <remarks>This is only valid if <see cref="Find"/> has previously returned true.</remarks> public int ValueLength { get { return _readValueLength; } } /// <summary> /// Get the index for the current read value. /// </summary> /// <remarks>This is only valid if <see cref="Find"/> has previously returned true. /// Initially the result will be the index of the first byte of actual data. The value is updated after calls to /// <see cref="ReadInt"/>, <see cref="ReadShort"/> and <see cref="ReadLong"/>. </remarks> public int CurrentReadIndex { get { return _index; } } /// <summary> /// Get the number of bytes remaining to be read for the current value; /// </summary> public int UnreadCount { get { if ((_readValueStart > _data.Length) || (_readValueStart < 4)) { throw new ZipException("Find must be called before calling a Read method"); } return _readValueStart + _readValueLength - _index; } } /// <summary> /// Find an extra data value /// </summary> /// <param name="headerID">The identifier for the value to find.</param> /// <returns>Returns true if the value was found; false otherwise.</returns> public bool Find(int headerID) { _readValueStart = _data.Length; _readValueLength = 0; _index = 0; int localLength = _readValueStart; int localTag = headerID - 1; // Trailing bytes that cant make up an entry (as there arent enough // bytes for a tag and length) are ignored! while ((localTag != headerID) && (_index < _data.Length - 3)) { localTag = ReadShortInternal(); localLength = ReadShortInternal(); if (localTag != headerID) { _index += localLength; } } bool result = (localTag == headerID) && ((_index + localLength) <= _data.Length); if (result) { _readValueStart = _index; _readValueLength = localLength; } return result; } /// <summary> /// Add a new entry to extra data. /// </summary> /// <param name="taggedData">The <see cref="ITaggedData"/> value to add.</param> public void AddEntry(ITaggedData taggedData) { if (taggedData == null) { throw new ArgumentNullException(nameof(taggedData)); } AddEntry(taggedData.TagID, taggedData.GetData()); } /// <summary> /// Add a new entry to extra data /// </summary> /// <param name="headerID">The ID for this entry.</param> /// <param name="fieldData">The data to add.</param> /// <remarks>If the ID already exists its contents are replaced.</remarks> public void AddEntry(int headerID, byte[] fieldData) { if ((headerID > ushort.MaxValue) || (headerID < 0)) { throw new ArgumentOutOfRangeException(nameof(headerID)); } int addLength = (fieldData == null) ? 0 : fieldData.Length; if (addLength > ushort.MaxValue) { throw new ArgumentOutOfRangeException(nameof(fieldData), "exceeds maximum length"); } // Test for new length before adjusting data. int newLength = _data.Length + addLength + 4; if (Find(headerID)) { newLength -= (ValueLength + 4); } if (newLength > ushort.MaxValue) { throw new ZipException("Data exceeds maximum length"); } Delete(headerID); byte[] newData = new byte[newLength]; _data.CopyTo(newData, 0); int index = _data.Length; _data = newData; SetShort(ref index, headerID); SetShort(ref index, addLength); if (fieldData != null) { fieldData.CopyTo(newData, index); } } /// <summary> /// Start adding a new entry. /// </summary> /// <remarks>Add data using <see cref="AddData(byte[])"/>, <see cref="AddLeShort"/>, <see cref="AddLeInt"/>, or <see cref="AddLeLong"/>. /// The new entry is completed and actually added by calling <see cref="AddNewEntry"/></remarks> /// <seealso cref="AddEntry(ITaggedData)"/> public void StartNewEntry() { _newEntry = new MemoryStream(); } /// <summary> /// Add entry data added since <see cref="StartNewEntry"/> using the ID passed. /// </summary> /// <param name="headerID">The identifier to use for this entry.</param> public void AddNewEntry(int headerID) { byte[] newData = _newEntry.ToArray(); _newEntry = null; AddEntry(headerID, newData); } /// <summary> /// Add a byte of data to the pending new entry. /// </summary> /// <param name="data">The byte to add.</param> /// <seealso cref="StartNewEntry"/> public void AddData(byte data) { _newEntry.WriteByte(data); } /// <summary> /// Add data to a pending new entry. /// </summary> /// <param name="data">The data to add.</param> /// <seealso cref="StartNewEntry"/> public void AddData(byte[] data) { if (data == null) { throw new ArgumentNullException(nameof(data)); } _newEntry.Write(data, 0, data.Length); } /// <summary> /// Add a short value in little endian order to the pending new entry. /// </summary> /// <param name="toAdd">The data to add.</param> /// <seealso cref="StartNewEntry"/> public void AddLeShort(int toAdd) { unchecked { _newEntry.WriteByte((byte)toAdd); _newEntry.WriteByte((byte)(toAdd >> 8)); } } /// <summary> /// Add an integer value in little endian order to the pending new entry. /// </summary> /// <param name="toAdd">The data to add.</param> /// <seealso cref="StartNewEntry"/> public void AddLeInt(int toAdd) { unchecked { AddLeShort((short)toAdd); AddLeShort((short)(toAdd >> 16)); } } /// <summary> /// Add a long value in little endian order to the pending new entry. /// </summary> /// <param name="toAdd">The data to add.</param> /// <seealso cref="StartNewEntry"/> public void AddLeLong(long toAdd) { unchecked { AddLeInt((int)(toAdd & 0xffffffff)); AddLeInt((int)(toAdd >> 32)); } } /// <summary> /// Delete an extra data field. /// </summary> /// <param name="headerID">The identifier of the field to delete.</param> /// <returns>Returns true if the field was found and deleted.</returns> public bool Delete(int headerID) { bool result = false; if (Find(headerID)) { result = true; int trueStart = _readValueStart - 4; byte[] newData = new byte[_data.Length - (ValueLength + 4)]; Array.Copy(_data, 0, newData, 0, trueStart); int trueEnd = trueStart + ValueLength + 4; Array.Copy(_data, trueEnd, newData, trueStart, _data.Length - trueEnd); _data = newData; } return result; } #region Reading Support /// <summary> /// Read a long in little endian form from the last <see cref="Find">found</see> data value /// </summary> /// <returns>Returns the long value read.</returns> public long ReadLong() { ReadCheck(8); return (ReadInt() & 0xffffffff) | (((long)ReadInt()) << 32); } /// <summary> /// Read an integer in little endian form from the last <see cref="Find">found</see> data value. /// </summary> /// <returns>Returns the integer read.</returns> public int ReadInt() { ReadCheck(4); int result = _data[_index] + (_data[_index + 1] << 8) + (_data[_index + 2] << 16) + (_data[_index + 3] << 24); _index += 4; return result; } /// <summary> /// Read a short value in little endian form from the last <see cref="Find">found</see> data value. /// </summary> /// <returns>Returns the short value read.</returns> public int ReadShort() { ReadCheck(2); int result = _data[_index] + (_data[_index + 1] << 8); _index += 2; return result; } /// <summary> /// Read a byte from an extra data /// </summary> /// <returns>The byte value read or -1 if the end of data has been reached.</returns> public int ReadByte() { int result = -1; if ((_index < _data.Length) && (_readValueStart + _readValueLength > _index)) { result = _data[_index]; _index += 1; } return result; } /// <summary> /// Skip data during reading. /// </summary> /// <param name="amount">The number of bytes to skip.</param> public void Skip(int amount) { ReadCheck(amount); _index += amount; } void ReadCheck(int length) { if ((_readValueStart > _data.Length) || (_readValueStart < 4)) { throw new ZipException("Find must be called before calling a Read method"); } if (_index > _readValueStart + _readValueLength - length) { throw new ZipException("End of extra data"); } if (_index + length < 4) { throw new ZipException("Cannot read before start of tag"); } } /// <summary> /// Internal form of <see cref="ReadShort"/> that reads data at any location. /// </summary> /// <returns>Returns the short value read.</returns> int ReadShortInternal() { if (_index > _data.Length - 2) { throw new ZipException("End of extra data"); } int result = _data[_index] + (_data[_index + 1] << 8); _index += 2; return result; } void SetShort(ref int index, int source) { _data[index] = (byte)source; _data[index + 1] = (byte)(source >> 8); index += 2; } #endregion #region IDisposable Members /// <summary> /// Dispose of this instance. /// </summary> public void Dispose() { if (_newEntry != null) { _newEntry.Close(); } } #endregion #region Instance Fields int _index; int _readValueStart; int _readValueLength; MemoryStream _newEntry; byte[] _data; #endregion } }
using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using PartsUnlimited.Models; using System; using PartsUnlimited.Data; namespace PartsUnlimitedWebsite.Migrations { [ContextType(typeof(PartsUnlimitedContext))] public partial class InitialMigration : IMigrationMetadata { string IMigrationMetadata.MigrationId { get { return "201503130633247_InitialMigration"; } } string IMigrationMetadata.ProductVersion { get { return "7.0.0-beta3-12166"; } } IModel IMigrationMetadata.TargetModel { get { var builder = new BasicModelBuilder(); builder.Entity("Microsoft.AspNet.Identity.IdentityRole", b => { b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<string>("Id") .GenerateValueOnAdd(); b.Property<string>("Name"); b.Property<string>("NormalizedName"); b.Key("Id"); b.ForRelational().Table("AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<int>("Id") .GenerateValueOnAdd(); b.Property<string>("RoleId"); b.Key("Id"); b.ForRelational().Table("AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<int>("Id") .GenerateValueOnAdd(); b.Property<string>("UserId"); b.Key("Id"); b.ForRelational().Table("AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderDisplayName"); b.Property<string>("ProviderKey"); b.Property<string>("UserId"); b.Key("LoginProvider", "ProviderKey"); b.ForRelational().Table("AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.Property<string>("RoleId"); b.Property<string>("UserId"); b.Key("UserId", "RoleId"); b.ForRelational().Table("AspNetUserRoles"); }); builder.Entity("PartsUnlimited.Models.ApplicationUser", b => { b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<string>("Email"); b.Property<bool>("EmailConfirmed"); b.Property<string>("Id") .GenerateValueOnAdd(); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("Name"); b.Property<string>("NormalizedEmail"); b.Property<string>("NormalizedUserName"); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName"); b.Key("Id"); b.ForRelational().Table("AspNetUsers"); }); builder.Entity("PartsUnlimited.Models.CartItem", b => { b.Property<string>("CartId"); b.Property<int>("CartItemId") .GenerateValueOnAdd(); b.Property<int>("Count"); b.Property<DateTime>("DateCreated"); b.Property<int>("ProductId"); b.Key("CartItemId"); }); builder.Entity("PartsUnlimited.Models.Category", b => { b.Property<int>("CategoryId") .GenerateValueOnAdd(); b.Property<string>("Description"); b.Property<string>("Name"); b.Key("CategoryId"); }); builder.Entity("PartsUnlimited.Models.Order", b => { b.Property<string>("Address"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Email"); b.Property<string>("Name"); b.Property<DateTime>("OrderDate"); b.Property<int>("OrderId") .GenerateValueOnAdd(); b.Property<string>("Phone"); b.Property<string>("PostalCode"); b.Property<string>("State"); b.Property<decimal>("Total"); b.Property<string>("Username"); b.Key("OrderId"); }); builder.Entity("PartsUnlimited.Models.OrderDetail", b => { b.Property<int>("OrderDetailId") .GenerateValueOnAdd(); b.Property<int>("OrderId"); b.Property<int>("ProductId"); b.Property<int>("Quantity"); b.Property<decimal>("UnitPrice"); b.Key("OrderDetailId"); }); builder.Entity("PartsUnlimited.Models.Product", b => { b.Property<int>("CategoryId"); b.Property<DateTime>("Created"); b.Property<decimal>("Price"); b.Property<string>("ProductArtUrl"); b.Property<int>("ProductId") .GenerateValueOnAdd(); b.Property<decimal>("SalePrice"); b.Property<string>("Title"); b.Key("ProductId"); }); builder.Entity("PartsUnlimited.Models.Raincheck", b => { b.Property<string>("Name"); b.Property<int>("ProductId"); b.Property<int>("Quantity"); b.Property<int>("RaincheckId") .GenerateValueOnAdd(); b.Property<double>("SalePrice"); b.Property<int>("StoreId"); b.Key("RaincheckId"); }); builder.Entity("PartsUnlimited.Models.Store", b => { b.Property<string>("Name"); b.Property<int>("StoreId") .GenerateValueOnAdd(); b.Key("StoreId"); }); builder.Entity("Microsoft.AspNet.Identity.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.ForeignKey("Microsoft.AspNet.Identity.IdentityRole", "RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.ForeignKey("PartsUnlimited.Models.ApplicationUser", "UserId"); }); builder.Entity("Microsoft.AspNet.Identity.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.ForeignKey("PartsUnlimited.Models.ApplicationUser", "UserId"); }); builder.Entity("PartsUnlimited.Models.CartItem", b => { b.ForeignKey("PartsUnlimited.Models.Product", "ProductId"); }); builder.Entity("PartsUnlimited.Models.OrderDetail", b => { b.ForeignKey("PartsUnlimited.Models.Order", "OrderId"); b.ForeignKey("PartsUnlimited.Models.Product", "ProductId"); }); builder.Entity("PartsUnlimited.Models.Product", b => { b.ForeignKey("PartsUnlimited.Models.Category", "CategoryId"); }); builder.Entity("PartsUnlimited.Models.Raincheck", b => { b.ForeignKey("PartsUnlimited.Models.Store", "StoreId"); b.ForeignKey("PartsUnlimited.Models.Product", "ProductId"); }); return builder.Model; } } } }
/* * Qa full api * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: all * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HostMe.Sdk.Model { /// <summary> /// Reward /// </summary> [DataContract] public partial class Reward : IEquatable<Reward>, IValidatableObject { /// <summary> /// Gets or Sets Status /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum StatusEnum { /// <summary> /// Enum Published for "Published" /// </summary> [EnumMember(Value = "Published")] Published, /// <summary> /// Enum Unpublished for "Unpublished" /// </summary> [EnumMember(Value = "Unpublished")] Unpublished } /// <summary> /// Gets or Sets Status /// </summary> [DataMember(Name="status", EmitDefaultValue=true)] public StatusEnum? Status { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Reward" /> class. /// </summary> /// <param name="Conditions">Conditions.</param> /// <param name="Description">Description.</param> /// <param name="Id">Id.</param> /// <param name="ImageUrl">ImageUrl.</param> /// <param name="PriceInPoints">PriceInPoints.</param> /// <param name="Value">Value.</param> /// <param name="Status">Status.</param> public Reward(RewardConditions Conditions = null, string Description = null, string Id = null, string ImageUrl = null, double? PriceInPoints = null, RewardValue Value = null, StatusEnum? Status = null) { this.Conditions = Conditions; this.Description = Description; this.Id = Id; this.ImageUrl = ImageUrl; this.PriceInPoints = PriceInPoints; this.Value = Value; this.Status = Status; } /// <summary> /// Gets or Sets Conditions /// </summary> [DataMember(Name="conditions", EmitDefaultValue=true)] public RewardConditions Conditions { get; set; } /// <summary> /// Gets or Sets Description /// </summary> [DataMember(Name="description", EmitDefaultValue=true)] public string Description { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=true)] public string Id { get; set; } /// <summary> /// Gets or Sets ImageUrl /// </summary> [DataMember(Name="imageUrl", EmitDefaultValue=true)] public string ImageUrl { get; set; } /// <summary> /// Gets or Sets PriceInPoints /// </summary> [DataMember(Name="priceInPoints", EmitDefaultValue=true)] public double? PriceInPoints { get; set; } /// <summary> /// Gets or Sets Value /// </summary> [DataMember(Name="value", EmitDefaultValue=true)] public RewardValue Value { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Reward {\n"); sb.Append(" Conditions: ").Append(Conditions).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" ImageUrl: ").Append(ImageUrl).Append("\n"); sb.Append(" PriceInPoints: ").Append(PriceInPoints).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Reward); } /// <summary> /// Returns true if Reward instances are equal /// </summary> /// <param name="other">Instance of Reward to be compared</param> /// <returns>Boolean</returns> public bool Equals(Reward other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Conditions == other.Conditions || this.Conditions != null && this.Conditions.Equals(other.Conditions) ) && ( this.Description == other.Description || this.Description != null && this.Description.Equals(other.Description) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.ImageUrl == other.ImageUrl || this.ImageUrl != null && this.ImageUrl.Equals(other.ImageUrl) ) && ( this.PriceInPoints == other.PriceInPoints || this.PriceInPoints != null && this.PriceInPoints.Equals(other.PriceInPoints) ) && ( this.Value == other.Value || this.Value != null && this.Value.Equals(other.Value) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Conditions != null) hash = hash * 59 + this.Conditions.GetHashCode(); if (this.Description != null) hash = hash * 59 + this.Description.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.ImageUrl != null) hash = hash * 59 + this.ImageUrl.GetHashCode(); if (this.PriceInPoints != null) hash = hash * 59 + this.PriceInPoints.GetHashCode(); if (this.Value != null) hash = hash * 59 + this.Value.GetHashCode(); if (this.Status != null) hash = hash * 59 + this.Status.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using BayesSharp.Combiners; using BayesSharp.Tokenizers; using Newtonsoft.Json; namespace BayesSharp { public class BayesClassifier<TTokenType, TTagType> where TTagType : IComparable { private TagDictionary<TTokenType, TTagType> _tags = new TagDictionary<TTokenType, TTagType>(); private TagDictionary<TTokenType, TTagType> _cache; private readonly ITokenizer<TTokenType> _tokenizer; private readonly ICombiner _combiner; private bool _mustRecache; private const double Tolerance = 0.0001; private const double Threshold = 0.1; public BayesClassifier(ITokenizer<TTokenType> tokenizer) : this(tokenizer, new RobinsonCombiner()) { } public BayesClassifier(ITokenizer<TTokenType> tokenizer, ICombiner combiner) { if (tokenizer == null) throw new ArgumentNullException("tokenizer"); if (combiner == null) throw new ArgumentNullException("combiner"); _tokenizer = tokenizer; _combiner = combiner; _tags.SystemTag = new TagData<TTokenType>(); _mustRecache = true; } /// <summary> /// Create a new tag, without actually doing any training. /// </summary> /// <param name="tagId">Tag Id</param> public void AddTag(TTagType tagId) { GetAndAddIfNotFound(_tags.Items, tagId); _mustRecache = true; } /// <summary> /// Remove a tag /// </summary> /// <param name="tagId">Tag Id</param> public void RemoveTag(TTagType tagId) { _tags.Items.Remove(tagId); _mustRecache = true; } /// <summary> /// Change the Id of a tag /// </summary> /// <param name="oldTagId">Old Tag Id</param> /// <param name="newTagId">New Tag Id</param> public void ChangeTagId(TTagType oldTagId, TTagType newTagId) { _tags.Items[newTagId] = _tags.Items[oldTagId]; RemoveTag(oldTagId); _mustRecache = true; } /// <summary> /// Merge an existing tag into another /// </summary> /// <param name="sourceTagId">Tag to merged to destTagId and removed</param> /// <param name="destTagId">Destination tag Id</param> public void MergeTags(TTagType sourceTagId, TTagType destTagId) { var sourceTag = _tags.Items[sourceTagId]; var destTag = _tags.Items[destTagId]; var count = 0; foreach (var tagItem in sourceTag.Items) { count++; var tok = tagItem; if (destTag.Items.ContainsKey(tok.Key)) { destTag.Items[tok.Key] += count; } else { destTag.Items[tok.Key] = count; destTag.TokenCount += 1; } } RemoveTag(sourceTagId); _mustRecache = true; } /// <summary> /// Return a TagData object of a Tag Id informed /// </summary> /// <param name="tagId">Tag Id</param> public TagData<TTokenType> GetTagById(TTagType tagId) { return _tags.Items.ContainsKey(tagId) ? _tags.Items[tagId] : null; } /// <summary> /// Save Bayes Text Classifier into a file /// </summary> /// <param name="path">The file to write to</param> public void Save(string path) { using (var streamWriter = new StreamWriter(path, false, Encoding.UTF8)) { JsonSerializer.Create().Serialize(streamWriter, _tags); } } /// <summary> /// Load Bayes Text Classifier from a file /// </summary> /// <param name="path">The file to open for reading</param> public void Load(string path) { using (var streamReader = new StreamReader(path, Encoding.UTF8)) { using (var jsonTextReader = new JsonTextReader(streamReader)) { _tags = JsonSerializer.Create().Deserialize<TagDictionary<TTokenType, TTagType>>(jsonTextReader); } } _mustRecache = true; } /// <summary> /// Import Bayes Text Classifier from a json string /// </summary> /// <param name="json">The json content to be loaded</param> public void ImportJsonData(string json) { _tags = JsonConvert.DeserializeObject<TagDictionary<TTokenType, TTagType>>(json); _mustRecache = true; } /// <summary> /// Export Bayes Text Classifier to a json string /// </summary> public string ExportJsonData() { return JsonConvert.SerializeObject(_tags); } /// <summary> /// Return a sorted list of Tag Ids /// </summary> public IEnumerable<TTagType> TagIds() { return _tags.Items.Keys.OrderBy(p => p); } /// <summary> /// Train Bayes by telling him that input belongs in tag. /// </summary> /// <param name="tagId">Tag Id</param> /// <param name="input">Input to be trained</param> public void Train(TTagType tagId, string input) { var tokens = _tokenizer.Tokenize(input); var tag = GetAndAddIfNotFound(_tags.Items, tagId); _train(tag, tokens); _tags.SystemTag.TrainCount += 1; tag.TrainCount += 1; _mustRecache = true; } /// <summary> /// Untrain Bayes by telling him that input no more belongs in tag. /// </summary> /// <param name="tagId">Tag Id</param> /// <param name="input">Input to be untrained</param> public void Untrain(TTagType tagId, string input) { var tokens = _tokenizer.Tokenize(input); var tag = _tags.Items[tagId]; if (tag == null) { return; } _untrain(tag, tokens); _tags.SystemTag.TrainCount += 1; tag.TrainCount += 1; _mustRecache = true; } /// <summary> /// Returns the scores in each tag the provided input /// </summary> /// <param name="input">Input to be classified</param> public Dictionary<TTagType, double> Classify(string input) { var tokens = _tokenizer.Tokenize(input).ToList(); var tags = CreateCacheAnsGetTags(); var stats = new Dictionary<TTagType, double>(); foreach (var tag in tags.Items) { var probs = GetProbabilities(tag.Value, tokens).ToList(); if (probs.Count() != 0) { stats[tag.Key] = _combiner.Combine(probs); } } return stats.OrderByDescending(s => s.Value).ToDictionary(s => s.Key, pair => pair.Value); } #region Private Methods private void _train(TagData<TTokenType> tag, IEnumerable<TTokenType> tokens) { var tokenCount = 0; foreach (var token in tokens) { var count = tag.Get(token, 0); tag.Items[token] = count + 1; count = _tags.SystemTag.Get(token, 0); _tags.SystemTag.Items[token] = count + 1; tokenCount += 1; } tag.TokenCount += tokenCount; _tags.SystemTag.TokenCount += tokenCount; } private void _untrain(TagData<TTokenType> tag, IEnumerable<TTokenType> tokens) { foreach (var token in tokens) { var count = tag.Get(token, 0); if (count > 0) { if (Math.Abs(count - 1) < Tolerance) { tag.Items.Remove(token); } else { tag.Items[token] = count - 1; } tag.TokenCount -= 1; } count = _tags.SystemTag.Get(token, 0); if (count > 0) { if (Math.Abs(count - 1) < Tolerance) { _tags.SystemTag.Items.Remove(token); } else { _tags.SystemTag.Items[token] = count - 1; } _tags.SystemTag.TokenCount -= 1; } } } private static TagData<TTokenType> GetAndAddIfNotFound(IDictionary<TTagType, TagData<TTokenType>> dic, TTagType key) { if (dic.ContainsKey(key)) { return dic[key]; } dic[key] = new TagData<TTokenType>(); return dic[key]; } private TagDictionary<TTokenType, TTagType> CreateCacheAnsGetTags() { if (!_mustRecache) return _cache; _cache = new TagDictionary<TTokenType, TTagType> { SystemTag = _tags.SystemTag }; foreach (var tag in _tags.Items) { var thisTagTokenCount = tag.Value.TokenCount; var otherTagsTokenCount = Math.Max(_tags.SystemTag.TokenCount - thisTagTokenCount, 1); var cachedTag = GetAndAddIfNotFound(_cache.Items, tag.Key); foreach (var systemTagItem in _tags.SystemTag.Items) { var thisTagTokenFreq = tag.Value.Get(systemTagItem.Key, 0.0); if (Math.Abs(thisTagTokenFreq) < Tolerance) { continue; } var otherTagsTokenFreq = systemTagItem.Value - thisTagTokenFreq; var goodMetric = thisTagTokenCount == 0 ? 1.0 : Math.Min(1.0, otherTagsTokenFreq / thisTagTokenCount); var badMetric = Math.Min(1.0, thisTagTokenFreq / otherTagsTokenCount); var f = badMetric / (goodMetric + badMetric); if (Math.Abs(f - 0.5) >= Threshold) { cachedTag.Items[systemTagItem.Key] = Math.Max(Tolerance, Math.Min(1 - Tolerance, f)); } } } _mustRecache = false; return _cache; } private static IEnumerable<double> GetProbabilities(TagData<TTokenType> tag, IEnumerable<TTokenType> tokens) { var probs = tokens.Where(tag.Items.ContainsKey).Select(t => tag.Items[t]); return probs.OrderByDescending(p => p).Take(2048); } #endregion } }
using System; using HalconDotNet; namespace ViewROI { /// <summary> /// This class implements an ROI shaped as a circular /// arc. ROICircularArc inherits from the base class ROI and /// implements (besides other auxiliary methods) all virtual methods /// defined in ROI.cs. /// </summary> public class ROICircularArc : ROI { //handles private double midR, midC; // 0. handle: midpoint private double sizeR, sizeC; // 1. handle private double startR, startC; // 2. handle private double extentR, extentC; // 3. handle //model data to specify the arc private double radius; private double startPhi, extentPhi; // -2*PI <= x <= 2*PI //display attributes private HXLDCont contour; private HXLDCont arrowHandleXLD; private string circDir; private double TwoPI; private double PI; public ROICircularArc() { NumHandles = 4; // midpoint handle + three handles on the arc activeHandleIdx = 0; contour = new HXLDCont(); circDir = ""; TwoPI = 2 * Math.PI; PI = Math.PI; arrowHandleXLD = new HXLDCont(); arrowHandleXLD.GenEmptyObj(); } /// <summary>Creates a new ROI instance at the mouse position</summary> public override void createROI(double midX, double midY) { midR = midY; midC = midX; radius = 100; sizeR = midR; sizeC = midC - radius; startPhi = PI * 0.25; extentPhi = PI * 1.5; circDir = "positive"; determineArcHandles(); updateArrowHandle(); } /// <summary>Paints the ROI into the supplied window</summary> /// <param name="window">HALCON window</param> public override void draw(HalconDotNet.HWindow window) { contour.Dispose(); contour.GenCircleContourXld(midR, midC, radius, startPhi, (startPhi + extentPhi), circDir, 1.0); window.DispObj(contour); window.DispRectangle2(sizeR, sizeC, 0, 5, 5); window.DispRectangle2(midR, midC, 0, 5, 5); window.DispRectangle2(startR, startC, startPhi, 10, 2); window.DispObj(arrowHandleXLD); } /// <summary> /// Returns the distance of the ROI handle being /// closest to the image point(x,y) /// </summary> public override double distToClosestHandle(double x, double y) { double max = 10000; double [] val = new double[NumHandles]; val[0] = HMisc.DistancePp(y, x, midR, midC); // midpoint val[1] = HMisc.DistancePp(y, x, sizeR, sizeC); // border handle val[2] = HMisc.DistancePp(y, x, startR, startC); // border handle val[3] = HMisc.DistancePp(y, x, extentR, extentC); // border handle for (int i=0; i < NumHandles; i++) { if (val[i] < max) { max = val[i]; activeHandleIdx = i; } }// end of for return val[activeHandleIdx]; } /// <summary> /// Paints the active handle of the ROI object into the supplied window /// </summary> public override void displayActive(HalconDotNet.HWindow window) { switch (activeHandleIdx) { case 0: window.DispRectangle2(midR, midC, 0, 5, 5); break; case 1: window.DispRectangle2(sizeR, sizeC, 0, 5, 5); break; case 2: window.DispRectangle2(startR, startC, startPhi, 10, 2); break; case 3: window.DispObj(arrowHandleXLD); break; } } /// <summary> /// Recalculates the shape of the ROI. Translation is /// performed at the active handle of the ROI object /// for the image coordinate (x,y) /// </summary> public override void moveByHandle(double newX, double newY) { HTuple distance; double dirX, dirY, prior, next, valMax, valMin; switch (activeHandleIdx) { case 0: // midpoint dirY = midR - newY; dirX = midC - newX; midR = newY; midC = newX; sizeR -= dirY; sizeC -= dirX; determineArcHandles(); break; case 1: // handle at circle border sizeR = newY; sizeC = newX; HOperatorSet.DistancePp(new HTuple(sizeR), new HTuple(sizeC), new HTuple(midR), new HTuple(midC), out distance); radius = distance[0].D; determineArcHandles(); break; case 2: // start handle for arc dirY = newY - midR; dirX = newX - midC; startPhi = Math.Atan2(-dirY, dirX); if (startPhi < 0) startPhi = PI + (startPhi + PI); setStartHandle(); prior = extentPhi; extentPhi = HMisc.AngleLl(midR, midC, startR, startC, midR, midC, extentR, extentC); if (extentPhi < 0 && prior > PI * 0.8) extentPhi = (PI + extentPhi) + PI; else if (extentPhi > 0 && prior < -PI * 0.7) extentPhi = -PI - (PI - extentPhi); break; case 3: // end handle for arc dirY = newY - midR; dirX = newX - midC; prior = extentPhi; next = Math.Atan2(-dirY, dirX); if (next < 0) next = PI + (next + PI); if (circDir == "positive" && startPhi >= next) extentPhi = (next + TwoPI) - startPhi; else if (circDir == "positive" && next > startPhi) extentPhi = next - startPhi; else if (circDir == "negative" && startPhi >= next) extentPhi = -1.0 * (startPhi - next); else if (circDir == "negative" && next > startPhi) extentPhi = -1.0 * (startPhi + TwoPI - next); valMax = Math.Max(Math.Abs(prior), Math.Abs(extentPhi)); valMin = Math.Min(Math.Abs(prior), Math.Abs(extentPhi)); if ((valMax - valMin) >= PI) extentPhi = (circDir == "positive") ? -1.0 * valMin : valMin; setExtentHandle(); break; } circDir = (extentPhi < 0) ? "negative" : "positive"; updateArrowHandle(); } /// <summary>Gets the HALCON region described by the ROI</summary> public override HRegion getRegion() { HRegion region; contour.Dispose(); contour.GenCircleContourXld(midR, midC, radius, startPhi, (startPhi + extentPhi), circDir, 1.0); region = new HRegion(contour); return region; } /// <summary> /// Gets the model information described by the ROI /// </summary> public override HTuple getModelData() { return new HTuple(new double[] { midR, midC, radius, startPhi, extentPhi }); } /// <summary> /// Auxiliary method to determine the positions of the second and /// third handle. /// </summary> private void determineArcHandles() { setStartHandle(); setExtentHandle(); } /// <summary> /// Auxiliary method to recalculate the start handle for the arc /// </summary> private void setStartHandle() { startR = midR - radius * Math.Sin(startPhi); startC = midC + radius * Math.Cos(startPhi); } /// <summary> /// Auxiliary method to recalculate the extent handle for the arc /// </summary> private void setExtentHandle() { extentR = midR - radius * Math.Sin(startPhi + extentPhi); extentC = midC + radius * Math.Cos(startPhi + extentPhi); } /// <summary> /// Auxiliary method to display an arrow at the extent arc position /// </summary> private void updateArrowHandle() { double row1, col1, row2, col2; double rowP1, colP1, rowP2, colP2; double length,dr,dc, halfHW, sign, angleRad; double headLength = 15; double headWidth = 15; arrowHandleXLD.Dispose(); arrowHandleXLD.GenEmptyObj(); row2 = extentR; col2 = extentC; angleRad = (startPhi + extentPhi) + Math.PI * 0.5; sign = (circDir == "negative") ? -1.0 : 1.0; row1 = row2 + sign * Math.Sin(angleRad) * 20; col1 = col2 - sign * Math.Cos(angleRad) * 20; length = HMisc.DistancePp(row1, col1, row2, col2); if (length == 0) length = -1; dr = (row2 - row1) / length; dc = (col2 - col1) / length; halfHW = headWidth / 2.0; rowP1 = row1 + (length - headLength) * dr + halfHW * dc; rowP2 = row1 + (length - headLength) * dr - halfHW * dc; colP1 = col1 + (length - headLength) * dc - halfHW * dr; colP2 = col1 + (length - headLength) * dc + halfHW * dr; if (length == -1) arrowHandleXLD.GenContourPolygonXld(row1, col1); else arrowHandleXLD.GenContourPolygonXld(new HTuple(new double[] { row1, row2, rowP1, row2, rowP2, row2 }), new HTuple(new double[] { col1, col2, colP1, col2, colP2, col2 })); } }//end of class }//end of namespace
namespace FakeItEasy.Tests.Configuration { using System; using System.Collections.Generic; using System.Linq; using FakeItEasy.Configuration; using FakeItEasy.Core; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xunit; using ExceptionFactory = System.Func<FakeItEasy.Core.IFakeObjectCall, System.Exception>; public class AnyCallConfigurationTests { private readonly IConfigurationFactory configurationFactory; private readonly FakeManager fakeObject; private readonly AnyCallCallRule callRule; private readonly AnyCallConfiguration configuration; public AnyCallConfigurationTests() { this.fakeObject = A.Fake<FakeManager>(); this.callRule = A.Fake<AnyCallCallRule>(); this.configurationFactory = A.Fake<IConfigurationFactory>(); this.configuration = new AnyCallConfiguration(this.fakeObject, this.callRule, this.configurationFactory); } public static IEnumerable<object?[]> CallSpecificationActions => TestCases.FromObject<Action<IAnyCallConfigurationWithNoReturnTypeSpecified>>( configuration => configuration.WithReturnType<int>(), configuration => configuration.WithNonVoidReturnType(), configuration => configuration.WithVoidReturnType(), configuration => configuration.Where(call => true), configuration => configuration.WhenArgumentsMatch(args => true)); [Fact] public void WithReturnType_should_return_configuration_from_factory() { // Arrange var returnConfig = this.StubReturnConfig<int>(); // Act var result = this.configuration.WithReturnType<int>(); // Assert returnConfig.Should().BeSameAs(result); } [Fact] public void DoesNothing_delegates_to_configuration_produced_by_factory() { // Arrange var factoryConfig = this.StubVoidConfig(); // Act this.configuration.DoesNothing(); // Assert A.CallTo(() => factoryConfig.DoesNothing()).MustHaveHappened(); } [Fact] public void DoesNothing_returns_configuration_produced_by_factory() { // Arrange var factoryConfig = this.StubVoidConfig(); var doesNothingConfig = A.Fake<IAfterCallConfiguredConfiguration<IVoidConfiguration>>(); A.CallTo(() => factoryConfig.DoesNothing()).Returns(doesNothingConfig); // Act var result = this.configuration.DoesNothing(); // Assert result.Should().BeSameAs(doesNothingConfig); } [Fact] public void ThrowsLazily_delegates_to_configuration_produced_by_factory() { // Arrange var factoryConfig = this.StubVoidConfig(); var exceptionFactory = A.Dummy<ExceptionFactory>(); // Act this.configuration.Throws(exceptionFactory); // Assert A.CallTo(() => factoryConfig.Throws(exceptionFactory)).MustHaveHappened(); } [Fact] public void ThrowsLazily_returns_configuration_produced_by_factory() { // Arrange var factoryConfig = this.StubVoidConfig(); var throwsConfig = A.Fake<IAfterCallConfiguredConfiguration<IVoidConfiguration>>(); A.CallTo(() => factoryConfig.Throws(A<ExceptionFactory>._)).Returns(throwsConfig); // Act var result = this.configuration.Throws(A.Dummy<ExceptionFactory>()); // Assert result.Should().BeSameAs(throwsConfig); } [Fact] public void Invokes_delegates_to_configuration_produced_by_factory() { // Arrange var factoryConfig = this.StubVoidConfig(); Action<IFakeObjectCall> invocation = x => { }; // Act this.configuration.Invokes(invocation); // Assert A.CallTo(() => factoryConfig.Invokes(invocation)).MustHaveHappened(); } [Fact] public void Invokes_returns_configuration_produced_by_factory() { // Arrange Action<IFakeObjectCall> invocation = x => { }; var factoryConfig = this.StubVoidConfig(); var invokesConfig = A.Fake<IVoidAfterCallbackConfiguredConfiguration>(); A.CallTo(() => factoryConfig.Invokes(invocation)).Returns(invokesConfig); // Act var result = this.configuration.Invokes(invocation); // Assert result.Should().BeSameAs(invokesConfig); } [Fact] public void CallsBaseMethod_delegates_to_configuration_produced_by_factory() { // Arrange var factoryConfig = this.StubVoidConfig(); // Act this.configuration.CallsBaseMethod(); // Assert A.CallTo(() => factoryConfig.CallsBaseMethod()).MustHaveHappened(); } [Fact] public void CallsBaseMethod_returns_configuration_produced_by_factory() { // Arrange var factoryConfig = this.StubVoidConfig(); var callsBaseConfig = A.Fake<IAfterCallConfiguredConfiguration<IVoidConfiguration>>(); A.CallTo(() => factoryConfig.CallsBaseMethod()).Returns(callsBaseConfig); // Act var result = this.configuration.CallsBaseMethod(); // Assert result.Should().BeSameAs(callsBaseConfig); } [Fact] public void AssignsOutAndRefParametersLazily_delegates_to_configuration_produced_by_factory() { // Arrange Func<IFakeObjectCall, ICollection<object?>> valueProducer = x => new object[] { "a", "b" }; var factoryConfig = this.StubVoidConfig(); var nextConfig = A.Fake<IAfterCallConfiguredConfiguration<IVoidConfiguration>>(); A.CallTo(() => factoryConfig.AssignsOutAndRefParametersLazily(valueProducer)).Returns(nextConfig); // Act this.configuration.AssignsOutAndRefParametersLazily(valueProducer); // Assert A.CallTo(() => factoryConfig.AssignsOutAndRefParametersLazily(valueProducer)).MustHaveHappened(); } [Fact] public void AssignsOutAndRefParametersLazily_returns_configuration_produced_by_factory() { // Arrange Func<IFakeObjectCall, ICollection<object?>> valueProducer = x => new object[] { "a", "b" }; var factoryConfig = this.StubVoidConfig(); var nextConfig = A.Fake<IAfterCallConfiguredConfiguration<IVoidConfiguration>>(); A.CallTo(() => factoryConfig.AssignsOutAndRefParametersLazily(valueProducer)).Returns(nextConfig); // Act var result = this.configuration.AssignsOutAndRefParametersLazily(valueProducer); // Assert result.Should().BeSameAs(nextConfig); } [Fact] public void Where_should_apply_where_predicate_on_rule() { // Arrange Func<IFakeObjectCall, bool> predicate = x => true; Action<IOutputWriter> writer = x => { }; // Act this.configuration.Where(predicate, writer); // Assert A.CallTo(() => this.callRule.ApplyWherePredicate(predicate, writer)).MustHaveHappened(); } [Fact] public void Where_should_return_self() { // Arrange // Act // Assert this.configuration.Where(x => true, x => { }).Should().BeSameAs(this.configuration); } [Fact] public void WhenArgumentsMatch_should_delegate_to_buildable_rule() { // Arrange Func<ArgumentCollection, bool> predicate = x => true; // Act this.configuration.WhenArgumentsMatch(predicate); // Assert A.CallTo(() => this.callRule.UsePredicateToValidateArguments(predicate)) .MustHaveHappened(); } [Fact] public void WhenArgumentsMatch_should_return_self() { // Arrange // Act // Assert this.configuration.WhenArgumentsMatch(x => true).Should().BeSameAs(this.configuration); } [Theory] [MemberData(nameof(CallSpecificationActions))] public void Call_specification_method_should_not_add_rule_to_manager(Action<IAnyCallConfigurationWithNoReturnTypeSpecified> configurationAction) { // Arrange var foo = A.Fake<IFoo>(); var manager = Fake.GetFakeManager(foo); var initialRules = manager.Rules.ToList(); // Act configurationAction(A.CallTo(foo)); // Assert manager.Rules.Should().Equal(initialRules); } private IVoidArgumentValidationConfiguration StubVoidConfig() { var result = A.Fake<IAnyCallConfigurationWithVoidReturnType>(); A.CallTo(() => this.configurationFactory.CreateConfiguration(this.fakeObject, this.callRule)).Returns(result); return result; } private IReturnValueArgumentValidationConfiguration<T> StubReturnConfig<T>() { var result = A.Fake<IAnyCallConfigurationWithReturnTypeSpecified<T>>(); A.CallTo(() => this.configurationFactory.CreateConfiguration<T>(this.fakeObject, this.callRule)).Returns(result); return result; } } }
namespace StudentManagementSystem.Authentication.MongoDb { using System; using System.Linq; using MongoDB.Bson; using MongoDB.Driver; public class IdentityDatabaseContext<TUser, TRole, TKey> : IIdentityDatabaseContext<TUser, TRole, TKey>, IDisposable where TRole : IdentityRole<TKey> where TUser : IdentityUser<TKey> where TKey : IEquatable<TKey> { public string ConnectionString { get; set; } public string DatabaseName { get; set; } = "StudentManagementSystemDb"; public string UserCollectionName { get; set; } = "Users"; public string RoleCollectionName { get; set; } = "Roles"; /// <summary> /// When the <see cref="UserCollection"/> and <see cref="RoleCollection"/> collections are initially fetched - ensure the indexes are created (default: false) /// </summary> public bool EnsureCollectionIndexes { get; set; } = false; public MongoCollectionSettings CollectionSettings { get; set; } = new MongoCollectionSettings { WriteConcern = WriteConcern.WMajority }; public CreateCollectionOptions CreateCollectionOptions { get; set; } = new CreateCollectionOptions { AutoIndexId = true }; public CreateIndexOptions CreateIndexOptions { get; set; } = new CreateIndexOptions { Background = true, Sparse = true }; public virtual IMongoClient Client { get { if (this._client == null) { if (this._database != null) { this._client = this._database.Client; } if (string.IsNullOrWhiteSpace(this.ConnectionString)) { throw new NullReferenceException($"The parameter '{nameof(this.ConnectionString)}' in '{typeof(IdentityDatabaseContext<TUser, TRole, TKey>).FullName}' is null and must be set before calling '{nameof(this.Client)}'. This is usually configured as part of Startup.cs"); } this._client = new MongoClient(this.ConnectionString); } return this._client; } set { this._client = value; } } private IMongoClient _client; public virtual IMongoDatabase Database { get { if (this._database == null) { if (string.IsNullOrWhiteSpace(this.DatabaseName)) { throw new NullReferenceException($"The parameter '{nameof(this.DatabaseName)}' in '{typeof(IdentityDatabaseContext<TUser, TRole, TKey>).FullName}' is null and must be set before calling '{nameof(this.Database)}'. This is usually configured as part of Startup.cs"); } this._database = this.Client.GetDatabase(this.DatabaseName); } return this._database; } set { this._database = value; } } private IMongoDatabase _database; /// <summary> /// Initiates the user collection. If <see cref="EnsureCollectionIndexes"/> == true, will call <see cref="EnsureUserIndexesCreated"/> /// </summary> public virtual IMongoCollection<TUser> UserCollection { get { if (this._userCollection == null) { if (string.IsNullOrWhiteSpace(this.UserCollectionName)) { throw new NullReferenceException($"The parameter '{nameof(this.UserCollectionName)}' in '{typeof(IdentityDatabaseContext<TUser, TRole, TKey>).FullName}' is null and must be set before calling '{nameof(this.UserCollection)}'. This is usually configured as part of Startup.cs"); } if (this.EnsureCollectionIndexes) { this.EnsureUserIndexesCreated(); } this._userCollection = this.Database.GetCollection<TUser>(this.UserCollectionName, this.CollectionSettings); } return this._userCollection; } set { this._userCollection = value; } } private IMongoCollection<TUser> _userCollection; /// <summary> /// Initiates the role collection. If <see cref="EnsureCollectionIndexes"/> == true, will call <see cref="EnsureRoleIndexesCreated"/> /// </summary> public virtual IMongoCollection<TRole> RoleCollection { get { if (this._roleCollection == null) { if (string.IsNullOrWhiteSpace(this.RoleCollectionName)) { throw new NullReferenceException($"The parameter '{nameof(this.RoleCollectionName)}' in '{typeof(IdentityDatabaseContext<TUser, TRole, TKey>).FullName}' is null and must be set before calling '{nameof(this.RoleCollection)}'. This is usually configured as part of Startup.cs"); } if (this.EnsureCollectionIndexes) { this.EnsureRoleIndexesCreated(); } this._roleCollection = this.Database.GetCollection<TRole>(this.RoleCollectionName, this.CollectionSettings); } return this._roleCollection; } set { this._roleCollection = value; } } private IMongoCollection<TRole> _roleCollection; /// <summary> /// Ensures the user collection is instantiated, and has the standard indexes applied. Called when <see cref="UserCollection"/> is called if <see cref="EnsureCollectionIndexes"/> == true. /// </summary> /// <remarks> /// Indexes Created: /// Users: NormalizedUserName, NormalizedEmail, Logins.LoginProvider, Roles.NormalizedName, Claims.ClaimType + Roles.Claims.ClaimType /// </remarks> public virtual void EnsureUserIndexesCreated() { // only check on app startup if (_doneUserIndexes) return; _doneUserIndexes = true; // ensure collection exists if (!this.CollectionExists(this.UserCollectionName)) { this.Database.CreateCollectionAsync(this.UserCollectionName, this.CreateCollectionOptions).Wait(); } // ensure NormalizedUserName index exists var normalizedNameIndex = Builders<TUser>.IndexKeys.Ascending(x => x.NormalizedUserName); this.UserCollection.Indexes.CreateOneAsync(normalizedNameIndex, this.CreateIndexOptions); // ensure NormalizedEmail index exists var normalizedEmailIndex = Builders<TUser>.IndexKeys.Ascending(x => x.NormalizedEmail); this.UserCollection.Indexes.CreateOneAsync(normalizedEmailIndex, this.CreateIndexOptions); // ensure Roles.NormalizedName index exists var roleNameIndex = Builders<TUser>.IndexKeys.Ascending("Roles_NormalizedName"); this.UserCollection.Indexes.CreateOneAsync(roleNameIndex, this.CreateIndexOptions); // ensure LoginProvider index exists var loginProviderIndex = Builders<TUser>.IndexKeys.Ascending("Logins_LoginProvider"); this.UserCollection.Indexes.CreateOneAsync(loginProviderIndex, this.CreateIndexOptions); // ensure claims index exists var claimsProviderIndex = Builders<TUser>.IndexKeys.Ascending("AllClaims_ClaimType"); this.UserCollection.Indexes.CreateOneAsync(claimsProviderIndex, this.CreateIndexOptions); } /// <summary> /// Singleton property. Only want to check collection indexes are done once, not on every call /// </summary> protected static bool _doneUserIndexes = false; protected static bool _doneRoleIndexes = false; /// <summary> /// Ensures the role collection is instantiated, and has the standard indexes applied. Called when <see cref="RoleCollection"/> is called if <see cref="EnsureCollectionIndexes"/> == true. /// </summary> /// <remarks> /// Indexes Created: /// Roles: NormalizedName /// </remarks> public virtual void EnsureRoleIndexesCreated() { // only check on app startup if (_doneRoleIndexes) return; _doneRoleIndexes = true; // ensure collection exists if (!this.CollectionExists(this.RoleCollectionName)) { this.Database.CreateCollectionAsync(this.RoleCollectionName, this.CreateCollectionOptions).Wait(); } // ensure NormalizedName index exists var normalizedNameIndex = Builders<TRole>.IndexKeys.Ascending(x => x.NormalizedName); this.RoleCollection.Indexes.CreateOneAsync(normalizedNameIndex, this.CreateIndexOptions); } /// <summary> /// WARNING: Permanently deletes user collection, including all indexes and data. /// </summary> public virtual void DeleteUserCollection() { this.Database.DropCollectionAsync(this.UserCollectionName).Wait(); _doneUserIndexes = false; } /// <summary> /// WARNING: Permanently deletes role collection, including all indexes and data. /// </summary> public virtual void DeleteRoleCollection() { this.Database.DropCollectionAsync(this.RoleCollectionName).Wait(); _doneRoleIndexes = false; } /// <summary> /// check if the collection already exists /// </summary> /// <param name="collectionName"></param> /// <returns></returns> protected virtual bool CollectionExists(string collectionName) { var filter = new BsonDocument("name", collectionName); var cursorTask = this.Database.ListCollectionsAsync(new ListCollectionsOptions { Filter = filter }); cursorTask.Wait(); var cursor = cursorTask.Result.ToListAsync(); cursor.Wait(); return cursor.Result.Any(); } public void Dispose() { } } }
namespace Microsoft.Protocols.TestSuites.Common { using System; using System.IO; using System.Xml; /// <summary> /// A class represents a Xml Writer XmlWriterInjector which inherits from "XmlWriter". /// Use this class instead of XmlWriter to get the request data from request stream during the processing of the proxy class generated by WSDL.exe. /// </summary> public class XmlWriterInjector : XmlWriter { /// <summary> /// An XmlWriter instance. /// </summary> private XmlWriter originalXmlWriter; /// <summary> /// An XmlTextWriter instance. /// </summary> private XmlTextWriter injectorXmlTextWriter; /// <summary> /// A StringWriter instance. /// </summary> private StringWriter stringWriterInstance; /// <summary> /// Initializes a new instance of the XmlWriterInjector class. /// </summary> /// <param name="implementation">A parameter instance represents an XmlWriter type implementation.</param> public XmlWriterInjector(XmlWriter implementation) { this.originalXmlWriter = implementation; this.stringWriterInstance = new StringWriter(); this.injectorXmlTextWriter = new XmlTextWriter(this.stringWriterInstance); this.injectorXmlTextWriter.Formatting = Formatting.Indented; } /// <summary> /// Gets the xml string which is written to request stream. /// </summary> public string Xml { get { return this.stringWriterInstance == null ? null : this.stringWriterInstance.ToString(); } } /// <summary> /// A method used to override the method "WriteState" of XmlWriter. /// </summary> public override WriteState WriteState { get { return this.originalXmlWriter.WriteState; } } /// <summary> /// Gets the current xml:lang scope. /// </summary> public override string XmlLang { get { return this.originalXmlWriter.XmlLang; } } /// <summary> /// Gets an System.Xml.XmlSpace representing the current xml:space scope. /// None: This is the default value if no xml:space scope exists. /// Default: This value is meaning the current scope is xml:space="default". /// Preserve: This value is meaning the current scope is xml:space="preserve". /// </summary> public override XmlSpace XmlSpace { get { return this.originalXmlWriter.XmlSpace; } } /// <summary> /// A method used to override the method "Flush". /// It flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. /// </summary> public override void Flush() { this.originalXmlWriter.Flush(); this.injectorXmlTextWriter.Flush(); this.stringWriterInstance.Flush(); } /// <summary> /// A method used to override the method "Close". /// It closes this stream and the underlying stream. /// </summary> public override void Close() { this.originalXmlWriter.Close(); this.injectorXmlTextWriter.Close(); } /// <summary> /// A method used to override the method "LookupPrefix". /// It returns the closest prefix defined in the current namespace scope for the namespace URI. /// </summary> /// <param name="ns">A method represents the namespace URI whose prefix you want to find.</param> /// <returns> A return value represents the matching prefix or null if no matching namespace URI is found in the current scope.</returns> public override string LookupPrefix(string ns) { return this.originalXmlWriter.LookupPrefix(ns); } /// <summary> /// A method used to override the method "WriteBase64" of XmlWriter. /// </summary> /// <param name="buffer">A parameter represents Byte array to encode.</param> /// <param name="index">A parameter represents the position in the buffer indicating the start of the bytes to write.</param> /// <param name="count">A parameter represents the number of bytes to write.</param> public override void WriteBase64(byte[] buffer, int index, int count) { this.originalXmlWriter.WriteBase64(buffer, index, count); this.injectorXmlTextWriter.WriteBase64(buffer, index, count); } /// <summary> /// A method used to override the method "WriteCData" of XmlWriter. /// </summary> /// <param name="text">A parameter represents the text to place inside the CDATA block.</param> public override void WriteCData(string text) { this.originalXmlWriter.WriteCData(text); this.injectorXmlTextWriter.WriteCData(text); } /// <summary> /// A method used to override the method "WriteCharEntity" of XmlWriter. /// </summary> /// <param name="ch">A parameter represents the Unicode character for which to generate a character entity.</param> public override void WriteCharEntity(char ch) { this.originalXmlWriter.WriteCharEntity(ch); this.injectorXmlTextWriter.WriteCharEntity(ch); } /// <summary> /// A method used to override the method "WriteChars" of XmlWriter. /// </summary> /// <param name="buffer">A parameter represents the character array containing the text to write.</param> /// <param name="index">A parameter represents the position in the buffer indicating the start of the text to write.</param> /// <param name="count">A parameter represents the number of characters to write.</param> public override void WriteChars(char[] buffer, int index, int count) { this.originalXmlWriter.WriteChars(buffer, index, count); this.injectorXmlTextWriter.WriteChars(buffer, index, count); } /// <summary> /// A method used to override the method "WriteComment" of XmlWriter. /// </summary> /// <param name="text">A parameter represents the text to place inside the comment.</param> public override void WriteComment(string text) { this.originalXmlWriter.WriteComment(text); this.injectorXmlTextWriter.WriteComment(text); } /// <summary> /// A method used to override the method "WriteDocType" of XmlWriter. /// </summary> /// <param name="name">A parameter represents the name of the DOCTYPE. This must be non-empty.</param> /// <param name="pubid">A parameter represents that if non-null it also writes PUBLIC "pubid" "sysid" where pubid and sysid /// are replaced with the value of the given arguments.</param> /// <param name="sysid">A parameter represents that if pubid is null and sysid is non-null it writes SYSTEM "sysid" where /// sysid is replaced with the value of this argument.</param> /// <param name="subset">A parameter represents that if non-null it writes [subset] where subset is replaced with the value of this argument.</param> public override void WriteDocType(string name, string pubid, string sysid, string subset) { this.originalXmlWriter.WriteDocType(name, pubid, sysid, subset); this.injectorXmlTextWriter.WriteDocType(name, pubid, sysid, subset); } /// <summary> /// A method used to override the method "WriteEndAttribute" of XmlWriter. /// </summary> public override void WriteEndAttribute() { this.originalXmlWriter.WriteEndAttribute(); this.injectorXmlTextWriter.WriteEndAttribute(); } /// <summary> /// A method used to override the method "WriteEndDocument" of XmlWriter. /// </summary> public override void WriteEndDocument() { this.originalXmlWriter.WriteEndDocument(); this.injectorXmlTextWriter.WriteEndDocument(); } /// <summary> /// A method used to override the method "WriteEndElement" of XmlWriter. /// </summary> public override void WriteEndElement() { this.originalXmlWriter.WriteEndElement(); this.injectorXmlTextWriter.WriteEndElement(); } /// <summary> /// A method used to override the method "WriteEntityRef" of XmlWriter. /// </summary> /// <param name="name">A parameter represents the name of the entity reference.</param> public override void WriteEntityRef(string name) { this.originalXmlWriter.WriteEntityRef(name); this.injectorXmlTextWriter.WriteEntityRef(name); } /// <summary> /// A method used to override the method "WriteFullEndElement" of XmlWriter. /// </summary> public override void WriteFullEndElement() { this.originalXmlWriter.WriteFullEndElement(); this.injectorXmlTextWriter.WriteFullEndElement(); } /// <summary> /// A method used to override the method "WriteProcessingInstruction" of XmlWriter. /// </summary> /// <param name="name">A parameter represents the name of the processing instruction.</param> /// <param name="text">A parameter represents the text to include in the processing instruction.</param> public override void WriteProcessingInstruction(string name, string text) { this.originalXmlWriter.WriteProcessingInstruction(name, text); this.injectorXmlTextWriter.WriteProcessingInstruction(name, text); } /// <summary> /// A method used to override the method "WriteRaw" of XmlWriter. /// </summary> /// <param name="data">A parameter represents the string containing the text to write.</param> public override void WriteRaw(string data) { this.originalXmlWriter.WriteRaw(data); this.injectorXmlTextWriter.WriteRaw(data); } /// <summary> /// A method used to override the method "WriteRaw" of XmlWriter. /// </summary> /// <param name="buffer">A parameter represents character array containing the text to write.</param> /// <param name="index">A parameter represents the position within the buffer indicating the start of the text to write.</param> /// <param name="count">A parameter represents the number of characters to write.</param> public override void WriteRaw(char[] buffer, int index, int count) { this.originalXmlWriter.WriteRaw(buffer, index, count); this.injectorXmlTextWriter.WriteRaw(buffer, index, count); } /// <summary> /// A method used to override the method "WriteStartAttribute" of XmlWriter. /// </summary> /// <param name="prefix">A parameter represents the namespace prefix of the attribute.</param> /// <param name="localName">A parameter represents the local name of the attribute.</param> /// <param name="ns">A parameter represents the namespace URI for the attribute.</param> public override void WriteStartAttribute(string prefix, string localName, string ns) { this.originalXmlWriter.WriteStartAttribute(prefix, localName, ns); this.injectorXmlTextWriter.WriteStartAttribute(prefix, localName, ns); } /// <summary> /// A method used to override the method "WriteStartDocument" of XmlWriter. /// </summary> /// <param name="standalone">A parameter represents that if true, it writes "standalone=yes"; if false, it writes "standalone=no".</param> public override void WriteStartDocument(bool standalone) { this.originalXmlWriter.WriteStartDocument(standalone); this.injectorXmlTextWriter.WriteStartDocument(standalone); } /// <summary> /// A method used to override the method "WriteStartDocument" of XmlWriter. /// </summary> public override void WriteStartDocument() { this.originalXmlWriter.WriteStartDocument(); this.injectorXmlTextWriter.WriteStartDocument(); } /// <summary> /// A method used to override the method "WriteStartElement" of XmlWriter. /// </summary> /// <param name="prefix">A parameter represents the namespace prefix of the element.</param> /// <param name="localName">A parameter represents the local name of the element.</param> /// <param name="ns">A parameter represents the namespace URI to associate with the element.</param> public override void WriteStartElement(string prefix, string localName, string ns) { this.originalXmlWriter.WriteStartElement(prefix, localName, ns); this.injectorXmlTextWriter.WriteStartElement(prefix, localName, ns); } /// <summary> /// A method used to override the method "WriteString" of XmlWriter. /// </summary> /// <param name="text">A parameter represents the text to write.</param> public override void WriteString(string text) { this.originalXmlWriter.WriteString(text); this.injectorXmlTextWriter.WriteString(text); } /// <summary> /// A method used to override the method "WriteSurrogateCharEntity" of XmlWriter. /// </summary> /// <param name="lowChar">A parameter represents the low surrogate. This must be a value between 0xDC00 and 0xDFFF.</param> /// <param name="highChar">A parameter represents the high surrogate. This must be a value between 0xD800 and 0xDBFF.</param> public override void WriteSurrogateCharEntity(char lowChar, char highChar) { this.originalXmlWriter.WriteSurrogateCharEntity(lowChar, highChar); this.injectorXmlTextWriter.WriteSurrogateCharEntity(lowChar, highChar); } /// <summary> /// A method used to override the method "WriteWhitespace" of XmlWriter. /// </summary> /// <param name="ws">A parameter represents the string of white space characters.</param> public override void WriteWhitespace(string ws) { this.originalXmlWriter.WriteWhitespace(ws); this.injectorXmlTextWriter.WriteWhitespace(ws); } /// <summary> /// A method used to writes out all the attributes found at the current position in the System.Xml.XmlReader. /// </summary> /// <param name="reader">The XmlReader from which to copy the attributes.</param> /// <param name="defattr">A parameter represents whether copy the default attributes from the XmlReader, true means copy, false means not copy.</param> public override void WriteAttributes(XmlReader reader, bool defattr) { base.WriteAttributes(reader, defattr); } /// <summary> /// A method used to writes out the specified name, ensuring it is a valid name according to the W3C XML 1.0. /// </summary> /// <param name="name">A parameter represents the name to write.</param> public override void WriteName(string name) { this.originalXmlWriter.WriteName(name); this.injectorXmlTextWriter.WriteName(name); } /// <summary> /// A method used to encodes the specified binary bytes as BinHex and writes out the resulting text. /// </summary> /// <param name="buffer">A parameter represents the Byte array to encode.</param> /// <param name="index">A parameter represents the position in the buffer indicating the start of the bytes to write.</param> /// <param name="count">A parameter represents the number of bytes to write.</param> public override void WriteBinHex(byte[] buffer, int index, int count) { this.originalXmlWriter.WriteBinHex(buffer, index, count); this.injectorXmlTextWriter.WriteBinHex(buffer, index, count); } /// <summary> /// A method used to writes out the specified name, ensuring it is a valid NmToken according to the W3C XML 1.0. /// </summary> /// <param name="name">A parameter represents the name to write.</param> public override void WriteNmToken(string name) { this.originalXmlWriter.WriteNmToken(name); this.injectorXmlTextWriter.WriteNmToken(name); } /// <summary> /// A method used to copies everything from the reader to the writer and moves the reader to the start of the next sibling. /// </summary> /// <param name="navigator">A parameter represents the System.Xml.XPath.XPathNavigator to copy from.</param> /// <param name="defattr">A parameter represents whether copy the default attributes from the XmlReader, true means copy, false means not copy.</param> public override void WriteNode(System.Xml.XPath.XPathNavigator navigator, bool defattr) { this.originalXmlWriter.WriteNode(navigator, defattr); this.injectorXmlTextWriter.WriteNode(navigator, defattr); } /// <summary> /// A method used to copies everything from the reader to the writer and moves the reader to the start of the next sibling. /// </summary> /// <param name="reader">A parameter represents the System.Xml.XmlReader to read from.</param> /// <param name="defattr">A parameter represents whether copy the default attributes from the XmlReader, true means copy, false means not copy.</param> public override void WriteNode(XmlReader reader, bool defattr) { this.originalXmlWriter.WriteNode(reader, defattr); this.injectorXmlTextWriter.WriteNode(reader, defattr); } /// <summary> /// A method used to writes out the namespace-qualified name. /// </summary> /// <param name="localName">A parameter represents the local name to write.</param> /// <param name="ns">>A parameter represents the namespace URI for the name.</param> public override void WriteQualifiedName(string localName, string ns) { this.originalXmlWriter.WriteQualifiedName(localName, ns); this.injectorXmlTextWriter.WriteQualifiedName(localName, ns); } /// <summary> /// A method used to writes a System.Boolean value. /// </summary> /// <param name="value">A parameter represents the System.Boolean value to write.</param> public override void WriteValue(bool value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to writes a System.DateTime value. /// </summary> /// <param name="value">A parameter represents the System.DateTime value to write.</param> public override void WriteValue(DateTime value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to writes a System.Decimal value. /// </summary> /// <param name="value">A parameter represents the System.Decimal value to write.</param> public override void WriteValue(decimal value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to writes a System.Double value. /// </summary> /// <param name="value">A parameter represents the System.Double value to write.</param> public override void WriteValue(double value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to writes a single-precision floating-point number. /// </summary> /// <param name="value">A parameter represents the single-precision floating-point number to write.</param> public override void WriteValue(float value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to writes a System.Int32 value. /// </summary> /// <param name="value">A parameter represents the System.Int32 value to write.</param> public override void WriteValue(int value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to writes a System.Int64 value. /// </summary> /// <param name="value">A parameter represents the System.Int64 value to write.</param> public override void WriteValue(long value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method used to writes the object value. /// </summary> /// <param name="value">A parameter represents the object value to write.</param> public override void WriteValue(object value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } /// <summary> /// A method writes a System.String value. /// </summary> /// <param name="value">A parameter represents the System.Boolean value to write.</param> public override void WriteValue(string value) { this.originalXmlWriter.WriteValue(value); this.injectorXmlTextWriter.WriteValue(value); } } }
using System; using System.Linq; using UnityEngine; using UnityEngine.UI; using System.Collections; using DG.Tweening; using GoogleFu; public class GameManager : MonoBehaviour { public static GameManager instance; public Player player1; public Player player2; public Card cardSelected; public CardContext contextCard; public RectTransform contextRect; public RectTransform yourTurnText; public Player localPlayer; public bool localPlayerTurn = true; public bool offlineMode = false; public PhotonView photonView; public Button buttonEndTurn; public Text startGameText; public bool gameEnded = false; private bool _gameStarted = false; private float _timeElapsed = 0f; public Slider SliderTimer; public EndScreen End; // Use this for initialization void Awake () { instance = this; photonView = GetComponent<PhotonView>(); PhotonNetwork.offlineMode = offlineMode; if (offlineMode) { //PhotonNetwork.JoinLobby(); PhotonNetwork.JoinOrCreateRoom("localRoom", new RoomOptions {maxPlayers = 2}, TypedLobby.Default); } localPlayer = PhotonNetwork.isMasterClient ? player1 : player2; localPlayer.fullName = PhotonNetwork.playerName; if(!offlineMode) getOtherPlayer(localPlayer).fullName = PhotonNetwork.otherPlayers[0].name; localPlayerTurn = localPlayer == player1; if (!localPlayerTurn) localPlayer.Swap(); if(offlineMode) player2.Swap(); buttonEndTurn.interactable = false; } void Start() { StartCoroutine(StartGame()); } public void LeaveGame() { PhotonNetwork.LeaveRoom(); PhotonNetwork.LoadLevel(0); //Application.Quit(); } void OnPhotonPlayerDisconnected() { PhotonNetwork.LeaveRoom(); PhotonNetwork.LoadLevel(0); } void InstantiateDecks() { // TODO if (!PlayerPrefs.HasKey("deck")) return; var playerid = localPlayer == player1 ? PlayerID.Player1 : PlayerID.Player2; for (var i = 0; i < PlayerPrefs.GetInt("deck"); i++) { var id = PlayerPrefs.GetString("deck_card_id_" + i); var nb = PlayerPrefs.GetInt("deck_card_nb_" + i); for (int j = 0; j < nb; j++) { if(id.StartsWith("ACTION")) CardFactory.Instance.CreateAction(id, playerid); else if(id.StartsWith("ACTOR")) CardFactory.Instance.CreateActor(id, playerid); else if(id.StartsWith("TREND")) CardFactory.Instance.CreateContext(id, playerid); } } if (!offlineMode) return; playerid = localPlayer == player1 ? PlayerID.Player2 : PlayerID.Player1; for (var i = 0; i < PlayerPrefs.GetInt("deck"); i++) { var id = PlayerPrefs.GetString("deck_card_id_" + i); var nb = PlayerPrefs.GetInt("deck_card_nb_" + i); for (int j = 0; j < nb; j++) { if (id.StartsWith("ACTION")) CardFactory.Instance.CreateAction(id, playerid); else if (id.StartsWith("ACTOR")) CardFactory.Instance.CreateActor(id, playerid); else if (id.StartsWith("TREND")) CardFactory.Instance.CreateContext(id, playerid); } } } IEnumerator StartGame() { if(!offlineMode) startGameText.text = PhotonNetwork.playerList[0].name + " vs " + PhotonNetwork.playerList[1].name; startGameText.transform.DOLocalMove(Vector3.zero, 2f).SetEase(Ease.OutElastic); InstantiateDecks(); yield return new WaitForSeconds(3f); startGameText.transform.DOLocalMove(new Vector3(1920,0,0), 1f).SetEase(Ease.InCirc); if (PhotonNetwork.isMasterClient) { activePlayer().DrawRPC(2); getOtherPlayer(activePlayer()).DrawRPC(3); } yield return new WaitForSeconds(1f); if (localPlayerTurn) { DOTween.Sequence() .Append(yourTurnText.DOLocalMove(new Vector3(0f, 0f, 0f), 1.0f).SetEase(Ease.OutBounce)) .AppendInterval(1.0f) .Append(yourTurnText.DOLocalMove(new Vector3(0f, (float) Screen.height*2f, 0f), 0f)); buttonEndTurn.interactable = true; buttonEndTurn.GetComponentInChildren<Text>().text = "Finir mon tour"; } else { buttonEndTurn.GetComponentInChildren<Text>().text = "Tour de l'adversaire en cours"; } _gameStarted = true; activePlayer().OnTurnStart(); } void Update() { if (contextCard) { contextCard.transform.SetParent(contextRect); if (!contextCard.InAnimation) { if (contextCard.transform.localPosition != Vector3.zero) { contextCard.transform.DOLocalMove(Vector3.zero, 1.0f); contextCard.InAnimation = true; } } //contextCard.transform.localPosition = Vector3.zero; } if (_gameStarted) { _timeElapsed += Time.deltaTime; } SliderTimer.value = _timeElapsed; if (localPlayerTurn && _timeElapsed >= 60f) { _timeElapsed = 0f; EndTurn(); } } public void playerDied(Player deadPlayer) { gameEnded = true; /*player1.ClearAll(); player2.ClearAll(); if (contextCard) contextCard.transform.localScale = Vector3.zero;*/ if (deadPlayer == localPlayer) { LocalHasLost = true; yourTurnText.GetComponent<Text>().text = "Vous avez perdu !"; SoundManager.Instance.PlayDefeatSound(); DOTween.Sequence() .Append(yourTurnText.DOLocalMove(new Vector3(0f, 285f, 0f), 1.0f).SetEase(Ease.OutBounce)); } else { LocalHasLost = false; yourTurnText.GetComponent<Text>().text = "Victoire !"; SoundManager.Instance.PlayVictorySound(); DOTween.Sequence() .Append(yourTurnText.DOLocalMove(new Vector3(0f, 285f, 0f), 1.0f).SetEase(Ease.OutBounce)); } End.ShowPanel(); } public bool? LocalHasLost = null; [RPC] void SetContext(int viewID) { if (contextCard) { contextCard.destroy(); } contextCard = PhotonView.Find(viewID).GetComponent<CardContext>(); contextCard.owner.RemoveCard(contextCard); contextCard.show(); contextCard.TargetType = TargetType.Context; SoundManager.Instance.PlayCardSlide(); } public void EndTurn() { if (!gameEnded) photonView.RPC("EndTurnRPC", PhotonTargets.AllBuffered); } [RPC] void EndTurnRPC() { if (cardSelected) { cardSelected.setSelected(false); cardSelected = null; } activePlayer().OnTurnEnd(); localPlayerTurn = !localPlayerTurn; if (localPlayerTurn) { DOTween.Sequence() .Append(yourTurnText.DOLocalMove(new Vector3(0f, 0f, 0f), 1.0f).SetEase(Ease.OutBounce)) .AppendInterval(1.0f) .Append(yourTurnText.DOLocalMove(new Vector3(0f, (float) Screen.height*2f, 0f), 0f)); buttonEndTurn.interactable = true; buttonEndTurn.GetComponentInChildren<Text>().text = "Finir mon tour"; } else { buttonEndTurn.interactable = offlineMode; buttonEndTurn.GetComponentInChildren<Text>().text = "Tour de l'adversaire en cours"; } _timeElapsed = 0f; activePlayer().OnTurnStart(); } public Player activePlayer() { return localPlayerTurn ? localPlayer : getOtherPlayer(localPlayer); } public Player getOtherPlayer(Player p){ return p == player1 ? player2 : player1; } public void elementClicked(Target c){ if (!localPlayerTurn && !offlineMode) return; if (gameEnded) return; if (cardSelected == null && c.TargetType == TargetType.Card) { Card ca = (Card)c; if (ca.owner == activePlayer() && ca != contextCard){ if (ca.cardType == CardType.Actor && ca.place == Place.Board) if (!((CardActor)ca).canAttack) return; cardSelected = ca; cardSelected.setSelected(true); activePlayer().OutlinePossibleTargets(cardSelected); } } else if (cardSelected != null) { // A card is selected if (cardSelected == c) { cardSelected.setSelected(false); cardSelected = null; activePlayer().ResetOutlines(true); } else { bool result = false; switch (c.TargetType) { case TargetType.Card: { // We clicked on another card Card ca = (Card)c; if (ca.place == Place.Board) { result = cardSelected.isValidTarget(c); } else if (ca.owner == activePlayer() && ca != contextCard) { cardSelected.setSelected(false); cardSelected = (Card)c; cardSelected.setSelected(true); activePlayer().OutlinePossibleTargets(cardSelected); return; } } break; case TargetType.Player: result = cardSelected.isValidTarget(c); break; case TargetType.Board: if (cardSelected.place == Place.Hand && cardSelected.cardType == CardType.Actor) { cardSelected.owner.MoveToBoard(cardSelected); cardSelected.setSelected(false); cardSelected = null; activePlayer().ResetOutlines(true); } break; case TargetType.Context: { if (cardSelected.cardType == CardType.Context) { photonView.RPC("SetContext", PhotonTargets.AllBuffered, cardSelected.photonView.viewID); cardSelected.setSelected(false); cardSelected = null; activePlayer().ResetOutlines(true); } } break; case TargetType.Graveyard: { if (cardSelected.place == Place.Hand) { activePlayer().Discard(cardSelected); cardSelected.setSelected(false); cardSelected = null; activePlayer().ResetOutlines(true); } } break; } // If we have a valid target, we use the card if (result) { cardSelected.useOn(c); cardSelected.setSelected(false); cardSelected = null; activePlayer().ResetOutlines(true); } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace StacksOfWax.AttributeRoutingApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // namespace System.Security.Permissions { using System; #if FEATURE_CAS_POLICY using SecurityElement = System.Security.SecurityElement; #endif // FEATURE_CAS_POLICY using System.Globalization; using System.Runtime.Serialization; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] sealed public class ZoneIdentityPermission : CodeAccessPermission, IBuiltInPermission { //------------------------------------------------------ // // PRIVATE STATE DATA // //------------------------------------------------------ // Zone Enum Flag // ----- ----- ----- // NoZone -1 0x00 // MyComputer 0 0x01 (1 << 0) // Intranet 1 0x02 (1 << 1) // Trusted 2 0x04 (1 << 2) // Internet 3 0x08 (1 << 3) // Untrusted 4 0x10 (1 << 4) private const uint AllZones = 0x1f; [OptionalField(VersionAdded = 2)] private uint m_zones; #if FEATURE_REMOTING // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission [OptionalField(VersionAdded = 2)] private String m_serializedPermission; // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes private SecurityZone m_zone = SecurityZone.NoZone; [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { // v2.0 and beyond XML case if (m_serializedPermission != null) { FromXml(SecurityElement.FromString(m_serializedPermission)); m_serializedPermission = null; } else //v1.x case where we read the m_zone value { SecurityZone = m_zone; m_zone = SecurityZone.NoZone; } } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case m_zone = SecurityZone; } } [OnSerialized] private void OnSerialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = null; m_zone = SecurityZone.NoZone; } } #endif // FEATURE_REMOTING //------------------------------------------------------ // // PUBLIC CONSTRUCTORS // //------------------------------------------------------ public ZoneIdentityPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { m_zones = AllZones; } else if (state == PermissionState.None) { m_zones = 0; } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } } public ZoneIdentityPermission( SecurityZone zone ) { this.SecurityZone = zone; } internal ZoneIdentityPermission( uint zones ) { m_zones = (zones & AllZones); } // Internal function to append all the Zone in this permission to the input ArrayList internal void AppendZones(ArrayList zoneList) { int nEnum = 0; uint nFlag; for(nFlag = 1; nFlag < AllZones; nFlag <<= 1) { if((m_zones & nFlag) != 0) { zoneList.Add((SecurityZone)nEnum); } nEnum++; } } //------------------------------------------------------ // // PUBLIC ACCESSOR METHODS // //------------------------------------------------------ public SecurityZone SecurityZone { set { VerifyZone( value ); if(value == SecurityZone.NoZone) m_zones = 0; else m_zones = (uint)1 << (int)value; } get { SecurityZone z = SecurityZone.NoZone; int nEnum = 0; uint nFlag; for(nFlag = 1; nFlag < AllZones; nFlag <<= 1) { if((m_zones & nFlag) != 0) { if(z == SecurityZone.NoZone) z = (SecurityZone)nEnum; else return SecurityZone.NoZone; } nEnum++; } return z; } } //------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ private static void VerifyZone( SecurityZone zone ) { if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted) { throw new ArgumentException( Environment.GetResourceString("Argument_IllegalZone") ); } Contract.EndContractBlock(); } //------------------------------------------------------ // // CODEACCESSPERMISSION IMPLEMENTATION // //------------------------------------------------------ //------------------------------------------------------ // // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ public override IPermission Copy() { return new ZoneIdentityPermission(this.m_zones); } public override bool IsSubsetOf(IPermission target) { if (target == null) return this.m_zones == 0; ZoneIdentityPermission that = target as ZoneIdentityPermission; if (that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); return (this.m_zones & that.m_zones) == this.m_zones; } public override IPermission Intersect(IPermission target) { if (target == null) return null; ZoneIdentityPermission that = target as ZoneIdentityPermission; if (that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); uint newZones = this.m_zones & that.m_zones; if(newZones == 0) return null; return new ZoneIdentityPermission(newZones); } public override IPermission Union(IPermission target) { if (target == null) return this.m_zones != 0 ? this.Copy() : null; ZoneIdentityPermission that = target as ZoneIdentityPermission; if (that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); return new ZoneIdentityPermission(this.m_zones | that.m_zones); } #if FEATURE_CAS_POLICY public override SecurityElement ToXml() { SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ZoneIdentityPermission" ); if (SecurityZone != SecurityZone.NoZone) { esd.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), this.SecurityZone ) ); } else { int nEnum = 0; uint nFlag; for(nFlag = 1; nFlag < AllZones; nFlag <<= 1) { if((m_zones & nFlag) != 0) { SecurityElement child = new SecurityElement("Zone"); child.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), (SecurityZone)nEnum ) ); esd.AddChild(child); } nEnum++; } } return esd; } public override void FromXml(SecurityElement esd) { m_zones = 0; CodeAccessPermission.ValidateElement( esd, this ); String eZone = esd.Attribute( "Zone" ); if (eZone != null) SecurityZone = (SecurityZone)Enum.Parse( typeof( SecurityZone ), eZone ); if(esd.Children != null) { foreach(SecurityElement child in esd.Children) { eZone = child.Attribute( "Zone" ); int enm = (int)Enum.Parse( typeof( SecurityZone ), eZone ); if(enm == (int)SecurityZone.NoZone) continue; m_zones |= ((uint)1 << enm); } } } #endif // FEATURE_CAS_POLICY /// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return ZoneIdentityPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.ZoneIdentityPermissionIndex; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true); internal CSharpCommandLineParser(bool isScriptRunner = false) : base(CSharp.MessageProvider.Instance, isScriptRunner) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsScriptRunner ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool deterministic = false; // TODO(5431): Enable deterministic mode by default bool emitPdb = false; DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb; bool debugPlus = false; string pdbPath = null; bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts string outputDirectory = baseDirectory; ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> sourcePaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; string instrument = ""; CultureInfo preferredUILang = null; string touchedFilesPath = null; bool optionsEnded = false; bool interactiveMode = false; bool publicSign = false; string sourceLink = null; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsScriptRunner) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); if (sourceFiles.Count > 0) { sourceFilesSpecified = true; } continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "lib": case "libpath": case "libpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsScriptRunner) { switch (name) { case "-": // csi -- script.csx if (value != null) break; // Indicates that the remaining arguments should not be treated as options. optionsEnded = true; continue; case "i": case "i+": if (value != null) break; interactiveMode = true; continue; case "i-": if (value != null) break; interactiveMode = false; continue; case "loadpath": case "loadpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": case "usings": case "import": case "imports": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "instrument": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { instrument = value; } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": // The use of SQM is deprecated in the compiler but we still support the parsing of the option for // back compat reasons. if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { Guid sqmSessionGuid; if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": value = RemoveQuotesAndSlashes(value); if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "sourcelink": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { sourceLink = ParseGenericPathToFile(value, diagnostics, baseDirectory); } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only value = RemoveQuotesAndSlashes(value); if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); continue; } switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) break; emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "deterministic": case "deterministic+": if (value != null) break; deterministic = true; continue; case "deterministic-": if (value != null) break; deterministic = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveQuotesAndSlashes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": value = RemoveQuotesAndSlashes(value); ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "pathmap": // "/pathmap:K1=V1,K2=V2..." { if (value == null) break; pathMap = pathMap.Concat(ParsePathMap(value, diagnostics)); } continue; case "filealign": value = RemoveQuotesAndSlashes(value); ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib && sdkDirectory != null) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } if (sourceLink != null) { if (!emitPdb || debugInformationFormat != DebugInformationFormat.PortablePdb && debugInformationFormat != DebugInformationFormat.Embedded) { AddDiagnostic(diagnostics, ErrorCode.ERR_SourceLinkRequiresPortablePdb); } } var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features); string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular, features: parsedFeatures ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics won't be reported on the command line. var reportSuppressedDiagnostics = errorLogPath != null; var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions, reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion, instrument: instrument ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsScriptRunner = IsScriptRunner, InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, PathMap = pathMap, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, SourceLink = sourceLink, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, SourcePaths = sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, ReportAnalyzer = reportAnalyzer }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!PortableShim.Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveQuotesAndSlashes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsScriptRunner && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsScriptRunner); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // Add SDK directory if it is available if (sdkDirectoryOpt != null) { builder.Add(sdkDirectoryOpt); } // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, out LanguageVersion version) { var defaultVersion = LanguageVersion.Latest.MapLatestToVersion(); if (str == null) { version = defaultVersion; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "7": version = LanguageVersion.CSharp7; return true; case "default": version = defaultVersion; return true; default: // We are likely to introduce minor version numbers after C# 7, thus breaking the // one-to-one correspondence between the integers and the corresponding // LanguageVersion enum values. But for compatibility we continue to accept any // integral value parsed by int.TryParse for its corresponding LanguageVersion enum // value for language version C# 6 and earlier (e.g. leading zeros are allowed) int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && versionNumber <= 6 && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = defaultVersion; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ISymbolWriter ** ** ** Represents a symbol writer for managed code. Provides methods to ** define documents, sequence points, lexical scopes, and variables. ** ** ===========================================================*/ namespace System.Diagnostics.SymbolStore { using System; using System.Text; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Versioning; // Interface does not need to be marked with the serializable attribute [System.Runtime.InteropServices.ComVisible(true)] public interface ISymbolWriter { // Set the IMetadataEmitter that this symbol writer is associated // with. This must be done only once before any other ISymbolWriter // methods are called. [ResourceExposure(ResourceScope.Machine)] void Initialize(IntPtr emitter, String filename, bool fFullBuild); // Define a source document. Guid's will be provided for the // languages, vendors, and document types that we currently know // about. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif ISymbolDocumentWriter DefineDocument(String url, Guid language, Guid languageVendor, Guid documentType); // Define the method that the user has defined as their entrypoint // for this module. This would be, perhaps, the user's main method // rather than compiler generated stubs before main. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void SetUserEntryPoint(SymbolToken entryMethod); // Open a method to emit symbol information into. The given method // becomes the current method for calls do define sequence points, // parameters and lexical scopes. There is an implicit lexical // scope around the entire method. Re-opening a method that has // been previously closed effectivley erases any previously // defined symbols for that method. // // There can be only one open method at a time. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void OpenMethod(SymbolToken method); // Close the current method. Once a method is closed, no more // symbols can be defined within it. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void CloseMethod(); // Define a group of sequence points within the current method. // Each line/column defines the start of a statement within a // method. The arrays should be sorted by offset. The offset is // always the offset from the start of the method, in bytes. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns); // Open a new lexical scope in the current method. The scope // becomes the new current scope and is effectivley pushed onto a // stack of scopes. startOffset is the offset, in bytes from the // beginning of the method, of the first instruction in the // lexical scope. Scopes must form a hierarchy. Siblings are not // allowed to overlap. // // OpenScope returns an opaque scope id that can be used with // SetScopeRange to define a scope's start/end offset at a later // time. In this case, the offsets passed to OpenScope and // CloseScope are ignored. // // Note: scope id's are only valid in the current method. // // <TODO>@todo: should we require that startOffset and endOffset for // scopes also be defined as sequence points?</TODO> #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif int OpenScope(int startOffset); // Close the current lexical scope. Once a scope is closed no more // variables can be defined within it. endOffset points past the // last instruction in the scope. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void CloseScope(int endOffset); // Define the offset range for a given lexical scope. void SetScopeRange(int scopeID, int startOffset, int endOffset); // Define a single variable in the current lexical // scope. startOffset and endOffset are optional. If 0, then they // are ignored and the variable is defined over the entire // scope. If non-zero, then they must fall within the offsets of // the current scope. This can be called multiple times for a // variable of the same name that has multiple homes throughout a // scope. (Note: start/end offsets must not overlap in such a // case.) #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void DefineLocalVariable(String name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset); // Define a single parameter in the current method. The type of // each parameter is taken from its position (sequence) within the // method's signature. // // Note: if parameters are defined in the metadata for a given // method, then clearly one would not have to define them again // with calls to this method. The symbol readers will have to be // smart enough to check the normal metadata for these first then // fall back to the symbol store. void DefineParameter(String name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3); // Define a single variable not within a method. This is used for // certian fields in classes, bitfields, etc. void DefineField(SymbolToken parent, String name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3); // Define a single global variable. void DefineGlobalVariable(String name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3); // Close will close the ISymbolWriter and commit the symbols // to the symbol store. The ISymbolWriter becomes invalid // after this call for further updates. void Close(); // Defines a custom attribute based upon its name. Not to be // confused with Metadata custom attributes, these attributes are // held in the symbol store. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void SetSymAttribute(SymbolToken parent, String name, byte[] data); // Opens a new namespace. Call this before defining methods or // variables that live within a namespace. Namespaces can be nested. void OpenNamespace(String name); // Close the most recently opened namespace. void CloseNamespace(); // Specifies that the given, fully qualified namespace name is // being used within the currently open lexical scope. Closing the // current scope will also stop using the namespace, and the // namespace will be in use in all scopes that inherit from the // currently open scope. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void UsingNamespace(String fullName); // Specifies the true start and end of a method within a source // file. Use this to specify the extent of a method independently // of what sequence points exist within the method. void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn); // Used to set the underlying ISymUnmanagedWriter that a // managed ISymbolWriter may use to emit symbols with. void SetUnderlyingWriter(IntPtr underlyingWriter); } }
// 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.Linq; using System.Xml.Linq; using Xunit; namespace CoreXml.Test.XLinq.FunctionalTests.EventsTests { public class EventsRemove { public static object[][] ExecuteXDocumentVariationParams = new object[][] { new object[] { new XNode[] { new XElement("element") }, 0 }, new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, 0 }, new object[] { new XNode[] { new XDocumentType("root", "", "", "") }, 0 }, new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, 0 }, new object[] { new XNode[] { new XComment("Comment") }, 0 }, new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, 1 } }; [Theory, MemberData("ExecuteXDocumentVariationParams")] public void ExecuteXDocumentVariation(XNode[] content, int index) { XDocument xDoc = new XDocument(content); XDocument xDocOriginal = new XDocument(xDoc); XNode toRemove = xDoc.Nodes().ElementAt(index); using (UndoManager undo = new UndoManager(xDoc)) { undo.Group(); using (EventsHelper docHelper = new EventsHelper(xDoc)) { toRemove.Remove(); docHelper.Verify(XObjectChange.Remove, toRemove); } undo.Undo(); Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!"); } } public static object[][] ExecuteXElementVariationParams = new object[][] { new object[] { new XNode[] { new XElement("element") }, 0 }, new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) }, 0 }, new object[] { new XNode[] { new XElement("parent", "parent text"), new XElement("child", "child text") }, 1 }, new object[] { new XNode[] { new XElement("parent", "parent text"), new XText("text"), new XElement("child", "child text") }, 1 }, new object[] { new XNode[] { new XCData("x+y >= z-m") }, 0 }, new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") }, 0 }, new object[] { new XNode[] { new XComment("Comment") }, 0 }, new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, 0 }, new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, 1 }, new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") }, 2 }, new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray(), 50 } }; [Theory, MemberData("ExecuteXElementVariationParams")] public void ExecuteXElementVariation(XNode[] content, int index) { XElement xElem = new XElement("root", content); XNode toRemove = xElem.Nodes().ElementAt(index); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper elemHelper = new EventsHelper(xElem)) { toRemove.Remove(); xElem.Verify(); elemHelper.Verify(XObjectChange.Remove, toRemove); } undo.Undo(); Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } public static object[][] ExecuteXAttributeVariationParams = new object[][] { new object[] { new XAttribute[] { new XAttribute("xxx", "yyy") }, 0 }, new object[] { new XAttribute[] { new XAttribute("{a}xxx", "a_yyy") }, 0 }, new object[] { new XAttribute[] { new XAttribute("xxx", "yyy"), new XAttribute("a", "aa") }, 1 }, new object[] { new XAttribute[] { new XAttribute("{b}xxx", "b_yyy"), new XAttribute("{a}xxx", "a_yyy") }, 0 }, new object[] { InputSpace.GetAttributeElement(10, 1000).Elements().Attributes().ToArray(), 10 } }; [Theory, MemberData("ExecuteXAttributeVariationParams")] public void ExecuteXAttributeVariation(XAttribute[] content, int index) { XElement xElem = new XElement("root", content); XAttribute toRemove = xElem.Attributes().ElementAt(index); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper elemHelper = new EventsHelper(xElem)) { toRemove.Remove(); xElem.Verify(); elemHelper.Verify(XObjectChange.Remove, toRemove); } undo.Undo(); Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } [Fact] public void XElementWorkOnTextNodes1() { XElement elem = new XElement("A", "text2"); elem.Add("text0"); elem.Add("text1"); using (UndoManager undo = new UndoManager(elem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(elem)) { elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); Assert.True(elem.IsEmpty, "Did not remove correctly"); } undo.Undo(); Assert.Equal(elem.Value, "text2text0text1"); } } [Fact] public void XElementWorkOnTextNodes2() { XElement elem = new XElement("A", "text2"); elem.AddFirst("text0"); elem.AddFirst("text1"); using (UndoManager undo = new UndoManager(elem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(elem)) { elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); Assert.False(elem.IsEmpty, "Did not remove correctly"); elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); Assert.False(elem.IsEmpty, "Did not remove correctly"); elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); Assert.True(elem.IsEmpty, "Did not remove correctly"); } undo.Undo(); Assert.Equal(elem.Value, "text1text0text2"); } } [Fact] public void XElementWorkOnTextNodes3() { XElement elem = new XElement("A", "text2"); elem.FirstNode.AddBeforeSelf("text0"); elem.FirstNode.AddBeforeSelf("text1"); using (UndoManager undo = new UndoManager(elem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(elem)) { elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); Assert.False(elem.IsEmpty, "Did not remove correctly"); elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); Assert.False(elem.IsEmpty, "Did not remove correctly"); elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); Assert.True(elem.IsEmpty, "Did not remove correctly"); } undo.Undo(); Assert.Equal(elem.Value, "text1text0text2"); } } [Fact] public void XElementWorkOnTextNodes4() { XElement elem = new XElement("A", "text2"); elem.FirstNode.AddAfterSelf("text0"); elem.FirstNode.AddAfterSelf("text1"); using (UndoManager undo = new UndoManager(elem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(elem)) { elem.FirstNode.Remove(); eHelper.Verify(XObjectChange.Remove); Assert.True(elem.IsEmpty, "Did not remove correctly"); } undo.Undo(); Assert.Equal(elem.Value, "text2text0text1"); } } [Fact] public void XAttributeRemoveOneByOne() { XDocument xDoc = new XDocument(InputSpace.GetAttributeElement(1, 100)); XDocument xDocOriginal = new XDocument(xDoc); using (UndoManager undo = new UndoManager(xDoc)) { undo.Group(); using (EventsHelper docHelper = new EventsHelper(xDoc)) { using (EventsHelper eHelper = new EventsHelper(xDoc.Root)) { List<XAttribute> list = xDoc.Root.Attributes().ToList(); foreach (XAttribute x in list) { x.Remove(); eHelper.Verify(XObjectChange.Remove, x); } docHelper.Verify(XObjectChange.Remove, list.Count); } } undo.Undo(); Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!"); } } [Fact] public void XElementRemoveOneByOne() { XDocument xDoc = new XDocument(InputSpace.GetElement(100, 10)); XDocument xDocOriginal = new XDocument(xDoc); using (UndoManager undo = new UndoManager(xDoc)) { undo.Group(); using (EventsHelper docHelper = new EventsHelper(xDoc)) { using (EventsHelper eHelper = new EventsHelper(xDoc.Root)) { List<XElement> list = xDoc.Root.Elements().ToList(); foreach (XElement x in list) { x.Remove(); eHelper.Verify(XObjectChange.Remove, x); } docHelper.Verify(XObjectChange.Remove, list.Count); } } undo.Undo(); Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!"); } } [Fact] public void XAttributeRemoveSeq() { XDocument xDoc = new XDocument(InputSpace.GetAttributeElement(100, 100)); XDocument xDocOriginal = new XDocument(xDoc); using (UndoManager undo = new UndoManager(xDoc)) { undo.Group(); using (EventsHelper docHelper = new EventsHelper(xDoc)) { using (EventsHelper eHelper = new EventsHelper(xDoc.Root)) { List<XAttribute> list = xDoc.Root.Attributes().ToList(); xDoc.Root.Attributes().Remove(); eHelper.Verify(XObjectChange.Remove, list.ToArray()); docHelper.Verify(XObjectChange.Remove, list.ToArray()); } } undo.Undo(); Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!"); } } [Fact] public void XElementRemoveSeq() { XDocument xDoc = new XDocument(InputSpace.GetElement(100, 10)); XDocument xDocOriginal = new XDocument(xDoc); using (UndoManager undo = new UndoManager(xDoc)) { undo.Group(); using (EventsHelper docHelper = new EventsHelper(xDoc)) { using (EventsHelper eHelper = new EventsHelper(xDoc.Root)) { List<XElement> list = xDoc.Root.Elements().ToList(); xDoc.Root.Elements().Remove(); eHelper.Verify(XObjectChange.Remove, list.ToArray()); docHelper.Verify(XObjectChange.Remove, list.ToArray()); } } undo.Undo(); Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!"); } } [Fact] public void XElementParentedXNode() { bool firstTime = true; XElement element = XElement.Parse("<root></root>"); XElement child = new XElement("Add", "Me"); element.Add(child); element.Changing += new EventHandler<XObjectChangeEventArgs>( delegate (object sender, XObjectChangeEventArgs e) { if (firstTime) { firstTime = false; child.Remove(); } }); Assert.Throws<InvalidOperationException>(() => { child.Remove(); }); element.Verify(); } [Fact] public void XElementChangeAttributesParentInThePreEventHandler() { bool firstTime = true; XElement element = XElement.Parse("<root></root>"); XAttribute child = new XAttribute("Add", "Me"); element.Add(child); element.Changing += new EventHandler<XObjectChangeEventArgs>( delegate (object sender, XObjectChangeEventArgs e) { if (firstTime) { firstTime = false; child.Remove(); } }); Assert.Throws<InvalidOperationException>(() => { child.Remove(); }); element.Verify(); } } public class EventsRemoveNodes { public static object[][] ExecuteXDocumentVariationParams = new object[][] { new object[] { new XNode[] { new XElement("element") } }, new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) } }, new object[] { new XNode[] { new XDocumentType("root", "", "", "") } }, new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") } }, new object[] { new XNode[] { new XComment("Comment") } }, new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") } } }; [Theory, MemberData("ExecuteXDocumentVariationParams")] public void ExecuteXDocumentVariation(XNode[] content) { XDocument xDoc = new XDocument(content); XDocument xDocOriginal = new XDocument(xDoc); using (UndoManager undo = new UndoManager(xDoc)) { undo.Group(); using (EventsHelper docHelper = new EventsHelper(xDoc)) { xDoc.RemoveNodes(); docHelper.Verify(XObjectChange.Remove, content); } undo.Undo(); Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!"); } } public static object[][] ExecuteXElementVariationParams = new object[][] { new object[] { new XNode[] { new XElement("element") } }, new object[] { new XNode[] { new XElement("parent", new XElement("child", "child text")) } }, new object[] { new XNode[] { new XCData("x+y >= z-m") } }, new object[] { new XNode[] { new XProcessingInstruction("PI", "Data") } }, new object[] { new XNode[] { new XComment("Comment") } }, new object[] { new XNode[] { new XText(""), new XText(" "), new XText("\t") } }, new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray() } }; [Theory, MemberData("ExecuteXElementVariationParams")] public void ExecuteXElementVariation(XNode[] content) { XElement xElem = new XElement("root", InputSpace.GetAttributeElement(10, 1000).Elements().Attributes(), content); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper elemHelper = new EventsHelper(xElem)) { xElem.RemoveNodes(); Assert.True(xElem.IsEmpty, "Not all content were removed"); Assert.True(xElem.HasAttributes, "RemoveNodes removed the attributes"); xElem.Verify(); elemHelper.Verify(XObjectChange.Remove, content); } undo.Undo(); Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } [Fact] public void XElementEmptyElementSpecialCase() { XElement e = XElement.Parse(@"<A></A>"); EventsHelper eHelper = new EventsHelper(e); e.RemoveNodes(); //eHelper.Verify(XObjectChange.Remove, e.Nodes()); eHelper.Verify(XObjectChange.Value); } [Fact] public void XElementChangeNodeValueInThePreEventHandler() { bool firstTime = true; XElement element = XElement.Parse("<root></root>"); XElement child = new XElement("Add", "Me"); element.Changing += new EventHandler<XObjectChangeEventArgs>( delegate (object sender, XObjectChangeEventArgs e) { if (firstTime) { firstTime = false; element.Add(child); } }); Assert.Throws<InvalidOperationException>(() => { element.RemoveNodes(); }); element.Verify(); Assert.NotNull(element.Element("Add")); } [Fact] public void XElementChangeNodesInThePreEventHandler() { bool firstTime = true; XElement element = XElement.Parse("<root></root>"); XElement oneChild = new XElement("one", "1"); XElement twoChild = new XElement("two", "2"); element.Add(oneChild, twoChild); element.Changing += new EventHandler<XObjectChangeEventArgs>( delegate (object sender, XObjectChangeEventArgs e) { if (firstTime) { firstTime = false; element.RemoveNodes(); } }); Assert.Throws<InvalidOperationException>(() => { element.RemoveNodes(); }); element.Verify(); } [Fact] public void XElementChangeAttributesInThePreEventHandler() { bool firstTime = true; XElement element = XElement.Parse("<root></root>"); XAttribute oneChild = new XAttribute("one", "1"); XAttribute twoChild = new XAttribute("two", "2"); element.Add(oneChild, twoChild); element.Changing += new EventHandler<XObjectChangeEventArgs>( delegate (object sender, XObjectChangeEventArgs e) { if (firstTime) { firstTime = false; element.RemoveAttributes(); } }); Assert.Throws<InvalidOperationException>(() => { element.RemoveAttributes(); }); element.Verify(); } } public class EventsRemoveAll { public static object[][] ExecuteXElementVariationParams = new object[][] { new object[] { new XObject[] { new XElement("element") } }, new object[] { new XObject[] { new XElement("parent", new XElement("child", "child text")) } }, new object[] { new XObject[] { new XCData("x+y >= z-m") } }, new object[] { new XObject[] { new XProcessingInstruction("PI", "Data") } }, new object[] { new XObject[] { new XComment("Comment") } }, new object[] { new XObject[] { new XText(""), new XText(" "), new XText("\t") } }, new object[] { InputSpace.GetElement(100, 10).DescendantNodes().ToArray() }, new object[] { new XObject[] { new XAttribute("xxx", "yyy") } }, new object[] { new XObject[] { new XAttribute("{a}xxx", "a_yyy") } }, new object[] { new XObject[] { new XAttribute("xxx", "yyy"), new XAttribute("a", "aa") } }, new object[] { new XObject[] { new XAttribute("{b}xxx", "b_yyy"), new XAttribute("{a}xxx", "a_yyy") } }, new object[] { InputSpace.GetAttributeElement(10, 1000).Elements().Attributes().ToArray() }, new object[] { new XObject[] { new XAttribute("{b}xxx", "b_yyy"), new XElement("parent", new XElement("child", "child text")) } } }; [Theory, MemberData("ExecuteXElementVariationParams")] public void ExecuteXElementVariation(XObject[] content) { XElement xElem = new XElement("root", content); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper elemHelper = new EventsHelper(xElem)) { xElem.RemoveAll(); Assert.True(xElem.IsEmpty, "Not all content were removed"); Assert.True(!xElem.HasAttributes, "RemoveAll did not remove attributes"); xElem.Verify(); elemHelper.Verify(XObjectChange.Remove, content); } undo.Undo(); Assert.True(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); Assert.True(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } }
#region Copyright Notice // Copyright 2011-2013 Eleftherios Aslanoglou // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion #region Using Directives using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; #endregion namespace NonByteAlignedBinaryRW { public class NonByteAlignedBinaryReader : BinaryReader { private int _inBytePosition; public NonByteAlignedBinaryReader(Stream stream) : base(stream) { } public NonByteAlignedBinaryReader(Stream stream, Encoding encoding) : base(stream, encoding) { } public int InBytePosition { get { return _inBytePosition; } set { if (value >= 0 && value <= 7) { _inBytePosition = value; } else { throw new ArgumentOutOfRangeException("value", "The InBytePosition value can't be less than 0 or larger than 7."); } } } public byte ReadNonByteAlignedByte() { if (_inBytePosition == 0) { return ReadByte(); } else { var ba = new BitArray(ReadBytes(2)); BaseStream.Position -= 1; var r = new BitArray(8); for (int i = _inBytePosition; i < _inBytePosition + 8; i++) { int pos = 7 + i - 2*(i%8); r[i - _inBytePosition] = ba[pos]; } var temp = new BitArray(8); for (int i = 0; i < 8; i++) { temp[i] = r[7 - i]; } return BitArrayToByte(temp); } } public byte[] ReadNonByteAlignedBytes(int count) { if (count <= 0) throw new ArgumentOutOfRangeException("count"); if (_inBytePosition == 0) { return ReadBytes(count); } else { var bytes = new byte[count]; for (int i = 0; i < count; i++) { bytes[i] = ReadNonByteAlignedByte(); } return bytes; } } public string ReadNonByteAlignedBits(int count) { if (count <= 0) throw new ArgumentOutOfRangeException("count"); string s = ""; int bytesToRead = count/8; if (bytesToRead > 0) { byte[] bytes = ReadNonByteAlignedBytes(bytesToRead); s += ByteArrayToBitString(bytes); } int bitsToRead = (count%8); if (bitsToRead > 0) { var newStart = 0; if (BaseStream.Length == BaseStream.Position + 1) { if (count <= 8 - _inBytePosition) { newStart = _inBytePosition; //bitsToRead = 8; _inBytePosition = 0; } } byte rem = ReadNonByteAlignedByte(); _inBytePosition += bitsToRead; if (_inBytePosition >= 8) { _inBytePosition = _inBytePosition%8; } else if (count + newStart != 8) { BaseStream.Position -= 1; } s += ByteToBitString(rem, bitsToRead, newStart); } return s; } public static string ByteToBitString(byte b, int length = 8, int offset = 0) { if (length + offset > 8) throw new ArgumentOutOfRangeException(); /* var ba = new BitArray(new[] {b}); string s = ""; for (int i = 7 - offset; i > 7 - length; i--) { if (ba[i]) s += "1"; else s += "0"; } */ var s = Convert.ToString(b, 2).PadLeft(8, '0').Substring(offset, length); return s; } public static byte BitStringToByte(string s) { return BitStringToByteArray(s)[0]; } public static byte[] BitStringToByteArray(string s) { int count = ((s.Length - 1)/8) + 1; var ba = new byte[count]; for (int j = 0; j < count; j++) { byte b = 0; char[] ca = s.Skip(j*8).Take(8).Reverse().ToArray(); for (int i = 0; i < ca.Length; i++) { if (ca[i] == '1') { b += Convert.ToByte(Math.Pow(2, i)); } } ba[j] = b; } return ba; } public static string ByteArrayToBitString(IEnumerable<byte> bytes) { return bytes.Aggregate("", (current, b) => current + ByteToBitString(b)); } public static byte[] BitArrayToByteArray(BitArray bits) { var ret = new byte[bits.Length/8]; bits.CopyTo(ret, 0); return ret; } public static byte BitArrayToByte(BitArray bits) { if (bits.Length != 8) throw new ArgumentException("The BitArray parameter can't have a length other than 8 bits."); return BitArrayToByteArray(bits)[0]; } public void MoveStreamPosition(int bytes, int bits) { if ((_inBytePosition + bits >= 8)) { BaseStream.Position += (_inBytePosition + bits)/8; } if (_inBytePosition + bits >= 0) { _inBytePosition = (_inBytePosition + bits)%8; } else { BaseStream.Position += ((_inBytePosition + bits)/8) - 1; _inBytePosition = ((_inBytePosition + bits)%8) + 8; } BaseStream.Position += bytes; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace CslaContrib.Mvc { public class FactoryMethodLocator : IFactoryMethodLocator { public static readonly IList<PatternMap> PatternMappings = new List<PatternMap> { new PatternMap{ActionPattern = "create.*", MethodPatterns = new[] {"New.*"}}, new PatternMap{ActionPattern = "add.*", MethodPatterns = new[] {"New.*"}}, new PatternMap{ActionPattern = "edit.*", MethodPatterns = new[] {"Get.*"}}, new PatternMap{ActionPattern = "detail.*", MethodPatterns = new[] {"Get.*"}}, new PatternMap{ActionPattern = "update.*", MethodPatterns = new[] {"Get.*"}}, new PatternMap{ActionPattern = "show.*", MethodPatterns = new[] {"Get.*"}}, new PatternMap{ActionPattern = "index.*", MethodPatterns = new[] {"Get.*List", "Get.*Collection"}}, new PatternMap{ActionPattern = "list.*", MethodPatterns = new[] {"Get.*List", "Get.*Collection"}} }; public MethodInfo GetMethod(Type factoryType, Type returnType, string methodName, Type[] parameterTypes) { if (factoryType == null) factoryType = returnType; if (parameterTypes == null) parameterTypes = Type.EmptyTypes; //might use separate factory class BindingFlags flags = factoryType == returnType ? ftorMethodFlags : ftorFlags; var method = factoryType.GetMethod(methodName, flags, null, parameterTypes, null); if (method == null || method.ReturnType != returnType) return null; return method; } public MethodInfo GetMethod(Type factoryType, Type returnType, string methodName, object[] argumentValues) { var argTypes = argumentValues == null ? Type.EmptyTypes : argumentValues.GetTypes().ToArray(); if (!argTypes.Any(t => t.IsArray)) return GetMethod(factoryType, returnType, methodName, argTypes); //argument type contain object[] which indicate it contains unknown type //1. find matching methods given method name and number of arguments //2. determine which ones contain assignable arguments; also convert value var methods = FindMatchingMethods(factoryType, returnType, methodName, argTypes.Length); methods = FindMethodsWithMatchingArguments(methods, argumentValues); if (methods == null || methods.Length == 0) return null; if (methods.Length > 1) { var methodNames = Array.ConvertAll(methods, m => m.Name); var message = "Unable to find factory method. " + string.Format("There are multiple factory methods found: {0}. ", string.Join(", ", methodNames)) + "Please use CslaBind attribute to specify the intended method."; throw new AmbiguousMatchException(message); } return methods[0]; } public MethodInfo GetMethod(string actionName, Type factoryType, Type returnType, object[] argumentValues) { var argTypes = argumentValues == null ? Type.EmptyTypes : argumentValues.GetTypes().ToArray(); //1. find matching methods with equal number of arguments based on action name //2. determine which ones contain assignable arguments; also convert value if value is unknown type var methods = FindMatchingMethods(actionName, factoryType, returnType, argTypes.Length); methods = FindMethodsWithMatchingArguments(methods, argumentValues); if (methods == null || methods.Length == 0) return null; if (methods.Length > 1) { var methodNames = Array.ConvertAll(methods, m => m.Name); var message = "Unable to find factory method by convention. " + string.Format("There are multiple factory methods found: {0}. ", string.Join(", ", methodNames)) + "Please use CslaBind attribute to specify the intended method."; throw new AmbiguousMatchException(message); } return methods[0]; } protected MethodInfo[] FindMatchingMethods(Type factoryType, Type returnType, string methodName, int parameterCount) { return (from m in AllFactoryMethods(factoryType, returnType, parameterCount) where m.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase) select m).ToArray(); } protected MethodInfo[] FindMatchingMethods(string actionName, Type factoryType, Type returnType, int parameterCount) { if (factoryType == null) factoryType = returnType; return (from m in AllFactoryMethods(factoryType, returnType, parameterCount) let patterns = from p in PatternMappings where Regex.Match(actionName, p.ActionPattern, RegexOptions.IgnoreCase).Success select p where patterns.Any(mp => mp.MethodPatterns.Any(p => Regex.Match(m.Name, p, RegexOptions.IgnoreCase).Success)) select m).ToArray(); } BindingFlags ftorFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy; BindingFlags ftorMethodFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy; protected IEnumerable<MethodInfo> AllFactoryMethods(Type factoryType, Type returnType, int parameterCount) { if (factoryType == null || factoryType == returnType) { //use factory method return from m in returnType.GetMethods(ftorMethodFlags) where m.GetParameters().Count() == parameterCount && m.ReturnType == returnType && m.IsStatic select m; } //use object factory class return from m in factoryType.GetMethods(ftorFlags) where m.GetParameters().Count() == parameterCount && m.ReturnType == returnType select m; } protected virtual MethodInfo[] FindMethodsWithMatchingArguments(MethodInfo[] methods, object[] argumentValues) { if (methods == null) return null; if(argumentValues == null) return methods; var matches = new List<MethodInfo>(); foreach (MethodInfo method in methods) { //make sure all argument types are match bool match = true; var pis = method.GetParameters(); for (int i = 0; i < argumentValues.Length; i++) { var param = pis[i]; var argValue = argumentValues[i]; if (argValue.GetType().IsArray) { //argument type is unknown, check if assignable var paramType = param.ParameterType; argValue = ((IList)argValue)[0]; object convertedValue; if (TryConvertArgument(paramType, argValue, out convertedValue)) { argumentValues[i] = convertedValue; continue; } //not match match = false; break; } if (!param.ParameterType.IsAssignableFrom(argValue.GetType())) { match = false; break; } } if (match) matches.Add(method); } return matches.ToArray(); } protected virtual bool TryConvertArgument(Type type, object value, out object convertedValue) { if (type.IsAssignableFrom(value.GetType())) { convertedValue = value; return true; } var converter = TypeDescriptor.GetConverter(value); if (converter != null && converter.CanConvertTo(type)) { //convert argument value convertedValue = converter.ConvertTo(value, type); return true; } converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.CanConvertFrom(value.GetType())) { try { //convert argument value convertedValue = converter.ConvertFrom(value); return true; } catch { /* not convertible, continue..*/ } } try { convertedValue = Convert.ChangeType(value, type); return true; } catch { /* not convertible, continue..*/ } // no possible conversion convertedValue = null; return false; } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Diagnostics; using dnlib.PE; namespace dnlib.DotNet { /// <summary> /// All native vtables /// </summary> [DebuggerDisplay("RVA = {RVA}, Count = {VTables.Count}")] public sealed class VTableFixups : IEnumerable<VTable> { RVA rva; IList<VTable> vtables; /// <summary> /// Gets/sets the RVA of the vtable fixups /// </summary> public RVA RVA { get => rva; set => rva = value; } /// <summary> /// Gets all <see cref="VTable"/>s /// </summary> public IList<VTable> VTables => vtables; /// <summary> /// Default constructor /// </summary> public VTableFixups() => vtables = new List<VTable>(); /// <summary> /// Constructor /// </summary> /// <param name="module">Module</param> public VTableFixups(ModuleDefMD module) => Initialize(module); void Initialize(ModuleDefMD module) { var info = module.Metadata.ImageCor20Header.VTableFixups; if (info.VirtualAddress == 0 || info.Size == 0) { vtables = new List<VTable>(); return; } rva = info.VirtualAddress; vtables = new List<VTable>((int)info.Size / 8); var peImage = module.Metadata.PEImage; var reader = peImage.CreateReader(); reader.Position = (uint)peImage.ToFileOffset(info.VirtualAddress); ulong endPos = (ulong)reader.Position + info.Size; while ((ulong)reader.Position + 8 <= endPos && reader.CanRead(8U)) { var tableRva = (RVA)reader.ReadUInt32(); int numSlots = reader.ReadUInt16(); var flags = (VTableFlags)reader.ReadUInt16(); var vtable = new VTable(tableRva, flags, numSlots); vtables.Add(vtable); var pos = reader.Position; reader.Position = (uint)peImage.ToFileOffset(tableRva); uint slotSize = vtable.Is64Bit ? 8U : 4; while (numSlots-- > 0 && reader.CanRead(slotSize)) { vtable.Methods.Add(module.ResolveToken(reader.ReadUInt32()) as IMethod); if (slotSize == 8) reader.ReadUInt32(); } reader.Position = pos; } } /// <inheritdoc/> public IEnumerator<VTable> GetEnumerator() => vtables.GetEnumerator(); /// <inheritdoc/> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } /// <summary> /// See COR_VTABLE_XXX in CorHdr.h /// </summary> [Flags] public enum VTableFlags : ushort { /// <summary> /// 32-bit vtable slots /// </summary> Bit32 = 0x01, /// <summary> /// 64-bit vtable slots /// </summary> Bit64 = 0x02, /// <summary> /// Transition from unmanaged code /// </summary> FromUnmanaged = 0x04, /// <summary> /// Also retain app domain /// </summary> FromUnmanagedRetainAppDomain = 0x08, /// <summary> /// Call most derived method /// </summary> CallMostDerived = 0x10, } /// <summary> /// One VTable accessed by native code /// </summary> public sealed class VTable : IEnumerable<IMethod> { RVA rva; VTableFlags flags; readonly IList<IMethod> methods; /// <summary> /// Gets/sets the <see cref="RVA"/> of this vtable /// </summary> public RVA RVA { get => rva; set => rva = value; } /// <summary> /// Gets/sets the flags /// </summary> public VTableFlags Flags { get => flags; set => flags = value; } /// <summary> /// <c>true</c> if each vtable slot is 32 bits in size /// </summary> public bool Is32Bit => (flags & VTableFlags.Bit32) != 0; /// <summary> /// <c>true</c> if each vtable slot is 64 bits in size /// </summary> public bool Is64Bit => (flags & VTableFlags.Bit64) != 0; /// <summary> /// Gets the vtable methods /// </summary> public IList<IMethod> Methods => methods; /// <summary> /// Default constructor /// </summary> public VTable() => methods = new List<IMethod>(); /// <summary> /// Constructor /// </summary> /// <param name="flags">Flags</param> public VTable(VTableFlags flags) { this.flags = flags; methods = new List<IMethod>(); } /// <summary> /// Constructor /// </summary> /// <param name="rva">RVA of this vtable</param> /// <param name="flags">Flgas</param> /// <param name="numSlots">Number of methods in vtable</param> public VTable(RVA rva, VTableFlags flags, int numSlots) { this.rva = rva; this.flags = flags; methods = new List<IMethod>(numSlots); } /// <summary> /// Constructor /// </summary> /// <param name="rva">RVA of this vtable</param> /// <param name="flags">Flgas</param> /// <param name="methods">Vtable methods</param> public VTable(RVA rva, VTableFlags flags, IEnumerable<IMethod> methods) { this.rva = rva; this.flags = flags; this.methods = new List<IMethod>(methods); } /// <inheritdoc/> public IEnumerator<IMethod> GetEnumerator() => methods.GetEnumerator(); /// <inheritdoc/> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); /// <inheritdoc/> public override string ToString() { if (methods.Count == 0) return $"{methods.Count} {(uint)rva:X8}"; return $"{methods.Count} {(uint)rva:X8} {methods[0]}"; } } }
//#define Trace // ParallelDeflateOutputStream.cs // ------------------------------------------------------------------ // // A DeflateStream that does compression only, it uses a // divide-and-conquer approach with multiple threads to exploit multiple // CPUs for the DEFLATE computation. // // last saved: <2011-July-31 14:49:40> // // ------------------------------------------------------------------ // // Copyright (c) 2009-2011 by Dino Chiesa // All rights reserved! // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Threading; using Ionic.Zlib; using System.IO; namespace Ionic.Zlib { internal class WorkItem { public byte[] buffer; public byte[] compressed; public int crc; public int index; public int ordinal; public int inputBytesAvailable; public int compressedBytesAvailable; public ZlibCodec compressor; public WorkItem(int size, Ionic.Zlib.CompressionLevel compressLevel, CompressionStrategy strategy, int ix) { this.buffer= new byte[size]; // alloc 5 bytes overhead for every block (margin of safety= 2) int n = size + ((size / 32768)+1) * 5 * 2; this.compressed = new byte[n]; this.compressor = new ZlibCodec(); this.compressor.InitializeDeflate(compressLevel, false); this.compressor.OutputBuffer = this.compressed; this.compressor.InputBuffer = this.buffer; this.index = ix; } } /// <summary> /// A class for compressing streams using the /// Deflate algorithm with multiple threads. /// </summary> /// /// <remarks> /// <para> /// This class performs DEFLATE compression through writing. For /// more information on the Deflate algorithm, see IETF RFC 1951, /// "DEFLATE Compressed Data Format Specification version 1.3." /// </para> /// /// <para> /// This class is similar to <see cref="Ionic.Zlib.DeflateStream"/>, except /// that this class is for compression only, and this implementation uses an /// approach that employs multiple worker threads to perform the DEFLATE. On /// a multi-cpu or multi-core computer, the performance of this class can be /// significantly higher than the single-threaded DeflateStream, particularly /// for larger streams. How large? Anything over 10mb is a good candidate /// for parallel compression. /// </para> /// /// <para> /// The tradeoff is that this class uses more memory and more CPU than the /// vanilla DeflateStream, and also is less efficient as a compressor. For /// large files the size of the compressed data stream can be less than 1% /// larger than the size of a compressed data stream from the vanialla /// DeflateStream. For smaller files the difference can be larger. The /// difference will also be larger if you set the BufferSize to be lower than /// the default value. Your mileage may vary. Finally, for small files, the /// ParallelDeflateOutputStream can be much slower than the vanilla /// DeflateStream, because of the overhead associated to using the thread /// pool. /// </para> /// /// </remarks> /// <seealso cref="Ionic.Zlib.DeflateStream" /> public class ParallelDeflateOutputStream : System.IO.Stream { private static readonly int IO_BUFFER_SIZE_DEFAULT = 64 * 1024; // 128k private static readonly int BufferPairsPerCore = 4; private System.Collections.Generic.List<WorkItem> _pool; private bool _leaveOpen; private bool emitting; private System.IO.Stream _outStream; private int _maxBufferPairs; private int _bufferSize = IO_BUFFER_SIZE_DEFAULT; private AutoResetEvent _newlyCompressedBlob; //private ManualResetEvent _writingDone; //private ManualResetEvent _sessionReset; private object _outputLock = new object(); private bool _isClosed; private bool _firstWriteDone; private int _currentlyFilling; private int _lastFilled; private int _lastWritten; private int _latestCompressed; private int _Crc32; private Ionic.Crc.CRC32 _runningCrc; private object _latestLock = new object(); private System.Collections.Generic.Queue<int> _toWrite; private System.Collections.Generic.Queue<int> _toFill; private Int64 _totalBytesProcessed; private Ionic.Zlib.CompressionLevel _compressLevel; private volatile Exception _pendingException; private bool _handlingException; private object _eLock = new Object(); // protects _pendingException // This bitfield is used only when Trace is defined. //private TraceBits _DesiredTrace = TraceBits.Write | TraceBits.WriteBegin | //TraceBits.WriteDone | TraceBits.Lifecycle | TraceBits.Fill | TraceBits.Flush | //TraceBits.Session; //private TraceBits _DesiredTrace = TraceBits.WriteBegin | TraceBits.WriteDone | TraceBits.Synch | TraceBits.Lifecycle | TraceBits.Session ; private TraceBits _DesiredTrace = TraceBits.Session | TraceBits.Compress | TraceBits.WriteTake | TraceBits.WriteEnter | TraceBits.EmitEnter | TraceBits.EmitDone | TraceBits.EmitLock | TraceBits.EmitSkip | TraceBits.EmitBegin; /// <summary> /// Create a ParallelDeflateOutputStream. /// </summary> /// <remarks> /// /// <para> /// This stream compresses data written into it via the DEFLATE /// algorithm (see RFC 1951), and writes out the compressed byte stream. /// </para> /// /// <para> /// The instance will use the default compression level, the default /// buffer sizes and the default number of threads and buffers per /// thread. /// </para> /// /// <para> /// This class is similar to <see cref="Ionic.Zlib.DeflateStream"/>, /// except that this implementation uses an approach that employs /// multiple worker threads to perform the DEFLATE. On a multi-cpu or /// multi-core computer, the performance of this class can be /// significantly higher than the single-threaded DeflateStream, /// particularly for larger streams. How large? Anything over 10mb is /// a good candidate for parallel compression. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a ParallelDeflateOutputStream to compress /// data. It reads a file, compresses it, and writes the compressed data to /// a second, output file. /// /// <code> /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n= -1; /// String outputFile = fileToCompress + ".compressed"; /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(outputFile)) /// { /// using (Stream compressor = new ParallelDeflateOutputStream(raw)) /// { /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Dim outputFile As String = (fileToCompress &amp; ".compressed") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(outputFile) /// Using compressor As Stream = New ParallelDeflateOutputStream(raw) /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream to which compressed data will be written.</param> public ParallelDeflateOutputStream(System.IO.Stream stream) : this(stream, CompressionLevel.Default, CompressionStrategy.Default, false) { } /// <summary> /// Create a ParallelDeflateOutputStream using the specified CompressionLevel. /// </summary> /// <remarks> /// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/> /// constructor for example code. /// </remarks> /// <param name="stream">The stream to which compressed data will be written.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level) : this(stream, level, CompressionStrategy.Default, false) { } /// <summary> /// Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open /// when the ParallelDeflateOutputStream is closed. /// </summary> /// <remarks> /// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/> /// constructor for example code. /// </remarks> /// <param name="stream">The stream to which compressed data will be written.</param> /// <param name="leaveOpen"> /// true if the application would like the stream to remain open after inflation/deflation. /// </param> public ParallelDeflateOutputStream(System.IO.Stream stream, bool leaveOpen) : this(stream, CompressionLevel.Default, CompressionStrategy.Default, leaveOpen) { } /// <summary> /// Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open /// when the ParallelDeflateOutputStream is closed. /// </summary> /// <remarks> /// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/> /// constructor for example code. /// </remarks> /// <param name="stream">The stream to which compressed data will be written.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> /// <param name="leaveOpen"> /// true if the application would like the stream to remain open after inflation/deflation. /// </param> public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level, bool leaveOpen) : this(stream, CompressionLevel.Default, CompressionStrategy.Default, leaveOpen) { } /// <summary> /// Create a ParallelDeflateOutputStream using the specified /// CompressionLevel and CompressionStrategy, and specifying whether to /// leave the captive stream open when the ParallelDeflateOutputStream is /// closed. /// </summary> /// <remarks> /// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/> /// constructor for example code. /// </remarks> /// <param name="stream">The stream to which compressed data will be written.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> /// <param name="strategy"> /// By tweaking this parameter, you may be able to optimize the compression for /// data with particular characteristics. /// </param> /// <param name="leaveOpen"> /// true if the application would like the stream to remain open after inflation/deflation. /// </param> public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level, CompressionStrategy strategy, bool leaveOpen) { TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "-------------------------------------------------------"); TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "Create {0:X8}", this.GetHashCode()); _outStream = stream; _compressLevel= level; Strategy = strategy; _leaveOpen = leaveOpen; this.MaxBufferPairs = 16; // default } /// <summary> /// The ZLIB strategy to be used during compression. /// </summary> /// public CompressionStrategy Strategy { get; private set; } /// <summary> /// The maximum number of buffer pairs to use. /// </summary> /// /// <remarks> /// <para> /// This property sets an upper limit on the number of memory buffer /// pairs to create. The implementation of this stream allocates /// multiple buffers to facilitate parallel compression. As each buffer /// fills up, this stream uses <see /// cref="System.Threading.ThreadPool.QueueUserWorkItem(WaitCallback)"> /// ThreadPool.QueueUserWorkItem()</see> /// to compress those buffers in a background threadpool thread. After a /// buffer is compressed, it is re-ordered and written to the output /// stream. /// </para> /// /// <para> /// A higher number of buffer pairs enables a higher degree of /// parallelism, which tends to increase the speed of compression on /// multi-cpu computers. On the other hand, a higher number of buffer /// pairs also implies a larger memory consumption, more active worker /// threads, and a higher cpu utilization for any compression. This /// property enables the application to limit its memory consumption and /// CPU utilization behavior depending on requirements. /// </para> /// /// <para> /// For each compression "task" that occurs in parallel, there are 2 /// buffers allocated: one for input and one for output. This property /// sets a limit for the number of pairs. The total amount of storage /// space allocated for buffering will then be (N*S*2), where N is the /// number of buffer pairs, S is the size of each buffer (<see /// cref="BufferSize"/>). By default, DotNetZip allocates 4 buffer /// pairs per CPU core, so if your machine has 4 cores, and you retain /// the default buffer size of 128k, then the /// ParallelDeflateOutputStream will use 4 * 4 * 2 * 128kb of buffer /// memory in total, or 4mb, in blocks of 128kb. If you then set this /// property to 8, then the number will be 8 * 2 * 128kb of buffer /// memory, or 2mb. /// </para> /// /// <para> /// CPU utilization will also go up with additional buffers, because a /// larger number of buffer pairs allows a larger number of background /// threads to compress in parallel. If you find that parallel /// compression is consuming too much memory or CPU, you can adjust this /// value downward. /// </para> /// /// <para> /// The default value is 16. Different values may deliver better or /// worse results, depending on your priorities and the dynamic /// performance characteristics of your storage and compute resources. /// </para> /// /// <para> /// This property is not the number of buffer pairs to use; it is an /// upper limit. An illustration: Suppose you have an application that /// uses the default value of this property (which is 16), and it runs /// on a machine with 2 CPU cores. In that case, DotNetZip will allocate /// 4 buffer pairs per CPU core, for a total of 8 pairs. The upper /// limit specified by this property has no effect. /// </para> /// /// <para> /// The application can set this value at any time, but it is effective /// only before the first call to Write(), which is when the buffers are /// allocated. /// </para> /// </remarks> public int MaxBufferPairs { get { return _maxBufferPairs; } set { if (value < 4) throw new ArgumentException("MaxBufferPairs", "Value must be 4 or greater."); _maxBufferPairs = value; } } /// <summary> /// The size of the buffers used by the compressor threads. /// </summary> /// <remarks> /// /// <para> /// The default buffer size is 128k. The application can set this value /// at any time, but it is effective only before the first Write(). /// </para> /// /// <para> /// Larger buffer sizes implies larger memory consumption but allows /// more efficient compression. Using smaller buffer sizes consumes less /// memory but may result in less effective compression. For example, /// using the default buffer size of 128k, the compression delivered is /// within 1% of the compression delivered by the single-threaded <see /// cref="Ionic.Zlib.DeflateStream"/>. On the other hand, using a /// BufferSize of 8k can result in a compressed data stream that is 5% /// larger than that delivered by the single-threaded /// <c>DeflateStream</c>. Excessively small buffer sizes can also cause /// the speed of the ParallelDeflateOutputStream to drop, because of /// larger thread scheduling overhead dealing with many many small /// buffers. /// </para> /// /// <para> /// The total amount of storage space allocated for buffering will be /// (N*S*2), where N is the number of buffer pairs, and S is the size of /// each buffer (this property). There are 2 buffers used by the /// compressor, one for input and one for output. By default, DotNetZip /// allocates 4 buffer pairs per CPU core, so if your machine has 4 /// cores, then the number of buffer pairs used will be 16. If you /// accept the default value of this property, 128k, then the /// ParallelDeflateOutputStream will use 16 * 2 * 128kb of buffer memory /// in total, or 4mb, in blocks of 128kb. If you set this property to /// 64kb, then the number will be 16 * 2 * 64kb of buffer memory, or /// 2mb. /// </para> /// /// </remarks> public int BufferSize { get { return _bufferSize;} set { if (value < 1024) throw new ArgumentOutOfRangeException("BufferSize", "BufferSize must be greater than 1024 bytes"); _bufferSize = value; } } /// <summary> /// The CRC32 for the data that was written out, prior to compression. /// </summary> /// <remarks> /// This value is meaningful only after a call to Close(). /// </remarks> public int Crc32 { get { return _Crc32; } } /// <summary> /// The total number of uncompressed bytes processed by the ParallelDeflateOutputStream. /// </summary> /// <remarks> /// This value is meaningful only after a call to Close(). /// </remarks> public Int64 BytesProcessed { get { return _totalBytesProcessed; } } private void _InitializePoolOfWorkItems() { _toWrite = new Queue<int>(); _toFill = new Queue<int>(); _pool = new System.Collections.Generic.List<WorkItem>(); int nTasks = BufferPairsPerCore * Environment.ProcessorCount; nTasks = Math.Min(nTasks, _maxBufferPairs); for(int i=0; i < nTasks; i++) { _pool.Add(new WorkItem(_bufferSize, _compressLevel, Strategy, i)); _toFill.Enqueue(i); } _newlyCompressedBlob = new AutoResetEvent(false); _runningCrc = new Ionic.Crc.CRC32(); _currentlyFilling = -1; _lastFilled = -1; _lastWritten = -1; _latestCompressed = -1; } /// <summary> /// Write data to the stream. /// </summary> /// /// <remarks> /// /// <para> /// To use the ParallelDeflateOutputStream to compress data, create a /// ParallelDeflateOutputStream with CompressionMode.Compress, passing a /// writable output stream. Then call Write() on that /// ParallelDeflateOutputStream, providing uncompressed data as input. The /// data sent to the output stream will be the compressed form of the data /// written. /// </para> /// /// <para> /// To decompress data, use the <see cref="Ionic.Zlib.DeflateStream"/> class. /// </para> /// /// </remarks> /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { bool mustWait = false; // This method does this: // 0. handles any pending exceptions // 1. write any buffers that are ready to be written, // 2. fills a work buffer; when full, flip state to 'Filled', // 3. if more data to be written, goto step 1 if (_isClosed) throw new InvalidOperationException(); // dispense any exceptions that occurred on the BG threads if (_pendingException != null) { _handlingException = true; var pe = _pendingException; _pendingException = null; throw pe; } if (count == 0) return; if (!_firstWriteDone) { // Want to do this on first Write, first session, and not in the // constructor. We want to allow MaxBufferPairs to // change after construction, but before first Write. _InitializePoolOfWorkItems(); _firstWriteDone = true; } do { // may need to make buffers available EmitPendingBuffers(false, mustWait); mustWait = false; // use current buffer, or get a new buffer to fill int ix = -1; if (_currentlyFilling >= 0) { ix = _currentlyFilling; TraceOutput(TraceBits.WriteTake, "Write notake wi({0}) lf({1})", ix, _lastFilled); } else { TraceOutput(TraceBits.WriteTake, "Write take?"); if (_toFill.Count == 0) { // no available buffers, so... need to emit // compressed buffers. mustWait = true; continue; } ix = _toFill.Dequeue(); TraceOutput(TraceBits.WriteTake, "Write take wi({0}) lf({1})", ix, _lastFilled); ++_lastFilled; // TODO: consider rollover? } WorkItem workitem = _pool[ix]; int limit = ((workitem.buffer.Length - workitem.inputBytesAvailable) > count) ? count : (workitem.buffer.Length - workitem.inputBytesAvailable); workitem.ordinal = _lastFilled; TraceOutput(TraceBits.Write, "Write lock wi({0}) ord({1}) iba({2})", workitem.index, workitem.ordinal, workitem.inputBytesAvailable ); // copy from the provided buffer to our workitem, starting at // the tail end of whatever data we might have in there currently. Buffer.BlockCopy(buffer, offset, workitem.buffer, workitem.inputBytesAvailable, limit); count -= limit; offset += limit; workitem.inputBytesAvailable += limit; if (workitem.inputBytesAvailable == workitem.buffer.Length) { // No need for interlocked.increment: the Write() // method is documented as not multi-thread safe, so // we can assume Write() calls come in from only one // thread. TraceOutput(TraceBits.Write, "Write QUWI wi({0}) ord({1}) iba({2}) nf({3})", workitem.index, workitem.ordinal, workitem.inputBytesAvailable ); if (!ThreadPool.QueueUserWorkItem( _DeflateOne, workitem )) throw new Exception("Cannot enqueue workitem"); _currentlyFilling = -1; // will get a new buffer next time } else _currentlyFilling = ix; if (count > 0) TraceOutput(TraceBits.WriteEnter, "Write more"); } while (count > 0); // until no more to write TraceOutput(TraceBits.WriteEnter, "Write exit"); return; } private void _FlushFinish() { // After writing a series of compressed buffers, each one closed // with Flush.Sync, we now write the final one as Flush.Finish, // and then stop. byte[] buffer = new byte[128]; var compressor = new ZlibCodec(); int rc = compressor.InitializeDeflate(_compressLevel, false); compressor.InputBuffer = null; compressor.NextIn = 0; compressor.AvailableBytesIn = 0; compressor.OutputBuffer = buffer; compressor.NextOut = 0; compressor.AvailableBytesOut = buffer.Length; rc = compressor.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) throw new Exception("deflating: " + compressor.Message); if (buffer.Length - compressor.AvailableBytesOut > 0) { TraceOutput(TraceBits.EmitBegin, "Emit begin flush bytes({0})", buffer.Length - compressor.AvailableBytesOut); _outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut); TraceOutput(TraceBits.EmitDone, "Emit done flush"); } compressor.EndDeflate(); _Crc32 = _runningCrc.Crc32Result; } private void _Flush(bool lastInput) { if (_isClosed) throw new InvalidOperationException(); if (emitting) return; // compress any partial buffer if (_currentlyFilling >= 0) { WorkItem workitem = _pool[_currentlyFilling]; _DeflateOne(workitem); _currentlyFilling = -1; // get a new buffer next Write() } if (lastInput) { EmitPendingBuffers(true, false); _FlushFinish(); } else { EmitPendingBuffers(false, false); } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_pendingException != null) { _handlingException = true; var pe = _pendingException; _pendingException = null; throw pe; } if (_handlingException) return; _Flush(false); } /// <summary> /// Close the stream. /// </summary> /// <remarks> /// You must call Close on the stream to guarantee that all of the data written in has /// been compressed, and the compressed data has been written out. /// </remarks> public override void Close() { TraceOutput(TraceBits.Session, "Close {0:X8}", this.GetHashCode()); if (_pendingException != null) { _handlingException = true; var pe = _pendingException; _pendingException = null; throw pe; } if (_handlingException) return; if (_isClosed) return; _Flush(true); if (!_leaveOpen) _outStream.Close(); _isClosed= true; } // workitem 10030 - implement a new Dispose method /// <summary>Dispose the object</summary> /// <remarks> /// <para> /// Because ParallelDeflateOutputStream is IDisposable, the /// application must call this method when finished using the instance. /// </para> /// <para> /// This method is generally called implicitly upon exit from /// a <c>using</c> scope in C# (<c>Using</c> in VB). /// </para> /// </remarks> new public void Dispose() { TraceOutput(TraceBits.Lifecycle, "Dispose {0:X8}", this.GetHashCode()); Close(); _pool = null; Dispose(true); } /// <summary>The Dispose method</summary> /// <param name="disposing"> /// indicates whether the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { base.Dispose(disposing); } /// <summary> /// Resets the stream for use with another stream. /// </summary> /// <remarks> /// Because the ParallelDeflateOutputStream is expensive to create, it /// has been designed so that it can be recycled and re-used. You have /// to call Close() on the stream first, then you can call Reset() on /// it, to use it again on another stream. /// </remarks> /// /// <param name="stream"> /// The new output stream for this era. /// </param> /// /// <example> /// <code> /// ParallelDeflateOutputStream deflater = null; /// foreach (var inputFile in listOfFiles) /// { /// string outputFile = inputFile + ".compressed"; /// using (System.IO.Stream input = System.IO.File.OpenRead(inputFile)) /// { /// using (var outStream = System.IO.File.Create(outputFile)) /// { /// if (deflater == null) /// deflater = new ParallelDeflateOutputStream(outStream, /// CompressionLevel.Best, /// CompressionStrategy.Default, /// true); /// deflater.Reset(outStream); /// /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// deflater.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// </example> public void Reset(Stream stream) { TraceOutput(TraceBits.Session, "-------------------------------------------------------"); TraceOutput(TraceBits.Session, "Reset {0:X8} firstDone({1})", this.GetHashCode(), _firstWriteDone); if (!_firstWriteDone) return; // reset all status _toWrite.Clear(); _toFill.Clear(); foreach (var workitem in _pool) { _toFill.Enqueue(workitem.index); workitem.ordinal = -1; } _firstWriteDone = false; _totalBytesProcessed = 0L; _runningCrc = new Ionic.Crc.CRC32(); _isClosed= false; _currentlyFilling = -1; _lastFilled = -1; _lastWritten = -1; _latestCompressed = -1; _outStream = stream; } private void EmitPendingBuffers(bool doAll, bool mustWait) { // When combining parallel deflation with a ZipSegmentedStream, it's // possible for the ZSS to throw from within this method. In that // case, Close/Dispose will be called on this stream, if this stream // is employed within a using or try/finally pair as required. But // this stream is unaware of the pending exception, so the Close() // method invokes this method AGAIN. This can lead to a deadlock. // Therefore, failfast if re-entering. if (emitting) return; emitting = true; if (doAll || mustWait) _newlyCompressedBlob.WaitOne(); do { int firstSkip = -1; int millisecondsToWait = doAll ? 200 : (mustWait ? -1 : 0); int nextToWrite = -1; do { if (Monitor.TryEnter(_toWrite, millisecondsToWait)) { nextToWrite = -1; try { if (_toWrite.Count > 0) nextToWrite = _toWrite.Dequeue(); } finally { Monitor.Exit(_toWrite); } if (nextToWrite >= 0) { WorkItem workitem = _pool[nextToWrite]; if (workitem.ordinal != _lastWritten + 1) { // out of order. requeue and try again. TraceOutput(TraceBits.EmitSkip, "Emit skip wi({0}) ord({1}) lw({2}) fs({3})", workitem.index, workitem.ordinal, _lastWritten, firstSkip); lock(_toWrite) { _toWrite.Enqueue(nextToWrite); } if (firstSkip == nextToWrite) { // We went around the list once. // None of the items in the list is the one we want. // Now wait for a compressor to signal again. _newlyCompressedBlob.WaitOne(); firstSkip = -1; } else if (firstSkip == -1) firstSkip = nextToWrite; continue; } firstSkip = -1; TraceOutput(TraceBits.EmitBegin, "Emit begin wi({0}) ord({1}) cba({2})", workitem.index, workitem.ordinal, workitem.compressedBytesAvailable); _outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable); _runningCrc.Combine(workitem.crc, workitem.inputBytesAvailable); _totalBytesProcessed += workitem.inputBytesAvailable; workitem.inputBytesAvailable = 0; TraceOutput(TraceBits.EmitDone, "Emit done wi({0}) ord({1}) cba({2}) mtw({3})", workitem.index, workitem.ordinal, workitem.compressedBytesAvailable, millisecondsToWait); _lastWritten = workitem.ordinal; _toFill.Enqueue(workitem.index); // don't wait next time through if (millisecondsToWait == -1) millisecondsToWait = 0; } } else nextToWrite = -1; } while (nextToWrite >= 0); //} while (doAll && (_lastWritten != _latestCompressed)); } while (doAll && (_lastWritten != _latestCompressed || _lastWritten != _lastFilled)); emitting = false; } #if OLD private void _PerpetualWriterMethod(object state) { TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod START"); try { do { // wait for the next session TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.WaitOne(begin) PWM"); _sessionReset.WaitOne(); TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.WaitOne(done) PWM"); if (_isDisposed) break; TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.Reset() PWM"); _sessionReset.Reset(); // repeatedly write buffers as they become ready WorkItem workitem = null; Ionic.Zlib.CRC32 c= new Ionic.Zlib.CRC32(); do { workitem = _pool[_nextToWrite % _pc]; lock(workitem) { if (_noMoreInputForThisSegment) TraceOutput(TraceBits.Write, "Write drain wi({0}) stat({1}) canuse({2}) cba({3})", workitem.index, workitem.status, (workitem.status == (int)WorkItem.Status.Compressed), workitem.compressedBytesAvailable); do { if (workitem.status == (int)WorkItem.Status.Compressed) { TraceOutput(TraceBits.WriteBegin, "Write begin wi({0}) stat({1}) cba({2})", workitem.index, workitem.status, workitem.compressedBytesAvailable); workitem.status = (int)WorkItem.Status.Writing; _outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable); c.Combine(workitem.crc, workitem.inputBytesAvailable); _totalBytesProcessed += workitem.inputBytesAvailable; _nextToWrite++; workitem.inputBytesAvailable= 0; workitem.status = (int)WorkItem.Status.Done; TraceOutput(TraceBits.WriteDone, "Write done wi({0}) stat({1}) cba({2})", workitem.index, workitem.status, workitem.compressedBytesAvailable); Monitor.Pulse(workitem); break; } else { int wcycles = 0; // I've locked a workitem I cannot use. // Therefore, wake someone else up, and then release the lock. while (workitem.status != (int)WorkItem.Status.Compressed) { TraceOutput(TraceBits.WriteWait, "Write waiting wi({0}) stat({1}) nw({2}) nf({3}) nomore({4})", workitem.index, workitem.status, _nextToWrite, _nextToFill, _noMoreInputForThisSegment ); if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill) break; wcycles++; // wake up someone else Monitor.Pulse(workitem); // release and wait Monitor.Wait(workitem); if (workitem.status == (int)WorkItem.Status.Compressed) TraceOutput(TraceBits.WriteWait, "Write A-OK wi({0}) stat({1}) iba({2}) cba({3}) cyc({4})", workitem.index, workitem.status, workitem.inputBytesAvailable, workitem.compressedBytesAvailable, wcycles); } if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill) break; } } while (true); } if (_noMoreInputForThisSegment) TraceOutput(TraceBits.Write, "Write nomore nw({0}) nf({1}) break({2})", _nextToWrite, _nextToFill, (_nextToWrite == _nextToFill)); if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill) break; } while (true); // Finish: // After writing a series of buffers, closing each one with // Flush.Sync, we now write the final one as Flush.Finish, and // then stop. byte[] buffer = new byte[128]; ZlibCodec compressor = new ZlibCodec(); int rc = compressor.InitializeDeflate(_compressLevel, false); compressor.InputBuffer = null; compressor.NextIn = 0; compressor.AvailableBytesIn = 0; compressor.OutputBuffer = buffer; compressor.NextOut = 0; compressor.AvailableBytesOut = buffer.Length; rc = compressor.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) throw new Exception("deflating: " + compressor.Message); if (buffer.Length - compressor.AvailableBytesOut > 0) { TraceOutput(TraceBits.WriteBegin, "Write begin flush bytes({0})", buffer.Length - compressor.AvailableBytesOut); _outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut); TraceOutput(TraceBits.WriteBegin, "Write done flush"); } compressor.EndDeflate(); _Crc32 = c.Crc32Result; // signal that writing is complete: TraceOutput(TraceBits.Synch, "Synch _writingDone.Set() PWM"); _writingDone.Set(); } while (true); } catch (System.Exception exc1) { lock(_eLock) { // expose the exception to the main thread if (_pendingException!=null) _pendingException = exc1; } } TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod FINIS"); } #endif private void _DeflateOne(Object wi) { // compress one buffer WorkItem workitem = (WorkItem) wi; try { int myItem = workitem.index; Ionic.Crc.CRC32 crc = new Ionic.Crc.CRC32(); // calc CRC on the buffer crc.SlurpBlock(workitem.buffer, 0, workitem.inputBytesAvailable); // deflate it DeflateOneSegment(workitem); // update status workitem.crc = crc.Crc32Result; TraceOutput(TraceBits.Compress, "Compress wi({0}) ord({1}) len({2})", workitem.index, workitem.ordinal, workitem.compressedBytesAvailable ); lock(_latestLock) { if (workitem.ordinal > _latestCompressed) _latestCompressed = workitem.ordinal; } lock (_toWrite) { _toWrite.Enqueue(workitem.index); } _newlyCompressedBlob.Set(); } catch (System.Exception exc1) { lock(_eLock) { // expose the exception to the main thread if (_pendingException!=null) _pendingException = exc1; } } } private bool DeflateOneSegment(WorkItem workitem) { ZlibCodec compressor = workitem.compressor; int rc= 0; compressor.ResetDeflate(); compressor.NextIn = 0; compressor.AvailableBytesIn = workitem.inputBytesAvailable; // step 1: deflate the buffer compressor.NextOut = 0; compressor.AvailableBytesOut = workitem.compressed.Length; do { compressor.Deflate(FlushType.None); } while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0); // step 2: flush (sync) rc = compressor.Deflate(FlushType.Sync); workitem.compressedBytesAvailable= (int) compressor.TotalBytesOut; return true; } [System.Diagnostics.ConditionalAttribute("Trace")] private void TraceOutput(TraceBits bits, string format, params object[] varParams) { if ((bits & _DesiredTrace) != 0) { lock(_outputLock) { int tid = Thread.CurrentThread.GetHashCode(); #if !SILVERLIGHT Console.ForegroundColor = (ConsoleColor) (tid % 8 + 8); #endif Console.Write("{0:000} PDOS ", tid); Console.WriteLine(format, varParams); #if !SILVERLIGHT Console.ResetColor(); #endif } } } // used only when Trace is defined [Flags] enum TraceBits : uint { None = 0, NotUsed1 = 1, EmitLock = 2, EmitEnter = 4, // enter _EmitPending EmitBegin = 8, // begin to write out EmitDone = 16, // done writing out EmitSkip = 32, // writer skipping a workitem EmitAll = 58, // All Emit flags Flush = 64, Lifecycle = 128, // constructor/disposer Session = 256, // Close/Reset Synch = 512, // thread synchronization Instance = 1024, // instance settings Compress = 2048, // compress task Write = 4096, // filling buffers, when caller invokes Write() WriteEnter = 8192, // upon entry to Write() WriteTake = 16384, // on _toFill.Take() All = 0xffffffff, } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream supports Read operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanRead { get {return false;} } /// <summary> /// Indicates whether the stream supports Write operations. /// </summary> /// <remarks> /// Returns true if the provided stream is writable. /// </remarks> public override bool CanWrite { get { return _outStream.CanWrite; } } /// <summary> /// Reading this property always throws a NotSupportedException. /// </summary> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// Returns the current position of the output stream. /// </summary> /// <remarks> /// <para> /// Because the output gets written by a background thread, /// the value may change asynchronously. Setting this /// property always throws a NotSupportedException. /// </para> /// </remarks> public override long Position { get { return _outStream.Position; } set { throw new NotSupportedException(); } } /// <summary> /// This method always throws a NotSupportedException. /// </summary> /// <param name="buffer"> /// The buffer into which data would be read, IF THIS METHOD /// ACTUALLY DID ANYTHING. /// </param> /// <param name="offset"> /// The offset within that data array at which to insert the /// data that is read, IF THIS METHOD ACTUALLY DID /// ANYTHING. /// </param> /// <param name="count"> /// The number of bytes to write, IF THIS METHOD ACTUALLY DID /// ANYTHING. /// </param> /// <returns>nothing.</returns> public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } /// <summary> /// This method always throws a NotSupportedException. /// </summary> /// <param name="offset"> /// The offset to seek to.... /// IF THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// <param name="origin"> /// The reference specifying how to apply the offset.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// <returns>nothing. It always throws.</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// This method always throws a NotSupportedException. /// </summary> /// <param name="value"> /// The new value for the stream length.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> public override void SetLength(long value) { throw new NotSupportedException(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Reflection; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A class that represents a script that you can run. /// /// Create a script using a language specific script class such as CSharpScript or VisualBasicScript. /// </summary> public abstract class Script { internal readonly ScriptCompiler Compiler; internal readonly ScriptBuilder Builder; private Compilation _lazyCompilation; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) { Debug.Assert(code != null); Debug.Assert(options != null); Debug.Assert(compiler != null); Debug.Assert(builder != null); Compiler = compiler; Builder = builder; Previous = previousOpt; Code = code; Options = options; GlobalsType = globalsTypeOpt; } internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, string codeOpt, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt) { return new Script<T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), codeOpt ?? "", optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null); } /// <summary> /// A script that will run first when this script is run. /// Any declarations made in the previous script can be referenced in this script. /// The end state from running this script includes all declarations made by both scripts. /// </summary> public Script Previous { get; } /// <summary> /// The options used by this script. /// </summary> public ScriptOptions Options { get; } /// <summary> /// The source code of the script. /// </summary> public string Code { get; } /// <summary> /// The type of an object whose members can be accessed by the script as global variables. /// </summary> public Type GlobalsType { get; } /// <summary> /// The expected return type of the script. /// </summary> public abstract Type ReturnType { get; } /// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options); internal abstract Script WithOptionsInternal(ScriptOptions options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<object> ContinueWith(string code, ScriptOptions options = null) => ContinueWith<object>(code, options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<TResult> ContinueWith<TResult>(string code, ScriptOptions options = null) => new Script<TResult>(Compiler, Builder, code ?? "", options ?? InheritOptions(Options), GlobalsType, this); private static ScriptOptions InheritOptions(ScriptOptions previous) { // don't inherit references or imports, they have already been applied: return previous. WithReferences(ImmutableArray<MetadataReference>.Empty). WithImports(ImmutableArray<string>.Empty); } /// <summary> /// Get's the <see cref="Compilation"/> that represents the semantics of the script. /// </summary> public Compilation GetCompilation() { if (_lazyCompilation == null) { var compilation = Compiler.CreateSubmission(this); Interlocked.CompareExchange(ref _lazyCompilation, compilation, null); } return _lazyCompilation; } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal Task<object> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonEvaluateAsync(globals, cancellationToken); internal abstract Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonRunAsync(globals, cancellationToken); internal abstract Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Continue script execution from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> internal Task<ScriptState> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) => CommonContinueAsync(previousState, cancellationToken); internal abstract Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken); /// <summary> /// Forces the script through the compilation step. /// If not called directly, the compilation step will occur on the first call to Run. /// </summary> public ImmutableArray<Diagnostic> Compile(CancellationToken cancellationToken = default(CancellationToken)) => CommonCompile(cancellationToken); internal abstract ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken); internal abstract Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken); // Apply recursive alias <host> to the host assembly reference, so that we hide its namespaces and global types behind it. internal static readonly MetadataReferenceProperties HostAssemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("<host>")).WithRecursiveAliases(true); /// <summary> /// Gets the references that need to be assigned to the compilation. /// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance. /// </summary> internal ImmutableArray<MetadataReference> GetReferencesForCompilation( CommonMessageProvider messageProvider, DiagnosticBag diagnostics, MetadataReference languageRuntimeReferenceOpt = null) { var resolver = Options.MetadataResolver; var references = ArrayBuilder<MetadataReference>.GetInstance(); try { if (Previous == null) { var corLib = MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly); references.Add(corLib); if (GlobalsType != null) { var globalsAssembly = GlobalsType.GetTypeInfo().Assembly; // If the assembly doesn't have metadata (it's an in-memory or dynamic assembly), // the host has to add reference to the metadata where globals type is located explicitly. if (MetadataReference.HasMetadata(globalsAssembly)) { references.Add(MetadataReference.CreateFromAssemblyInternal(globalsAssembly, HostAssemblyReferenceProperties)); } } if (languageRuntimeReferenceOpt != null) { references.Add(languageRuntimeReferenceOpt); } } // add new references: foreach (var reference in Options.MetadataReferences) { var unresolved = reference as UnresolvedMetadataReference; if (unresolved != null) { var resolved = resolver.ResolveReference(unresolved.Reference, null, unresolved.Properties); if (resolved.IsDefault) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataFileNotFound, Location.None, unresolved.Reference)); } else { references.AddRange(resolved); } } else { references.Add(reference); } } return references.ToImmutable(); } finally { references.Free(); } } // TODO: remove internal bool HasReturnValue() { return GetCompilation().HasSubmissionResult(); } } public sealed class Script<T> : Script { private ImmutableArray<Func<object[], Task>> _lazyPrecedingExecutors; private Func<object[], Task<T>> _lazyExecutor; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) : base(compiler, builder, code, options, globalsTypeOpt, previousOpt) { } public override Type ReturnType => typeof(T); public new Script<T> WithOptions(ScriptOptions options) { return (options == Options) ? this : new Script<T>(Compiler, Builder, Code, options, GlobalsType, Previous); } internal override Script WithOptionsInternal(ScriptOptions options) => WithOptions(options); internal override ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken) { // TODO: avoid throwing exception, report all diagnostics https://github.com/dotnet/roslyn/issues/5949 try { GetPrecedingExecutors(cancellationToken); GetExecutor(cancellationToken); return ImmutableArray.CreateRange(GetCompilation().GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Warning)); } catch (CompilationErrorException e) { return ImmutableArray.CreateRange(e.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning)); } } internal override Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken) => GetExecutor(cancellationToken); internal override Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken) => EvaluateAsync(globals, cancellationToken).CastAsync<T, object>(); internal override Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken) => RunAsync(globals, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); internal override Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken) => ContinueAsync(previousState, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private Func<object[], Task<T>> GetExecutor(CancellationToken cancellationToken) { if (_lazyExecutor == null) { Interlocked.CompareExchange(ref _lazyExecutor, Builder.CreateExecutor<T>(Compiler, GetCompilation(), cancellationToken), null); } return _lazyExecutor; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> GetPrecedingExecutors(CancellationToken cancellationToken) { if (_lazyPrecedingExecutors.IsDefault) { var preceding = TryGetPrecedingExecutors(null, cancellationToken); Debug.Assert(!preceding.IsDefault); InterlockedOperations.Initialize(ref _lazyPrecedingExecutors, preceding); } return _lazyPrecedingExecutors; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> TryGetPrecedingExecutors(Script lastExecutedScriptInChainOpt, CancellationToken cancellationToken) { Script script = Previous; if (script == lastExecutedScriptInChainOpt) { return ImmutableArray<Func<object[], Task>>.Empty; } var scriptsReversed = ArrayBuilder<Script>.GetInstance(); while (script != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Add(script); script = script.Previous; } if (lastExecutedScriptInChainOpt != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Free(); return default(ImmutableArray<Func<object[], Task>>); } var executors = ArrayBuilder<Func<object[], Task>>.GetInstance(scriptsReversed.Count); // We need to build executors in the order in which they are chained, // so that assemblies created for the submissions are loaded in the correct order. for (int i = scriptsReversed.Count - 1; i >= 0; i--) { executors.Add(scriptsReversed[i].CommonGetExecutor(cancellationToken)); } return executors.ToImmutableAndFree(); } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal new Task<T> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => RunAsync(globals, cancellationToken).GetEvaluationResultAsync(); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="CompilationErrorException">Compilation has errors.</exception> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception> public new Task<ScriptState<T>> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor contruction may throw; // do so synchronously so that the exception is not wrapped in the task. ValidateGlobals(globals, GlobalsType); var executionState = ScriptExecutionState.Create(globals); var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); return RunSubmissionsAsync(executionState, precedingExecutors, currentExecutor, cancellationToken); } /// <summary> /// Creates a delegate that will run this script from the beginning when invoked. /// </summary> /// <remarks> /// The delegate doesn't hold on this script or its compilation. /// </remarks> public ScriptRunner<T> CreateDelegate(CancellationToken cancellationToken = default(CancellationToken)) { var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); var globalsType = GlobalsType; return (globals, token) => { ValidateGlobals(globals, globalsType); return ScriptExecutionState.Create(globals).RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, token); }; } /// <summary> /// Continue script execution from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception> internal new Task<ScriptState<T>> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor contruction may throw; // do so synchronously so that the exception is not wrapped in the task. if (previousState == null) { throw new ArgumentNullException(nameof(previousState)); } if (previousState.Script == this) { // this state is already the output of running this script. return Task.FromResult((ScriptState<T>)previousState); } var precedingExecutors = TryGetPrecedingExecutors(previousState.Script, cancellationToken); if (precedingExecutors.IsDefault) { throw new ArgumentException(ScriptingResources.StartingStateIncompatible, nameof(previousState)); } var currentExecutor = GetExecutor(cancellationToken); ScriptExecutionState newExecutionState = previousState.ExecutionState.FreezeAndClone(); return RunSubmissionsAsync(newExecutionState, precedingExecutors, currentExecutor, cancellationToken); } private async Task<ScriptState<T>> RunSubmissionsAsync(ScriptExecutionState executionState, ImmutableArray<Func<object[], Task>> precedingExecutors, Func<object[], Task> currentExecutor, CancellationToken cancellationToken) { var result = await executionState.RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); return new ScriptState<T>(executionState, result, this); } private static void ValidateGlobals(object globals, Type globalsType) { if (globalsType != null) { if (globals == null) { throw new ArgumentException(ScriptingResources.ScriptRequiresGlobalVariables, nameof(globals)); } var runtimeType = globals.GetType().GetTypeInfo(); var globalsTypeInfo = globalsType.GetTypeInfo(); if (!globalsTypeInfo.IsAssignableFrom(runtimeType)) { throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsTypeInfo), nameof(globals)); } } else if (globals != null) { throw new ArgumentException(ScriptingResources.GlobalVariablesWithoutGlobalType, nameof(globals)); } } } }
/*************************************************************************** * Scheduler.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> ****************************************************************************/ /* 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. */ using System; using System.Threading; using System.Collections.Generic; namespace Banshee.Kernel { public delegate void JobEventHandler(IJob job); public static class Scheduler { private static object this_mutex = new object(); private static IntervalHeap<IJob> heap = new IntervalHeap<IJob>(); private static Thread job_thread; private static bool disposed; private static IJob current_running_job; public static event JobEventHandler JobStarted; public static event JobEventHandler JobFinished; public static event JobEventHandler JobScheduled; public static event JobEventHandler JobUnscheduled; public static void Schedule(IJob job) { Schedule(job, JobPriority.Normal); } public static void Schedule(IJob job, JobPriority priority) { lock(this_mutex) { if(IsDisposed()) { return; } heap.Push(job, (int)priority); Debug("Job scheduled ({0}, {1})", job, priority); OnJobScheduled(job); CheckRun(); } } public static void Unschedule(IJob job) { lock(this_mutex) { if(IsDisposed()) { return; } if(heap.Remove(job)) { Debug("Job unscheduled ({0}), job", job); OnJobUnscheduled(job); } else { Debug("Job not unscheduled; not located in heap"); } } } public static void Unschedule(Type type) { lock(this_mutex) { Queue<IJob> to_remove = new Queue<IJob>(); foreach(IJob job in ScheduledJobs) { Type job_type = job.GetType(); if((type.IsInterface && job_type.GetInterface(type.Name) != null) || job_type == type || job_type.IsSubclassOf(job_type)) { to_remove.Enqueue(job); } } while(to_remove.Count > 0) { Unschedule(to_remove.Dequeue()); } } } public static bool IsScheduled(IJob job) { lock(this_mutex) { if(IsDisposed()) { return false; } return heap.Contains(job); } } public static bool IsScheduled(Type type) { lock(this_mutex) { if(IsDisposed()) { return false; } foreach(IJob job in heap) { if(job.GetType() == type) { return true; } } return false; } } public static bool IsInstanceCriticalJobScheduled { get { lock(this_mutex) { if(IsDisposed()) { return false; } foreach(IJob job in heap) { if(job is IInstanceCriticalJob) { return true; } } return false; } } } public static IEnumerable<IJob> ScheduledJobs { get { lock(this_mutex) { return heap; } } } public static int ScheduledJobsCount { get { lock(this_mutex) { return heap.Count; } } } public static void Dispose() { lock(this_mutex) { disposed = true; } } private static bool IsDisposed() { if(disposed) { Debug("Job not unscheduled; disposing scheduler"); return true; } return false; } private static void CheckRun() { if(heap.Count <= 0) { return; } else if(job_thread == null) { Debug("execution thread created"); job_thread = new Thread(new ThreadStart(ProcessJobThread)); job_thread.Priority = ThreadPriority.BelowNormal; job_thread.IsBackground = true; job_thread.Start(); } } private static void ProcessJobThread() { while(true) { current_running_job = null; lock(this_mutex) { if(disposed) { Console.WriteLine("execution thread destroyed, dispose requested"); return; } try { current_running_job = heap.Pop(); } catch(InvalidOperationException) { Debug("execution thread destroyed, no more jobs scheduled"); job_thread = null; return; } } try { Debug("Job started ({0})", current_running_job); OnJobStarted(current_running_job); current_running_job.Run(); Debug("Job ended ({0})", current_running_job); OnJobFinished(current_running_job); } catch(Exception e) { Debug("Job threw an unhandled exception: {0}", e); } } } public static IJob CurrentJob { get { return current_running_job; } } private static void OnJobStarted(IJob job) { JobEventHandler handler = JobStarted; if(handler != null) { handler(job); } } private static void OnJobFinished(IJob job) { JobEventHandler handler = JobFinished; if(handler != null) { handler(job); } } private static void OnJobScheduled(IJob job) { JobEventHandler handler = JobScheduled; if(handler != null) { handler(job); } } private static void OnJobUnscheduled(IJob job) { JobEventHandler handler = JobUnscheduled; if(handler != null) { handler(job); } } private static void Debug(string message, params object [] args) { if(Banshee.Base.Globals.Debugging) { Console.Error.WriteLine(String.Format("** Scheduler: {0}", message), args); } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Logging; using Prism.Modularity; using Prism.Regions; using StructureMap; using System.Linq; using Prism.Events; namespace Prism.StructureMap.Wpf.Tests { [TestClass] public class StructureMapBootstrapperRunMethodFixture { [TestMethod] public void CanRunBootstrapper() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); } [TestMethod] public void RunShouldNotFailIfReturnedNullShell() { var bootstrapper = new DefaultStructureMapBootstrapper { ShellObject = null }; bootstrapper.Run(); } [TestMethod] public void RunConfiguresServiceLocatorProvider() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(Microsoft.Practices.ServiceLocation.ServiceLocator.Current is StructureMapServiceLocatorAdapter); } [TestMethod] public void RunShouldInitializeContainer() { var bootstrapper = new DefaultStructureMapBootstrapper(); var container = bootstrapper.BaseContainer; Assert.IsNull(container); bootstrapper.Run(); container = bootstrapper.BaseContainer; Assert.IsNotNull(container); Assert.IsInstanceOfType(container, typeof(Container)); } [TestMethod] public void RunAddsCompositionContainerToContainer() { var bootstrapper = new DefaultStructureMapBootstrapper(); var createdContainer = bootstrapper.CallCreateContainer(); var returnedContainer = createdContainer.GetInstance<IContainer>(); Assert.IsNotNull(returnedContainer); Assert.AreEqual(typeof(Container), returnedContainer.GetType()); } [TestMethod] public void RunShouldCallInitializeModules() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.InitializeModulesCalled); } [TestMethod] public void RunShouldCallConfigureDefaultRegionBehaviors() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureDefaultRegionBehaviorsCalled); } [TestMethod] public void RunShouldCallConfigureRegionAdapterMappings() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureRegionAdapterMappingsCalled); } [TestMethod] public void RunShouldAssignRegionManagerToReturnedShell() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsNotNull(RegionManager.GetRegionManager(bootstrapper.BaseShell)); } [TestMethod] public void RunShouldCallCreateLogger() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateLoggerCalled); } [TestMethod] public void RunShouldCallCreateModuleCatalog() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateModuleCatalogCalled); } [TestMethod] public void RunShouldCallConfigureModuleCatalog() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureModuleCatalogCalled); } [TestMethod] public void RunShouldCallCreateContainer() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateContainerCalled); } [TestMethod] public void RunShouldCallCreateShell() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateShellCalled); } [TestMethod] public void RunShouldCallConfigureContainer() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureContainerCalled); } // unable to mock Configure methods // so registration is tested through checking the resolved type against interface [TestMethod] public void RunRegistersInstanceOfILoggerFacade() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var logger = bootstrapper.BaseContainer.GetInstance<ILoggerFacade>(); Assert.IsNotNull(logger); Assert.IsTrue(logger.GetType().IsClass); Assert.IsTrue(logger.GetType().GetInterfaces().Contains(typeof(ILoggerFacade))); } [TestMethod] public void RunRegistersInstanceOfIModuleCatalog() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var moduleCatalog = bootstrapper.BaseContainer.GetInstance<IModuleCatalog>(); Assert.IsNotNull(moduleCatalog); Assert.IsTrue(moduleCatalog.GetType().IsClass); Assert.IsTrue(moduleCatalog.GetType().GetInterfaces().Contains(typeof(IModuleCatalog))); } [TestMethod] public void RunRegistersTypeForIModuleInitializer() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var moduleInitializer = bootstrapper.BaseContainer.GetInstance<IModuleInitializer>(); Assert.IsNotNull(moduleInitializer); Assert.IsTrue(moduleInitializer.GetType().IsClass); Assert.IsTrue(moduleInitializer.GetType().GetInterfaces().Contains(typeof(IModuleInitializer))); } [TestMethod] public void RunRegistersTypeForIRegionManager() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var regionManager = bootstrapper.BaseContainer.GetInstance<IRegionManager>(); Assert.IsNotNull(regionManager); Assert.IsTrue(regionManager.GetType().IsClass); Assert.IsTrue(regionManager.GetType().GetInterfaces().Contains(typeof(IRegionManager))); } [TestMethod] public void RunRegistersTypeForRegionAdapterMappings() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var regionAdapterMappings = bootstrapper.BaseContainer.GetInstance<RegionAdapterMappings>(); Assert.IsNotNull(regionAdapterMappings); Assert.AreEqual(typeof(RegionAdapterMappings), regionAdapterMappings.GetType()); } [TestMethod] public void RunRegistersTypeForIRegionViewRegistry() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var regionViewRegistry = bootstrapper.BaseContainer.GetInstance<IRegionViewRegistry>(); Assert.IsNotNull(regionViewRegistry); Assert.IsTrue(regionViewRegistry.GetType().IsClass); Assert.IsTrue(regionViewRegistry.GetType().GetInterfaces().Contains(typeof(IRegionViewRegistry))); } [TestMethod] public void RunRegistersTypeForIRegionBehaviorFactory() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var regionBehaviorFactory = bootstrapper.BaseContainer.GetInstance<IRegionBehaviorFactory>(); Assert.IsNotNull(regionBehaviorFactory); Assert.IsTrue(regionBehaviorFactory.GetType().IsClass); Assert.IsTrue(regionBehaviorFactory.GetType().GetInterfaces().Contains(typeof(IRegionBehaviorFactory))); } [TestMethod] public void RunRegistersTypeForIEventAggregator() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var eventAggregator = bootstrapper.BaseContainer.GetInstance<IEventAggregator>(); Assert.IsNotNull(eventAggregator); Assert.IsTrue(eventAggregator.GetType().IsClass); Assert.IsTrue(eventAggregator.GetType().GetInterfaces().Contains(typeof(IEventAggregator))); } [TestMethod] public void RunShouldCallTheMethodsInOrder() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); Assert.AreEqual("CreateLogger", bootstrapper.MethodCalls[0]); Assert.AreEqual("CreateModuleCatalog", bootstrapper.MethodCalls[1]); Assert.AreEqual("ConfigureModuleCatalog", bootstrapper.MethodCalls[2]); Assert.AreEqual("CreateContainer", bootstrapper.MethodCalls[3]); Assert.AreEqual("ConfigureContainer", bootstrapper.MethodCalls[4]); Assert.AreEqual("ConfigureServiceLocator", bootstrapper.MethodCalls[5]); Assert.AreEqual("ConfigureRegionAdapterMappings", bootstrapper.MethodCalls[6]); Assert.AreEqual("ConfigureDefaultRegionBehaviors", bootstrapper.MethodCalls[7]); Assert.AreEqual("RegisterFrameworkExceptionTypes", bootstrapper.MethodCalls[8]); Assert.AreEqual("CreateShell", bootstrapper.MethodCalls[9]); Assert.AreEqual("InitializeShell", bootstrapper.MethodCalls[10]); Assert.AreEqual("InitializeModules", bootstrapper.MethodCalls[11]); } [TestMethod] public void RunShouldLogBootstrapperSteps() { var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages[0].Contains("Logger was created successfully.")); Assert.IsTrue(messages[1].Contains("Creating module catalog.")); Assert.IsTrue(messages[2].Contains("Configuring module catalog.")); Assert.IsTrue(messages[3].Contains("Creating StructureMap container.")); Assert.IsTrue(messages[4].Contains("Configuring the StructureMap container.")); Assert.IsTrue(messages[5].Contains("Configuring ServiceLocator singleton.")); Assert.IsTrue(messages[6].Contains("Configuring the ViewModelLocator to use StructureMap.")); Assert.IsTrue(messages[7].Contains("Configuring region adapters.")); Assert.IsTrue(messages[8].Contains("Configuring default region behaviors.")); Assert.IsTrue(messages[9].Contains("Registering Framework Exception Types.")); Assert.IsTrue(messages[10].Contains("Creating the shell.")); Assert.IsTrue(messages[11].Contains("Setting the RegionManager.")); Assert.IsTrue(messages[12].Contains("Updating Regions.")); Assert.IsTrue(messages[13].Contains("Initializing the shell.")); Assert.IsTrue(messages[14].Contains("Initializing modules.")); Assert.IsTrue(messages[15].Contains("Bootstrapper sequence completed.")); } [TestMethod] public void RunShouldLogLoggerCreationSuccess() { const string expectedMessageText = "Logger was created successfully."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutModuleCatalogCreation() { const string expectedMessageText = "Creating module catalog."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringModuleCatalog() { const string expectedMessageText = "Configuring module catalog."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutCreatingTheContainer() { const string expectedMessageText = "Creating StructureMap container."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringContainer() { const string expectedMessageText = "Configuring the StructureMap container."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringRegionAdapters() { const string expectedMessageText = "Configuring region adapters."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringRegionBehaviors() { const string expectedMessageText = "Configuring default region behaviors."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutRegisteringFrameworkExceptionTypes() { const string expectedMessageText = "Registering Framework Exception Types."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutCreatingTheShell() { const string expectedMessageText = "Creating the shell."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutInitializingTheShellIfShellCreated() { const string expectedMessageText = "Initializing the shell."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldNotLogAboutInitializingTheShellIfShellIsNotCreated() { const string expectedMessageText = "Initializing shell"; var bootstrapper = new DefaultStructureMapBootstrapper { ShellObject = null }; bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsFalse(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutInitializingModules() { const string expectedMessageText = "Initializing modules."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutRunCompleting() { const string expectedMessageText = "Bootstrapper sequence completed."; var bootstrapper = new DefaultStructureMapBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } } }
// 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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class ParameterTests : ParameterExpressionTests { [Theory] [MemberData(nameof(ValidTypeData))] public void CreateParameterForValidTypeNoName(Type type) { ParameterExpression param = Expression.Parameter(type); Assert.Equal(type, param.Type); Assert.False(param.IsByRef); Assert.Null(param.Name); } [Theory] [MemberData(nameof(ValidTypeData))] public void CrateParamForValidTypeWithName(Type type) { ParameterExpression param = Expression.Parameter(type, "name"); Assert.Equal(type, param.Type); Assert.False(param.IsByRef); Assert.Equal("name", param.Name); } [Fact] public void NameNeedNotBeCSharpValid() { ParameterExpression param = Expression.Parameter(typeof(int), "a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c."); Assert.Equal("a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.", param.Name); } [Fact] public void ParameterCannotBeTypeVoid() { Assert.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(void))); Assert.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(void), "var")); } [Theory] [ClassData(typeof(InvalidTypesData))] public void OpenGenericType_ThrowsArgumentException(Type type) { Assert.Throws<ArgumentException>("type", () => Expression.Parameter(type)); Assert.Throws<ArgumentException>("type", () => Expression.Parameter(type, "name")); } [Fact] public void NullType() { Assert.Throws<ArgumentNullException>("type", () => Expression.Parameter(null)); Assert.Throws<ArgumentNullException>("type", () => Expression.Parameter(null, "var")); } [Theory] [MemberData(nameof(ByRefTypeData))] public void ParameterCanBeByRef(Type type) { ParameterExpression param = Expression.Parameter(type); Assert.Equal(type.GetElementType(), param.Type); Assert.True(param.IsByRef); Assert.Null(param.Name); } [Theory] [MemberData(nameof(ByRefTypeData))] public void NamedParameterCanBeByRef(Type type) { ParameterExpression param = Expression.Parameter(type, "name"); Assert.Equal(type.GetElementType(), param.Type); Assert.True(param.IsByRef); Assert.Equal("name", param.Name); } [Theory] [PerCompilationType(nameof(ValueData))] public void CanWriteAndReadBack(object value, bool useInterpreter) { Type type = value.GetType(); ParameterExpression param = Expression.Parameter(type); Assert.True( Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(value), Expression.Block( type, new[] { param }, Expression.Assign(param, Expression.Constant(value)), param ) ) ).Compile(useInterpreter)() ); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaParameter(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(int)); Func<int, int> addOne = Expression.Lambda<Func<int, int>>( Expression.Add(param, Expression.Constant(1)), param ).Compile(useInterpreter); Assert.Equal(3, addOne(2)); } public delegate void ByRefFunc<T>(ref T arg); [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaByRefParameter(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(int).MakeByRefType()); ByRefFunc<int> addOneInPlace = Expression.Lambda<ByRefFunc<int>>( Expression.PreIncrementAssign(param), param ).Compile(useInterpreter); int argument = 5; addOneInPlace(ref argument); Assert.Equal(6, argument); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaByRefParameter_String(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(string).MakeByRefType()); ByRefFunc<string> f = Expression.Lambda<ByRefFunc<string>>( Expression.Assign(param, Expression.Call(param, typeof(string).GetMethod(nameof(string.ToUpper), Type.EmptyTypes))), param ).Compile(useInterpreter); string argument = "bar"; f(ref argument); Assert.Equal("BAR", argument); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaByRefParameter_Char(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(char).MakeByRefType()); ByRefFunc<char> f = Expression.Lambda<ByRefFunc<char>>( Expression.Assign(param, Expression.Call(typeof(char).GetMethod(nameof(char.ToUpper), new[] { typeof(char) }), param)), param ).Compile(useInterpreter); char argument = 'a'; f(ref argument); Assert.Equal('A', argument); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanUseAsLambdaByRefParameter_Bool(bool useInterpreter) { ParameterExpression param = Expression.Parameter(typeof(bool).MakeByRefType()); ByRefFunc<bool> f = Expression.Lambda<ByRefFunc<bool>>( Expression.ExclusiveOrAssign(param, Expression.Constant(true)), param ).Compile(useInterpreter); bool b1 = false; f(ref b1); Assert.Equal(false ^ true, b1); bool b2 = true; f(ref b2); Assert.Equal(true ^ true, b2); } [Theory] [ClassData(typeof(CompilationTypes))] public void CanReadFromRefParameter(bool useInterpreter) { AssertCanReadFromRefParameter<byte>(byte.MaxValue, useInterpreter); AssertCanReadFromRefParameter<sbyte>(sbyte.MaxValue, useInterpreter); AssertCanReadFromRefParameter<short>(short.MaxValue, useInterpreter); AssertCanReadFromRefParameter<ushort>(ushort.MaxValue, useInterpreter); AssertCanReadFromRefParameter<int>(int.MaxValue, useInterpreter); AssertCanReadFromRefParameter<uint>(uint.MaxValue, useInterpreter); AssertCanReadFromRefParameter<long>(long.MaxValue, useInterpreter); AssertCanReadFromRefParameter<ulong>(ulong.MaxValue, useInterpreter); AssertCanReadFromRefParameter<decimal>(49.94m, useInterpreter); AssertCanReadFromRefParameter<float>(3.1415926535897931f, useInterpreter); AssertCanReadFromRefParameter<double>(2.7182818284590451, useInterpreter); AssertCanReadFromRefParameter('a', useInterpreter); AssertCanReadFromRefParameter(ByteEnum.A, useInterpreter); AssertCanReadFromRefParameter(SByteEnum.A, useInterpreter); AssertCanReadFromRefParameter(Int16Enum.A, useInterpreter); AssertCanReadFromRefParameter(UInt16Enum.A, useInterpreter); AssertCanReadFromRefParameter(Int32Enum.A, useInterpreter); AssertCanReadFromRefParameter(UInt32Enum.A, useInterpreter); AssertCanReadFromRefParameter(Int64Enum.A, useInterpreter); AssertCanReadFromRefParameter(UInt64Enum.A, useInterpreter); AssertCanReadFromRefParameter(new DateTime(1983, 2, 11), useInterpreter); AssertCanReadFromRefParameter<object>(null, useInterpreter); AssertCanReadFromRefParameter<object>(new object(), useInterpreter); AssertCanReadFromRefParameter<string>("bar", useInterpreter); AssertCanReadFromRefParameter<int?>(null, useInterpreter); AssertCanReadFromRefParameter<int?>(int.MaxValue, useInterpreter); AssertCanReadFromRefParameter<Int64Enum?>(null, useInterpreter); AssertCanReadFromRefParameter<Int64Enum?>(Int64Enum.A, useInterpreter); AssertCanReadFromRefParameter<DateTime?>(null, useInterpreter); AssertCanReadFromRefParameter<DateTime?>(new DateTime(1983, 2, 11), useInterpreter); } public delegate T ByRefReadFunc<T>(ref T arg); private void AssertCanReadFromRefParameter<T>(T value, bool useInterpreter) { ParameterExpression @ref = Expression.Parameter(typeof(T).MakeByRefType()); ByRefReadFunc<T> f = Expression.Lambda<ByRefReadFunc<T>>( @ref, @ref ).Compile(useInterpreter); Assert.Equal(value, f(ref value)); } public delegate void ByRefWriteAction<T>(ref T arg, T value); [Theory] [ClassData(typeof(CompilationTypes))] public void CanWriteToRefParameter(bool useInterpreter) { AssertCanWriteToRefParameter<byte>(byte.MaxValue, useInterpreter); AssertCanWriteToRefParameter<sbyte>(sbyte.MaxValue, useInterpreter); AssertCanWriteToRefParameter<short>(short.MaxValue, useInterpreter); AssertCanWriteToRefParameter<ushort>(ushort.MaxValue, useInterpreter); AssertCanWriteToRefParameter<int>(int.MaxValue, useInterpreter); AssertCanWriteToRefParameter<uint>(uint.MaxValue, useInterpreter); AssertCanWriteToRefParameter<long>(long.MaxValue, useInterpreter); AssertCanWriteToRefParameter<ulong>(ulong.MaxValue, useInterpreter); AssertCanWriteToRefParameter<decimal>(49.94m, useInterpreter); AssertCanWriteToRefParameter<float>(3.1415926535897931f, useInterpreter); AssertCanWriteToRefParameter<double>(2.7182818284590451, useInterpreter); AssertCanWriteToRefParameter('a', useInterpreter); AssertCanWriteToRefParameter(ByteEnum.A, useInterpreter); AssertCanWriteToRefParameter(SByteEnum.A, useInterpreter); AssertCanWriteToRefParameter(Int16Enum.A, useInterpreter); AssertCanWriteToRefParameter(UInt16Enum.A, useInterpreter); AssertCanWriteToRefParameter(Int32Enum.A, useInterpreter); AssertCanWriteToRefParameter(UInt32Enum.A, useInterpreter); AssertCanWriteToRefParameter(Int64Enum.A, useInterpreter); AssertCanWriteToRefParameter(UInt64Enum.A, useInterpreter); AssertCanWriteToRefParameter(new DateTime(1983, 2, 11), useInterpreter); AssertCanWriteToRefParameter<object>(null, useInterpreter); AssertCanWriteToRefParameter<object>(new object(), useInterpreter); AssertCanWriteToRefParameter<string>("bar", useInterpreter); AssertCanWriteToRefParameter<int?>(null, useInterpreter, original: 42); AssertCanWriteToRefParameter<int?>(int.MaxValue, useInterpreter); AssertCanWriteToRefParameter<Int64Enum?>(null, useInterpreter, original: Int64Enum.A); AssertCanWriteToRefParameter<Int64Enum?>(Int64Enum.A, useInterpreter); AssertCanWriteToRefParameter<DateTime?>(null, useInterpreter, original: new DateTime(1983, 2, 11)); AssertCanWriteToRefParameter<DateTime?>(new DateTime(1983, 2, 11), useInterpreter); } private void AssertCanWriteToRefParameter<T>(T value, bool useInterpreter, T original = default(T)) { ParameterExpression @ref = Expression.Parameter(typeof(T).MakeByRefType()); ParameterExpression val = Expression.Parameter(typeof(T)); ByRefWriteAction<T> f = Expression.Lambda<ByRefWriteAction<T>>( Expression.Assign(@ref, val), @ref, val ).Compile(useInterpreter); T res = original; f(ref res, value); Assert.Equal(res, value); } [Fact] public void CannotReduce() { ParameterExpression param = Expression.Parameter(typeof(int)); Assert.False(param.CanReduce); Assert.Same(param, param.Reduce()); Assert.Throws<ArgumentException>(null, () => param.ReduceAndCheck()); } [Fact] public void CannotBePointerType() { Assert.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(int*))); Assert.Throws<ArgumentException>("type", () => Expression.Parameter(typeof(int*), "pointer")); } [Theory] [MemberData(nameof(ReadAndWriteRefCases))] public void ReadAndWriteRefParameters(bool useInterpreter, object value, object increment, object result) { Type type = value.GetType(); MethodInfo method = typeof(ParameterTests).GetMethod(nameof(AssertReadAndWriteRefParameters), BindingFlags.NonPublic | BindingFlags.Static); method.MakeGenericMethod(type).Invoke(null, new object[] { useInterpreter, value, increment, result }); } private static void AssertReadAndWriteRefParameters<T>(bool useInterpreter, T value, T increment, T result) { ParameterExpression param = Expression.Parameter(typeof(T).MakeByRefType()); ByRefFunc<T> addOneInPlace = Expression.Lambda<ByRefFunc<T>>( Expression.AddAssign(param, Expression.Constant(increment, typeof(T))), param ).Compile(useInterpreter); T argument = value; addOneInPlace(ref argument); Assert.Equal(result, argument); } public static IEnumerable<object[]> ReadAndWriteRefCases() { foreach (var useInterpreter in new[] { true, false }) { yield return new object[] { useInterpreter, (short)41, (short)1, (short)42 }; yield return new object[] { useInterpreter, (ushort)41, (ushort)1, (ushort)42 }; yield return new object[] { useInterpreter, 41, 1, 42 }; yield return new object[] { useInterpreter, 41U, 1U, 42U }; yield return new object[] { useInterpreter, 41L, 1L, 42L }; yield return new object[] { useInterpreter, 41UL, 1UL, 42UL }; yield return new object[] { useInterpreter, 41.0F, 1.0F, Apply((x, y) => x + y, 41.0F, 1.0F) }; yield return new object[] { useInterpreter, 41.0D, 1.0D, Apply((x, y) => x + y, 41.0D, 1.0D) }; yield return new object[] { useInterpreter, TimeSpan.FromSeconds(41), TimeSpan.FromSeconds(1), Apply((x, y) => x + y, TimeSpan.FromSeconds(41), TimeSpan.FromSeconds(1)) }; } } private static T Apply<T>(Func<T, T, T> f, T x, T y) => f(x, y); } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace WeifenLuo.WinFormsUI.Docking { /// <summary> /// Visual Studio 2012 Light theme. /// </summary> public class VS2012LightTheme : ThemeBase { /// <summary> /// Applies the specified theme to the dock panel. /// </summary> /// <param name="dockPanel">The dock panel.</param> public override void Apply(DockPanel dockPanel) { if (dockPanel == null) { throw new NullReferenceException("dockPanel"); } Measures.SplitterSize = 6; dockPanel.Extender.DockPaneCaptionFactory = new VS2012LightDockPaneCaptionFactory(); dockPanel.Extender.AutoHideStripFactory = new VS2012LightAutoHideStripFactory(); dockPanel.Extender.AutoHideWindowFactory = new VS2012LightAutoHideWindowFactory(); dockPanel.Extender.DockPaneStripFactory = new VS2013LightDockPaneStripFactory(); dockPanel.Extender.DockPaneSplitterControlFactory = new VS2012LightDockPaneSplitterControlFactory(); dockPanel.Extender.DockWindowSplitterControlFactory = new VS2012LightDockWindowSplitterControlFactory(); dockPanel.Extender.DockWindowFactory = new VS2012LightDockWindowFactory(); dockPanel.Extender.PaneIndicatorFactory = new VS2012LightPaneIndicatorFactory(); dockPanel.Extender.PanelIndicatorFactory = new VS2012LightPanelIndicatorFactory(); dockPanel.Extender.DockOutlineFactory = new VS2012LightDockOutlineFactory(); dockPanel.Skin = CreateVisualStudio2012Light(); } public override void Apply(DockContent dockContent) { if (dockContent == null) return; } private class VS2012LightDockOutlineFactory : DockPanelExtender.IDockOutlineFactory { public DockOutlineBase CreateDockOutline() { return new VS2012LightDockOutline(); } private class VS2012LightDockOutline : DockOutlineBase { public VS2012LightDockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = Color.FromArgb(0xff, 91, 173, 255); DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) { if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = new Region(Rectangle.Empty); } else if (DragForm.Region != null) { DragForm.Region.Dispose(); DragForm.Region = null; } } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = region; } } } private class VS2012LightPanelIndicatorFactory : DockPanelExtender.IPanelIndicatorFactory { public DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style) { return new VS2012LightPanelIndicator(style); } private class VS2012LightPanelIndicator : PictureBox, DockPanel.IPanelIndicator { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft_VS2012; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight_VS2012; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop_VS2012; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom_VS2012; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill_VS2012; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_VS2012; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_VS2012; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_VS2012; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_VS2012; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_VS2012; public VS2012LightPanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } } private class VS2012LightPaneIndicatorFactory : DockPanelExtender.IPaneIndicatorFactory { public DockPanel.IPaneIndicator CreatePaneIndicator() { return new VS2012LightPaneIndicator(); } private class VS2012LightPaneIndicator : PictureBox, DockPanel.IPaneIndicator { private static Bitmap _bitmapPaneDiamond = Resources.Dockindicator_PaneDiamond_VS2012; private static Bitmap _bitmapPaneDiamondLeft = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondRight = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondTop = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondBottom = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondFill = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.Dockindicator_PaneDiamond_Hotspot_VS2012; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotspotIndex_VS2012; private static DockPanel.HotSpotIndex[] _hotSpots = new[] { new DockPanel.HotSpotIndex(1, 0, DockStyle.Top), new DockPanel.HotSpotIndex(0, 1, DockStyle.Left), new DockPanel.HotSpotIndex(1, 1, DockStyle.Fill), new DockPanel.HotSpotIndex(2, 1, DockStyle.Right), new DockPanel.HotSpotIndex(1, 2, DockStyle.Bottom) }; private GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public VS2012LightPaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } } private class VS2012LightAutoHideWindowFactory : DockPanelExtender.IAutoHideWindowFactory { public DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel) { return new VS2012LightAutoHideWindowControl(panel); } } private class VS2012LightDockPaneSplitterControlFactory : DockPanelExtender.IDockPaneSplitterControlFactory { public DockPane.SplitterControlBase CreateSplitterControl(DockPane pane) { return new VS2012LightSplitterControl(pane); } } private class VS2012LightDockWindowSplitterControlFactory : DockPanelExtender.IDockWindowSplitterControlFactory { public SplitterBase CreateSplitterControl() { return new VS2012LightDockWindow.VS2012LightDockWindowSplitterControl(); } } private class VS2013LightDockPaneStripFactory : DockPanelExtender.IDockPaneStripFactory { public DockPaneStripBase CreateDockPaneStrip(DockPane pane) { return new VS2012LightDockPaneStrip(pane); } } private class VS2012LightAutoHideStripFactory : DockPanelExtender.IAutoHideStripFactory { public AutoHideStripBase CreateAutoHideStrip(DockPanel panel) { return new VS2012LightAutoHideStrip(panel); } } private class VS2012LightDockPaneCaptionFactory : DockPanelExtender.IDockPaneCaptionFactory { public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) { return new VS2012LightDockPaneCaption(pane); } } private class VS2012LightDockWindowFactory : DockPanelExtender.IDockWindowFactory { public DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState) { return new VS2012LightDockWindow(dockPanel, dockState); } } public static DockPanelSkin CreateVisualStudio2012Light() { var specialBlue = Color.FromArgb(0xFF, 0x00, 0x7A, 0xCC); var dot = Color.FromArgb(80, 170, 220); var activeTab = specialBlue; var mouseHoverTab = Color.FromArgb(0xFF, 28, 151, 234); var inactiveTab = SystemColors.Control; var lostFocusTab = Color.FromArgb(0xFF, 204, 206, 219); var skin = new DockPanelSkin(); skin.AutoHideStripSkin.DockStripGradient.StartColor = specialBlue; skin.AutoHideStripSkin.DockStripGradient.EndColor = SystemColors.ControlLight; skin.AutoHideStripSkin.TabGradient.TextColor = SystemColors.ControlDarkDark; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = activeTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = lostFocusTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = inactiveTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = Color.Black; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.GrayText; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor = dot; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.ControlDark; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.GrayText; return skin; } } }
namespace Microsoft.Xml.XMLGen { using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Text; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; using System.Globalization; using System.Reflection; internal enum AddSubtractState { StartPlusInc = 0, StartMinusInc = 1, MaxMinusInc = 2, MinPlusInc = 3, } internal abstract class XmlValueGenerator { internal static ArrayList ids = new ArrayList(); internal static Generator_ID g_ID = new Generator_ID(); internal static Generator_IDREF g_IDREF = new Generator_IDREF(); internal static int IDCnt = 0; internal static bool IDRef = false; internal static Type TypeOfString = typeof(System.String); protected ArrayList AllowedValues = null; protected int occurNum = 0; string prefix = null; XmlSchemaDatatype datatype; internal static XmlValueGenerator AnyGenerator = new Generator_anyType(); internal static XmlValueGenerator AnySimpleTypeGenerator = new Generator_anySimpleType(); internal static AddSubtractState[] states = { AddSubtractState.StartPlusInc, AddSubtractState.MinPlusInc, AddSubtractState.MaxMinusInc, AddSubtractState.StartMinusInc}; internal static ArrayList IDList { get { return ids; } } public virtual string Prefix { get { return prefix; } set { prefix = value; } } public virtual void AddGenerator(XmlValueGenerator genr) { return; } public abstract string GenerateValue(); public XmlSchemaDatatype Datatype { get { return datatype; } } internal static XmlValueGenerator CreateGenerator(XmlSchemaDatatype datatype, int listLength) { XmlTypeCode typeCode = datatype.TypeCode; object restriction = datatype.GetType().InvokeMember("Restriction", BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance, null, datatype, null); CompiledFacets rFacets = new CompiledFacets(restriction); XmlValueGenerator generator; if (datatype.Variety == XmlSchemaDatatypeVariety.Union) { generator = CreateUnionGenerator(datatype, rFacets, listLength); } else if (datatype.Variety == XmlSchemaDatatypeVariety.List) { generator = CreateListGenerator(datatype, rFacets, listLength); } else { switch (typeCode) { case XmlTypeCode.None: generator = AnyGenerator; break; case XmlTypeCode.Item: generator = AnyGenerator; break; case XmlTypeCode.AnyAtomicType: generator = AnySimpleTypeGenerator; break; case XmlTypeCode.String: generator = new Generator_string(rFacets); break; case XmlTypeCode.Boolean: generator = new Generator_boolean(); break; case XmlTypeCode.Float: generator = new Generator_float(rFacets); break; case XmlTypeCode.Double: generator = new Generator_double(rFacets); break; case XmlTypeCode.AnyUri: generator = new Generator_anyURI(rFacets); break; case XmlTypeCode.Integer: generator = new Generator_integer(rFacets); break; case XmlTypeCode.Decimal: generator = new Generator_decimal(rFacets); break; case XmlTypeCode.NonPositiveInteger: generator = new Generator_nonPositiveInteger(rFacets); break; case XmlTypeCode.NegativeInteger: generator = new Generator_negativeInteger(rFacets); break; case XmlTypeCode.Long: generator = new Generator_long(rFacets); break; case XmlTypeCode.Int: generator = new Generator_int(rFacets); break; case XmlTypeCode.Short: generator = new Generator_short(rFacets); break; case XmlTypeCode.Byte: generator = new Generator_byte(rFacets); break; case XmlTypeCode.NonNegativeInteger: generator = new Generator_nonNegativeInteger(rFacets); break; case XmlTypeCode.UnsignedLong: generator = new Generator_unsignedLong(rFacets); break; case XmlTypeCode.UnsignedInt: generator = new Generator_unsignedInt(rFacets); break; case XmlTypeCode.UnsignedShort: generator = new Generator_unsignedShort(rFacets); break; case XmlTypeCode.UnsignedByte: generator = new Generator_unsignedByte(rFacets); break; case XmlTypeCode.PositiveInteger: generator = new Generator_positiveInteger(rFacets); break; case XmlTypeCode.Duration: generator = new Generator_duration(rFacets); break; case XmlTypeCode.DateTime: generator = new Generator_dateTime(rFacets); break; case XmlTypeCode.Date: generator = new Generator_date(rFacets); break; case XmlTypeCode.GYearMonth: generator = new Generator_gYearMonth(rFacets); break; case XmlTypeCode.GYear: generator = new Generator_gYear(rFacets); break; case XmlTypeCode.GMonthDay: generator = new Generator_gMonthDay(rFacets); break; case XmlTypeCode.GDay: generator = new Generator_gDay(rFacets); break; case XmlTypeCode.GMonth: generator = new Generator_gMonth(rFacets); break; case XmlTypeCode.Time: generator = new Generator_time(rFacets); break; case XmlTypeCode.HexBinary: generator = new Generator_hexBinary(rFacets); break; case XmlTypeCode.Base64Binary: generator = new Generator_base64Binary(rFacets); break; case XmlTypeCode.QName: generator = new Generator_QName(rFacets); break; case XmlTypeCode.Notation: generator = new Generator_Notation(rFacets); break; case XmlTypeCode.NormalizedString: generator = new Generator_normalizedString(rFacets); break; case XmlTypeCode.Token: generator = new Generator_token(rFacets); break; case XmlTypeCode.Language: generator = new Generator_language(rFacets); break; case XmlTypeCode.NmToken: generator = new Generator_NMTOKEN(rFacets); break; case XmlTypeCode.Name: generator = new Generator_Name(rFacets); break; case XmlTypeCode.NCName: generator = new Generator_NCName(rFacets); break; case XmlTypeCode.Id: g_ID.CheckFacets(rFacets); generator = g_ID; break; case XmlTypeCode.Idref: g_IDREF.CheckFacets(rFacets); generator = g_IDREF; break; default: generator = AnyGenerator; break; } } generator.SetDatatype(datatype); return generator; } private static XmlValueGenerator CreateUnionGenerator(XmlSchemaDatatype dtype, CompiledFacets facets, int listLength) { XmlSchemaSimpleType[] memberTypes = (XmlSchemaSimpleType[])dtype.GetType().InvokeMember("types", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, dtype, null); Generator_Union union_genr = new Generator_Union(facets); foreach(XmlSchemaSimpleType st1 in memberTypes) { union_genr.AddGenerator(XmlValueGenerator.CreateGenerator(st1.Datatype, listLength)); } return union_genr; } private static XmlValueGenerator CreateListGenerator(XmlSchemaDatatype dtype, CompiledFacets facets, int listLength) { XmlSchemaDatatype itemType = (XmlSchemaDatatype)dtype.GetType().InvokeMember("itemType", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, dtype, null); Generator_List list_genr = new Generator_List(facets); list_genr.ListLength = listLength; list_genr.AddGenerator(XmlValueGenerator.CreateGenerator(itemType, listLength)); return list_genr; } private void SetDatatype(XmlSchemaDatatype datatype) { this.datatype = datatype; } } internal class Generator_anyType : XmlValueGenerator { string value = "anyType"; public override string GenerateValue() { return value; } } internal class Generator_anySimpleType : XmlValueGenerator { string value = "anySimpleType"; public override string GenerateValue() { return value; } } internal class Generator_facetBase : XmlValueGenerator { protected int minLength = -1; protected int maxLength = -1; protected int length = -1; internal void CheckFacets(CompiledFacets genFacets) { if(genFacets != null) { RestrictionFlags flags = genFacets.Flags; if ((flags & RestrictionFlags.Length) != 0) { length = genFacets.Length; } if ((flags & RestrictionFlags.MinLength) != 0) { minLength = genFacets.MinLength; } if ((flags & RestrictionFlags.MaxLength) != 0) { maxLength = genFacets.MaxLength; } if ((flags & RestrictionFlags.Enumeration) != 0) { AllowedValues = genFacets.Enumeration; } } } public override string GenerateValue() { return string.Empty; } public object GetEnumerationValue() { Debug.Assert(AllowedValues != null); try { return AllowedValues[occurNum++ % AllowedValues.Count]; } catch (OverflowException) { occurNum = 0; return AllowedValues[occurNum++]; } } public void ProcessLengthFacet(ref StringBuilder genString, int index) { int pLength = genString.Length; int indexLen = index.ToString().Length; int correctLen = length - indexLen; if(pLength > correctLen) { genString.Remove(correctLen,pLength-correctLen); } else if(pLength < correctLen) { int addCount = correctLen - pLength; for(int i=0; i < addCount; i++) { genString.Append("_"); } } } public void ProcessMinLengthFacet(ref StringBuilder genString, int index) { int pLength = genString.Length; int indexLen = index.ToString().Length; int correctLen = minLength - indexLen; if(pLength < correctLen) { int addCount = correctLen - pLength; for(int i=0; i < addCount; i++) { genString.Append("_"); } } } public void ProcessMaxLengthFacet(ref StringBuilder genString, int index) { int pLength = genString.Length; int indexLen = index.ToString().Length; int correctLen = maxLength - indexLen; if(pLength > correctLen) { genString.Remove(correctLen,pLength-correctLen); } } } //End of class stringBase internal class Generator_string : Generator_facetBase { int step = 1; int endValue = 0; StringBuilder genString; public Generator_string() { } public Generator_string(CompiledFacets rFacets) { if(rFacets != null) { CheckFacets(rFacets); } } public override string GenerateValue() { if(AllowedValues != null) { object enumValue = GetEnumerationValue(); return enumValue.ToString(); } else { if (genString == null) { genString = new StringBuilder(Prefix); } else { genString.Append(Prefix); } try { endValue = endValue + step; } catch (OverflowException) { //reset endValue = 1; } if(length == -1 && minLength == -1 && maxLength == -1) { genString.Append(endValue); } else { if(length != -1) { // The length facet is set ProcessLengthFacet(ref genString, endValue); genString.Append(endValue); } else { if(minLength != -1) { ProcessMinLengthFacet(ref genString, endValue); } if(maxLength != -1) { ProcessMaxLengthFacet(ref genString, endValue); } genString.Append(endValue); } } string result = genString.ToString(); genString.Length = 0; //Clear the stringBuilder return result; } } // End of genValue } internal class Generator_decimal : XmlValueGenerator { protected decimal increment = 0; protected decimal startValue = 1; protected decimal step = 0.1m; protected decimal maxBound = decimal.MaxValue; protected decimal minBound = decimal.MinValue; int stateStep = 1; public Generator_decimal(CompiledFacets rFacets) { CheckFacets(rFacets); } public Generator_decimal() { } public decimal StartValue { set { startValue = value; } } public void CheckFacets(CompiledFacets genFacets) { if(genFacets != null) { RestrictionFlags flags = genFacets.Flags; if ((flags & RestrictionFlags.MaxInclusive) != 0) { maxBound = (decimal)Convert.ChangeType(genFacets.MaxInclusive, typeof(decimal)); } if ((flags & RestrictionFlags.MaxExclusive) != 0) { maxBound = (decimal)Convert.ChangeType(genFacets.MaxExclusive, typeof(decimal)) - 1; } if ((flags & RestrictionFlags.MinInclusive) != 0) { startValue = (decimal)Convert.ChangeType(genFacets.MinInclusive, typeof(decimal)); minBound = startValue; } if ((flags & RestrictionFlags.MinExclusive) != 0) { startValue = (decimal)Convert.ChangeType(genFacets.MinExclusive, typeof(decimal)) + 1; minBound = startValue; } if ((flags & RestrictionFlags.Enumeration) != 0) { AllowedValues = genFacets.Enumeration; } if ((flags & RestrictionFlags.TotalDigits) != 0) { decimal totalDigitsValue = (decimal)Math.Pow(10,genFacets.TotalDigits) - 1; if (totalDigitsValue <= maxBound) { //Use the lower of totalDigits value and maxInc/maxEx maxBound = totalDigitsValue; minBound = 0 - maxBound; } } if ((flags & RestrictionFlags.FractionDigits) != 0 && genFacets.FractionDigits > 0) { if ((flags & RestrictionFlags.TotalDigits) != 0) { //if (T,F) is (6,3) the max value is not 999.999 but 99999.9d but we are going with the smaller range on the integral part to generate more varied fractional part. int range = genFacets.TotalDigits - genFacets.FractionDigits; double integralPart = Math.Pow(10,range) - 1; double fractionPart = integralPart/Math.Pow(10,range); maxBound = (decimal)(integralPart + fractionPart); minBound = 0 - maxBound; step = (decimal)(1/Math.Pow(10,range)); } //If there is no TotalDigits facet, we use the step for decimal as 0.1 anyway which will satisfy fractionDigits >= 1 } if(maxBound <= 0) { startValue = maxBound; occurNum++; stateStep = 2; } if (startValue == minBound) { stateStep = 2; } } } public override string GenerateValue() { decimal result = 0; if(AllowedValues != null) { try { result = (decimal)AllowedValues[occurNum++ % AllowedValues.Count]; } catch(OverflowException) { occurNum = 0; result = (decimal)AllowedValues[occurNum++]; } } else { try { AddSubtractState state = states[occurNum % states.Length]; switch (state) { case AddSubtractState.StartPlusInc: result = startValue + increment; break; case AddSubtractState.MinPlusInc: result = minBound + increment; break; case AddSubtractState.MaxMinusInc: result = maxBound - increment; if (stateStep == 2) { increment = increment + step; } break; case AddSubtractState.StartMinusInc: increment = increment + step; //stateStep is 1 or 2, we need to increment now result = startValue - increment; break; default: Debug.Assert(false); break; } occurNum = occurNum + stateStep; } catch (OverflowException) { //reset result = ResetState(); } if (result >= maxBound) { result = maxBound; } else if (result <= minBound) { result = minBound; } } return result.ToString(null, NumberFormatInfo.InvariantInfo); } private decimal ResetState() { increment = 0; if (startValue == maxBound) { occurNum = 1; stateStep = 2; } if (startValue == minBound) { occurNum = 0; stateStep = 2; } return startValue; } } internal class Generator_integer : Generator_decimal { public Generator_integer(CompiledFacets rFacets) : base(rFacets) { step = 1; } public Generator_integer() { step = 1; } } internal class Generator_nonPositiveInteger : Generator_integer { public Generator_nonPositiveInteger() { } public Generator_nonPositiveInteger(CompiledFacets rFacets) { startValue = 0; increment = 1; maxBound = 0; CheckFacets(rFacets); } } internal class Generator_negativeInteger : Generator_nonPositiveInteger { public Generator_negativeInteger(CompiledFacets rFacets) { startValue = -1; maxBound = -1; CheckFacets(rFacets); } } internal class Generator_long : Generator_integer { public Generator_long() { maxBound = 9223372036854775807; minBound = -9223372036854775807; } public Generator_long(CompiledFacets rFacets) { maxBound = 9223372036854775807; minBound = -9223372036854775807; CheckFacets(rFacets); } } internal class Generator_int : Generator_long { public Generator_int() { maxBound = 2147483647; minBound = -2147483647; } public Generator_int(CompiledFacets rFacets) { maxBound = 2147483647; minBound = -2147483647; CheckFacets(rFacets); } } internal class Generator_short : Generator_int { public Generator_short() { maxBound = 32767; minBound = -32768; } public Generator_short(CompiledFacets rFacets) { maxBound = 32767; minBound = -32768; CheckFacets(rFacets); } } internal class Generator_byte : Generator_short { public Generator_byte(CompiledFacets rFacets) { maxBound = 127; minBound = -128; CheckFacets(rFacets); } } internal class Generator_nonNegativeInteger : Generator_integer { public Generator_nonNegativeInteger() { startValue = 0; minBound = 0; } public Generator_nonNegativeInteger(CompiledFacets rFacets) { startValue = 0; minBound = 0; CheckFacets(rFacets); } } internal class Generator_unsignedLong : Generator_nonNegativeInteger { public Generator_unsignedLong() { } public Generator_unsignedLong(CompiledFacets rFacets) { maxBound = 18446744073709551615; CheckFacets(rFacets); } } internal class Generator_unsignedInt : Generator_unsignedLong { public Generator_unsignedInt() { } public Generator_unsignedInt(CompiledFacets rFacets) { maxBound = 4294967295; CheckFacets(rFacets); } } internal class Generator_unsignedShort : Generator_unsignedInt { public Generator_unsignedShort() { } public Generator_unsignedShort(CompiledFacets rFacets) { maxBound = 65535; CheckFacets(rFacets); } } internal class Generator_unsignedByte : Generator_unsignedShort { public Generator_unsignedByte() { } public Generator_unsignedByte(CompiledFacets rFacets) { maxBound = 255; CheckFacets(rFacets); } } internal class Generator_positiveInteger : Generator_nonNegativeInteger { public Generator_positiveInteger(CompiledFacets rFacets) { startValue = 1; minBound = 1; CheckFacets(rFacets); } } internal class Generator_boolean : XmlValueGenerator { public override string GenerateValue() { if ((occurNum & 0x1) == 0) { occurNum = 1; return "true"; } else { occurNum = 0; return "false"; } } } internal class Generator_double : XmlValueGenerator { double increment = 0F; protected double startValue = 1; protected double step = 1.1F; protected double maxBound = double.MaxValue; protected double minBound = double.MinValue; int stateStep = 1; public Generator_double() { } public Generator_double(CompiledFacets rFacets) { CheckFacets(rFacets); } public void CheckFacets(CompiledFacets genFacets) { if(genFacets != null) { RestrictionFlags flags = genFacets.Flags; if ((flags & RestrictionFlags.MaxInclusive) != 0) { maxBound = (double)genFacets.MaxInclusive; } if ((flags & RestrictionFlags.MaxExclusive) != 0) { maxBound = (double)genFacets.MaxExclusive - 1; } if ((flags & RestrictionFlags.MinInclusive) != 0) { startValue = (double)genFacets.MinInclusive; minBound = startValue; } if ((flags & RestrictionFlags.MinExclusive) != 0) { startValue = (double)genFacets.MinExclusive + 1; minBound = startValue; } if ((flags & RestrictionFlags.Enumeration) != 0) { AllowedValues = genFacets.Enumeration; } if(maxBound <= 0) { startValue = maxBound; occurNum++; stateStep = 2; } if (startValue == minBound) { stateStep = 2; } } } public override string GenerateValue() { double result = 0; if(AllowedValues != null) { try { result = (double)AllowedValues[occurNum++ % AllowedValues.Count]; } catch(OverflowException) { occurNum = 0; result = (double)AllowedValues[occurNum++]; } } else { try { AddSubtractState state = states[occurNum % states.Length]; switch (state) { case AddSubtractState.StartPlusInc: result = startValue + increment; break; case AddSubtractState.MinPlusInc: result = minBound + increment; break; case AddSubtractState.MaxMinusInc: result = maxBound - increment; if (stateStep == 2) { increment = increment + step; } break; case AddSubtractState.StartMinusInc: increment = increment + step; //stateStep is 1 or 2, we need to increment now result = startValue - increment; break; default: Debug.Assert(false); break; } occurNum = occurNum + stateStep; } catch (OverflowException) { //reset result = ResetState(); } if (result > maxBound) { result = maxBound; } else if (result < minBound) { result = minBound; } } return XmlConvert.ToString(result); } private double ResetState() { increment = 0F; if (startValue == maxBound) { occurNum = 1; stateStep = 2; } if (startValue == minBound) { occurNum = 0; stateStep = 2; } return startValue; } } internal class Generator_float : XmlValueGenerator { float increment = 0F; float startValue = 1; float step = 1.1F; float maxBound = float.MaxValue; float minBound = float.MinValue; int stateStep = 1; public Generator_float(CompiledFacets rFacets) { CheckFacets(rFacets); } public void CheckFacets(CompiledFacets genFacets) { if(genFacets != null) { RestrictionFlags flags = genFacets.Flags; if ((flags & RestrictionFlags.MaxInclusive) != 0) { maxBound = (float)genFacets.MaxInclusive; } if ((flags & RestrictionFlags.MaxExclusive) != 0) { maxBound = (float)genFacets.MaxExclusive - 1; } if ((flags & RestrictionFlags.MinInclusive) != 0) { startValue = (float)genFacets.MinInclusive; minBound = startValue; } if ((flags & RestrictionFlags.MinExclusive) != 0) { startValue = (float)genFacets.MinExclusive + 1; minBound = startValue; } if ((flags & RestrictionFlags.Enumeration) != 0) { AllowedValues = genFacets.Enumeration; } if(maxBound <= 0) { startValue = maxBound; occurNum++; stateStep = 2; } if (startValue == minBound) { stateStep = 2; } } } public override string GenerateValue() { float result = 0; if(AllowedValues != null) { try { result = (float)AllowedValues[occurNum++ % AllowedValues.Count]; } catch(OverflowException) { occurNum = 0; result = (float)AllowedValues[occurNum++]; } } else { try { AddSubtractState state = states[occurNum % states.Length]; switch (state) { case AddSubtractState.StartPlusInc: result = startValue + increment; break; case AddSubtractState.MinPlusInc: result = minBound + increment; break; case AddSubtractState.MaxMinusInc: result = maxBound - increment; if (stateStep == 2) { increment = increment + step; } break; case AddSubtractState.StartMinusInc: increment = increment + step; //stateStep is 1 or 2, we need to increment now result = startValue - increment; break; default: Debug.Assert(false); break; } occurNum = occurNum + stateStep; } catch (OverflowException) { //reset result = ResetState(); } if (result > maxBound) { result = maxBound; } else if (result < minBound) { result = minBound; } } return XmlConvert.ToString(result); } private float ResetState() { increment = 0F; if (startValue == maxBound) { occurNum = 1; stateStep = 2; } if (startValue == minBound) { occurNum = 0; stateStep = 2; } return startValue; } } internal class Generator_duration : XmlValueGenerator { TimeSpan startValue = XmlConvert.ToTimeSpan("P1Y1M1DT1H1M1S"); TimeSpan step = XmlConvert.ToTimeSpan("P1Y"); TimeSpan increment = new TimeSpan(0,0,0,0); TimeSpan endValue = new TimeSpan(1,0,0,0); TimeSpan minBound = new TimeSpan(TimeSpan.MinValue.Days,TimeSpan.MinValue.Hours,TimeSpan.MinValue.Minutes,TimeSpan.MinValue.Seconds,TimeSpan.MinValue.Milliseconds); TimeSpan maxBound = new TimeSpan(TimeSpan.MaxValue.Days,TimeSpan.MaxValue.Hours,TimeSpan.MaxValue.Minutes,TimeSpan.MaxValue.Seconds,TimeSpan.MaxValue.Milliseconds); int stateStep = 1; public Generator_duration(CompiledFacets rFacets) { CheckFacets(rFacets); } public void CheckFacets(CompiledFacets genFacets) { if(genFacets != null) { RestrictionFlags flags = genFacets.Flags; if ((flags & RestrictionFlags.MaxInclusive) != 0) { maxBound = (TimeSpan)genFacets.MaxInclusive; } if ((flags & RestrictionFlags.MaxExclusive) != 0) { maxBound = (TimeSpan)genFacets.MaxExclusive - endValue; } if ((flags & RestrictionFlags.MinInclusive) != 0) { startValue = (TimeSpan)genFacets.MinInclusive; minBound = startValue; } if ((flags & RestrictionFlags.MinExclusive) != 0) { startValue = (TimeSpan)genFacets.MinExclusive + endValue; minBound = startValue; } if ((flags & RestrictionFlags.Enumeration) != 0) { AllowedValues = genFacets.Enumeration; } if(TimeSpan.Compare(maxBound, TimeSpan.Zero) == -1) { startValue = maxBound; occurNum++; stateStep = 2; } if (TimeSpan.Compare(minBound, startValue) == 0) { stateStep = 2; } } } public override string GenerateValue() { TimeSpan result = TimeSpan.Zero; if(AllowedValues != null) { try { result = (TimeSpan)AllowedValues[occurNum++ % AllowedValues.Count]; } catch (OverflowException) { occurNum = 0; result = (TimeSpan)AllowedValues[occurNum++]; } } else { try { AddSubtractState state = states[occurNum % states.Length]; switch (state) { case AddSubtractState.StartPlusInc: result = startValue + increment; break; case AddSubtractState.MinPlusInc: result = minBound + increment; break; case AddSubtractState.MaxMinusInc: result = maxBound - increment; if (stateStep == 2) { increment = increment + step; } break; case AddSubtractState.StartMinusInc: increment = increment + step; //stateStep is 1 or 2, we need to increment now result = startValue - increment; break; default: Debug.Assert(false); break; } occurNum = occurNum + stateStep; } catch (OverflowException) { //Reset result = ResetState(); } if (result > maxBound) { result = maxBound; } else if (result < minBound) { result = minBound; } } return XmlConvert.ToString(result); } private TimeSpan ResetState() { increment = TimeSpan.Zero; occurNum = 0; if(TimeSpan.Compare(maxBound, startValue) == 0) { occurNum++; stateStep = 2; } if (TimeSpan.Compare(minBound, startValue) == 0) { stateStep = 2; } return startValue; } } // End of class Generator_duration internal class Generator_dateTime : XmlValueGenerator { TimeSpan increment; protected DateTime startValue = new DateTime(1900,1,1,1,1,1); protected TimeSpan step = XmlConvert.ToTimeSpan("P32D"); protected DateTime minBound = DateTime.MinValue; protected DateTime maxBound = DateTime.MaxValue; int stateStep = 1; public Generator_dateTime() { } public Generator_dateTime (CompiledFacets rFacets) { CheckFacets(rFacets); } public void CheckFacets(CompiledFacets genFacets) { if(genFacets != null) { RestrictionFlags flags = genFacets.Flags; if ((flags & RestrictionFlags.MaxInclusive) != 0) { maxBound = (DateTime)genFacets.MaxInclusive; } if ((flags & RestrictionFlags.MaxExclusive) != 0) { maxBound = ((DateTime)genFacets.MaxExclusive).Subtract(step); } if ((flags & RestrictionFlags.MinInclusive) != 0) { startValue = (DateTime)genFacets.MinInclusive; minBound = startValue; } if ((flags & RestrictionFlags.MinExclusive) != 0) { startValue = ((DateTime)genFacets.MinExclusive).Add(step); minBound = startValue; } if ((flags & RestrictionFlags.Enumeration) != 0) { AllowedValues = genFacets.Enumeration; } if (DateTime.Compare(startValue, maxBound) == 0) { occurNum++; stateStep = 2; } if (DateTime.Compare(startValue, minBound) == 0) { stateStep = 2; } } } public override string GenerateValue() { DateTime result = GenerateDate(); return XmlConvert.ToString(result); } protected DateTime GenerateDate() { if (AllowedValues != null) { try { return (DateTime)AllowedValues[occurNum++ % AllowedValues.Count]; } catch(OverflowException) { occurNum = 0; return (DateTime)AllowedValues[occurNum++]; } } else { DateTime result = DateTime.UtcNow; try { AddSubtractState state = states[occurNum % states.Length]; switch (state) { case AddSubtractState.StartPlusInc: result = startValue.Add(increment); break; case AddSubtractState.MinPlusInc: result = minBound.Add(increment); break; case AddSubtractState.MaxMinusInc: result = maxBound.Subtract(increment); if (stateStep == 2) { increment = increment + step; } break; case AddSubtractState.StartMinusInc: increment = increment + step; //stateStep is 1 or 2, we need to increment now result = startValue.Subtract(increment); break; default: Debug.Assert(false); break; } occurNum = occurNum + stateStep; } catch (ArgumentOutOfRangeException) { //reset result = ResetState(); } if (result >= maxBound) { result = maxBound; } else if (result <= minBound) { result = minBound; } return result; } } private DateTime ResetState() { increment = TimeSpan.Zero; occurNum = 0; if (DateTime.Compare(startValue, maxBound) == 0) { occurNum++; stateStep = 2; } if (DateTime.Compare(startValue, minBound) == 0) { stateStep = 2; } return startValue; } }// End of class dateTime internal class Generator_date : Generator_dateTime { public Generator_date(CompiledFacets rFacets) : base (rFacets){ } public override string GenerateValue() { DateTime result = GenerateDate(); return XmlConvert.ToString(result.Date, "yyyy-MM-dd"); } } internal class Generator_gYearMonth : Generator_dateTime { public Generator_gYearMonth(CompiledFacets rFacets) { step = XmlConvert.ToTimeSpan("P32D"); CheckFacets(rFacets); } public override string GenerateValue() { DateTime result = GenerateDate(); return XmlConvert.ToString(result.Date, "yyyy-MM"); } } internal class Generator_gYear : Generator_dateTime { public Generator_gYear(CompiledFacets rFacets) { step = XmlConvert.ToTimeSpan("P380D"); CheckFacets(rFacets); } public override string GenerateValue() { DateTime result = GenerateDate(); return XmlConvert.ToString(result.Date, "yyyy"); } } internal class Generator_gMonthDay : Generator_dateTime { public Generator_gMonthDay(CompiledFacets rFacets) { step = XmlConvert.ToTimeSpan("P1M5D"); CheckFacets(rFacets); } public override string GenerateValue() { DateTime result = GenerateDate(); return XmlConvert.ToString(result.Date, "--MM-dd"); } } internal class Generator_gDay : Generator_dateTime { public Generator_gDay(CompiledFacets rFacets) : base (rFacets){ } public override string GenerateValue() { DateTime result = GenerateDate(); return XmlConvert.ToString(result.Date, "---dd"); } } internal class Generator_gMonth : Generator_dateTime { public Generator_gMonth(CompiledFacets rFacets) { step = XmlConvert.ToTimeSpan("P32D"); CheckFacets(rFacets); } public override string GenerateValue() { DateTime result = GenerateDate(); return XmlConvert.ToString(GenerateDate().Date, "--MM--"); } } internal class Generator_time : Generator_dateTime { public Generator_time(CompiledFacets rFacets) { step = XmlConvert.ToTimeSpan("PT1M30S"); CheckFacets(rFacets); } public override string GenerateValue() { return XmlConvert.ToString(GenerateDate(), "HH:mm:ss"); } } internal class Generator_hexBinary : Generator_facetBase { Generator_integer binGen = new Generator_int(); public Generator_hexBinary(CompiledFacets rFacets) { binGen.StartValue = 4023; base.CheckFacets(rFacets); } public override string GenerateValue() { if(AllowedValues != null) { object enumValue = GetEnumerationValue(); return (string)this.Datatype.ChangeType(enumValue, TypeOfString); } else { int binNo = (int)Convert.ChangeType(binGen.GenerateValue(), typeof(int)); StringBuilder str = new StringBuilder(binNo.ToString("X4")); if(length == -1 && minLength == -1 && maxLength == -1) { return str.ToString(); } else if (length != -1){ ProcessLengthFacet(ref str); } else { ProcessMinMaxLengthFacet(ref str); } return str.ToString(); } } // End of GenValue private void ProcessLengthFacet(ref StringBuilder str) { int pLength = str.Length; if (pLength % 2 != 0) { throw new Exception("Total length of binary data should be even"); } int correctLen = pLength / 2; if(correctLen > length) { //Need to remove (correctLen - length) * 2 chars str.Remove(length,(correctLen - length) * 2 ); } else if(correctLen < length) { //Need to add (length - correctLen) * 2 chars int addCount = length - correctLen; for(int i=0; i < addCount; i++) { str.Append("0A"); } } } private void ProcessMinMaxLengthFacet(ref StringBuilder str) { int pLength = str.Length; if (pLength % 2 != 0) { throw new Exception("Total length of binary data should be even"); } int correctLen = pLength / 2; if(minLength != -1) { if(correctLen < minLength) { int addCount = minLength - correctLen; for(int i=0; i < addCount; i++) { str.Append("0A"); } } } else { //if maxLength != -1 if(correctLen > maxLength) { //Need to remove (correctLen - maxlength) * 2 chars str.Remove(maxLength,(correctLen - maxLength) * 2 ); } } } } internal class Generator_base64Binary : Generator_facetBase { public Generator_base64Binary(CompiledFacets rFacets) { CheckFacets(rFacets); } public override string GenerateValue() { if(AllowedValues != null) { object enumValue = GetEnumerationValue(); return Convert.ToBase64String(enumValue as byte[]); } else { return "base64Binary Content"; } } } internal class Generator_QName : Generator_string { public Generator_QName() { } public Generator_QName(CompiledFacets rFacets) { Prefix = "qname"; CheckFacets(rFacets); } public override string GenerateValue() { string result = base.GenerateValue(); if (result.Length == 1) { //If it is a qname of length 1, then return a char to be sure return new string(Prefix[0], 1); } return result; } } internal class Generator_Notation : Generator_QName { public Generator_Notation(CompiledFacets rFacets) { CheckFacets(rFacets); } } internal class Generator_normalizedString : Generator_string { public Generator_normalizedString() { } public Generator_normalizedString(CompiledFacets rFacets) : base(rFacets){ } } internal class Generator_token : Generator_normalizedString { public Generator_token() { } public Generator_token(CompiledFacets rFacets) { Prefix = "Token"; CheckFacets(rFacets); } } internal class Generator_language : Generator_string { //A derived type of token static string[] languageList = new string[] {"en", "fr", "de", "da", "el", "it", "en-US"}; public Generator_language(CompiledFacets rFacets) : base(rFacets){ } public override string GenerateValue() { if(AllowedValues != null) { return base.GenerateValue(); } else { return languageList[occurNum++ % languageList.Length]; } } } internal class Generator_NMTOKEN : Generator_token { public Generator_NMTOKEN() { } public Generator_NMTOKEN(CompiledFacets rFacets) : base(rFacets){ } } internal class Generator_Name : Generator_string { public Generator_Name(CompiledFacets rFacets){ Prefix = "Name"; CheckFacets(rFacets); } } internal class Generator_NCName : Generator_string { public Generator_NCName(CompiledFacets rFacets) { Prefix = "NcName"; CheckFacets(rFacets); } } internal class Generator_ID : Generator_string { public Generator_ID() { Prefix="ID"; } public override string GenerateValue() { if (IDRef) { IDRef = false; return (string)IDList[IDCnt-1]; } else { string id = base.GenerateValue(); IDList.Add(id); //Add to arraylist so that you can retreive it from there for IDREF return (string)IDList[IDCnt++]; } } } internal class Generator_IDREF : Generator_string { int refCnt = 0; public Generator_IDREF() { } public override string GenerateValue() { if (IDList.Count == 0) { string id = g_ID.GenerateValue(); IDRef = true; } if (refCnt >= IDList.Count) { refCnt = refCnt - IDList.Count; } return (string)IDList[refCnt++]; } } internal class Generator_anyURI : Generator_string { public Generator_anyURI(CompiledFacets rFacets) { Prefix = "http://uri"; CheckFacets(rFacets); } } internal class Generator_Union : Generator_facetBase { ArrayList unionGens = new ArrayList(); public Generator_Union() { } public Generator_Union(CompiledFacets rFacets) { CheckFacets(rFacets); } public override void AddGenerator(XmlValueGenerator genr) { unionGens.Add(genr); } internal ArrayList Generators { get { return unionGens; } } public override string GenerateValue() { if(AllowedValues != null) { object enumValue = GetEnumerationValue(); //Unpack the union enumeration value into memberType and typedValue object typedValue = CompiledFacets.XsdSimpleValueType.InvokeMember("typedValue", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, enumValue, null); return (string)this.Datatype.ChangeType(typedValue, TypeOfString); } else if (unionGens.Count > 0){ XmlValueGenerator genr = (XmlValueGenerator)(unionGens[occurNum % unionGens.Count]); genr.Prefix = this.Prefix; occurNum = occurNum + 1; return genr.GenerateValue(); } return string.Empty; } } internal class Generator_List : Generator_facetBase { XmlValueGenerator genr; int listLength; StringBuilder resultBuilder; public Generator_List() { } public Generator_List(CompiledFacets rFacets) { CheckFacets(rFacets); } public int ListLength { get { return listLength; } set { listLength = value; } } public override void AddGenerator(XmlValueGenerator valueGenr) { genr = valueGenr; } public override string GenerateValue() { if (resultBuilder == null) { resultBuilder = new StringBuilder(); } else { //Clear old value resultBuilder.Length = 0; } if (AllowedValues != null) { object enumValue = GetEnumerationValue(); return (string)this.Datatype.ChangeType(enumValue, TypeOfString); } else { genr.Prefix = this.Prefix; int NoItems = listLength; if (length != -1) { NoItems = length; } else if (minLength != -1) { NoItems = minLength; } else if (maxLength != -1) { NoItems = maxLength; } for(int i=0; i < NoItems; i++) { resultBuilder.Append(genr.GenerateValue()); resultBuilder.Append(" "); } } return resultBuilder.ToString(); } } }
//--------------------------------------------------------------------------- // // <copyright file="MultiBindingExpression.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: Defines MultiBindingExpression object, uses a collection of BindingExpressions together. // // See spec at http://avalon/connecteddata/Specs/Data%20Binding.mht // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Windows.Threading; using System.Threading; using System.Windows.Controls; using System.Windows.Input; // FocusChangedEvent using System.Windows.Markup; using MS.Internal.Controls; // Validation using MS.Internal.KnownBoxes; using MS.Internal.Data; using MS.Utility; using MS.Internal; // Invariant.Assert namespace System.Windows.Data { /// <summary> /// Describes a collection of BindingExpressions attached to a single property. /// The inner BindingExpressions contribute their values to the MultiBindingExpression, /// which combines/converts them into a resultant final value. /// In the reverse direction, the target value is tranlated to /// a set of values that are fed back into the inner BindingExpressions. /// </summary> public sealed class MultiBindingExpression: BindingExpressionBase, IDataBindEngineClient { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> Constructor </summary> private MultiBindingExpression(MultiBinding binding, BindingExpressionBase owner) : base(binding, owner) { int count = binding.Bindings.Count; // reduce repeated allocations _tempValues = new object[count]; _tempTypes = new Type[count]; } //------------------------------------------------------ // // Interfaces // //------------------------------------------------------ void IDataBindEngineClient.TransferValue() { TransferValue(); } void IDataBindEngineClient.UpdateValue() { UpdateValue(); } bool IDataBindEngineClient.AttachToContext(bool lastChance) { AttachToContext(lastChance); return !TransferIsDeferred; } void IDataBindEngineClient.VerifySourceReference(bool lastChance) { } void IDataBindEngineClient.OnTargetUpdated() { OnTargetUpdated(); } DependencyObject IDataBindEngineClient.TargetElement { get { return !UsingMentor ? TargetElement : Helper.FindMentor(TargetElement); } } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> Binding from which this expression was created </summary> public MultiBinding ParentMultiBinding { get { return (MultiBinding)ParentBindingBase; } } /// <summary> List of inner BindingExpression </summary> public ReadOnlyCollection<BindingExpressionBase> BindingExpressions { get { return new ReadOnlyCollection<BindingExpressionBase>(MutableBindingExpressions); } } //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ /// <summary> Send the current value back to the source(s) </summary> /// <remarks> Does nothing when binding's Mode is not TwoWay or OneWayToSource </remarks> public override void UpdateSource() { // ultimately, what would be better would be to have a status flag that // indicates that this MultiBindingExpression has been Detached, as opposed to a // MultiBindingExpression that doesn't have anything in its BindingExpressions collection // in the first place. Added to which, there should be distinct error // messages for both of these error conditions. if (MutableBindingExpressions.Count == 0) throw new InvalidOperationException(SR.Get(SRID.BindingExpressionIsDetached)); NeedsUpdate = true; // force update Update(); // update synchronously } /// <summary> Force a data transfer from sources to target </summary> /// <remarks> Will transfer data even if binding's Mode is OneWay </remarks> public override void UpdateTarget() { // ultimately, what would be better would be to have a status flag that // indicates that this MultiBindingExpression has been Detached, as opposed to a // MultiBindingExpression that doesn't have anything in its BindingExpressions collection // in the first place. Added to which, there should be distinct error // messages for both of these error conditions. if (MutableBindingExpressions.Count == 0) throw new InvalidOperationException(SR.Get(SRID.BindingExpressionIsDetached)); UpdateTarget(true); } #region Expression overrides #endregion Expression overrides //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ internal override bool IsParentBindingUpdateTriggerDefault { get { return (ParentMultiBinding.UpdateSourceTrigger == UpdateSourceTrigger.Default); } } //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ // Create a new BindingExpression from the given Binding description internal static MultiBindingExpression CreateBindingExpression(DependencyObject d, DependencyProperty dp, MultiBinding binding, BindingExpressionBase owner) { FrameworkPropertyMetadata fwMetaData = dp.GetMetadata(d.DependencyObjectType) as FrameworkPropertyMetadata; if ((fwMetaData != null && !fwMetaData.IsDataBindingAllowed) || dp.ReadOnly) throw new ArgumentException(SR.Get(SRID.PropertyNotBindable, dp.Name), "dp"); // create the BindingExpression MultiBindingExpression bindExpr = new MultiBindingExpression(binding, owner); bindExpr.ResolvePropertyDefaultSettings(binding.Mode, binding.UpdateSourceTrigger, fwMetaData); return bindExpr; } // Attach to things that may require tree context (parent, root, etc.) void AttachToContext(bool lastChance) { DependencyObject target = TargetElement; if (target == null) return; Debug.Assert(ParentMultiBinding.Converter != null || !String.IsNullOrEmpty(EffectiveStringFormat), "MultiBindingExpression should not exist if its bind does not have a valid converter."); bool isExtendedTraceEnabled = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.AttachToContext); _converter = ParentMultiBinding.Converter; if (_converter == null && String.IsNullOrEmpty(EffectiveStringFormat)) { TraceData.Trace(TraceEventType.Error, TraceData.MultiBindingHasNoConverter, ParentMultiBinding); } if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.AttachToContext( TraceData.Identify(this), lastChance ? " (last chance)" : String.Empty)); } TransferIsDeferred = true; bool attached = true; // true if all child bindings have attached int count = MutableBindingExpressions.Count; for (int i = 0; i < count; ++i) { if (MutableBindingExpressions[i].StatusInternal == BindingStatusInternal.Unattached) attached = false; } // if the child bindings aren't ready yet, try again later. Leave // TransferIsDeferred set, to indicate we're not ready yet. if (!attached && !lastChance) { if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.ChildNotAttached( TraceData.Identify(this))); } return; } // listen to the Language property, if needed if (UsesLanguage) { WeakDependencySource[] commonSources = new WeakDependencySource[] { new WeakDependencySource(TargetElement, FrameworkElement.LanguageProperty) }; WeakDependencySource[] newSources = CombineSources(-1, MutableBindingExpressions, MutableBindingExpressions.Count, null, commonSources); ChangeSources(newSources); } // initial transfer bool initialTransferIsUpdate = IsOneWayToSource; object currentValue; if (ShouldUpdateWithCurrentValue(target, out currentValue)) { initialTransferIsUpdate = true; ChangeValue(currentValue, /*notify*/false); NeedsUpdate = true; } SetStatus(BindingStatusInternal.Active); if (!initialTransferIsUpdate) { UpdateTarget(false); } else { UpdateValue(); } } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// The ValidationError that caused this /// BindingExpression to be invalid. /// </summary> public override ValidationError ValidationError { get { ValidationError validationError = base.ValidationError; if (validationError == null) { for ( int i = 0; i < MutableBindingExpressions.Count; i++ ) { validationError = MutableBindingExpressions[i].ValidationError; if (validationError != null) break; } } return validationError; } } /// <summary> /// HasError returns true if any of the ValidationRules /// of any of its inner bindings failed its validation rule /// or the Multi-/PriorityBinding itself has a failing validation rule. /// </summary> public override bool HasError { get { bool hasError = base.HasError; if (!hasError) { for ( int i = 0; i < MutableBindingExpressions.Count; i++ ) { if (MutableBindingExpressions[i].HasError) return true; } } return hasError; } } /// <summary> /// HasValidationError returns true if any of the ValidationRules /// of any of its inner bindings failed its validation rule /// or the Multi-/PriorityBinding itself has a failing validation rule. /// </summary> public override bool HasValidationError { get { bool hasError = base.HasValidationError; if (!hasError) { for ( int i = 0; i < MutableBindingExpressions.Count; i++ ) { if (MutableBindingExpressions[i].HasValidationError) return true; } } return hasError; } } //------------------------------------------------------ // // Protected Internal Methods // //------------------------------------------------------ /// <summary> /// Attach a BindingExpression to the given target (element, property) /// </summary> /// <param name="d">DependencyObject being set</param> /// <param name="dp">Property being set</param> internal override bool AttachOverride(DependencyObject d, DependencyProperty dp) { if (!base.AttachOverride(d, dp)) return false; DependencyObject target = TargetElement; if (target == null) return false; // listen for lost focus if (IsUpdateOnLostFocus) { LostFocusEventManager.AddHandler(target, OnLostFocus); } TransferIsDeferred = true; // Defer data transfer until after we activate all the BindingExpressions int count = ParentMultiBinding.Bindings.Count; for (int i = 0; i < count; ++i) { // ISSUE: It may be possible to have _attachedBindingExpressions be non-zero // at the end of Detach if the conditions for the increment on Attach // and the decrement on Detach are not precisely the same. AttachBindingExpression(i, false); // create new binding and have it added to end } // attach to things that need tree context. Do it synchronously // if possible, otherwise post a task. This gives the parser et al. // a chance to assemble the tree before we start walking it. AttachToContext(false /* lastChance */); if (TransferIsDeferred) { Engine.AddTask(this, TaskOps.AttachToContext); if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.AttachToContext)) { TraceData.Trace(TraceEventType.Warning, TraceData.DeferAttachToContext( TraceData.Identify(this))); } } return true; } /// <summary> sever all connections </summary> internal override void DetachOverride() { DependencyObject target = TargetElement; if (target != null && IsUpdateOnLostFocus) { LostFocusEventManager.RemoveHandler(target, OnLostFocus); } // Theoretically, we only need to detach number of AttentiveBindingExpressions, // but we'll traverse the whole list anyway and do aggressive clean-up. int count = MutableBindingExpressions.Count; for (int i = count - 1; i >= 0; i--) { BindingExpressionBase b = MutableBindingExpressions[i]; if (b != null) { b.Detach(); MutableBindingExpressions.RemoveAt(i); } } ChangeSources(null); base.DetachOverride(); } /// <summary> /// Invalidate the given child expression. /// </summary> internal override void InvalidateChild(BindingExpressionBase bindingExpression) { int index = MutableBindingExpressions.IndexOf(bindingExpression); // do a sanity check that we care about this BindingExpression if (0 <= index && IsDynamic) { NeedsDataTransfer = true; Transfer(); // this will Invalidate target property. } } /// <summary> /// Change the dependency sources for the given child expression. /// </summary> internal override void ChangeSourcesForChild(BindingExpressionBase bindingExpression, WeakDependencySource[] newSources) { int index = MutableBindingExpressions.IndexOf(bindingExpression); if (index >= 0) { WeakDependencySource[] commonSources = null; if (UsesLanguage) { commonSources = new WeakDependencySource[] { new WeakDependencySource(TargetElement, FrameworkElement.LanguageProperty) }; } WeakDependencySource[] combinedSources = CombineSources(index, MutableBindingExpressions, MutableBindingExpressions.Count, newSources, commonSources); ChangeSources(combinedSources); } } /// <summary> /// Replace the given child expression with a new one. /// </summary> internal override void ReplaceChild(BindingExpressionBase bindingExpression) { int index = MutableBindingExpressions.IndexOf(bindingExpression); DependencyObject target = TargetElement; if (index >= 0 && target != null) { // detach and clean up the old binding bindingExpression.Detach(); // replace BindingExpression AttachBindingExpression(index, true); } } // register the leaf bindings with the binding group internal override void UpdateBindingGroup(BindingGroup bg) { for (int i=0, n=MutableBindingExpressions.Count-1; i<n; ++i) { MutableBindingExpressions[i].UpdateBindingGroup(bg); } } /// <summary> /// Get the converted proposed value /// <summary> internal override object ConvertProposedValue(object value) { object result; bool success = ConvertProposedValueImpl(value, out result); // if the conversion failed, signal a validation error if (!success) { result = DependencyProperty.UnsetValue; ValidationError validationError = new ValidationError(ConversionValidationRule.Instance, this, SR.Get(SRID.Validation_ConversionFailed, value), null); UpdateValidationError(validationError); } return result; } private bool ConvertProposedValueImpl(object value, out object result) { DependencyObject target = TargetElement; if (target == null) { result = DependencyProperty.UnsetValue; return false; } result = GetValuesForChildBindings(value); if (IsDetached) { return false; // user code detached the binding. give up. } if (result == DependencyProperty.UnsetValue) { SetStatus(BindingStatusInternal.UpdateSourceError); return false; } object[] values = (object[])result; if (values == null) { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.BadMultiConverterForUpdate( Converter.GetType().Name, AvTrace.ToStringHelper(value), AvTrace.TypeName(value)), this); } result = DependencyProperty.UnsetValue; return false; } if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Update)) { for (int i=0; i<values.Length; ++i) { TraceData.Trace(TraceEventType.Warning, TraceData.UserConvertBackMulti( TraceData.Identify(this), i, TraceData.Identify(values[i]))); } } // if lengths are mismatched, show warning int count = MutableBindingExpressions.Count; if (values.Length != count && TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Information, TraceData.MultiValueConverterMismatch, Converter.GetType().Name, count, values.Length, TraceData.DescribeTarget(target, TargetProperty)); } // use the smaller count if (values.Length < count) count = values.Length; // using the result of ConvertBack as the raw value, run each child binding // through the first two steps of the update/validate process bool success = true; for (int i = 0; i < count; ++i) { value = values[i]; if (value != Binding.DoNothing && value != DependencyProperty.UnsetValue) { BindingExpressionBase bindExpr = MutableBindingExpressions[i]; bindExpr.SetValue(target, TargetProperty, value); // could pass (null, null, values[i]) value = bindExpr.GetRawProposedValue(); if (!bindExpr.Validate(value, ValidationStep.RawProposedValue)) value = DependencyProperty.UnsetValue; value = bindExpr.ConvertProposedValue(value); } else if (value == DependencyProperty.UnsetValue && TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Information, TraceData.UnsetValueInMultiBindingExpressionUpdate( Converter.GetType().Name, AvTrace.ToStringHelper(value), i, _tempTypes[i] ), this); } if (value == DependencyProperty.UnsetValue) { success = false; } values[i] = value; } Array.Clear(_tempTypes, 0, _tempTypes.Length); result = values; return success; } object GetValuesForChildBindings(object rawValue) { if (Converter == null) { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.MultiValueConverterMissingForUpdate, this); } return DependencyProperty.UnsetValue; } CultureInfo culture = GetCulture(); int count = MutableBindingExpressions.Count; for (int i = 0; i < count; ++i) { BindingExpressionBase bindExpr = MutableBindingExpressions[i]; BindingExpression be = bindExpr as BindingExpression; if (be != null && be.UseDefaultValueConverter) _tempTypes[i] = be.ConverterSourceType; else _tempTypes[i] = TargetProperty.PropertyType; } // MultiValueConverters are always user-defined, so don't catch exceptions (bug 992237) return Converter.ConvertBack(rawValue, _tempTypes, ParentMultiBinding.ConverterParameter, culture); } /// <summary> /// Get the converted proposed value and inform the binding group /// <summary> internal override bool ObtainConvertedProposedValue(BindingGroup bindingGroup) { bool result = true; if (NeedsUpdate) { object value = bindingGroup.GetValue(this); if (value != DependencyProperty.UnsetValue) { object[] values; value = ConvertProposedValue(value); if (value == DependencyProperty.UnsetValue) { result = false; } else if ((values = value as object[]) != null) { for (int i=0; i<values.Length; ++i) { if (values[i] == DependencyProperty.UnsetValue) { result = false; } } } } StoreValueInBindingGroup(value, bindingGroup); } else { bindingGroup.UseSourceValue(this); } return result; } /// <summary> /// Update the source value /// <summary> internal override object UpdateSource(object convertedValue) { if (convertedValue == DependencyProperty.UnsetValue) { SetStatus(BindingStatusInternal.UpdateSourceError); return convertedValue; } object[] values = convertedValue as object[]; int count = MutableBindingExpressions.Count; if (values.Length < count) count = values.Length; BeginSourceUpdate(); bool updateActuallyHappened = false; for (int i = 0; i < count; ++i) { object value = values[i]; if (value != Binding.DoNothing) { BindingExpressionBase bindExpr = MutableBindingExpressions[i]; bindExpr.UpdateSource(value); if (bindExpr.StatusInternal == BindingStatusInternal.UpdateSourceError) { SetStatus(BindingStatusInternal.UpdateSourceError); } updateActuallyHappened = true; } } if (!updateActuallyHappened) { IsInUpdate = false; // inhibit the "$10 bug" re-fetch if nothing actually updated } EndSourceUpdate(); OnSourceUpdated(); return convertedValue; } /// <summary> /// Update the source value and inform the binding group /// <summary> internal override bool UpdateSource(BindingGroup bindingGroup) { bool result = true; if (NeedsUpdate) { object value = bindingGroup.GetValue(this); UpdateSource(value); if (value == DependencyProperty.UnsetValue) { result = false; } } return result; } /// <summary> /// Store the value in the binding group /// </summary> internal override void StoreValueInBindingGroup(object value, BindingGroup bindingGroup) { bindingGroup.SetValue(this, value); object[] values = value as object[]; if (values != null) { int count = MutableBindingExpressions.Count; if (values.Length < count) count = values.Length; for (int i=0; i<count; ++i) { MutableBindingExpressions[i].StoreValueInBindingGroup(values[i], bindingGroup); } } else { for (int i=MutableBindingExpressions.Count-1; i>=0; --i) { MutableBindingExpressions[i].StoreValueInBindingGroup(DependencyProperty.UnsetValue, bindingGroup); } } } /// <summary> /// Run validation rules for the given step /// <summary> internal override bool Validate(object value, ValidationStep validationStep) { if (value == Binding.DoNothing) return true; if (value == DependencyProperty.UnsetValue) { SetStatus(BindingStatusInternal.UpdateSourceError); return false; } // run rules attached to this multibinding bool result = base.Validate(value, validationStep); // run rules attached to the child bindings switch (validationStep) { case ValidationStep.RawProposedValue: // the child bindings don't get raw values until the Convert step break; default: object[] values = value as object[]; int count = MutableBindingExpressions.Count; if (values.Length < count) count = values.Length; for (int i=0; i<count; ++i) { value = values[i]; if (value == DependencyProperty.UnsetValue) { // an unset value means the binding failed validation at an earlier step, // typically at Raw step, evaluated during the MultiBinding's ConvertValue //result = false; // COMPAT: This should mean the MultiBinding as a whole fails validation, but // in 3.5 this didn't happen. Instead the process continued, writing back // values to child bindings that succeeded, and simply not writing back // to child bindings that didn't. } else if (value != Binding.DoNothing) { if (!MutableBindingExpressions[i].Validate(value, validationStep)) { values[i] = DependencyProperty.UnsetValue; // prevent writing an invalid value //result = false; // COMPAT: as above, preserve v3.5 behavior by not failing when a // child binding fails to validate } } } break; } return result; } /// <summary> /// Run validation rules for the given step, and inform the binding group /// <summary> internal override bool CheckValidationRules(BindingGroup bindingGroup, ValidationStep validationStep) { if (!NeedsValidation) return true; object value; switch (validationStep) { case ValidationStep.RawProposedValue: case ValidationStep.ConvertedProposedValue: case ValidationStep.UpdatedValue: case ValidationStep.CommittedValue: value = bindingGroup.GetValue(this); break; default: throw new InvalidOperationException(SR.Get(SRID.ValidationRule_UnknownStep, validationStep, bindingGroup)); } bool result = Validate(value, validationStep); if (result && validationStep == ValidationStep.CommittedValue) { NeedsValidation = false; } return result; } /// <summary> /// Get the proposed value(s) that would be written to the source(s), applying /// conversion and checking UI-side validation rules. /// </summary> internal override bool ValidateAndConvertProposedValue(out Collection<ProposedValue> values) { Debug.Assert(NeedsValidation, "check NeedsValidation before calling this"); values = null; // validate raw proposed value object rawValue = GetRawProposedValue(); bool isValid = Validate(rawValue, ValidationStep.RawProposedValue); if (!isValid) { return false; } // apply conversion object conversionResult = GetValuesForChildBindings(rawValue); if (IsDetached || conversionResult == DependencyProperty.UnsetValue || conversionResult == null) { return false; } int count = MutableBindingExpressions.Count; object[] convertedValues = (object[])conversionResult; if (convertedValues.Length < count) count = convertedValues.Length; values = new Collection<ProposedValue>(); bool result = true; // validate child bindings for (int i = 0; i < count; ++i) { object value = convertedValues[i]; if (value == Binding.DoNothing) { } else if (value == DependencyProperty.UnsetValue) { // conversion failure result = false; } else { // send converted value to child binding BindingExpressionBase bindExpr = MutableBindingExpressions[i]; bindExpr.Value = value; // validate child binding if (bindExpr.NeedsValidation) { Collection<ProposedValue> childValues; bool childResult = bindExpr.ValidateAndConvertProposedValue(out childValues); // append child's values to our values if (childValues != null) { for (int k=0, n=childValues.Count; k<n; ++k) { values.Add(childValues[k]); } } // merge child's result result = result && childResult; } } } return result; } // Return the object from which the given value was obtained, if possible internal override object GetSourceItem(object newValue) { if (newValue == null) return null; // this avoids false positive results // It's impossible to find the source item in the general case - the value // may have been produced by the multi-converter, combining inputs from // several different sources. But we can do it in the special case where // one of the child bindings actually produced the final value, and the // converter merely selected it (or did other extraneous work). int count = MutableBindingExpressions.Count; for (int i = 0; i < count; ++i) { object value = MutableBindingExpressions[i].GetValue(null, null); // could pass (null, null) if (Object.Equals(value, newValue)) return MutableBindingExpressions[i].GetSourceItem(newValue); } return null; } //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ /// <summary> /// expose a mutable version of the list of all BindingExpressions; /// derived internal classes need to be able to populate this list /// </summary> private Collection<BindingExpressionBase> MutableBindingExpressions { get { return _list; } } IMultiValueConverter Converter { get { return _converter; } set { _converter = value; } } //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ // Create a BindingExpression for position i BindingExpressionBase AttachBindingExpression(int i, bool replaceExisting) { DependencyObject target = TargetElement; if (target == null) return null; BindingBase binding = ParentMultiBinding.Bindings[i]; // Check if replacement bindings have the correct UpdateSourceTrigger MultiBinding.CheckTrigger(binding); BindingExpressionBase bindExpr = binding.CreateBindingExpression(target, TargetProperty, this); if (replaceExisting) // replace exisiting or add as new binding? MutableBindingExpressions[i] = bindExpr; else MutableBindingExpressions.Add(bindExpr); bindExpr.Attach(target, TargetProperty); return bindExpr; } internal override void HandlePropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args) { DependencyProperty dp = args.Property; if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Events)) { TraceData.Trace(TraceEventType.Warning, TraceData.GotPropertyChanged( TraceData.Identify(this), TraceData.Identify(d), dp.Name)); } bool isConnected = true; TransferIsDeferred = true; if (UsesLanguage && d == TargetElement && dp == FrameworkElement.LanguageProperty) { InvalidateCulture(); NeedsDataTransfer = true; // force a transfer - it will honor the new culture } // if the binding has been detached (by the reference to TargetElement), quit now if (IsDetached) return; int n = MutableBindingExpressions.Count; for (int i = 0; i < n; ++i) { BindingExpressionBase bindExpr = MutableBindingExpressions[i]; if (bindExpr != null) { DependencySource[] sources = bindExpr.GetSources(); if (sources != null) { for (int j = 0; j < sources.Length; ++j) { DependencySource source = sources[j]; if (source.DependencyObject == d && source.DependencyProperty == dp) { bindExpr.OnPropertyInvalidation(d, args); break; } } } if (bindExpr.IsDisconnected) { isConnected = false; } } } TransferIsDeferred = false; if (isConnected) { Transfer(); // Transfer if inner BindingExpressions have called Invalidate(binding) } else { Disconnect(); } } /// <summary> /// Handle events from the centralized event table /// </summary> internal override bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { return false; // this method is no longer used (but must remain, for compat) } internal override void OnLostFocus(object sender, RoutedEventArgs e) { if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Events)) { TraceData.Trace(TraceEventType.Warning, TraceData.GotEvent( TraceData.Identify(this), "LostFocus", TraceData.Identify(sender))); } Update(); } #region Value /// <summary> Force a data transfer from source(s) to target </summary> /// <param name="includeInnerBindings"> /// use true to propagate UpdateTarget call to all inner BindingExpressions; /// use false to avoid forcing data re-transfer from one-time inner BindingExpressions /// </param> void UpdateTarget(bool includeInnerBindings) { TransferIsDeferred = true; if (includeInnerBindings) { foreach (BindingExpressionBase b in MutableBindingExpressions) { b.UpdateTarget(); } } TransferIsDeferred = false; NeedsDataTransfer = true; // force data transfer Transfer(); NeedsUpdate = false; } // transfer a value from the source to the target void Transfer() { // required state for transfer if ( NeedsDataTransfer // Transfer is needed && StatusInternal != BindingStatusInternal.Unattached // All bindings are attached && !TransferIsDeferred) // Not aggregating transfers { TransferValue(); } } // transfer a value from the source to the target void TransferValue() { IsInTransfer = true; NeedsDataTransfer = false; DependencyObject target = TargetElement; if (target == null) goto Done; bool isExtendedTraceEnabled = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Transfer); object value = DependencyProperty.UnsetValue; object preFormattedValue = _tempValues; CultureInfo culture = GetCulture(); // gather values from inner BindingExpressions int count = MutableBindingExpressions.Count; for (int i = 0; i < count; ++i) { _tempValues[i] = MutableBindingExpressions[i].GetValue(target, TargetProperty); // could pass (null, null) if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.GetRawValueMulti( TraceData.Identify(this), i, TraceData.Identify(_tempValues[i]))); } } // apply the converter if (Converter != null) { // MultiValueConverters are always user-defined, so don't catch exceptions (bug 992237) preFormattedValue = Converter.Convert(_tempValues, TargetProperty.PropertyType, ParentMultiBinding.ConverterParameter, culture); if (IsDetached) { // user code detached the binding. Give up. return; } if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.UserConverter( TraceData.Identify(this), TraceData.Identify(preFormattedValue))); } } else if (EffectiveStringFormat != null) { // preFormattedValue = _tempValues; // But check for child binding conversion errors for (int i=0; i<_tempValues.Length; ++i) { if (_tempValues[i] == DependencyProperty.UnsetValue) { preFormattedValue = DependencyProperty.UnsetValue; break; } } } else // no converter (perhaps user specified it in error) { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.MultiValueConverterMissingForTransfer, this); } goto Done; } // apply string formatting if (EffectiveStringFormat == null || preFormattedValue == Binding.DoNothing || preFormattedValue == DependencyProperty.UnsetValue) { value = preFormattedValue; } else { try { // we call String.Format either with multiple values (obtained from // the child bindings) or a single value (as produced by the converter). // The if-test is needed to avoid wrapping _tempValues inside another object[]. if (preFormattedValue == _tempValues) { value = String.Format(culture, EffectiveStringFormat, _tempValues); } else { value = String.Format(culture, EffectiveStringFormat, preFormattedValue); } if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.FormattedValue( TraceData.Identify(this), TraceData.Identify(value))); } } catch (FormatException) { // formatting didn't work value = DependencyProperty.UnsetValue; if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.FormattingFailed( TraceData.Identify(this), EffectiveStringFormat)); } } } Array.Clear(_tempValues, 0, _tempValues.Length); // the special value DoNothing means no error, but no data transfer if (value == Binding.DoNothing) goto Done; // ultimately, TargetNullValue should get assigned implicitly, // even if the user doesn't declare it. We can't do this yet because // of back-compat. I wrote it both ways, and #if'd out the breaking // change. #if TargetNullValueBC //BreakingChange if (IsNullValue(value)) #else if (EffectiveTargetNullValue != DependencyProperty.UnsetValue && IsNullValue(value)) #endif { value = EffectiveTargetNullValue; if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.NullConverter( TraceData.Identify(this), TraceData.Identify(value))); } } // if the value isn't acceptable to the target property, don't use it if (value != DependencyProperty.UnsetValue && !TargetProperty.IsValidValue(value)) { if (TraceData.IsEnabled) { TraceData.Trace(TraceLevel, TraceData.BadValueAtTransfer, value, this); } if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.BadValueAtTransferExtended( TraceData.Identify(this), TraceData.Identify(value))); } value = DependencyProperty.UnsetValue; } // if we can't obtain a value, try the fallback value. if (value == DependencyProperty.UnsetValue) { value = UseFallbackValue(); if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.UseFallback( TraceData.Identify(this), TraceData.Identify(value))); } } if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.TransferValue( TraceData.Identify(this), TraceData.Identify(value))); } // if this is a re-transfer after a source update and the value // hasn't changed, don't do any more work. bool realTransfer = !(IsInUpdate && Object.Equals(value, Value)); if (realTransfer) { // update the cached value ChangeValue(value, true); // push the new value through the property engine Invalidate(false); Validation.ClearInvalid(this); } // after updating all the state (value, validation), mark the binding clean Clean(); if (realTransfer) { OnTargetUpdated(); } Done: IsInTransfer = false; } void OnTargetUpdated() { if (NotifyOnTargetUpdated) { DependencyObject target = TargetElement; if (target != null) { // while attaching a normal (not style-defined) BindingExpression, // we must defer raising the event until after the // property has been invalidated, so that the event handler // gets the right value if it asks (bug 1036862) if (IsAttaching && this == target.ReadLocalValue(TargetProperty)) { Engine.AddTask(this, TaskOps.RaiseTargetUpdatedEvent); } else { BindingExpression.OnTargetUpdated(target, TargetProperty); } } } } void OnSourceUpdated() { if (NotifyOnSourceUpdated) { DependencyObject target = TargetElement; if (target != null) { BindingExpression.OnSourceUpdated(target, TargetProperty); } } } // transfer a value from the target to the source internal override bool UpdateOverride() { // various reasons not to update: if ( !NeedsUpdate // nothing to do || !IsReflective // no update desired || IsInTransfer // in a transfer || StatusInternal == BindingStatusInternal.Unattached // not ready yet ) return true; return UpdateValue(); } #endregion Value //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ Collection<BindingExpressionBase> _list = new Collection<BindingExpressionBase>(); IMultiValueConverter _converter; object[] _tempValues; Type[] _tempTypes; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Internal reflective serializer. /// </summary> internal sealed class BinaryReflectiveSerializerInternal : IBinarySerializerInternal { /** Raw mode flag. */ private readonly bool _rawMode; /** Write actions to be performed. */ private readonly BinaryReflectiveWriteAction[] _wActions; /** Read actions to be performed. */ private readonly BinaryReflectiveReadAction[] _rActions; /** Callback type descriptor. */ private readonly SerializableTypeDescriptor _serializableDescriptor; /// <summary> /// Initializes a new instance of the <see cref="BinaryReflectiveSerializer"/> class. /// </summary> public BinaryReflectiveSerializerInternal(bool raw) { _rawMode = raw; } /// <summary> /// Initializes a new instance of the <see cref="BinaryReflectiveSerializer"/> class. /// </summary> private BinaryReflectiveSerializerInternal(BinaryReflectiveWriteAction[] wActions, BinaryReflectiveReadAction[] rActions, bool raw, SerializableTypeDescriptor serializableDescriptor) { Debug.Assert(wActions != null); Debug.Assert(rActions != null); Debug.Assert(serializableDescriptor != null); _wActions = wActions; _rActions = rActions; _rawMode = raw; _serializableDescriptor = serializableDescriptor; } /** <inheritdoc /> */ void IBinarySerializerInternal.WriteBinary<T>(T obj, BinaryWriter writer) { Debug.Assert(_wActions != null); Debug.Assert(writer != null); var ctx = GetStreamingContext(writer); _serializableDescriptor.OnSerializing(obj, ctx); foreach (var action in _wActions) action(obj, writer); _serializableDescriptor.OnSerialized(obj, ctx); } /** <inheritdoc /> */ T IBinarySerializerInternal.ReadBinary<T>(BinaryReader reader, IBinaryTypeDescriptor desc, int pos, Type typeOverride) { Debug.Assert(_rActions != null); Debug.Assert(reader != null); Debug.Assert(desc != null); var obj = FormatterServices.GetUninitializedObject(typeOverride ?? desc.Type); var ctx = GetStreamingContext(reader); _serializableDescriptor.OnDeserializing(obj, ctx); DeserializationCallbackProcessor.Push(obj); try { reader.AddHandle(pos, obj); foreach (var action in _rActions) action(obj, reader); _serializableDescriptor.OnDeserialized(obj, ctx); DeserializationCallbackProcessor.Pop(); } catch (Exception) { // Clear callbacks on exception to avoid dangling objects. DeserializationCallbackProcessor.Clear(); throw; } return (T) obj; } /** <inheritdoc /> */ bool IBinarySerializerInternal.SupportsHandles { get { return true; } } /// <summary> /// Register type. /// </summary> /// <param name="type">Type.</param> /// <param name="typeId">Type ID.</param> /// <param name="converter">Name converter.</param> /// <param name="idMapper">ID mapper.</param> /// <param name="forceTimestamp">Force timestamp serialization for DateTime fields..</param> /// <returns>Resulting serializer.</returns> internal BinaryReflectiveSerializerInternal Register(Type type, int typeId, IBinaryNameMapper converter, IBinaryIdMapper idMapper, bool forceTimestamp) { Debug.Assert(_wActions == null && _rActions == null); var fields = ReflectionUtils.GetAllFields(type).Where(x => !x.IsNotSerialized).ToList(); IDictionary<int, string> idMap = new Dictionary<int, string>(); foreach (FieldInfo field in fields) { string fieldName = BinaryUtils.CleanFieldName(field.Name); int fieldId = BinaryUtils.FieldId(typeId, fieldName, converter, idMapper); if (idMap.ContainsKey(fieldId)) { if (fieldName == idMap[fieldId]) { string baseClassName = field.DeclaringType != null ? field.DeclaringType.Name : null; throw new BinaryObjectException(string.Format( "{0} derives from {1} and hides field {2} from the base class. " + "Ignite can not serialize two fields with the same name.", type.Name, baseClassName, fieldName)); } throw new BinaryObjectException(string.Format( "Conflicting field IDs [type={0}, field1={1}, field2={2}, fieldId={3}])", type.Name, idMap[fieldId], fieldName, fieldId)); } idMap[fieldId] = fieldName; } fields.Sort(Compare); var wActions = new BinaryReflectiveWriteAction[fields.Count]; var rActions = new BinaryReflectiveReadAction[fields.Count]; for (int i = 0; i < fields.Count; i++) { BinaryReflectiveWriteAction writeAction; BinaryReflectiveReadAction readAction; BinaryReflectiveActions.GetTypeActions(fields[i], out writeAction, out readAction, _rawMode, forceTimestamp); wActions[i] = writeAction; rActions[i] = readAction; } var serDesc = SerializableTypeDescriptor.Get(type); return new BinaryReflectiveSerializerInternal(wActions, rActions, _rawMode, serDesc); } /// <summary> /// Compare two FieldInfo instances. /// </summary> private static int Compare(FieldInfo info1, FieldInfo info2) { string name1 = BinaryUtils.CleanFieldName(info1.Name); string name2 = BinaryUtils.CleanFieldName(info2.Name); return string.Compare(name1, name2, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets the streaming context. /// </summary> private static StreamingContext GetStreamingContext(IBinaryReader reader) { return new StreamingContext(StreamingContextStates.All, reader); } /// <summary> /// Gets the streaming context. /// </summary> private static StreamingContext GetStreamingContext(IBinaryWriter writer) { return new StreamingContext(StreamingContextStates.All, writer); } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using System.Globalization; using System.Linq; namespace Noesis { //////////////////////////////////////////////////////////////////////////////////////////////// // Manages Noesis Extensibility //////////////////////////////////////////////////////////////////////////////////////////////// internal partial class Extend { //////////////////////////////////////////////////////////////////////////////////////////////// private delegate IntPtr BoxDelegate(object val); private static Dictionary<RuntimeTypeHandle, BoxDelegate> _boxFunctions = CreateBoxFunctions(); private static Dictionary<RuntimeTypeHandle, BoxDelegate> CreateBoxFunctions() { Dictionary<RuntimeTypeHandle, BoxDelegate> boxFunctions = new Dictionary<RuntimeTypeHandle, BoxDelegate>(100); boxFunctions[typeof(string).TypeHandle] = (val) => NoesisGUI_.Box_String((string)val); boxFunctions[typeof(bool).TypeHandle] = (val) => NoesisGUI_.Box_Bool((bool)val); boxFunctions[typeof(float).TypeHandle] = (val) => NoesisGUI_.Box_Float((float)val); boxFunctions[typeof(double).TypeHandle] = (val) => NoesisGUI_.Box_Double((double)val); boxFunctions[typeof(decimal).TypeHandle] = (val) => NoesisGUI_.Box_Double((double)(decimal)val); boxFunctions[typeof(int).TypeHandle] = (val) => NoesisGUI_.Box_Int((int)val); boxFunctions[typeof(long).TypeHandle] = (val) => NoesisGUI_.Box_Int((int)(long)val); boxFunctions[typeof(uint).TypeHandle] = (val) => NoesisGUI_.Box_UInt((uint)val); boxFunctions[typeof(ulong).TypeHandle] = (val) => NoesisGUI_.Box_UInt((uint)(ulong)val); boxFunctions[typeof(char).TypeHandle] = (val) => NoesisGUI_.Box_UInt((uint)(char)val); boxFunctions[typeof(short).TypeHandle] = (val) => NoesisGUI_.Box_Short((short)val); boxFunctions[typeof(sbyte).TypeHandle] = (val) => NoesisGUI_.Box_Short((short)(sbyte)val); boxFunctions[typeof(ushort).TypeHandle] = (val) => NoesisGUI_.Box_UShort((ushort)val); boxFunctions[typeof(byte).TypeHandle] = (val) => NoesisGUI_.Box_UShort((ushort)(byte)val); boxFunctions[typeof(Noesis.Color).TypeHandle] = (val) => NoesisGUI_.Box_Color((Noesis.Color)val); boxFunctions[typeof(Noesis.Point).TypeHandle] = (val) => NoesisGUI_.Box_Point((Noesis.Point)val); boxFunctions[typeof(Noesis.Rect).TypeHandle] = (val) => NoesisGUI_.Box_Rect((Noesis.Rect)val); boxFunctions[typeof(Noesis.Size).TypeHandle] = (val) => NoesisGUI_.Box_Size((Noesis.Size)val); boxFunctions[typeof(Noesis.Thickness).TypeHandle] = (val) => NoesisGUI_.Box_Thickness((Noesis.Thickness)val); boxFunctions[typeof(Noesis.CornerRadius).TypeHandle] = (val) => NoesisGUI_.Box_CornerRadius((Noesis.CornerRadius)val); boxFunctions[typeof(Noesis.Duration).TypeHandle] = (val) => NoesisGUI_.Box_Duration((Noesis.Duration)val); boxFunctions[typeof(Noesis.KeyTime).TypeHandle] = (val) => NoesisGUI_.Box_KeyTime((Noesis.KeyTime)val); boxFunctions[typeof(System.TimeSpan).TypeHandle] = (val) => NoesisGUI_.Box_TimeSpan((System.TimeSpan)val); boxFunctions[typeof(Noesis.VirtualizationCacheLength).TypeHandle] = (val) => NoesisGUI_.Box_VirtualizationCacheLength((Noesis.VirtualizationCacheLength)val); boxFunctions[typeof(bool?).TypeHandle] = (val) => NoesisGUI_.Box_NullableBool((bool?)val); boxFunctions[typeof(float?).TypeHandle] = (val) => NoesisGUI_.Box_NullableFloat((float?)val); boxFunctions[typeof(double?).TypeHandle] = (val) => NoesisGUI_.Box_NullableDouble((double?)val); boxFunctions[typeof(decimal?).TypeHandle] = (val) => NoesisGUI_.Box_NullableDouble((double?)(decimal?)val); boxFunctions[typeof(int?).TypeHandle] = (val) => NoesisGUI_.Box_NullableInt32((int?)val); boxFunctions[typeof(long?).TypeHandle] = (val) => NoesisGUI_.Box_NullableInt32((int?)(long?)val); boxFunctions[typeof(uint?).TypeHandle] = (val) => NoesisGUI_.Box_NullableUInt32((uint?)val); boxFunctions[typeof(ulong?).TypeHandle] = (val) => NoesisGUI_.Box_NullableUInt32((uint?)(ulong?)val); boxFunctions[typeof(char?).TypeHandle] = (val) => NoesisGUI_.Box_NullableUInt32((uint?)(char?)val); boxFunctions[typeof(short?).TypeHandle] = (val) => NoesisGUI_.Box_NullableInt16((short?)val); boxFunctions[typeof(sbyte?).TypeHandle] = (val) => NoesisGUI_.Box_NullableInt16((short?)(sbyte?)val); boxFunctions[typeof(ushort?).TypeHandle] = (val) => NoesisGUI_.Box_NullableUInt16((ushort?)val); boxFunctions[typeof(byte?).TypeHandle] = (val) => NoesisGUI_.Box_NullableUInt16((ushort?)(byte?)val); boxFunctions[typeof(Noesis.Color?).TypeHandle] = (val) => NoesisGUI_.Box_NullableColor((Noesis.Color?)val); boxFunctions[typeof(Noesis.Point?).TypeHandle] = (val) => NoesisGUI_.Box_NullablePoint((Noesis.Point?)val); boxFunctions[typeof(Noesis.Rect?).TypeHandle] = (val) => NoesisGUI_.Box_NullableRect((Noesis.Rect?)val); boxFunctions[typeof(Noesis.Size?).TypeHandle] = (val) => NoesisGUI_.Box_NullableSize((Noesis.Size?)val); boxFunctions[typeof(Noesis.Thickness?).TypeHandle] = (val) => NoesisGUI_.Box_NullableThickness((Noesis.Thickness?)val); boxFunctions[typeof(Noesis.CornerRadius?).TypeHandle] = (val) => NoesisGUI_.Box_NullableCornerRadius((Noesis.CornerRadius?)val); boxFunctions[typeof(Noesis.Duration?).TypeHandle] = (val) => NoesisGUI_.Box_NullableDuration((Noesis.Duration?)val); boxFunctions[typeof(Noesis.KeyTime?).TypeHandle] = (val) => NoesisGUI_.Box_NullableKeyTime((Noesis.KeyTime?)val); boxFunctions[typeof(System.TimeSpan?).TypeHandle] = (val) => NoesisGUI_.Box_NullableTimeSpan((System.TimeSpan?)val); boxFunctions[typeof(Noesis.AlignmentX).TypeHandle] = (val) => NoesisGUI_.Box_AlignmentX((Noesis.AlignmentX)val); boxFunctions[typeof(Noesis.AlignmentY).TypeHandle] = (val) => NoesisGUI_.Box_AlignmentY((Noesis.AlignmentY)val); boxFunctions[typeof(Noesis.AutoToolTipPlacement).TypeHandle] = (val) => NoesisGUI_.Box_AutoToolTipPlacement((Noesis.AutoToolTipPlacement)val); boxFunctions[typeof(Noesis.BindingMode).TypeHandle] = (val) => NoesisGUI_.Box_BindingMode((Noesis.BindingMode)val); boxFunctions[typeof(Noesis.BitmapScalingMode).TypeHandle] = (val) => NoesisGUI_.Box_BitmapScalingMode((Noesis.BitmapScalingMode)val); boxFunctions[typeof(Noesis.BrushMappingMode).TypeHandle] = (val) => NoesisGUI_.Box_BrushMappingMode((Noesis.BrushMappingMode)val); boxFunctions[typeof(Noesis.CharacterCasing).TypeHandle] = (val) => NoesisGUI_.Box_CharacterCasing((Noesis.CharacterCasing)val); boxFunctions[typeof(Noesis.ClickMode).TypeHandle] = (val) => NoesisGUI_.Box_ClickMode((Noesis.ClickMode)val); boxFunctions[typeof(Noesis.ColorInterpolationMode).TypeHandle] = (val) => NoesisGUI_.Box_ColorInterpolationMode((Noesis.ColorInterpolationMode)val); boxFunctions[typeof(Noesis.Dock).TypeHandle] = (val) => NoesisGUI_.Box_Dock((Noesis.Dock)val); boxFunctions[typeof(Noesis.ExpandDirection).TypeHandle] = (val) => NoesisGUI_.Box_ExpandDirection((Noesis.ExpandDirection)val); boxFunctions[typeof(Noesis.FillRule).TypeHandle] = (val) => NoesisGUI_.Box_FillRule((Noesis.FillRule)val); boxFunctions[typeof(Noesis.FlowDirection).TypeHandle] = (val) => NoesisGUI_.Box_FlowDirection((Noesis.FlowDirection)val); boxFunctions[typeof(Noesis.FontStretch).TypeHandle] = (val) => NoesisGUI_.Box_FontStretch((Noesis.FontStretch)val); boxFunctions[typeof(Noesis.FontStyle).TypeHandle] = (val) => NoesisGUI_.Box_FontStyle((Noesis.FontStyle)val); boxFunctions[typeof(Noesis.FontWeight).TypeHandle] = (val) => NoesisGUI_.Box_FontWeight((Noesis.FontWeight)val); boxFunctions[typeof(Noesis.GeometryCombineMode).TypeHandle] = (val) => NoesisGUI_.Box_GeometryCombineMode((Noesis.GeometryCombineMode)val); boxFunctions[typeof(Noesis.GradientSpreadMethod).TypeHandle] = (val) => NoesisGUI_.Box_GradientSpreadMethod((Noesis.GradientSpreadMethod)val); boxFunctions[typeof(Noesis.HorizontalAlignment).TypeHandle] = (val) => NoesisGUI_.Box_HorizontalAlignment((Noesis.HorizontalAlignment)val); boxFunctions[typeof(Noesis.KeyboardNavigationMode).TypeHandle] = (val) => NoesisGUI_.Box_KeyboardNavigationMode((Noesis.KeyboardNavigationMode)val); boxFunctions[typeof(Noesis.LineStackingStrategy).TypeHandle] = (val) => NoesisGUI_.Box_LineStackingStrategy((Noesis.LineStackingStrategy)val); boxFunctions[typeof(Noesis.ListSortDirection).TypeHandle] = (val) => NoesisGUI_.Box_ListSortDirection((Noesis.ListSortDirection)val); boxFunctions[typeof(Noesis.MenuItemRole).TypeHandle] = (val) => NoesisGUI_.Box_MenuItemRole((Noesis.MenuItemRole)val); boxFunctions[typeof(Noesis.Orientation).TypeHandle] = (val) => NoesisGUI_.Box_Orientation((Noesis.Orientation)val); boxFunctions[typeof(Noesis.OverflowMode).TypeHandle] = (val) => NoesisGUI_.Box_OverflowMode((Noesis.OverflowMode)val); boxFunctions[typeof(Noesis.PenLineCap).TypeHandle] = (val) => NoesisGUI_.Box_PenLineCap((Noesis.PenLineCap)val); boxFunctions[typeof(Noesis.PenLineJoin).TypeHandle] = (val) => NoesisGUI_.Box_PenLineJoin((Noesis.PenLineJoin)val); boxFunctions[typeof(Noesis.PlacementMode).TypeHandle] = (val) => NoesisGUI_.Box_PlacementMode((Noesis.PlacementMode)val); boxFunctions[typeof(Noesis.PopupAnimation).TypeHandle] = (val) => NoesisGUI_.Box_PopupAnimation((Noesis.PopupAnimation)val); boxFunctions[typeof(Noesis.RelativeSourceMode).TypeHandle] = (val) => NoesisGUI_.Box_RelativeSourceMode((Noesis.RelativeSourceMode)val); boxFunctions[typeof(Noesis.SelectionMode).TypeHandle] = (val) => NoesisGUI_.Box_SelectionMode((Noesis.SelectionMode)val); boxFunctions[typeof(Noesis.SizeToContent).TypeHandle] = (val) => NoesisGUI_.Box_SizeToContent((Noesis.SizeToContent)val); boxFunctions[typeof(Noesis.CornerRadius).TypeHandle] = (val) => NoesisGUI_.Box_CornerRadius((Noesis.CornerRadius)val); boxFunctions[typeof(Noesis.Stretch).TypeHandle] = (val) => NoesisGUI_.Box_Stretch((Noesis.Stretch)val); boxFunctions[typeof(Noesis.StretchDirection).TypeHandle] = (val) => NoesisGUI_.Box_StretchDirection((Noesis.StretchDirection)val); boxFunctions[typeof(Noesis.TextAlignment).TypeHandle] = (val) => NoesisGUI_.Box_TextAlignment((Noesis.TextAlignment)val); boxFunctions[typeof(Noesis.TextTrimming).TypeHandle] = (val) => NoesisGUI_.Box_TextTrimming((Noesis.TextTrimming)val); boxFunctions[typeof(Noesis.TextWrapping).TypeHandle] = (val) => NoesisGUI_.Box_TextWrapping((Noesis.TextWrapping)val); boxFunctions[typeof(Noesis.TickBarPlacement).TypeHandle] = (val) => NoesisGUI_.Box_TickBarPlacement((Noesis.TickBarPlacement)val); boxFunctions[typeof(Noesis.TickPlacement).TypeHandle] = (val) => NoesisGUI_.Box_TickPlacement((Noesis.TickPlacement)val); boxFunctions[typeof(Noesis.TileMode).TypeHandle] = (val) => NoesisGUI_.Box_TileMode((Noesis.TileMode)val); boxFunctions[typeof(Noesis.VerticalAlignment).TypeHandle] = (val) => NoesisGUI_.Box_VerticalAlignment((Noesis.VerticalAlignment)val); boxFunctions[typeof(Noesis.Visibility).TypeHandle] = (val) => NoesisGUI_.Box_Visibility((Noesis.Visibility)val); boxFunctions[typeof(Noesis.ClockState).TypeHandle] = (val) => NoesisGUI_.Box_ClockState((Noesis.ClockState)val); boxFunctions[typeof(Noesis.EasingMode).TypeHandle] = (val) => NoesisGUI_.Box_EasingMode((Noesis.EasingMode)val); boxFunctions[typeof(Noesis.SlipBehavior).TypeHandle] = (val) => NoesisGUI_.Box_SlipBehavior((Noesis.SlipBehavior)val); boxFunctions[typeof(Noesis.FillBehavior).TypeHandle] = (val) => NoesisGUI_.Box_FillBehavior((Noesis.FillBehavior)val); boxFunctions[typeof(Noesis.GridViewColumnHeaderRole).TypeHandle] = (val) => NoesisGUI_.Box_GridViewColumnHeaderRole((Noesis.GridViewColumnHeaderRole)val); boxFunctions[typeof(Noesis.HandoffBehavior).TypeHandle] = (val) => NoesisGUI_.Box_HandoffBehavior((Noesis.HandoffBehavior)val); boxFunctions[typeof(Noesis.PanningMode).TypeHandle] = (val) => NoesisGUI_.Box_PanningMode((Noesis.PanningMode)val); boxFunctions[typeof(Noesis.UpdateSourceTrigger).TypeHandle] = (val) => NoesisGUI_.Box_UpdateSourceTrigger((Noesis.UpdateSourceTrigger)val); boxFunctions[typeof(Noesis.ScrollUnit).TypeHandle] = (val) => NoesisGUI_.Box_ScrollUnit((Noesis.ScrollUnit)val); boxFunctions[typeof(Noesis.VirtualizationMode).TypeHandle] = (val) => NoesisGUI_.Box_VirtualizationMode((Noesis.VirtualizationMode)val); boxFunctions[typeof(Noesis.VirtualizationCacheLengthUnit).TypeHandle] = (val) => NoesisGUI_.Box_VirtualizationCacheLengthUnit((Noesis.VirtualizationCacheLengthUnit)val); return boxFunctions; } //////////////////////////////////////////////////////////////////////////////////////////////// public static IntPtr Box(object val) { BoxDelegate boxFunction; if (_boxFunctions.TryGetValue(val.GetType().TypeHandle, out boxFunction)) { return boxFunction(val); } else if (val.GetType().GetTypeInfo().IsEnum) { _boxFunctions.TryGetValue(typeof(int).TypeHandle, out boxFunction); return boxFunction((int)Convert.ToInt64(val)); } else { return IntPtr.Zero; } } //////////////////////////////////////////////////////////////////////////////////////////////// private class Boxed<T> { } private delegate object UnboxDelegate(IntPtr cPtr); private static Dictionary<RuntimeTypeHandle, UnboxDelegate> _unboxFunctions = CreateUnboxFunctions(); private static Dictionary<RuntimeTypeHandle, UnboxDelegate> CreateUnboxFunctions() { Dictionary<RuntimeTypeHandle, UnboxDelegate> unboxFunctions = new Dictionary<RuntimeTypeHandle, UnboxDelegate>(100); unboxFunctions[typeof(Boxed<string>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_String(cPtr); unboxFunctions[typeof(Boxed<bool>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Bool(cPtr); unboxFunctions[typeof(Boxed<float>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Float(cPtr); unboxFunctions[typeof(Boxed<double>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Double(cPtr); unboxFunctions[typeof(Boxed<int>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Int(cPtr); unboxFunctions[typeof(Boxed<uint>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_UInt(cPtr); unboxFunctions[typeof(Boxed<short>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Short(cPtr); unboxFunctions[typeof(Boxed<ushort>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_UShort(cPtr); unboxFunctions[typeof(Boxed<Noesis.Color>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Color(cPtr); unboxFunctions[typeof(Boxed<Noesis.Point>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Point(cPtr); unboxFunctions[typeof(Boxed<Noesis.Rect>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Rect(cPtr); unboxFunctions[typeof(Boxed<Noesis.Size>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Size(cPtr); unboxFunctions[typeof(Boxed<Noesis.Thickness>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Thickness(cPtr); unboxFunctions[typeof(Boxed<Noesis.CornerRadius>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_CornerRadius(cPtr); unboxFunctions[typeof(Boxed<Noesis.Duration>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Duration(cPtr); unboxFunctions[typeof(Boxed<Noesis.KeyTime>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_KeyTime(cPtr); unboxFunctions[typeof(Boxed<System.TimeSpan>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_TimeSpan(cPtr); unboxFunctions[typeof(Boxed<Noesis.VirtualizationCacheLength>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_VirtualizationCacheLength(cPtr); unboxFunctions[typeof(Boxed<bool?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableBool(cPtr); unboxFunctions[typeof(Boxed<float?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableFloat(cPtr); unboxFunctions[typeof(Boxed<double?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableDouble(cPtr); unboxFunctions[typeof(Boxed<int?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableInt32(cPtr); unboxFunctions[typeof(Boxed<uint?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableUInt32(cPtr); unboxFunctions[typeof(Boxed<short?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableInt16(cPtr); unboxFunctions[typeof(Boxed<ushort?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableUInt16(cPtr); unboxFunctions[typeof(Boxed<Noesis.Color?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableColor(cPtr); unboxFunctions[typeof(Boxed<Noesis.Point?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullablePoint(cPtr); unboxFunctions[typeof(Boxed<Noesis.Rect?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableRect(cPtr); unboxFunctions[typeof(Boxed<Noesis.Size?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableSize(cPtr); unboxFunctions[typeof(Boxed<Noesis.Thickness?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableThickness(cPtr); unboxFunctions[typeof(Boxed<Noesis.CornerRadius?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableCornerRadius(cPtr); unboxFunctions[typeof(Boxed<Noesis.Duration?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableDuration(cPtr); unboxFunctions[typeof(Boxed<Noesis.KeyTime?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableKeyTime(cPtr); unboxFunctions[typeof(Boxed<System.TimeSpan?>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_NullableTimeSpan(cPtr); unboxFunctions[typeof(Boxed<Noesis.AlignmentX>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_AlignmentX(cPtr); unboxFunctions[typeof(Boxed<Noesis.AlignmentY>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_AlignmentY(cPtr); unboxFunctions[typeof(Boxed<Noesis.AutoToolTipPlacement>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_AutoToolTipPlacement(cPtr); unboxFunctions[typeof(Boxed<Noesis.BindingMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_BindingMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.BitmapScalingMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_BitmapScalingMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.BrushMappingMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_BrushMappingMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.CharacterCasing>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_CharacterCasing(cPtr); unboxFunctions[typeof(Boxed<Noesis.ClickMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_ClickMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.ColorInterpolationMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_ColorInterpolationMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.Dock>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Dock(cPtr); unboxFunctions[typeof(Boxed<Noesis.ExpandDirection>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_ExpandDirection(cPtr); unboxFunctions[typeof(Boxed<Noesis.FillRule>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_FillRule(cPtr); unboxFunctions[typeof(Boxed<Noesis.FlowDirection>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_FlowDirection(cPtr); unboxFunctions[typeof(Boxed<Noesis.FontStretch>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_FontStretch(cPtr); unboxFunctions[typeof(Boxed<Noesis.FontStyle>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_FontStyle(cPtr); unboxFunctions[typeof(Boxed<Noesis.FontWeight>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_FontWeight(cPtr); unboxFunctions[typeof(Boxed<Noesis.GeometryCombineMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_GeometryCombineMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.GradientSpreadMethod>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_GradientSpreadMethod(cPtr); unboxFunctions[typeof(Boxed<Noesis.HorizontalAlignment>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_HorizontalAlignment(cPtr); unboxFunctions[typeof(Boxed<Noesis.KeyboardNavigationMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_KeyboardNavigationMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.LineStackingStrategy>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_LineStackingStrategy(cPtr); unboxFunctions[typeof(Boxed<Noesis.ListSortDirection>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_ListSortDirection(cPtr); unboxFunctions[typeof(Boxed<Noesis.MenuItemRole>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_MenuItemRole(cPtr); unboxFunctions[typeof(Boxed<Noesis.Orientation>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Orientation(cPtr); unboxFunctions[typeof(Boxed<Noesis.OverflowMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_OverflowMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.PenLineCap>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_PenLineCap(cPtr); unboxFunctions[typeof(Boxed<Noesis.PenLineJoin>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_PenLineJoin(cPtr); unboxFunctions[typeof(Boxed<Noesis.PlacementMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_PlacementMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.PopupAnimation>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_PopupAnimation(cPtr); unboxFunctions[typeof(Boxed<Noesis.RelativeSourceMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_RelativeSourceMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.SelectionMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_SelectionMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.SizeToContent>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_SizeToContent(cPtr); unboxFunctions[typeof(Boxed<Noesis.CornerRadius>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_CornerRadius(cPtr); unboxFunctions[typeof(Boxed<Noesis.Stretch>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Stretch(cPtr); unboxFunctions[typeof(Boxed<Noesis.StretchDirection>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_StretchDirection(cPtr); unboxFunctions[typeof(Boxed<Noesis.TextAlignment>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_TextAlignment(cPtr); unboxFunctions[typeof(Boxed<Noesis.TextTrimming>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_TextTrimming(cPtr); unboxFunctions[typeof(Boxed<Noesis.TextWrapping>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_TextWrapping(cPtr); unboxFunctions[typeof(Boxed<Noesis.TickBarPlacement>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_TickBarPlacement(cPtr); unboxFunctions[typeof(Boxed<Noesis.TickPlacement>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_TickPlacement(cPtr); unboxFunctions[typeof(Boxed<Noesis.TileMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_TileMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.VerticalAlignment>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_VerticalAlignment(cPtr); unboxFunctions[typeof(Boxed<Noesis.Visibility>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_Visibility(cPtr); unboxFunctions[typeof(Boxed<Noesis.ClockState>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_ClockState(cPtr); unboxFunctions[typeof(Boxed<Noesis.EasingMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_EasingMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.SlipBehavior>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_SlipBehavior(cPtr); unboxFunctions[typeof(Boxed<Noesis.FillBehavior>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_FillBehavior(cPtr); unboxFunctions[typeof(Boxed<Noesis.GridViewColumnHeaderRole>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_GridViewColumnHeaderRole(cPtr); unboxFunctions[typeof(Boxed<Noesis.HandoffBehavior>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_HandoffBehavior(cPtr); unboxFunctions[typeof(Boxed<Noesis.PanningMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_PanningMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.UpdateSourceTrigger>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_UpdateSourceTrigger(cPtr); unboxFunctions[typeof(Boxed<Noesis.ScrollUnit>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_ScrollUnit(cPtr); unboxFunctions[typeof(Boxed<Noesis.VirtualizationMode>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_VirtualizationMode(cPtr); unboxFunctions[typeof(Boxed<Noesis.VirtualizationCacheLengthUnit>).TypeHandle] = (cPtr) => NoesisGUI_.Unbox_VirtualizationCacheLengthUnit(cPtr); return unboxFunctions; } public static object Unbox(IntPtr cPtr, NativeTypeInfo info) { UnboxDelegate unboxFunction; if (_unboxFunctions.TryGetValue(info.Type.TypeHandle, out unboxFunction)) { return unboxFunction(cPtr); } throw new InvalidOperationException("Can't unbox native pointer"); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Runtime; namespace Orleans.Streams { [Serializable] internal class PubSubGrainState { public HashSet<PubSubPublisherState> Producers { get; set; } public HashSet<PubSubSubscriptionState> Consumers { get; set; } } [Providers.StorageProvider(ProviderName = "PubSubStore")] internal class PubSubRendezvousGrain : Grain<PubSubGrainState>, IPubSubRendezvousGrain { private Logger logger; private const bool DEBUG_PUB_SUB = false; private static readonly CounterStatistic counterProducersAdded; private static readonly CounterStatistic counterProducersRemoved; private static readonly CounterStatistic counterProducersTotal; private static readonly CounterStatistic counterConsumersAdded; private static readonly CounterStatistic counterConsumersRemoved; private static readonly CounterStatistic counterConsumersTotal; static PubSubRendezvousGrain() { counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED); counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED); counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL); counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED); counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED); counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL); } public override async Task OnActivateAsync() { logger = GetLogger(GetType().Name + "-" + RuntimeIdentity + "-" + IdentityString); LogPubSubCounts("OnActivateAsync"); if (State.Consumers == null) State.Consumers = new HashSet<PubSubSubscriptionState>(); if (State.Producers == null) State.Producers = new HashSet<PubSubPublisherState>(); int numRemoved = RemoveDeadProducers(); if (numRemoved > 0) { if (State.Producers.Count > 0 || State.Consumers.Count > 0) await WriteStateAsync(); else await ClearStateAsync(); //State contains no producers or consumers, remove it from storage } logger.Verbose("OnActivateAsync-Done"); } public override Task OnDeactivateAsync() { LogPubSubCounts("OnDeactivateAsync"); return TaskDone.Done; } private int RemoveDeadProducers() { // Remove only those we know for sure are Dead. int numRemoved = 0; if (State.Producers != null && State.Producers.Count > 0) numRemoved = State.Producers.RemoveWhere(producerState => IsDeadProducer(producerState.Producer)); if (numRemoved > 0) { LogPubSubCounts("RemoveDeadProducers: removed {0} outdated producers", numRemoved); } return numRemoved; } /// accept and notify only Active producers. private static bool IsActiveProducer(IStreamProducerExtension producer) { var grainRef = producer as GrainReference; if (grainRef !=null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget) return RuntimeClient.Current.GetSiloStatus(grainRef.SystemTargetSilo).Equals(SiloStatus.Active); return true; } private static bool IsDeadProducer(IStreamProducerExtension producer) { var grainRef = producer as GrainReference; if (grainRef != null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget) return RuntimeClient.Current.GetSiloStatus(grainRef.SystemTargetSilo).Equals(SiloStatus.Dead); return false; } public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, IStreamProducerExtension streamProducer) { counterProducersAdded.Increment(); if (!IsActiveProducer(streamProducer)) throw new ArgumentException($"Trying to register non active IStreamProducerExtension: {streamProducer}", "streamProducer"); try { int producersRemoved = RemoveDeadProducers(); var publisherState = new PubSubPublisherState(streamId, streamProducer); State.Producers.Add(publisherState); LogPubSubCounts("RegisterProducer {0}", streamProducer); await WriteStateAsync(); counterProducersTotal.DecrementBy(producersRemoved); counterProducersTotal.Increment(); } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterProducerFailed, $"Failed to register a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } return State.Consumers.Where(c => !c.IsFaulted).ToSet(); } public async Task UnregisterProducer(StreamId streamId, IStreamProducerExtension streamProducer) { counterProducersRemoved.Increment(); try { int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer)); LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved); if (numRemoved > 0) { Task updateStorageTask = State.Producers.Count == 0 && State.Consumers.Count == 0 ? ClearStateAsync() //State contains no producers or consumers, remove it from storage : WriteStateAsync(); await updateStorageTask; } counterProducersTotal.DecrementBy(numRemoved); } catch (Exception exc) { logger.Error(ErrorCode.Stream_UnegisterProducerFailed, $"Failed to unregister a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } if (State.Producers.Count == 0 && State.Consumers.Count == 0) { DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation } } public async Task RegisterConsumer( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { counterConsumersAdded.Increment(); PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId)); if (pubSubState != null && pubSubState.IsFaulted) throw new FaultedSubscriptionException(subscriptionId, streamId); try { if (pubSubState == null) { pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer); State.Consumers.Add(pubSubState); } if (filter != null) pubSubState.AddFilter(filter); LogPubSubCounts("RegisterConsumer {0}", streamConsumer); await WriteStateAsync(); counterConsumersTotal.Increment(); } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterConsumerFailed, $"Failed to register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } int numProducers = State.Producers.Count; if (numProducers <= 0) return; if (logger.IsVerbose) logger.Info("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}", numProducers, streamConsumer, Utils.EnumerableToString(State.Producers)); // Notify producers about a new streamConsumer. var tasks = new List<Task>(); var producers = State.Producers.ToList(); int initialProducerCount = producers.Count; try { foreach (var producerState in producers) { PubSubPublisherState producer = producerState; // Capture loop variable if (!IsActiveProducer(producer.Producer)) { // Producer is not active (could be stopping / shutting down) so skip if (logger.IsVerbose) logger.Verbose("Producer {0} on stream {1} is not active - skipping.", producer, streamId); continue; } tasks.Add(NotifyProducer(producer, subscriptionId, streamId, streamConsumer, filter)); } Exception exception = null; try { await Task.WhenAll(tasks); } catch (Exception exc) { exception = exc; } // if the number of producers has been changed, resave state. if (State.Producers.Count != initialProducerCount) { await WriteStateAsync(); counterConsumersTotal.DecrementBy(initialProducerCount - State.Producers.Count); } if (exception != null) { throw exception; } } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterConsumerFailed, $"Failed to update producers while register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } private async Task NotifyProducer(PubSubPublisherState producer, GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { try { await producer.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filter); } catch (GrainExtensionNotInstalledException) { RemoveProducer(producer); } catch (ClientNotAvailableException) { RemoveProducer(producer); } } private void RemoveProducer(PubSubPublisherState producer) { logger.Warn(ErrorCode.Stream_ProducerIsDead, "Producer {0} on stream {1} is no longer active - permanently removing producer.", producer, producer.Stream); State.Producers.Remove(producer); } public async Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId) { counterConsumersRemoved.Increment(); if (State.Consumers.Any(c => c.IsFaulted && c.Equals(subscriptionId))) throw new FaultedSubscriptionException(subscriptionId, streamId); try { int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId)); LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved); if (await TryClearState()) { // If state was cleared expedite Deactivation DeactivateOnIdle(); } else { if (numRemoved != 0) { await WriteStateAsync(); } await NotifyProducersOfRemovedSubscription(subscriptionId, streamId); } counterConsumersTotal.DecrementBy(numRemoved); } catch (Exception exc) { logger.Error(ErrorCode.Stream_UnregisterConsumerFailed, $"Failed to unregister a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } public Task<int> ProducerCount(StreamId streamId) { return Task.FromResult(State.Producers.Count); } public Task<int> ConsumerCount(StreamId streamId) { return Task.FromResult(GetConsumersForStream(streamId).Length); } public Task<PubSubSubscriptionState[]> DiagGetConsumers(StreamId streamId) { return Task.FromResult(GetConsumersForStream(streamId)); } private PubSubSubscriptionState[] GetConsumersForStream(StreamId streamId) { return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray(); } private void LogPubSubCounts(string fmt, params object[] args) { if (logger.IsVerbose || DEBUG_PUB_SUB) { int numProducers = 0; int numConsumers = 0; if (State?.Producers != null) numProducers = State.Producers.Count; if (State?.Consumers != null) numConsumers = State.Consumers.Count; string when = args != null && args.Length != 0 ? String.Format(fmt, args) : fmt; logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}", when, numProducers, numConsumers, Utils.EnumerableToString(State.Consumers), Utils.EnumerableToString(State.Producers)); } } // Check that what we have cached locally matches what is in the persistent table. public async Task Validate() { var captureProducers = State.Producers; var captureConsumers = State.Consumers; await ReadStateAsync(); if (captureProducers.Count != State.Producers.Count) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={captureProducers.Count}, State.Producers.Count={State.Producers.Count}"); } if (captureProducers.Any(producer => !State.Producers.Contains(producer))) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={Utils.EnumerableToString(captureProducers)}, State.Producers={Utils.EnumerableToString(State.Producers)}"); } if (captureConsumers.Count != State.Consumers.Count) { LogPubSubCounts("Validate: Consumer count mismatch"); throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={captureConsumers.Count}, State.Consumers.Count={State.Consumers.Count}"); } if (captureConsumers.Any(consumer => !State.Consumers.Contains(consumer))) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={Utils.EnumerableToString(captureConsumers)}, State.Consumers={Utils.EnumerableToString(State.Consumers)}"); } } public Task<List<GuidId>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer) { List<GuidId> subscriptionIds = State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer)) .Select(c => c.SubscriptionId) .ToList(); return Task.FromResult(subscriptionIds); } public async Task FaultSubscription(GuidId subscriptionId) { PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId)); if (pubSubState == null) { return; } try { pubSubState.Fault(); if (logger.IsVerbose) logger.Verbose("Setting subscription {0} to a faulted state.", subscriptionId.Guid); await WriteStateAsync(); await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream); } catch (Exception exc) { logger.Error(ErrorCode.Stream_SetSubscriptionToFaultedFailed, $"Failed to set subscription state to faulted. SubscriptionId {subscriptionId}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, StreamId streamId) { int numProducers = State.Producers.Count; if (numProducers > 0) { if (logger.IsVerbose) logger.Verbose("Notifying {0} existing producers about unregistered consumer.", numProducers); // Notify producers about unregistered consumer. List<Task> tasks = State.Producers.Where(producerState => IsActiveProducer(producerState.Producer)) .Select(producerState => producerState.Producer.RemoveSubscriber(subscriptionId, streamId)) .ToList(); await Task.WhenAll(tasks); } } /// <summary> /// Try clear state will only clear the state if there are no producers or consumers. /// </summary> /// <returns></returns> private async Task<bool> TryClearState() { if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause { await ClearStateAsync(); //State contains no producers or consumers, remove it from storage return true; } return false; } } }