context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region MIT License /* * Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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. */ #endregion // Contributor: Andrew D. Jones #if UseDouble using Scalar = System.Double; #else using Scalar = System.Single; #endif using System; using System.Collections.Generic; using System.Runtime.Serialization; using AdvanceMath.Geometry2D; namespace Physics2DDotNet.Detectors { /// <summary> /// Faster then sweep and prune and does not stutter like SingleSweep /// </summary> [Serializable] public sealed class SelectiveSweepDetector : BroadPhaseCollisionDetector { [Serializable] sealed class StubComparer : IComparer<Stub> { public int Compare(Stub left, Stub right) { if (left.value < right.value) { return -1; } if (left.value > right.value) { return 1; } return ((left == right) ? (0) : ((left.begin) ? (-1) : (1))); } } [Serializable] sealed class Wrapper : IDeserializationCallback { [NonSerialized] public LinkedListNode<Wrapper> node; public Body body; public bool shouldAddNode; public Scalar min; public Scalar max; Stub xBegin; Stub xEnd; Stub yBegin; Stub yEnd; public Wrapper(Body body) { this.body = body; this.node = new LinkedListNode<Wrapper>(this); xBegin = new Stub(this, true); xEnd = new Stub(this, false); yBegin = new Stub(this, true); yEnd = new Stub(this, false); } public void AddStubs(List<Stub> xStubs, List<Stub> yStubs) { xStubs.Add(xBegin); xStubs.Add(xEnd); yStubs.Add(yBegin); yStubs.Add(yEnd); } public void Update() { BoundingRectangle rect = body.Rectangle; //if it is a single point in space //then dont even add it to the link list. shouldAddNode = rect.Min.X != rect.Max.X || rect.Min.Y != rect.Max.Y; xBegin.value = rect.Min.X; xEnd.value = rect.Max.X; yBegin.value = rect.Min.Y; yEnd.value = rect.Max.Y; } public void SetX() { this.min = this.xBegin.value; this.max = this.xEnd.value; } public void SetY() { this.min = this.yBegin.value; this.max = this.yEnd.value; } void IDeserializationCallback.OnDeserialization(object sender) { this.node = new LinkedListNode<Wrapper>(this); } } [Serializable] sealed class Stub { public Wrapper wrapper; public bool begin; public Scalar value; public Stub(Wrapper wrapper, bool begin) { this.wrapper = wrapper; this.begin = begin; } } static StubComparer comparer = new StubComparer(); static bool WrapperIsRemoved(Wrapper wrapper) { return !wrapper.body.IsAdded; } static bool StubIsRemoved(Stub stub) { return !stub.wrapper.body.IsAdded; } List<Wrapper> wrappers; List<Stub> xStubs; List<Stub> yStubs; public SelectiveSweepDetector() { this.wrappers = new List<Wrapper>(); this.xStubs = new List<Stub>(); this.yStubs = new List<Stub>(); } protected internal override void AddBodyRange(List<Body> collection) { int wrappercount = collection.Count + wrappers.Count; if (wrappers.Capacity < wrappercount) { wrappers.Capacity = wrappercount; } int nodeCount = collection.Count * 2 + xStubs.Count; if (xStubs.Capacity < nodeCount) { xStubs.Capacity = nodeCount; yStubs.Capacity = nodeCount; } foreach (Body item in collection) { Wrapper wrapper = new Wrapper(item); wrappers.Add(wrapper); wrapper.AddStubs(xStubs, yStubs); } } protected internal override void Clear() { wrappers.Clear(); xStubs.Clear(); yStubs.Clear(); } protected internal override void RemoveExpiredBodies() { wrappers.RemoveAll(WrapperIsRemoved); xStubs.RemoveAll(StubIsRemoved); yStubs.RemoveAll(StubIsRemoved); } /// <summary> /// updates all the nodes to their new values and sorts the lists /// </summary> private void Update() { for (int index = 0; index < wrappers.Count; ++index) { wrappers[index].Update(); } xStubs.Sort(comparer); yStubs.Sort(comparer); } /// <summary> /// Finds how many collisions there are on the x and y and returns if /// the x axis has the least /// </summary> private bool ShouldDoX() { int xCount = 0; int xdepth = 0; int yCount = 0; int ydepth = 0; for (int index = 0; index < xStubs.Count; index++) { if (xStubs[index].begin) { xCount += xdepth++; } else { xdepth--; } if (yStubs[index].begin) { yCount += ydepth++; } else { ydepth--; } } return xCount < yCount; } public override void Detect(TimeStep step) { Update(); DetectInternal(step, ShouldDoX()); } private void DetectInternal(TimeStep step, bool doX) { List<Stub> stubs = (doX) ? (xStubs) : (yStubs); LinkedList<Wrapper> currentBodies = new LinkedList<Wrapper>(); for (int index = 0; index < stubs.Count; index++) { Stub stub = stubs[index]; Wrapper wrapper1 = stub.wrapper; if (stub.begin) { //set the min and max values if (doX) { wrapper1.SetY(); } else { wrapper1.SetX(); } Body body1 = wrapper1.body; for (LinkedListNode<Wrapper> node = currentBodies.First; node != null; node = node.Next) { Wrapper wrapper2 = node.Value; Body body2 = wrapper2.body; if (wrapper1.min <= wrapper2.max && //tests the other axis wrapper2.min <= wrapper1.max && Body.CanCollide(body1, body2)) { OnCollision(step, body1, body2); } } if (wrapper1.shouldAddNode) { currentBodies.AddLast(wrapper1.node); } } else { if (wrapper1.shouldAddNode) { currentBodies.Remove(wrapper1.node); } } } } } }
// 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.Data.ProviderBase; using System.Diagnostics; namespace System.Data.SqlClient { sealed internal class SqlConnectionFactory : DbConnectionFactory { private SqlConnectionFactory() : base() { } public static readonly SqlConnectionFactory SingletonInstance = new SqlConnectionFactory(); override public DbProviderFactory ProviderFactory { get { return SqlClientFactory.Instance; } } override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) { return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection, userOptions: null); } override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) { SqlConnectionString opt = (SqlConnectionString)options; SqlConnectionPoolKey key = (SqlConnectionPoolKey)poolKey; SqlInternalConnection result = null; SessionData recoverySessionData = null; SqlConnection sqlOwningConnection = (SqlConnection)owningConnection; bool applyTransientFaultHandling = sqlOwningConnection != null ? sqlOwningConnection._applyTransientFaultHandling : false; SqlConnectionString userOpt = null; if (userOptions != null) { userOpt = (SqlConnectionString)userOptions; } else if (sqlOwningConnection != null) { userOpt = (SqlConnectionString)(sqlOwningConnection.UserConnectionOptions); } if (sqlOwningConnection != null) { recoverySessionData = sqlOwningConnection._recoverySessionData; } bool redirectedUserInstance = false; DbConnectionPoolIdentity identity = null; // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security. // Used by notifications. if (opt.IntegratedSecurity) { if (pool != null) { identity = pool.Identity; } else { identity = DbConnectionPoolIdentity.GetCurrent(); } } // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES // If "user instance=true" is in the connection string, we're using SSE user instances if (opt.UserInstance) { // opt.DataSource is used to create the SSE connection redirectedUserInstance = true; string instanceName; if ((null == pool) || (null != pool && pool.Count <= 0)) { // Non-pooled or pooled and no connections in the pool. SqlInternalConnectionTds sseConnection = null; try { // We throw an exception in case of a failure // NOTE: Cloning connection option opt to set 'UserInstance=True' and 'Enlist=False' // This first connection is established to SqlExpress to get the instance name // of the UserInstance. SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, true /* user instance=true */); sseConnection = new SqlInternalConnectionTds(identity, sseopt, null, false, applyTransientFaultHandling: applyTransientFaultHandling); // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance. instanceName = sseConnection.InstanceName; if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal)) { throw SQL.NonLocalSSEInstance(); } if (null != pool) { // Pooled connection - cache result SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo; // No lock since we are already in creation mutex providerInfo.InstanceName = instanceName; } } finally { if (null != sseConnection) { sseConnection.Dispose(); } } } else { // Cached info from pool. SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo; // No lock since we are already in creation mutex instanceName = providerInfo.InstanceName; } // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was // retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'. // options immutable - stored in global hash - don't modify opt = new SqlConnectionString(opt, instanceName, false /* user instance=false */); poolGroupProviderInfo = null; // null so we do not pass to constructor below... } result = new SqlInternalConnectionTds(identity, opt, poolGroupProviderInfo, redirectedUserInstance, userOpt, recoverySessionData, applyTransientFaultHandling: applyTransientFaultHandling); return result; } protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous) { Debug.Assert(!string.IsNullOrEmpty(connectionString), "empty connectionString"); SqlConnectionString result = new SqlConnectionString(connectionString); return result; } override internal DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions) { DbConnectionPoolProviderInfo providerInfo = null; if (((SqlConnectionString)connectionOptions).UserInstance) { providerInfo = new SqlConnectionPoolProviderInfo(); } return providerInfo; } override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions) { SqlConnectionString opt = (SqlConnectionString)connectionOptions; DbConnectionPoolGroupOptions poolingOptions = null; if (opt.Pooling) { // never pool context connections. int connectionTimeout = opt.ConnectTimeout; if ((0 < connectionTimeout) && (connectionTimeout < Int32.MaxValue / 1000)) connectionTimeout *= 1000; else if (connectionTimeout >= Int32.MaxValue / 1000) connectionTimeout = Int32.MaxValue; poolingOptions = new DbConnectionPoolGroupOptions( opt.IntegratedSecurity, opt.MinPoolSize, opt.MaxPoolSize, connectionTimeout, opt.LoadBalanceTimeout ); } return poolingOptions; } override internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions) { return new SqlConnectionPoolGroupProviderInfo((SqlConnectionString)connectionOptions); } internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key) { SqlConnectionString connectionOptions = (SqlConnectionString)SingletonInstance.FindConnectionOptions(key); if (null == connectionOptions) { connectionOptions = new SqlConnectionString(key.ConnectionString); } if (connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } return connectionOptions; } override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) { SqlConnection c = (connection as SqlConnection); if (null != c) { return c.PoolGroup; } return null; } override internal DbConnectionInternal GetInnerConnection(DbConnection connection) { SqlConnection c = (connection as SqlConnection); if (null != c) { return c.InnerConnection; } return null; } override internal void PermissionDemand(DbConnection outerConnection) { SqlConnection c = (outerConnection as SqlConnection); if (null != c) { c.PermissionDemand(); } } override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { SqlConnection c = (outerConnection as SqlConnection); if (null != c) { c.PoolGroup = poolGroup; } } override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { c.SetInnerConnectionEvent(to); } } override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { return c.SetInnerConnectionFrom(to, from); } return false; } override internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { c.SetInnerConnectionTo(to); } } } }
// // SqlitePclRawStorageEngine.cs // // Author: // Zachary Gramana <zack@couchbase.com> // // Copyright (c) 2014 Couchbase Inc. // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, 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. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Couchbase.Lite.Storage; using Couchbase.Lite.Store; using Couchbase.Lite.Util; using SQLitePCL; using SQLitePCL.Ugly; #if !NET_3_5 using StringEx = System.String; #endif #if SQLITE namespace Couchbase.Lite.Storage.SystemSQLite #elif CUSTOM_SQLITE namespace Couchbase.Lite.Storage.CustomSQLite #else namespace Couchbase.Lite.Storage.SQLCipher #endif { internal sealed class SqlitePCLRawStorageEngine : ISQLiteStorageEngine, IDisposable { // NOTE: SqlitePCL.raw only defines a subset of the ones we want, // so we just redefine them here instead. private const int SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN = 0x00200000; private const int SQLITE_OPEN_READONLY = 0x00000001; private const int SQLITE_OPEN_READWRITE = 0x00000002; private const int SQLITE_OPEN_CREATE = 0x00000004; private const int SQLITE_OPEN_FULLMUTEX = 0x00010000; private const int SQLITE_OPEN_NOMUTEX = 0x00008000; private const int SQLITE_OPEN_PRIVATECACHE = 0x00040000; private const int SQLITE_OPEN_SHAREDCACHE = 0x00020000; private const int TRANSACTION_MAX_RETRIES = 10; private const int TRANSACTION_MAX_RETRY_DELAY = 50; //milliseconds private const String TAG = "SqlitePCLRawStorageEngine"; private sqlite3 _writeConnection; private SymmetricKey _encryptionKey; private ConnectionPool _readerConnections; private bool _readOnly; // Needed for issue with GetVersion() private string Path { get; set; } private TaskFactory Factory { get; set; } private CancellationTokenSource _cts = new CancellationTokenSource(); private bool IsOnDBThread { get { var scheduler = Factory.Scheduler as SingleThreadScheduler; return scheduler.IsOnSpecialThread; } } #region ISQLiteStorageEngine public bool InTransaction { get { return transactionCount > 0; } } public int LastErrorCode { get; private set; } // Returns true on success, false if encryption key is wrong, throws exception for other cases public bool Decrypt(SymmetricKey encryptionKey, sqlite3 connection) { #if !ENCRYPTION Log.To.Database.E(TAG, "Encryption not supported on this store, throwing..."); throw new InvalidOperationException("Encryption not supported on this store"); #else if (encryptionKey != null) { // http://sqlcipher.net/sqlcipher-api/#key var sql = String.Format("PRAGMA key = \"x'{0}'\"", encryptionKey.HexData); try { ExecSQL(sql, connection); } catch(CouchbaseLiteException) { Log.To.Database.E(TAG, "Decryption operation failed, rethrowing..."); throw; } catch(Exception e) { throw Misc.CreateExceptionAndLog(Log.To.Database, e, TAG, "Decryption operation failed"); } } // Verify that encryption key is correct (or db is unencrypted, if no key given): var result = raw.sqlite3_exec(connection, "SELECT count(*) FROM sqlite_master"); if (result != raw.SQLITE_OK) { if (result == raw.SQLITE_NOTADB) { return false; } else { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Cannot read from database ({0})", result); } } return true; #endif } public bool Open(String path, bool readOnly, string schema, SymmetricKey encryptionKey) { if (IsOpen) return true; Path = path; _readOnly = readOnly; _encryptionKey = encryptionKey; Factory = new TaskFactory(new SingleThreadScheduler()); try { OpenRWConnection(_readOnly); if(schema != null && GetVersion() == 0) { foreach (var statement in schema.Split(';')) { ExecSQL(statement); } } _readerConnections = new ConnectionPool (3, OpenROConnection, Close); } catch(CouchbaseLiteException) { Log.To.Database.W(TAG, "Error opening SQLite storage engine, rethrowing..."); throw; } catch (Exception ex) { throw Misc.CreateExceptionAndLog(Log.To.Database, ex, TAG, "Failed to open SQLite storage engine"); } return true; } sqlite3 OpenROConnection() { const int reader_flags = SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN | SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX; var db = OpenSqliteConnection (reader_flags); #if ENCRYPTION if (!Decrypt (_encryptionKey, db)) { throw Misc.CreateExceptionAndLog (Log.To.Database, StatusCode.Unauthorized, TAG, "Decryption of database failed"); } #endif return db; } void OpenRWConnection(bool forceRo) { int readFlag = forceRo ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; int writer_flags = SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN | readFlag | SQLITE_OPEN_FULLMUTEX; _writeConnection = OpenSqliteConnection (writer_flags); #if ENCRYPTION if (!Decrypt (_encryptionKey, _writeConnection)) { throw Misc.CreateExceptionAndLog (Log.To.Database, StatusCode.Unauthorized, TAG, "Decryption of database failed"); } #endif } sqlite3 OpenSqliteConnection(int flags) { sqlite3 db; LastErrorCode = raw.sqlite3_open_v2(Path, out db, flags, null); if (LastErrorCode != raw.SQLITE_OK) { Path = null; throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Failed to open SQLite storage engine at path {0} ({1})", Path, LastErrorCode); } #if !__ANDROID__ && !NET_3_5 && VERBOSE var i = 0; var val = raw.sqlite3_compileoption_get(i); while (val != null) { Log.To.Database.V(TAG, String.Format("Sqlite Config: {0}", val)); val = raw.sqlite3_compileoption_get(++i); } #endif Log.To.Database.I(TAG, "Open {0} (flags={1}{2})", Path, flags, (_encryptionKey != null ? ", encryption key given" : "")); raw.sqlite3_create_collation(db, "JSON", null, CouchbaseSqliteJsonUnicodeCollationFunction.Compare); raw.sqlite3_create_collation(db, "JSON_ASCII", null, CouchbaseSqliteJsonAsciiCollationFunction.Compare); raw.sqlite3_create_collation(db, "JSON_RAW", null, CouchbaseSqliteJsonRawCollationFunction.Compare); raw.sqlite3_create_collation(db, "REVID", null, CouchbaseSqliteRevIdCollationFunction.Compare); return db; } public int GetVersion() { const string commandText = "PRAGMA user_version;"; sqlite3_stmt statement; //NOTE.JHB Even though this is a read, iOS doesn't return the correct value on the read connection //but someone should try again when the version goes beyond 3.7.13 statement = BuildCommand (_writeConnection, commandText, null); var result = -1; try { LastErrorCode = raw.sqlite3_step(statement); if (LastErrorCode != raw.SQLITE_ERROR) { Debug.Assert(LastErrorCode == raw.SQLITE_ROW); result = raw.sqlite3_column_int(statement, 0); } } catch (Exception e) { Log.To.Database.E(TAG, "Error getting user version", e); } finally { statement.Dispose(); } return result; } public void SetVersion(int version) { if (_readOnly) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG, "Attempting to write to a readonly database"); } const string commandText = "PRAGMA user_version = ?"; Log.To.TaskScheduling.V(TAG, "Scheduling SetVersion({0})", version); Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running SetVersion({0})", version); sqlite3_stmt statement = BuildCommand(_writeConnection, commandText, null); if ((LastErrorCode = raw.sqlite3_bind_int(statement, 1, version)) == raw.SQLITE_ERROR) throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Unable to set version to {0} ({1})", version, LastErrorCode); try { LastErrorCode = statement.step(); if (LastErrorCode != raw.SQLITE_OK) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Unable to set version to {0} ({1})", version, LastErrorCode); } } catch (Exception e) { Log.To.Database.W(TAG, "Error getting user version, recording error...", e); LastErrorCode = raw.sqlite3_errcode(_writeConnection); } finally { statement.Dispose(); } }); } public bool IsOpen { get { return _writeConnection != null; } } int transactionCount = 0; public bool BeginTransaction() { if (_readOnly) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG, "Transactions not allowed on a readonly database"); } if (!IsOpen) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG, "BeginTransaction called on closed database"); } // NOTE.ZJG: Seems like we should really be using TO SAVEPOINT // but this is how Android SqliteDatabase does it, // so I'm matching that for now. var value = Interlocked.Increment(ref transactionCount); if (value == 1) { Log.To.TaskScheduling.V(TAG, "Scheduling BeginTransaction()..."); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running BeginTransaction()..."); try { using (var statement = BuildCommand(_writeConnection, "BEGIN IMMEDIATE TRANSACTION", null)) { statement.step_done(); return true; } } catch (Exception e) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); Log.To.Database.E(TAG, "Error beginning transaction, recording error...", e); Interlocked.Decrement(ref transactionCount); return false; } }); return t.Result; } else { Log.To.TaskScheduling.V(TAG, "Scheduling begin SAVEPOINT..."); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running begin SAVEPOINT()..."); try { var sql = String.Format("SAVEPOINT cbl_{0}", value - 1); using (var statement = BuildCommand(_writeConnection, sql, null)) { statement.step_done(); return true; } } catch (Exception e) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); Log.To.Database.E(TAG, "Error beginning transaction, recording error...", e); Interlocked.Decrement(ref transactionCount); return false; } }); return t.Result; } } public bool EndTransaction(bool successful) { if (_readOnly) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG, "Transactions not allowed on a readonly database"); } if (!IsOpen) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG, "EndTransaction called on closed database"); } var count = Interlocked.Decrement(ref transactionCount); if (count > 0) { Log.To.TaskScheduling.V(TAG, "Scheduling end SAVEPOINT"); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running end SAVEPOINT"); try { if (successful) { var sql = String.Format("RELEASE SAVEPOINT cbl_{0}", count); using (var statement = BuildCommand(_writeConnection, sql, null)) { statement.step_done(); return true; } } else { var sql = String.Format("ROLLBACK TO SAVEPOINT cbl_{0}", count); using (var statement = BuildCommand(_writeConnection, sql, null)) { statement.step_done(); return true; } } } catch (Exception e) { Log.To.Database.E(TAG, "Error ending transaction, recording error...", e); LastErrorCode = raw.sqlite3_errcode(_writeConnection); Interlocked.Increment(ref transactionCount); return false; } }); return t.Result; } else { Log.To.TaskScheduling.V(TAG, "Scheduling EndTransaction()"); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running EndTransaction()"); try { if (successful) { using (var statement = BuildCommand(_writeConnection, "COMMIT", null)) { statement.step_done(); return true; } } else { using (var statement = BuildCommand(_writeConnection, "ROLLBACK", null)) { statement.step_done(); return true; } } } catch (Exception e) { Log.To.Database.E(TAG, "Error ending transaction, recording error...", e); LastErrorCode = raw.sqlite3_errcode(_writeConnection); Interlocked.Increment(ref transactionCount); return false; } }); return t.Result; } } public bool RunInTransaction(RunInTransactionDelegate block) { var status = false; var t = Factory.StartNew(() => { var keepGoing = false; int retries = 0; do { keepGoing = false; if (!BeginTransaction()) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Error beginning begin transaction"); } try { status = block(); } catch (CouchbaseLiteException e) { if (e.Code == StatusCode.DbBusy) { // retry if locked out if (transactionCount > 1) { break; } if (++retries > TRANSACTION_MAX_RETRIES) { Log.To.Database.E(TAG, "Db busy, too many retries, giving up"); break; } Log.To.Database.I(TAG, "Db busy, retrying transaction ({0})", retries); Thread.Sleep(TRANSACTION_MAX_RETRY_DELAY); keepGoing = true; } else { Log.To.Database.E(TAG, "Failed to run transaction, rethrowing..."); status = false; throw; } } catch (Exception e) { status = false; throw Misc.CreateExceptionAndLog(Log.To.Database, e, TAG, "Error running transaction"); } finally { EndTransaction(status); } } while(keepGoing); }); try { t.Wait(); } catch(Exception e) { throw Misc.UnwrapAggregate(e); } return status; } /// <summary> /// Execute any SQL that changes the database. /// </summary> /// <param name="sql">Sql.</param> /// <param name="paramArgs">Parameter arguments.</param> public int ExecSQL(String sql, params Object[] paramArgs) { return ExecSQL(sql, _writeConnection, paramArgs); } /// <summary> /// Executes only read-only SQL. /// </summary> /// <returns>The query.</returns> /// <param name="sql">Sql.</param> /// <param name="paramArgs">Parameter arguments.</param> public Cursor RawQuery(String sql, params Object[] paramArgs) { if (!IsOpen) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG, "RawQuery called on closed database"); } Cursor cursor = null; sqlite3_stmt command = null; var connection = default (Connection); //Log.To.TaskScheduling.V(TAG, "Scheduling RawQuery"); //var t = Factory.StartNew (() => //{ Log.To.TaskScheduling.V(TAG, "Running RawQuery"); try { connection = IsOnDBThread ? new Connection(_writeConnection, null) : _readerConnections.Acquire(); Log.To.Database.V (TAG, "RawQuery sql ({2}): {0} ({1})", sql, String.Join (", ", paramArgs.ToStringArray ()), IsOnDBThread ? "read uncommit" : "read commit"); command = BuildCommand (connection.Raw, sql, paramArgs); cursor = new Cursor (command, connection); } catch (Exception e) { if (command != null) { command.Dispose (); } var args = new SecureLogJsonString(paramArgs, LogMessageSensitivity.PotentiallyInsecure); Log.To.Database.E (TAG, String.Format("Error executing raw query '{0}' with values '{1}', rethrowing...", sql, paramArgs == null ? (object)String.Empty : new SecureLogJsonString(args, LogMessageSensitivity.PotentiallyInsecure)), e); LastErrorCode = raw.sqlite3_errcode(connection.Raw); throw; } return cursor; //}); //return t.Result; } public long Insert(String table, String nullColumnHack, ContentValues values) { return InsertWithOnConflict(table, null, values, ConflictResolutionStrategy.None); } public long InsertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy) { if (_readOnly) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG, "Attempting to write to a readonly database"); } if (!StringEx.IsNullOrWhiteSpace(nullColumnHack)) { throw new InvalidOperationException("Don't use nullColumnHack"); } Log.To.TaskScheduling.V(TAG, "Scheduling InsertWithOnConflict"); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running InsertWithOnConflict"); var lastInsertedId = -1L; var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy); try { LastErrorCode = command.step(); command.Dispose(); if (LastErrorCode == raw.SQLITE_ERROR) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, raw.sqlite3_errmsg(_writeConnection)); } int changes = _writeConnection.changes(); if (changes > 0) { lastInsertedId = _writeConnection.last_insert_rowid(); } if (lastInsertedId == -1L) { if(conflictResolutionStrategy != ConflictResolutionStrategy.Ignore) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Error inserting {0} using {1}", initialValues, command); } } else { Log.To.Database.V(TAG, "Inserting row {0} into {1} with values {2}", lastInsertedId, table, initialValues); } } catch(CouchbaseLiteException) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); Log.To.Database.E(TAG, "Error inserting into table {0}, rethrowing...", table); throw; } catch (Exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); throw Misc.CreateExceptionAndLog(Log.To.Database, ex, StatusCode.DbError, TAG, "Error inserting into table {0}", table); } return lastInsertedId; }); var r = t.ConfigureAwait(false).GetAwaiter().GetResult(); if (t.Exception != null) throw t.Exception; return r; } public int Update(String table, ContentValues values, String whereClause, params String[] whereArgs) { if (_readOnly) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG, "Attempting to write to a readonly database"); } Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); Debug.Assert(values != null); Log.To.TaskScheduling.V(TAG, "Scheduling Update"); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running Update"); var resultCount = 0; var command = GetUpdateCommand(table, values, whereClause, whereArgs); try { LastErrorCode = command.step(); if (LastErrorCode == raw.SQLITE_ERROR) throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); } catch (ugly.sqlite3_exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); var msg = raw.sqlite3_extended_errcode(_writeConnection); Log.To.Database.E(TAG, String.Format("Error {0}: \"{1}\" while updating table {2}", ex.errcode, msg, table), ex); } resultCount = _writeConnection.changes(); if (resultCount < 0) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Error updating {0} with command '{1}'", values, command); } command.Dispose(); return resultCount; }, CancellationToken.None); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. //doesn't look good var r = t.ConfigureAwait(false).GetAwaiter().GetResult(); if (t.Exception != null) throw t.Exception; return r; } public int Delete(String table, String whereClause, params String[] whereArgs) { if (_readOnly) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG, "Attempting to write to a readonly database"); } Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); Log.To.TaskScheduling.V(TAG, "Scheduling Delete"); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running Delete"); var resultCount = -1; var command = GetDeleteCommand(table, whereClause, whereArgs); try { var result = command.step(); if (result == raw.SQLITE_ERROR) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Error deleting from table {0} ({1})", table, result); } resultCount = _writeConnection.changes(); if (resultCount < 0) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Failed to delete the requested records"); } } catch (Exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); Log.To.Database.E(TAG, String.Format("Error {0} when deleting from table {1}, rethrowing...", _writeConnection.extended_errcode(), table), ex); throw; } finally { command.Dispose(); } return resultCount; }); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. var r = t.GetAwaiter().GetResult(); if (t.Exception != null) { //this is bad: should not arbitrarily crash the app throw t.Exception; } return r; } public void Close() { _cts.Cancel(); ((SingleThreadScheduler)Factory.Scheduler).Dispose(); Close (ref _writeConnection); _readerConnections?.Dispose (); Path = null; } static void Close(ref sqlite3 db) { var dbCopy = Interlocked.Exchange(ref db, null); if (dbCopy == null) { return; } try { // Close any open statements, otherwise the // sqlite connection won't actually close. sqlite3_stmt next = null; while ((next = dbCopy.next_stmt(next))!= null) { next.Dispose(); } dbCopy.close(); } catch (KeyNotFoundException ex) { // Appears to be a bug in sqlite3.find_stmt. Concurrency issue in static dictionary? // Assuming we're done. Log.To.Database.W(TAG, "Abandoning database close.", ex); } catch (ugly.sqlite3_exception ex) { Log.To.Database.I(TAG, "Retrying database close due to exception.", ex); // Assuming a basic retry fixes this. Thread.Sleep(5000); dbCopy.close(); } try { dbCopy.Dispose(); } catch (Exception ex) { Log.To.Database.W(TAG, "Error while closing database, continuing...", ex); } } #endregion #region Non-public Members private sqlite3_stmt BuildCommand(sqlite3 db, string sql, object[] paramArgs) { if (db == null) { Log.To.Database.E(TAG, "db cannot be null in BuildCommand, throwing..."); throw new ArgumentNullException("db"); } if (!IsOpen) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG, "BuildCommand called on closed database"); } sqlite3_stmt command = null; try { lock(Cursor.StmtDisposeLock) { LastErrorCode = raw.sqlite3_prepare_v2(db, sql, out command); } if (LastErrorCode != raw.SQLITE_OK || command == null) { Log.To.Database.E(TAG, "sqlite3_prepare_v2: {0}", LastErrorCode); } if (paramArgs != null && paramArgs.Length > 0 && command != null && LastErrorCode != raw.SQLITE_ERROR) { command.bind(paramArgs); } } catch (CouchbaseLiteException) { Log.To.Database.E(TAG, "Error when building sql '{0}' with params {1}, rethrowing...", sql, new SecureLogJsonString(paramArgs, LogMessageSensitivity.PotentiallyInsecure)); throw; } catch (Exception e) { throw Misc.CreateExceptionAndLog(Log.To.Database, e, TAG, "Error when building sql '{0}' with params {1}", sql, new SecureLogJsonString(paramArgs, LogMessageSensitivity.PotentiallyInsecure)); } return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The update command.</returns> /// <param name="table">Table.</param> /// <param name="values">Values.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetUpdateCommand(string table, ContentValues values, string whereClause, string[] whereArgs) { if (!IsOpen) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG, "GetUpdateCommand called on closed database"); } var builder = new StringBuilder("UPDATE "); builder.Append(table); builder.Append(" SET "); // Append our content column names and create our SQL parameters. var valueSet = values.ValueSet(); var paramList = new List<object>(); var index = 0; foreach (var column in valueSet) { if (index++ > 0) { builder.Append(","); } builder.AppendFormat("{0} = ?", column.Key); paramList.Add(column.Value); } if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } if (whereArgs != null) { paramList.AddRange(whereArgs); } var sql = builder.ToString(); var command = BuildCommand(_writeConnection, sql, paramList.ToArray<object>()); return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The insert command.</returns> /// <param name="table">Table.</param> /// <param name="values">Values.</param> /// <param name="conflictResolutionStrategy">Conflict resolution strategy.</param> sqlite3_stmt GetInsertCommand(String table, ContentValues values, ConflictResolutionStrategy conflictResolutionStrategy) { if (!IsOpen) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG, "GetInsertCommand called on closed database"); } var builder = new StringBuilder("INSERT"); if (conflictResolutionStrategy != ConflictResolutionStrategy.None) { builder.Append(" OR "); builder.Append(conflictResolutionStrategy); } builder.Append(" INTO "); builder.Append(table); builder.Append(" ("); // Append our content column names and create our SQL parameters. var valueSet = values.ValueSet(); var valueBuilder = new StringBuilder(); var index = 0; var args = new object[valueSet.Count]; foreach (var column in valueSet) { if (index > 0) { builder.Append(","); valueBuilder.Append(","); } builder.AppendFormat("{0}", column.Key); valueBuilder.Append("?"); args[index] = column.Value; index++; } builder.Append(") VALUES ("); builder.Append(valueBuilder); builder.Append(")"); var sql = builder.ToString(); sqlite3_stmt command = null; if (args != null) { Log.To.Database.V(TAG, "Preparing statement: '{0}' with values: {1}", sql, new SecureLogJsonString(args, LogMessageSensitivity.PotentiallyInsecure)); } else { Log.To.Database.V(TAG, "Preparing statement: '{0}'", sql); } command = BuildCommand(_writeConnection, sql, args); return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The delete command.</returns> /// <param name="table">Table.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetDeleteCommand(string table, string whereClause, string[] whereArgs) { if (!IsOpen) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG, "GetDeleteCommand called on closed database"); } var builder = new StringBuilder("DELETE FROM "); builder.Append(table); if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } sqlite3_stmt command; command = BuildCommand(_writeConnection, builder.ToString(), whereArgs); return command; } private int ExecSQL(string sql, sqlite3 db, params object[] paramArgs) { Log.To.TaskScheduling.V(TAG, "Scheduling ExecSQL"); var t = Factory.StartNew(()=> { Log.To.TaskScheduling.V(TAG, "Running ExecSQL"); sqlite3_stmt command = null; try { command = BuildCommand(db, sql, paramArgs); LastErrorCode = command.step(); if (LastErrorCode == raw.SQLITE_ERROR) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "SQLite error in ExecSQL: {0}", raw.sqlite3_errmsg(db)); } } catch (ugly.sqlite3_exception e) { Log.To.Database.E(TAG, String.Format("Error {0}, {1} ({2}) executing sql '{3}'", e.errcode, db.extended_errcode(), raw.sqlite3_errmsg(db), sql), e); LastErrorCode = e.errcode; throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Error {0}, {1} ({2}) executing sql '{3}'", e.errcode, db.extended_errcode(), raw.sqlite3_errmsg(db), sql); } finally { if(command != null) { command.Dispose(); } } }, _cts.Token); try { t.Wait(_cts.Token); } catch (AggregateException ex) { throw ex.InnerException; } catch (OperationCanceledException) { //Closing the storage engine will cause the factory to stop processing, but still //accept new jobs into the scheduler. If execution has gotten here, it means that //ExecSQL was called after Close, and the job will be ignored. Might consider //subclassing the factory to avoid this awkward behavior Log.To.Database.I(TAG, "StorageEngine closed, canceling operation"); return 0; } return db.changes(); } #endregion #region IDisposable implementation public void Dispose() { Close(); } #endregion } }
// // DBMonitorCouchbaseResponseState.cs // // Author: // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2015 Couchbase, 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. // using System.Collections.Generic; using System.Text; using System.Threading; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Util; namespace Couchbase.Lite.Listener { /// <summary> /// This class will wait for the database to change before writing to and /// possibly closing the HTTP response /// </summary> internal class DBMonitorCouchbaseResponseState : ICouchbaseResponseState { #region Constants private const string TAG = "DBMonitorCouchbaseResponseState"; #endregion #region Variables private Timer _heartbeatTimer; private RevisionList _changes = new RevisionList(); #endregion #region Properties public ICouchbaseListenerContext Context { get; set; } public Database Db { get; set; } /// <summary> /// The changes feed mode being used to listen to the database /// </summary> public ChangesFeedMode ChangesFeedMode { get; set; } /// <summary> /// Whether or not to write the document properties along with the changes /// </summary> public bool ChangesIncludeDocs { get; set; } /// <summary> /// Whether or not to include conflict revisions in the changes /// </summary> public bool ChangesIncludeConflicts { get; set; } /// <summary> /// The options for retrieving data from the DB /// </summary> public DocumentContentOptions ContentOptions { get; set; } /// <summary> /// The delegate to filter the changes being written /// </summary> public FilterDelegate ChangesFilter { get; set; } /// <summary> /// The parameters used in the change filter /// </summary> /// <value>The filter parameters.</value> public IDictionary<string, object> FilterParams { get; set; } //ICouchbaseResponseState public CouchbaseLiteResponse Response { get; set; } //ICouchbaseResponseState public bool IsAsync { get; set; } #endregion #region COnstructors /// <summary> /// Constructor /// </summary> public DBMonitorCouchbaseResponseState() { IsAsync = false; } /// <summary> /// Constructor /// </summary> /// <param name="response">The response to write to</param> public DBMonitorCouchbaseResponseState(CouchbaseLiteResponse response) : this() { Response = response; } #endregion #region Public Methods /// <summary> /// Subscribes this object to the given database's <c>Changed</c> event for /// processing /// </summary> /// <param name="db">Db.</param> public void SubscribeToDatabase(Database db) { if (db == null) { return; } IsAsync = true; Db = db; Db.Changed += DatabaseChanged; } /// <summary> /// Starts a timer for writing heartbeat messages to the client /// </summary> /// <param name="response">The message to write</param> /// <param name="interval">The interval at which to write the message (in milliseconds)</param> public void StartHeartbeat(string response, int interval) { if (interval <= 0 || _heartbeatTimer != null) { return; } IsAsync = true; Response.WriteHeaders(); _heartbeatTimer = new Timer(SendHeartbeatResponse, Encoding.UTF8.GetBytes(response), interval, interval); } #endregion #region Private Methods // Attempts to write the heartbeat message to the client private void SendHeartbeatResponse(object state) { Log.D(TAG, "Sending heartbeat to client"); if (!Response.WriteData((byte[])state, false)) { if (_heartbeatTimer != null) { _heartbeatTimer.Dispose(); _heartbeatTimer = null; } } } // Processes a change in the subscribed database private void DatabaseChanged(object sender, DatabaseChangeEventArgs args) { foreach (var change in args.Changes) { var rev = change.AddedRevision; var winningRev = change.WinningRevisionId; if (!ChangesIncludeConflicts) { if (winningRev == null) { continue; // this change doesn't affect the winning rev ID, no need to send it } if (rev.Equals(winningRev)) { // This rev made a _different_ rev current, so substitute that one. // We need to emit the current sequence # in the feed, so put it in the rev. // This isn't correct internally (this is an old rev so it has an older sequence) // but consumers of the _changes feed don't care about the internal state. if (ChangesIncludeDocs) { Db.LoadRevisionBody(rev); } } } if (!Db.RunFilter(ChangesFilter, FilterParams, rev)) { continue; } if (ChangesFeedMode == ChangesFeedMode.LongPoll) { _changes.Add(rev); } else { Log.D(TAG, "Sending continuous change chunk"); var written = Response.SendContinuousLine(DatabaseMethods.ChangesDictForRev(rev, this), ChangesFeedMode); if (!written) { Terminate(); } } } if (ChangesFeedMode == ChangesFeedMode.LongPoll && _changes.Count > 0) { var body = new Body(DatabaseMethods.ResponseBodyForChanges(_changes, 0, this)); Response.WriteData(body.AsJson(), true); CouchbaseLiteRouter.ResponseFinished(this); } } // Tear down this object because an error occurred private void Terminate() { if (Db == null) { return; } Db.Changed -= DatabaseChanged; CouchbaseLiteRouter.ResponseFinished(this); Db = null; if (_heartbeatTimer != null) { _heartbeatTimer.Dispose(); _heartbeatTimer = null; } } #endregion } }
using UnityEngine; #if UNITY_5_3 || UNITY_5_4 using UnityEngine.SceneManagement; #endif #if ENABLE_IOS_ON_DEMAND_RESOURCES using UnityEngine.iOS; #endif using System.Collections; namespace AssetBundles { public abstract class AssetBundleLoadOperation : IEnumerator { public object Current { get { return null; } } public bool MoveNext() { return !IsDone(); } public void Reset() { } abstract public bool Update(); abstract public bool IsDone(); } public abstract class AssetBundleDownloadOperation : AssetBundleLoadOperation { bool done; public string assetBundleName { get; private set; } public LoadedAssetBundle assetBundle { get; protected set; } public string error { get; protected set; } protected abstract bool downloadIsDone { get; } protected abstract void FinishDownload(); public override bool Update() { if (!done && downloadIsDone) { FinishDownload(); done = true; } return !done; } public override bool IsDone() { return done; } public abstract string GetSourceURL(); public AssetBundleDownloadOperation(string assetBundleName) { this.assetBundleName = assetBundleName; } } #if ENABLE_IOS_ON_DEMAND_RESOURCES // Read asset bundle asynchronously from iOS / tvOS asset catalog that is downloaded // using on demand resources functionality. public class AssetBundleDownloadFromODROperation : AssetBundleDownloadOperation { OnDemandResourcesRequest request; public AssetBundleDownloadFromODROperation(string assetBundleName) : base(assetBundleName) { // Work around Xcode crash when opening Resources tab when a // resource name contains slash character request = OnDemandResources.PreloadAsync(new string[] { assetBundleName.Replace('/', '>') }); } protected override bool downloadIsDone { get { return (request == null) || request.isDone; } } public override string GetSourceURL() { return "odr://" + assetBundleName; } protected override void FinishDownload() { error = request.error; if (error != null) return; var path = "res://" + assetBundleName; var bundle = AssetBundle.CreateFromFile(path); if (bundle == null) { error = string.Format("Failed to load {0}", path); request.Dispose(); } else { assetBundle = new LoadedAssetBundle(bundle); // At the time of unload request is already set to null, so capture it to local variable. var localRequest = request; // Dispose of request only when bundle is unloaded to keep the ODR pin alive. assetBundle.unload += () => { localRequest.Dispose(); }; } request = null; } } #endif #if ENABLE_IOS_APP_SLICING // Read asset bundle synchronously from an iOS / tvOS asset catalog public class AssetBundleOpenFromAssetCatalogOperation : AssetBundleDownloadOperation { public AssetBundleOpenFromAssetCatalogOperation(string assetBundleName) : base(assetBundleName) { var path = "res://" + assetBundleName; var bundle = AssetBundle.CreateFromFile(path); if (bundle == null) error = string.Format("Failed to load {0}", path); else assetBundle = new LoadedAssetBundle(bundle); } protected override bool downloadIsDone { get { return true; } } protected override void FinishDownload() {} public override string GetSourceURL() { return "res://" + assetBundleName; } } #endif public class AssetBundleDownloadFromWebOperation : AssetBundleDownloadOperation { WWW m_WWW; string m_Url; public AssetBundleDownloadFromWebOperation(string assetBundleName, WWW www) : base(assetBundleName) { if (www == null) throw new System.ArgumentNullException("www"); m_Url = www.url; this.m_WWW = www; } protected override bool downloadIsDone { get { return (m_WWW == null) || m_WWW.isDone; } } protected override void FinishDownload() { error = m_WWW.error; if (!string.IsNullOrEmpty(error)) return; AssetBundle bundle = m_WWW.assetBundle; if (bundle == null) error = string.Format("{0} is not a valid asset bundle.", assetBundleName); else assetBundle = new LoadedAssetBundle(m_WWW.assetBundle); m_WWW.Dispose(); m_WWW = null; } public override string GetSourceURL() { return m_Url; } } #if UNITY_EDITOR public class AssetBundleLoadLevelSimulationOperation : AssetBundleLoadOperation { AsyncOperation m_Operation = null; public AssetBundleLoadLevelSimulationOperation(string assetBundleName, string levelName, bool isAdditive) { string[] levelPaths = UnityEditor.AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleName, levelName); if (levelPaths.Length == 0) { ///@TODO: The error needs to differentiate that an asset bundle name doesn't exist // from that there right scene does not exist in the asset bundle... Debug.LogError("There is no scene with name \"" + levelName + "\" in " + assetBundleName); return; } if (isAdditive) m_Operation = UnityEditor.EditorApplication.LoadLevelAdditiveAsyncInPlayMode(levelPaths[0]); else m_Operation = UnityEditor.EditorApplication.LoadLevelAsyncInPlayMode(levelPaths[0]); } public override bool Update() { return false; } public override bool IsDone() { return m_Operation == null || m_Operation.isDone; } } #endif public class AssetBundleLoadLevelOperation : AssetBundleLoadOperation { protected string m_AssetBundleName; protected string m_LevelName; protected bool m_IsAdditive; protected string m_DownloadingError; protected AsyncOperation m_Request; public AssetBundleLoadLevelOperation(string assetbundleName, string levelName, bool isAdditive) { m_AssetBundleName = assetbundleName; m_LevelName = levelName; m_IsAdditive = isAdditive; } public override bool Update() { if (m_Request != null) return false; LoadedAssetBundle bundle = AssetBundleManager.GetLoadedAssetBundle(m_AssetBundleName, out m_DownloadingError); if (bundle != null) { #if UNITY_5_3 || UNITY_5_4 m_Request = SceneManager.LoadSceneAsync(m_LevelName, m_IsAdditive ? LoadSceneMode.Additive : LoadSceneMode.Single); #else if (m_IsAdditive) m_Request = Application.LoadLevelAdditiveAsync(m_LevelName); else m_Request = Application.LoadLevelAsync(m_LevelName); #endif return false; } else return true; } public override bool IsDone() { // Return if meeting downloading error. // m_DownloadingError might come from the dependency downloading. if (m_Request == null && m_DownloadingError != null) { Debug.LogError(m_DownloadingError); return true; } return m_Request != null && m_Request.isDone; } } public abstract class AssetBundleLoadAssetOperation : AssetBundleLoadOperation { public abstract T GetAsset<T>() where T: UnityEngine.Object; } public class AssetBundleLoadAssetOperationSimulation : AssetBundleLoadAssetOperation { Object m_SimulatedObject; public AssetBundleLoadAssetOperationSimulation(Object simulatedObject) { m_SimulatedObject = simulatedObject; } public override T GetAsset<T>() { return m_SimulatedObject as T; } public override bool Update() { return false; } public override bool IsDone() { return true; } } public class AssetBundleLoadAssetOperationFull : AssetBundleLoadAssetOperation { protected string m_AssetBundleName; protected string m_AssetName; protected string m_DownloadingError; protected System.Type m_Type; protected AssetBundleRequest m_Request = null; public AssetBundleLoadAssetOperationFull(string bundleName, string assetName, System.Type type) { m_AssetBundleName = bundleName; m_AssetName = assetName; m_Type = type; } public override T GetAsset<T>() { if (m_Request != null && m_Request.isDone) return m_Request.asset as T; else return null; } // Returns true if more Update calls are required. public override bool Update() { if (m_Request != null) return false; LoadedAssetBundle bundle = AssetBundleManager.GetLoadedAssetBundle(m_AssetBundleName, out m_DownloadingError); if (bundle != null) { ///@TODO: When asset bundle download fails this throws an exception... m_Request = bundle.m_AssetBundle.LoadAssetAsync(m_AssetName, m_Type); return false; } else { return true; } } public override bool IsDone() { // Return if meeting downloading error. // m_DownloadingError might come from the dependency downloading. if (m_Request == null && m_DownloadingError != null) { Debug.LogError(m_DownloadingError); return true; } return m_Request != null && m_Request.isDone; } } public class AssetBundleLoadManifestOperation : AssetBundleLoadAssetOperationFull { public AssetBundleLoadManifestOperation(string bundleName, string assetName, System.Type type) : base(bundleName, assetName, type) { } public override bool Update() { base.Update(); if (m_Request != null && m_Request.isDone) { AssetBundleManager.AssetBundleManifestObject = GetAsset<AssetBundleManifest>(); return false; } else return true; } } }
/* * REST API Documentation for Schoolbus * * API Sample * * OpenAPI spec version: v1 * * */ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; using SchoolBusAPI; using System.Text; using System.Net; using Newtonsoft.Json; using SchoolBusAPI.Models; using SchoolBusAPI.ViewModels; namespace SchoolBusAPI.Test { public class UserApiIntegrationTest { private readonly TestServer _server; private readonly HttpClient _client; /// <summary> /// Setup the test /// </summary> public UserApiIntegrationTest() { _server = new TestServer(new WebHostBuilder() .UseEnvironment("Development") .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>()); _client = _server.CreateClient(); } [Fact] /// <summary> /// Integration test for Users Bulk /// </summary> public async void TestUsersBulk() { var request = new HttpRequestMessage(HttpMethod.Post, "/api/users/bulk"); request.Content = new StringContent("[]", Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); } [Fact] /// <summary> /// Basic Integration test for Users /// </summary> public async void TestUsersBasic() { string initialName = "InitialName"; string changedName = "ChangedName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/users"); // create a new object. UserViewModel user = new UserViewModel(); user.GivenName = initialName; string jsonString = user.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<UserViewModel>(jsonString); // get the id var id = user.Id; // change the name user.GivenName = changedName; // now do an update. request = new HttpRequestMessage(HttpMethod.Put, "/api/users/" + id); request.Content = new StringContent(user.ToJson(), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // do a get. request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<UserViewModel>(jsonString); // verify the change went through. Assert.Equal(user.GivenName, changedName); // do a delete. request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } [Fact] /// <summary> /// Integration test for User Favourites. /// </summary> public async void TestUserFavorites() { string initialName = "InitialName"; // create a user. var request = new HttpRequestMessage(HttpMethod.Post, "/api/users"); UserViewModel user = new UserViewModel(); user.GivenName = initialName; string jsonString = user.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<UserViewModel>(jsonString); // get the id var id = user.Id; // add and associate the favourite // verify the user has a favourite. request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id + "/favourites"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); UserFavouriteViewModel[] items = JsonConvert.DeserializeObject<UserFavouriteViewModel[]>(jsonString); // cleanup the user response.EnsureSuccessStatusCode(); } [Fact] /// <summary> /// Integration test for Users /// </summary> public async void TestUsers() { string initialName = "InitialName"; string changedName = "ChangedName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/users"); // create a new object. UserViewModel user = new UserViewModel(); user.GivenName = initialName; string jsonString = user.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<UserViewModel>(jsonString); // get the id var id = user.Id; // change the name user.GivenName = changedName; // now do an update. request = new HttpRequestMessage(HttpMethod.Put, "/api/users/" + id); request.Content = new StringContent(user.ToJson(), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // do a get. request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<UserViewModel>(jsonString); // verify the change went through. Assert.Equal(user.GivenName, changedName); // do a delete. request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.VisualBasic.Syntax; using Roslyn.Test.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { public partial class CodeGenerationTests { public class VisualBasic { [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddNamespace() { var input = "Namespace [|N1|]\n End Namespace"; var expected = "Namespace N1\n Namespace N2\n End Namespace\n End Namespace"; TestAddNamespace(input, expected, name: "N2"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddField() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public F As Integer\n End Class"; TestAddField(input, expected, type: GetTypeSymbol(typeof(int))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddSharedField() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Private Shared F As String\n End Class"; TestAddField(input, expected, type: GetTypeSymbol(typeof(string)), accessibility: Accessibility.Private, modifiers: new DeclarationModifiers(isStatic: true)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddArrayField() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public F As Integer()\n End Class"; TestAddField(input, expected, type: CreateArrayType(typeof(int))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddConstructor() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Sub New()\n End Sub\n End Class"; TestAddConstructor(input, expected); } [WorkItem(530785)] [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddConstructorWithXmlComment() { var input = @" Public Class [|C|] ''' <summary> ''' Do Nothing ''' </summary> Public Sub GetStates() End Sub End Class"; var expected = @" Public Class C Public Sub New() End Sub ''' <summary> ''' Do Nothing ''' </summary> Public Sub GetStates() End Sub End Class"; TestAddConstructor(input, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddConstructorWithoutBody() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Sub New()\n End Class"; TestAddConstructor(input, expected, codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddConstructorResolveNamespaceImport() { var input = "Class [|C|]\n End Class"; var expected = "Imports System.Text\n Class C\n Public Sub New(s As StringBuilder)\n End Sub\n End Class"; TestAddConstructor(input, expected, parameters: Parameters(Parameter(typeof(StringBuilder), "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddSharedConstructor() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Shared Sub New()\n End Sub\n End Class"; TestAddConstructor(input, expected, modifiers: new DeclarationModifiers(isStatic: true)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddChainedConstructor() { var input = "Class [|C|]\n Public Sub New(i As Integer)\n End Sub\n End Class"; var expected = "Class C\n Public Sub New()\n Me.New(42)\n End Sub\n Public Sub New(i As Integer)\n End Sub\n End Class"; TestAddConstructor(input, expected, thisArguments: new[] { VB.SyntaxFactory.ParseExpression("42") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544476)] public void AddClass() { var input = "Namespace [|N|]\n End Namespace"; var expected = @"Namespace N Public Class C End Class End Namespace"; TestAddNamedType(input, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddClassEscapeName() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Public Class [Class]\n End Class\n End Namespace"; TestAddNamedType(input, expected, name: "Class"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddClassUnicodeName() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Public Class [Class]\n End Class\n End Namespace"; TestAddNamedType(input, expected, name: "Cl\u0061ss"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477)] public void AddNotInheritableClass() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Public NotInheritable Class C\n End Class\n End Namespace"; TestAddNamedType(input, expected, modifiers: new DeclarationModifiers(isSealed: true)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477)] public void AddMustInheritClass() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Friend MustInherit Class C\n End Class\n End Namespace"; TestAddNamedType(input, expected, accessibility: Accessibility.Internal, modifiers: new DeclarationModifiers(isAbstract: true)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddStructure() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Friend Structure S\n End Structure\n End Namespace"; TestAddNamedType(input, expected, name: "S", accessibility: Accessibility.Internal, typeKind: TypeKind.Struct); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224)] public void AddSealedStructure() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Public Structure S\n End Structure\n End Namespace"; TestAddNamedType(input, expected, name: "S", accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isSealed: true), typeKind: TypeKind.Struct); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddInterface() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Public Interface I\n End Interface\n End Namespace"; TestAddNamedType(input, expected, name: "I", typeKind: TypeKind.Interface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544528)] public void AddEnum() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Public Enum E\n F1\n End Enum\n End Namespace"; TestAddNamedType(input, expected, "E", typeKind: TypeKind.Enum, members: Members(CreateEnumField("F1", null))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544527)] public void AddEnumWithValues() { var input = "Namespace [|N|]\n End Namespace"; var expected = "Namespace N\n Public Enum E\n F1 = 1\n F2 = 2\n End Enum\n End Namespace"; TestAddNamedType(input, expected, "E", typeKind: TypeKind.Enum, members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddEnumMember() { var input = "Public Enum [|E|]\n F1 = 1\n F2 = 2\n End Enum"; var expected = "Public Enum E\n F1 = 1\n F2 = 2\n F3\n End Enum"; TestAddField(input, expected, name: "F3"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddEnumMemberWithValue() { var input = "Public Enum [|E|]\n F1 = 1\n F2\n End Enum"; var expected = "Public Enum E\n F1 = 1\n F2\n F3 = 3\n End Enum"; TestAddField(input, expected, name: "F3", hasConstantValue: true, constantValue: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544529)] public void AddDelegateType() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Delegate Function D(s As String) As Integer\n End Class"; TestAddDelegateType(input, expected, returnType: typeof(int), parameters: Parameters(Parameter(typeof(string), "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224)] public void AddSealedDelegateType() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Delegate Function D(s As String) As Integer\n End Class"; TestAddDelegateType(input, expected, returnType: typeof(int), modifiers: new DeclarationModifiers(isSealed: true), parameters: Parameters(Parameter(typeof(string), "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddMethodToClass() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Sub M()\n End Sub\n End Class"; TestAddMethod(input, expected, returnType: typeof(void)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddMethodToClassEscapedName() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Protected Friend Sub [Sub]()\n End Sub\n End Class"; TestAddMethod(input, expected, accessibility: Accessibility.ProtectedOrInternal, name: "Sub", returnType: typeof(void)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477)] public void AddSharedMethodToStructure() { var input = "Structure [|S|]\n End Structure"; var expected = "Structure S\n Public Shared Function M() As Integer\n Return 0\n End Function\n End Structure"; TestAddMethod(input, expected, modifiers: new DeclarationModifiers(isStatic: true), returnType: typeof(int), statements: "Return 0"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddNotOverridableOverridesMethod() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public NotOverridable Overrides Function GetHashCode() As Integer\n $$ \nEnd Function\n End Class"; TestAddMethod(input, expected, name: "GetHashCode", modifiers: new DeclarationModifiers(isOverride: true, isSealed: true), returnType: typeof(int), statements: "Return 0"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddMustOverrideMethod() { var input = "MustInherit Class [|C|]\n End Class"; var expected = "MustInherit Class C\n Public MustOverride Sub M()\n End Class"; TestAddMethod(input, expected, modifiers: new DeclarationModifiers(isAbstract: true), returnType: typeof(void)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddMethodWithoutBody() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Sub M()\n End Class"; TestAddMethod(input, expected, returnType: typeof(void), codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddGenericMethod() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Function M(Of T)() As Integer\n $$ \nEnd Function\n End Class"; TestAddMethod(input, expected, returnType: typeof(int), typeParameters: new[] { CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T") }, statements: "Return new T().GetHashCode()"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddVirtualMethod() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Protected Overridable Function M() As Integer\n $$ End Function\n End Class"; TestAddMethod(input, expected, accessibility: Accessibility.Protected, modifiers: new DeclarationModifiers(isVirtual: true), returnType: typeof(int), statements: "Return 0\n"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddShadowsMethod() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Shadows Function ToString() As String\n $$ End Function\n End Class"; TestAddMethod(input, expected, name: "ToString", accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isNew: true), returnType: typeof(string), statements: "Return String.Empty\n"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddExplicitImplementation() { var input = "Interface I\n Sub M(i As Integer)\n End Interface\n Class [|C|]\n Implements I\n End Class"; var expected = "Interface I\n Sub M(i As Integer)\n End Interface\n Class C\n Implements I\n Public Sub M(i As Integer) Implements I.M\n End Sub\n End Class"; TestAddMethod(input, expected, name: "M", returnType: typeof(void), parameters: Parameters(Parameter(typeof(int), "i")), explicitInterface: s => s.LookupSymbols(input.IndexOf("M"), null, "M").First() as IMethodSymbol); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddTrueFalseOperators() { var input = @" Class [|C|] End Class "; var expected = @" Class C Public Shared Operator IsTrue(other As C) As Boolean $$ End Operator Public Shared Operator IsFalse(other As C) As Boolean $$ End Operator End Class "; TestAddOperators(input, expected, new[] { CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False }, parameters: Parameters(Parameter("C", "other")), returnType: typeof(bool), statements: "Return False"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddUnaryOperators() { var input = @" Class [|C|] End Class "; var expected = @" Class C Public Shared Operator + (other As C) As Object $$ End Operator Public Shared Operator -(other As C) As Object $$ End Operator Public Shared Operator Not(other As C) As Object $$ End Operator End Class "; TestAddOperators(input, expected, new[] { CodeGenerationOperatorKind.UnaryPlus, CodeGenerationOperatorKind.UnaryNegation, CodeGenerationOperatorKind.LogicalNot }, parameters: Parameters(Parameter("C", "other")), returnType: typeof(object), statements: "Return Nothing"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddBinaryOperators() { var input = @" Class [|C|] End Class "; var expected = @" Class C Public Shared Operator +(a As C, b As C) As Object $$ End Operator Public Shared Operator -(a As C, b As C) As Object $$ End Operator Public Shared Operator *(a As C, b As C) As Object $$ End Operator Public Shared Operator /(a As C, b As C) As Object $$ End Operator Public Shared Operator \(a As C, b As C) As Object $$ End Operator Public Shared Operator ^(a As C, b As C) As Object $$ End Operator Public Shared Operator &(a As C, b As C) As Object $$ End Operator Public Shared Operator Like(a As C, b As C) As Object $$ End Operator Public Shared Operator Mod(a As C, b As C) As Object $$ End Operator Public Shared Operator And(a As C, b As C) As Object $$ End Operator Public Shared Operator Or(a As C, b As C) As Object $$ End Operator Public Shared Operator Xor(a As C, b As C) As Object $$ End Operator Public Shared Operator <<(a As C, b As C) As Object $$ End Operator Public Shared Operator >>(a As C, b As C) As Object $$ End Operator End Class "; TestAddOperators(input, expected, new[] { CodeGenerationOperatorKind.Addition, CodeGenerationOperatorKind.Subtraction, CodeGenerationOperatorKind.Multiplication, CodeGenerationOperatorKind.Division, CodeGenerationOperatorKind.IntegerDivision, CodeGenerationOperatorKind.Exponent, CodeGenerationOperatorKind.Concatenate, CodeGenerationOperatorKind.Like, CodeGenerationOperatorKind.Modulus, CodeGenerationOperatorKind.BitwiseAnd, CodeGenerationOperatorKind.BitwiseOr, CodeGenerationOperatorKind.ExclusiveOr, CodeGenerationOperatorKind.LeftShift, CodeGenerationOperatorKind.RightShift }, parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")), returnType: typeof(object), statements: "Return Nothing"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddComparisonOperators() { var input = @" Class [|C|] End Class "; var expected = @" Class C Public Shared Operator =(a As C, b As C) As Boolean $$ End Operator Public Shared Operator <>(a As C, b As C) As Boolean $$ End Operator Public Shared Operator >(a As C, b As C) As Boolean $$ End Operator Public Shared Operator <(a As C, b As C) As Boolean $$ End Operator Public Shared Operator >=(a As C, b As C) As Boolean $$ End Operator Public Shared Operator <=(a As C, b As C) As Boolean $$ End Operator End Class "; TestAddOperators(input, expected, new[] { CodeGenerationOperatorKind.Equality, CodeGenerationOperatorKind.Inequality, CodeGenerationOperatorKind.GreaterThan, CodeGenerationOperatorKind.LessThan, CodeGenerationOperatorKind.GreaterThanOrEqual, CodeGenerationOperatorKind.LessThanOrEqual }, parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")), returnType: typeof(bool), statements: "Return True"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddUnsupportedOperator() { var input = "Class [|C|]\n End Class"; TestAddUnsupportedOperator(input, operatorKind: CodeGenerationOperatorKind.Increment, parameters: Parameters(Parameter("C", "other")), returnType: typeof(bool), statements: "Return True"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddExplicitConversion() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Shared Narrowing Operator CType(other As C) As Integer\n $$\n End Operator\n End Class"; TestAddConversion(input, expected, toType: typeof(int), fromType: Parameter("C", "other"), statements: "Return 0"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddImplicitConversion() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Shared Widening Operator CType(other As C) As Integer\n $$\n End Operator\n End Class"; TestAddConversion(input, expected, toType: typeof(int), fromType: Parameter("C", "other"), isImplicit: true, statements: "Return 0"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddStatementsToSub() { var input = "Class C\n [|Public Sub M\n Console.WriteLine(1)\n End Sub|]\n End Class"; var expected = "Class C\n Public Sub M\n Console.WriteLine(1)\n $$\n End Sub\n End Class"; TestAddStatements(input, expected, "Console.WriteLine(2)"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddStatementsToOperator() { var input = "Class C\n [|Shared Operator +(arg As C) As C\n Return arg\n End Operator|]\n End Class"; var expected = "Class C\n Shared Operator +(arg As C) As C\n Return arg\n $$\n End Operator\n End Class"; TestAddStatements(input, expected, "Return Nothing"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddStatementsToPropertySetter() { var input = "Imports System\n Class C\n WriteOnly Property P As String\n [|Set\n End Set|]\n End Property\n End Class"; var expected = "Imports System\n Class C\n WriteOnly Property P As String\n Set\n $$\n End Set\n End Property\n End Class"; TestAddStatements(input, expected, "Console.WriteLine(\"Setting the value\""); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddParametersToMethod() { var input = "Class C\n Public [|Sub M()\n End Sub|]\n End Class"; var expected = "Class C\n Public Sub M(num As Integer, Optional text As String = \"Hello!\", Optional floating As Single = 0.5)\n End Sub\n End Class"; TestAddParameters(input, expected, Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5F))); } [WorkItem(844460)] [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddParametersToPropertyBlock() { var input = "Class C\n [|Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property|]\n End Class"; var expected = "Class C\n Public Property P(num As Integer) As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class"; TestAddParameters(input, expected, Parameters(Parameter(typeof(int), "num"))); } [WorkItem(844460)] [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddParametersToPropertyStatement() { var input = "Class C\n [|Public Property P As String|]\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class"; var expected = "Class C\n Public Property P(num As Integer) As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class"; TestAddParameters(input, expected, Parameters(Parameter(typeof(int), "num"))); } [WorkItem(844460)] [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddParametersToPropertyGetter_ShouldNotSucceed() { var input = "Class C\n Public Property P As String\n [|Get\n Return String.Empty\n End Get|]\n Set(value As String)\n End Set\n End Property\n End Class"; var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class"; TestAddParameters(input, expected, Parameters(Parameter(typeof(int), "num"))); } [WorkItem(844460)] [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddParametersToPropertySetter_ShouldNotSucceed() { var input = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n [|Set(value As String)\n End Set|]\n End Property\n End Class"; var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class"; TestAddParameters(input, expected, Parameters(Parameter(typeof(int), "num"))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddParametersToOperator() { var input = "Class C\n [|Shared Operator +(a As C) As C\n Return a\n End Operator|]\n End Class"; var expected = "Class C\n Shared Operator +(a As C, b As C) As C\n Return a\n End Operator\n End Class"; TestAddParameters(input, expected, Parameters(Parameter("C", "b"))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAutoProperty() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Property P As Integer\n End Class"; TestAddProperty(input, expected, type: typeof(int)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddPropertyWithoutAccessorBodies() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Public Property P As Integer\n End Class"; TestAddProperty(input, expected, type: typeof(int), getStatements: "Return 0", setStatements: "Me.P = Value", codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddIndexer() { var input = "Class [|C|]\n End Class"; var expected = "Class C\n Default Public ReadOnly Property Item(i As Integer) As String\n Get\n $$ \nEnd Get\n End Property\n End Class"; TestAddProperty(input, expected, name: "Item", type: typeof(string), parameters: Parameters(Parameter(typeof(int), "i")), getStatements: "Return String.Empty", isIndexer: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToTypes() { var input = "Class [|C|]\n End Class"; var expected = "<Serializable> Class C\n End Class"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromTypes() { var input = @" <Serializable> Class [|C|] End Class"; var expected = @" Class C End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToMethods() { var input = "Class C\n Public Sub [|M()|] \n End Sub \n End Class"; var expected = "Class C\n <Serializable> Public Sub M() \n End Sub \n End Class"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromMethods() { var input = @" Class C <Serializable> Public Sub [|M()|] End Sub End Class"; var expected = @" Class C Public Sub M() End Sub End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToFields() { var input = "Class C\n [|Public F As Integer|]\n End Class"; var expected = "Class C\n <Serializable> Public F As Integer\n End Class"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromFields() { var input = @" Class C <Serializable> Public [|F|] As Integer End Class"; var expected = @" Class C Public F As Integer End Class"; TestRemoveAttribute<FieldDeclarationSyntax>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToProperties() { var input = "Class C \n Public Property [|P|] As Integer \n End Class"; var expected = "Class C \n <Serializable> Public Property P As Integer \n End Class"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromProperties() { var input = @" Class C <Serializable> Public Property [|P|] As Integer End Class"; var expected = @" Class C Public Property P As Integer End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToPropertyAccessor() { var input = "Class C \n Public ReadOnly Property P As Integer \n [|Get|] \n Return 10 \n End Get \n End Property \n End Class"; var expected = "Class C \n Public ReadOnly Property P As Integer \n <Serializable> Get \n Return 10 \n End Get \n End Property \n End Class"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromPropertyAccessor() { var input = @" Class C Public Property P As Integer <Serializable> [|Get|] Return 10 End Get End Class"; var expected = @" Class C Public Property P As Integer Get Return 10 End Get End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToEnums() { var input = "Module M \n [|Enum C|] \n One \n Two \n End Enum\n End Module"; var expected = "Module M \n <Serializable> Enum C \n One \n Two \n End Enum\n End Module"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromEnums() { var input = @" Module M <Serializable> Enum [|C|] One Two End Enum End Module"; var expected = @" Module M Enum C One Two End Enum End Module"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToEnumMembers() { var input = "Module M \n Enum C \n [|One|] \n Two \n End Enum\n End Module"; var expected = "Module M \n Enum C \n <Serializable> One \n Two \n End Enum\n End Module"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromEnumMembers() { var input = @" Module M Enum C <Serializable> [|One|] Two End Enum End Module"; var expected = @" Module M Enum C One Two End Enum End Module"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToModule() { var input = "Module [|M|] \n End Module"; var expected = "<Serializable> Module M \n End Module"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromModule() { var input = @" <Serializable> Module [|M|] End Module"; var expected = @" Module M End Module"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToOperator() { var input = "Class C \n Public Shared Operator [|+|] (x As C, y As C) As C \n Return New C() \n End Operator \n End Class"; var expected = "Class C \n <Serializable> Public Shared Operator +(x As C, y As C) As C \n Return New C() \n End Operator \n End Class"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromOperator() { var input = @" Module M Class C <Serializable> Public Shared Operator [|+|](x As C, y As C) As C Return New C() End Operator End Class End Module"; var expected = @" Module M Class C Public Shared Operator +(x As C, y As C) As C Return New C() End Operator End Class End Module"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToDelegate() { var input = "Module M \n Delegate Sub [|D()|]\n End Module"; var expected = "Module M \n <Serializable> Delegate Sub D()\n End Module"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromDelegate() { var input = @" Module M <Serializable> Delegate Sub [|D()|] End Module"; var expected = @" Module M Delegate Sub D() End Module"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToParam() { var input = "Class C \n Public Sub M([|x As Integer|]) \n End Sub \n End Class"; var expected = "Class C \n Public Sub M(<Serializable> x As Integer) \n End Sub \n End Class"; TestAddAttribute(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeFromParam() { var input = @" Class C Public Sub M(<Serializable> [|x As Integer|]) End Sub End Class"; var expected = @" Class C Public Sub M(x As Integer) End Sub End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeToCompilationUnit() { var input = "[|Class C \n End Class \n Class D \n End Class|]"; var expected = "<Assembly: Serializable> Class C \n End Class \n Class D \n End Class"; TestAddAttribute(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.AssemblyKeyword)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void AddAttributeWithWrongTarget() { var input = "[|Class C \n End Class \n Class D \n End Class|]"; var expected = "<Assembly: Serializable> Class C \n End Class \n Class D \n End Class"; Assert.Throws<AggregateException>(() => TestAddAttribute(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.ReturnKeyword))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeWithTrivia() { // With trivia. var input = @"' Comment 1 <System.Serializable> ' Comment 2 Class [|C|] End Class"; var expected = @"' Comment 1 Class C End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeWithTrivia_NewLine() { // With trivia, redundant newline at end of attribute removed. var input = @"' Comment 1 <System.Serializable> Class [|C|] End Class"; var expected = @"' Comment 1 Class C End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeWithMultipleAttributes() { // Multiple attributes. var input = @"' Comment 1 < System.Serializable , System.Flags> ' Comment 2 Class [|C|] End Class"; var expected = @"' Comment 1 <System.Flags> ' Comment 2 Class C End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void RemoveAttributeWithMultipleAttributeLists() { // Multiple attribute lists. var input = @"' Comment 1 < System.Serializable , System.Flags> ' Comment 2 <System.Obsolete> ' Comment 3 Class [|C|] End Class"; var expected = @"' Comment 1 <System.Flags> ' Comment 2 <System.Obsolete> ' Comment 3 Class C End Class"; TestRemoveAttribute<SyntaxNode>(input, expected, typeof(SerializableAttribute)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestUpdateModifiers() { var input = @"Public Shared Class [|C|] ' Comment 1 ' Comment 2 End Class"; var expected = @"Friend Partial NotInheritable Class C ' Comment 1 ' Comment 2 End Class"; var eol = VB.SyntaxFactory.EndOfLine(@"", elastic: false); var newModifiers = new[] { VB.SyntaxFactory.Token(VB.SyntaxKind.FriendKeyword).WithLeadingTrivia(eol) }.Concat( CreateModifierTokens(new DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.VisualBasic)); TestUpdateDeclaration<ClassStatementSyntax>(input, expected, modifiers: newModifiers); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestUpdateAccessibility() { var input = @"' Comment 0 Public Shared Class [|C|] ' Comment 1 ' Comment 2 End Class"; var expected = @"' Comment 0 Protected Friend Shared Class C ' Comment 1 ' Comment 2 End Class"; TestUpdateDeclaration<ClassStatementSyntax>(input, expected, accessibility: Accessibility.ProtectedOrFriend); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestUpdateDeclarationType() { var input = @" Public Shared Class C ' Comment 1 Public Shared Function [|F|]() As Char Return 0 End Function End Class"; var expected = @" Public Shared Class C ' Comment 1 Public Shared Function F() As Integer Return 0 End Function End Class"; TestUpdateDeclaration<MethodStatementSyntax>(input, expected, getType: GetTypeSymbol(typeof(int))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestUpdateDeclarationMembers() { var input = @" Public Shared Class [|C|] ' Comment 0 Public Shared {|RetainedMember:f|} As Integer ' Comment 1 Public Shared Function F() As Char Return 0 End Function End Class"; var expected = @" Public Shared Class C ' Comment 0 Public Shared f As Integer Public Shared f2 As Integer End Class"; var getField = CreateField(Accessibility.Public, new DeclarationModifiers(isStatic: true), typeof(int), "f2"); var getMembers = new List<Func<SemanticModel, ISymbol>>(); getMembers.Add(getField); TestUpdateDeclaration<ClassBlockSyntax>(input, expected, getNewMembers: getMembers); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)] public void SortModules() { var generationSource = "Public Class [|C|] \n End Class"; var initial = "Namespace [|N|] \n Module M \n End Module \n End Namespace"; var expected = "Namespace N \n Public Class C \n End Class \n Module M \n End Module \n End Namespace"; TestGenerateFromSourceSymbol(generationSource, initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)] public void SortOperators() { var generationSource = @" Namespace N Public Class [|C|] ' Unary operators Public Shared Operator IsFalse(other As C) As Boolean Return False End Operator Public Shared Operator IsTrue(other As C) As Boolean Return True End Operator Public Shared Operator Not(other As C) As C Return Nothing End Operator Public Shared Operator -(other As C) As C Return Nothing End Operator Public Shared Operator + (other As C) As C Return Nothing End Operator Public Shared Narrowing Operator CType(c As C) As Integer Return 0 End Operator ' Binary operators Public Shared Operator >= (a As C, b As C) As Boolean Return True End Operator Public Shared Operator <= (a As C, b As C) As Boolean Return True End Operator Public Shared Operator > (a As C, b As C) As Boolean Return True End Operator Public Shared Operator < (a As C, b As C) As Boolean Return True End Operator Public Shared Operator <> (a As C, b As C) As Boolean Return True End Operator Public Shared Operator = (a As C, b As C) As Boolean Return True End Operator Public Shared Operator >> (a As C, shift As Integer) As C Return Nothing End Operator Public Shared Operator << (a As C, shift As Integer) As C Return Nothing End Operator Public Shared Operator Xor(a As C, b As C) As C Return Nothing End Operator Public Shared Operator Or(a As C, b As C) As C Return Nothing End Operator Public Shared Operator And(a As C, b As C) As C Return Nothing End Operator Public Shared Operator Mod(a As C, b As C) As C Return Nothing End Operator Public Shared Operator Like (a As C, b As C) As C Return Nothing End Operator Public Shared Operator & (a As C, b As C) As C Return Nothing End Operator Public Shared Operator ^ (a As C, b As C) As C Return Nothing End Operator Public Shared Operator \ (a As C, b As C) As C Return Nothing End Operator Public Shared Operator / (a As C, b As C) As C Return Nothing End Operator Public Shared Operator *(a As C, b As C) As C Return Nothing End Operator Public Shared Operator -(a As C, b As C) As C Return Nothing End Operator Public Shared Operator + (a As C, b As C) As C Return Nothing End Operator End Class End Namespace"; var initial = "Namespace [|N|] \n End Namespace"; var expected = @" Namespace N Public Class C Public Shared Operator +(other As C) As C Public Shared Operator +(a As C, b As C) As C Public Shared Operator -(other As C) As C Public Shared Operator -(a As C, b As C) As C Public Shared Operator *(a As C, b As C) As C Public Shared Operator /(a As C, b As C) As C Public Shared Operator \(a As C, b As C) As C Public Shared Operator ^(a As C, b As C) As C Public Shared Operator &(a As C, b As C) As C Public Shared Operator Not(other As C) As C Public Shared Operator Like(a As C, b As C) As C Public Shared Operator Mod(a As C, b As C) As C Public Shared Operator And(a As C, b As C) As C Public Shared Operator Or(a As C, b As C) As C Public Shared Operator Xor(a As C, b As C) As C Public Shared Operator <<(a As C, shift As Integer) As C Public Shared Operator >>(a As C, shift As Integer) As C Public Shared Operator =(a As C, b As C) As Boolean Public Shared Operator <>(a As C, b As C) As Boolean Public Shared Operator >(a As C, b As C) As Boolean Public Shared Operator <(a As C, b As C) As Boolean Public Shared Operator >=(a As C, b As C) As Boolean Public Shared Operator <=(a As C, b As C) As Boolean Public Shared Operator IsTrue(other As C) As Boolean Public Shared Operator IsFalse(other As C) As Boolean Public Shared Narrowing Operator CType(c As C) As Integer End Class End Namespace"; TestGenerateFromSourceSymbol(generationSource, initial, expected, forceLanguage: LanguageNames.VisualBasic, codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false)); } [WorkItem(848357)] [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestConstraints() { var generationSource = @" Namespace N Public Class [|C|](Of T As Structure, U As Class) Public Sub Foo(Of Q As New, R As IComparable)() End Sub Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2) End Class End Namespace "; var initial = "Namespace [|N|] \n End Namespace"; var expected = @" Namespace N Public Class C(Of T As Structure, U As Class) Public Sub Foo(Of Q As New, R As IComparable)() Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2) End Class End Namespace "; TestGenerateFromSourceSymbol(generationSource, initial, expected, codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false), onlyGenerateMembers: true); } } } }
using System; using System.IO; using System.Linq; using System.Collections.Generic; using NUnit.Framework; using IO.Interfaces; namespace IO.Interfaces.Specs { [TestFixture] public class IDirectorySpec : Spec { // sample IFile implementation public class FileClass : IFileSpec.FileClass, IFile { public FileClass(string path) : base(path) {} } // sample IDirectory implementation public class DirClass : IDirectory { public DirClass(string path) { Path = path; } public string Path { get; set; } } string dir_1 = PathToTemp("base", "dir"); string dir_2 = PathToTemp("base", "other", "dir"); string[] AllDirectories { get { return Directory.GetDirectories(PathToTemp("base"), "*", SearchOption.AllDirectories); } } IDirectory Dir1Dir(string name) { return new DirClass(Path.Combine(dir_1, name)); } IDirectory Dir2Dir(string name) { return new DirClass(Path.Combine(dir_2, name)); } [SetUp] public void Before() { base.BeforeEach(); Directory.CreateDirectory(dir_1); Directory.CreateDirectory(dir_2); } [Test] public void Name() { Dir1Dir("foo").Name().ShouldEqual("foo"); Dir1Dir("bar/whatever").Name().ShouldEqual("whatever"); } [Test] public void Files() { var dir = Dir1Dir("foo").Create(); dir.Files().Should(Be.Empty); dir.GetFile("README").Touch(); dir.Files().ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir/foo/README") }); dir.GetDir("some/sub/dir").Create().GetFile("File.txt").Touch(); dir.Files().ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir/foo/README"), PathToTemp("base/dir/foo/some/sub/dir/File.txt") }); } [Test] public void Directories() { new Implementations.RealDirectory(PathToTemp("base")).Directories().ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir"), PathToTemp("base/other"), PathToTemp("base/other/dir"), }); new Implementations.RealDirectory(PathToTemp("base")).Dirs().ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir"), PathToTemp("base/other"), PathToTemp("base/other/dir"), }); } [Test] public void Search() { var dir = Dir1Dir("foo").Create(); dir.GetFile("index.html").Touch(); var stuff = dir.GetDir("stuff").Create(); stuff.GetFile("hi.html").Touch(); stuff.GetFile("foo.txt").Touch(); var another = stuff.GetDir("another").Create(); another.GetFile("hi.txt").Touch(); another.GetFile("more.html").Touch(); dir.Files().ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir/foo/index.html"), PathToTemp("base/dir/foo/stuff/foo.txt"), PathToTemp("base/dir/foo/stuff/hi.html"), PathToTemp("base/dir/foo/stuff/another/hi.txt"), PathToTemp("base/dir/foo/stuff/another/more.html") }); dir.Search("index.html").ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir/foo/index.html") }); dir.Search("*.html").ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir/foo/index.html") }); dir.Search("*/*.html").ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir/foo/stuff/hi.html") }); dir.Search("**/*.html").ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir/foo/stuff/hi.html"), PathToTemp("base/dir/foo/stuff/another/more.html") }); dir.Search("**.html").ToStrings().ShouldEqual(new List<string>{ PathToTemp("base/dir/foo/index.html"), PathToTemp("base/dir/foo/stuff/hi.html"), PathToTemp("base/dir/foo/stuff/another/more.html") }); } [Test] public void Create() { AllDirectories.Length.ShouldEqual(3); // the 2 base directories AllDirectories.ShouldContain(PathToTemp("base/dir")); AllDirectories.ShouldContain(PathToTemp("base/other")); AllDirectories.ShouldContain(PathToTemp("base/other/dir")); Dir1Dir("foo").Create(); AllDirectories.Length.ShouldEqual(4); AllDirectories.ShouldContain(PathToTemp("base/dir")); AllDirectories.ShouldContain(PathToTemp("base/dir/foo")); AllDirectories.ShouldContain(PathToTemp("base/other")); AllDirectories.ShouldContain(PathToTemp("base/other/dir")); Dir2Dir("sub/dir").Create(); AllDirectories.Length.ShouldEqual(6); AllDirectories.ShouldContain(PathToTemp("base/dir")); AllDirectories.ShouldContain(PathToTemp("base/dir/foo")); AllDirectories.ShouldContain(PathToTemp("base/other")); AllDirectories.ShouldContain(PathToTemp("base/other/dir")); AllDirectories.ShouldContain(PathToTemp("base/other/dir/sub")); AllDirectories.ShouldContain(PathToTemp("base/other/dir/sub/dir")); } [Test] public void Exists() { var dir = Dir1Dir("foo"); dir.Exists().Should(Be.False); dir.Create(); dir.Exists().Should(Be.True); } [Test] public void Copy() { // Make the directory to copy ... var dir = Dir1Dir("foo").Create(); dir.GetFile("FILE").Touch(); var subdir = dir.GetDir("subdir").Create(); subdir.GetFile("MyFile").Touch(); var subsubdir = subdir.GetDir("another").Create(); subsubdir.GetFile("w00t").Touch(); Directory.CreateDirectory(PathToTemp("base/other/dir/foo")); // <--- create new directory to copy into File.Exists(PathToTemp( "base/dir/foo/FILE" )).Should(Be.True); File.Exists(PathToTemp( "base/dir/foo/subdir/MyFile" )).Should(Be.True); File.Exists(PathToTemp( "base/dir/foo/subdir/another/w00t" )).Should(Be.True); Directory.Exists(PathToTemp( "base/other/dir/foo" )).Should(Be.True); // directory exists! File.Exists(PathToTemp( "base/other/dir/foo/FILE" )).Should(Be.False); // but content doesnt yet File.Exists(PathToTemp( "base/other/dir/foo/subdir/MyFile" )).Should(Be.False); File.Exists(PathToTemp( "base/other/dir/foo/subdir/another/w00t" )).Should(Be.False); // Copy to an existing directory. The directory is copied *into* the existing directory. dir.Copy(PathToTemp("base/other/dir")); File.Exists(PathToTemp( "base/dir/foo/FILE" )).Should(Be.True); // old files are STILL there File.Exists(PathToTemp( "base/dir/foo/subdir/MyFile" )).Should(Be.True); File.Exists(PathToTemp( "base/dir/foo/subdir/another/w00t" )).Should(Be.True); Directory.Exists(PathToTemp( "base/other/dir/foo" )).Should(Be.True); // directory exists! File.Exists(PathToTemp( "base/other/dir/foo/FILE" )).Should(Be.True); // and so does content File.Exists(PathToTemp( "base/other/dir/foo/subdir/MyFile" )).Should(Be.True); File.Exists(PathToTemp( "base/other/dir/foo/subdir/another/w00t" )).Should(Be.True); Directory.Exists(PathToTemp( "new" )).Should(Be.False); // new directory doesn't exist // Copy to a new directory. The directory is copied exactly there. dir.Copy(PathToTemp("new")); Directory.Exists(PathToTemp( "new" )).Should(Be.True); // new directory doesn't exist File.Exists(PathToTemp( "new/FILE" )).Should(Be.True); // old files are STILL there File.Exists(PathToTemp( "new/subdir/MyFile" )).Should(Be.True); File.Exists(PathToTemp( "new/subdir/another/w00t" )).Should(Be.True); File.Exists(PathToTemp( "base/dir/foo/subdir/another/w00t" )).Should(Be.True); // first directory still there File.Exists(PathToTemp( "base/other/dir/foo/subdir/another/w00t" )).Should(Be.True); // second directory still there } [Test] public void Move() { Directory.Exists(PathToTemp("base/dir/foo")).Should(Be.False); var dir = Dir1Dir("foo").Create(); dir.GetFile("FILE").Touch(); Directory.Exists(PathToTemp("base/dir/foo")).Should(Be.True); File.Exists(PathToTemp("base/dir/foo/FILE")).Should(Be.True); // move to existing directory moves it INTO directory Directory.Exists(PathToTemp("base/other/dir")).Should(Be.True); Directory.Exists(PathToTemp("base/other/dir/foo")).Should(Be.False); File.Exists(PathToTemp("base/other/dir/foo/FILE")).Should(Be.False); dir.Move(PathToTemp("base/other/dir")); Directory.Exists(PathToTemp("base/other/dir/foo")).Should(Be.True); // it moved INTO that dir File.Exists(PathToTemp("base/other/dir/foo/FILE")).Should(Be.True); Directory.Exists(PathToTemp("base/dir/foo")).Should(Be.False); // the original dir went away dir.Path.ShouldEqual(PathToTemp("base/other/dir/foo")); // the Path was updated // move to new directory, move it there Directory.Exists(PathToTemp("new")).Should(Be.False); dir.Move(PathToTemp("new")); Directory.Exists(PathToTemp("new")).Should(Be.True); File.Exists(PathToTemp("new/FILE")).Should(Be.True); Directory.Exists(PathToTemp("base/other/dir/foo")).Should(Be.False); // the last directory went away } [Test] public void Delete() { var dir = Dir1Dir("foo").Create(); dir.Exists().Should(Be.True); dir.Delete(); dir.Exists().Should(Be.False); } } }
// 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.Security.Principal.WindowsIdentity.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.Security.Principal { public partial class WindowsIdentity : IIdentity, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback, IDisposable { #region Methods and constructors public void Dispose() { } protected virtual new void Dispose(bool disposing) { } public static System.Security.Principal.WindowsIdentity GetAnonymous() { Contract.Ensures(Contract.Result<System.Security.Principal.WindowsIdentity>() != null); return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent(bool ifImpersonating) { return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess) { return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent() { return default(System.Security.Principal.WindowsIdentity); } public static WindowsImpersonationContext Impersonate(IntPtr userToken) { Contract.Ensures(Contract.Result<System.Security.Principal.WindowsImpersonationContext>() != null); return default(WindowsImpersonationContext); } public virtual new WindowsImpersonationContext Impersonate() { return default(WindowsImpersonationContext); } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(Object sender) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType) { } public WindowsIdentity(IntPtr userToken) { } public WindowsIdentity(IntPtr userToken, string type) { } public WindowsIdentity(string sUserPrincipalName, string type) { } public WindowsIdentity(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { Contract.Requires(info != null); } public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType, bool isAuthenticated) { } public WindowsIdentity(string sUserPrincipalName) { } #endregion #region Properties and indexers public string AuthenticationType { get { return default(string); } } public IdentityReferenceCollection Groups { get { return default(IdentityReferenceCollection); } } public TokenImpersonationLevel ImpersonationLevel { get { return default(TokenImpersonationLevel); } } public virtual new bool IsAnonymous { get { return default(bool); } } public virtual new bool IsAuthenticated { get { return default(bool); } } public virtual new bool IsGuest { get { return default(bool); } } public virtual new bool IsSystem { get { return default(bool); } } public virtual new string Name { get { return default(string); } } public SecurityIdentifier Owner { get { return default(SecurityIdentifier); } } public virtual new IntPtr Token { get { return default(IntPtr); } } public SecurityIdentifier User { get { return default(SecurityIdentifier); } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Provider; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; #pragma warning disable 1591 namespace Microsoft.WSMan.Management { #region "public Api" #region WsManEnumFlags /// <summary><para>_WSManEnumFlags enumeration.</para></summary> [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] [TypeLibType((short)0)] public enum WSManEnumFlags { /// <summary><para><c>WSManFlagNonXmlText</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 1.</para></summary> WSManFlagNonXmlText = 1, /// <summary><para><c>WSManFlagReturnObject</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 0.</para></summary> WSManFlagReturnObject = 0, /// <summary><para><c>WSManFlagReturnEPR</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 2.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] WSManFlagReturnEPR = 2, /// <summary><para><c>WSManFlagReturnObjectAndEPR</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 4.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] WSManFlagReturnObjectAndEPR = 4, /// <summary><para><c>WSManFlagHierarchyDeep</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 0.</para></summary> WSManFlagHierarchyDeep = 0, /// <summary><para><c>WSManFlagHierarchyShallow</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 32.</para></summary> WSManFlagHierarchyShallow = 32, /// <summary><para><c>WSManFlagHierarchyDeepBasePropsOnly</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 64.</para></summary> WSManFlagHierarchyDeepBasePropsOnly = 64, /// <summary><para><c>WSManFlagAssociationInstance </c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 64.</para></summary> WSManFlagAssociationInstance = 128 } #endregion WsManEnumFlags #region WsManSessionFlags /// <summary><para>WSManSessionFlags enumeration.</para></summary> [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] [TypeLibType((short)0)] public enum WSManSessionFlags { /// <summary><para><c>no flag</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1.</para></summary> WSManNone = 0, /// <summary><para><c>WSManFlagUTF8</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1.</para></summary> WSManFlagUtf8 = 1, /// <summary><para><c>WSManFlagCredUsernamePassword</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 4096.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] WSManFlagCredUserNamePassword = 4096, /// <summary><para><c>WSManFlagSkipCACheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 8192.</para></summary> WSManFlagSkipCACheck = 8192, /// <summary><para><c>WSManFlagSkipCNCheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 16384.</para></summary> WSManFlagSkipCNCheck = 16384, /// <summary><para><c>WSManFlagUseNoAuthentication</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 32768.</para></summary> WSManFlagUseNoAuthentication = 32768, /// <summary><para><c>WSManFlagUseDigest</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 65536.</para></summary> WSManFlagUseDigest = 65536, /// <summary><para><c>WSManFlagUseNegotiate</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 131072.</para></summary> WSManFlagUseNegotiate = 131072, /// <summary><para><c>WSManFlagUseBasic</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 262144.</para></summary> WSManFlagUseBasic = 262144, /// <summary><para><c>WSManFlagUseKerberos</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 524288.</para></summary> WSManFlagUseKerberos = 524288, /// <summary><para><c>WSManFlagNoEncryption</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1048576.</para></summary> WSManFlagNoEncryption = 1048576, /// <summary><para><c>WSManFlagEnableSPNServerPort</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 4194304.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Spn")] WSManFlagEnableSpnServerPort = 4194304, /// <summary><para><c>WSManFlagUTF16</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 8388608.</para></summary> WSManFlagUtf16 = 8388608, /// <summary><para><c>WSManFlagUseCredSsp</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 16777216.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ssp")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] WSManFlagUseCredSsp = 16777216, /// <summary><para><c>WSManFlagUseClientCertificate</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 2097152.</para></summary> WSManFlagUseClientCertificate = 2097152, /// <summary><para><c>WSManFlagSkipRevocationCheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 33554432.</para></summary> WSManFlagSkipRevocationCheck = 33554432, /// <summary><para><c>WSManFlagAllowNegotiateImplicitCredentials</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 67108864.</para></summary> WSManFlagAllowNegotiateImplicitCredentials = 67108864, /// <summary><para><c>WSManFlagUseSsl</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 134217728.</para></summary> WSManFlagUseSsl = 134217728 } #endregion WsManSessionFlags #region AuthenticationMechanism /// <summary>WSManEnumFlags enumeration</summary> [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] public enum AuthenticationMechanism { /// <summary> /// Use no authentication. /// </summary> None = 0x0, /// <summary> /// Use Default authentication. /// </summary> Default = 0x1, /// <summary> /// Use digest authentication for a remote operation. /// </summary> Digest = 0x2, /// <summary> /// Use negotiate authentication for a remote operation (may use kerberos or ntlm) /// </summary> Negotiate = 0x4, /// <summary> /// Use basic authentication for a remote operation. /// </summary> Basic = 0x8, /// <summary> /// Use kerberos authentication for a remote operation. /// </summary> Kerberos = 0x10, /// <summary> /// Use client certificate authentication for a remote operation. /// </summary> ClientCertificate = 0x20, /// <summary> /// Use CredSSP authentication for a remote operation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Credssp")] Credssp = 0x80, } #endregion AuthenticationMechanism #region IWsMan /// <summary><para><c>IWSMan</c> interface.</para></summary> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] [Guid("190D8637-5CD3-496D-AD24-69636BB5A3B5")] [ComImport] [TypeLibType((short)4304)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif public interface IWSMan { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>CreateSession</c> method of <c>IWSMan</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateSession</c> method was the following: <c>HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue); [DispId(1)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IUnknown)] object connectionOptions); #else [return: MarshalAs(UnmanagedType.IDispatch)] object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IDispatch)] object connectionOptions); #endif /// <summary><para><c>CreateConnectionOptions</c> method of <c>IWSMan</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateConnectionOptions</c> method was the following: <c>HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue); // [DispId(2)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] #else [return: MarshalAs(UnmanagedType.IDispatch)] #endif object CreateConnectionOptions(); /// <summary><para><c>CommandLine</c> property of <c>IWSMan</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks> // IDL: BSTR CommandLine; // string CommandLine { // IDL: HRESULT CommandLine ([out, retval] BSTR* ReturnValue); [DispId(3)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>Error</c> property of <c>IWSMan</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; // [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(4)] [return: MarshalAs(UnmanagedType.BStr)] get; } } #endregion IWsMan #region IWSManConnectionOptions /// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary> [Guid("F704E861-9E52-464F-B786-DA5EB2320FDD")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] public interface IWSManConnectionOptions { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>UserName</c> property of <c>IWSManConnectionOptions</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>UserName</c> property was the following: <c>BSTR UserName</c>;</para></remarks> // IDL: BSTR UserName; string UserName { // IDL: HRESULT UserName ([out, retval] BSTR* ReturnValue); [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] get; // IDL: HRESULT UserName (BSTR value); [DispId(1)] set; } /// <summary><para><c>Password</c> property of <c>IWSManConnectionOptions</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Password</c> property was the following: <c>BSTR Password</c>;</para></remarks> // IDL: BSTR Password; [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] string Password { // IDL: HRESULT Password (BSTR value); [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")] [DispId(2)] set; } } /// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary> [Guid("EF43EDF7-2A48-4d93-9526-8BD6AB6D4A6B")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public interface IWSManConnectionOptionsEx : IWSManConnectionOptions { /// <summary><para><c>CertificateThumbprint</c> property of <c>IWSManConnectionOptionsEx</c> interface.</para></summary> string CertificateThumbprint { [DispId(3)] [return: MarshalAs(UnmanagedType.BStr)] get; [DispId(1)] set; } } /// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary> [Guid("F500C9EC-24EE-48ab-B38D-FC9A164C658E")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif public interface IWSManConnectionOptionsEx2 : IWSManConnectionOptionsEx { /// <summary><para><c>SetProxy</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(4)] void SetProxy(int accessType, int authenticationMechanism, [In, MarshalAs(UnmanagedType.BStr)] string userName, [In, MarshalAs(UnmanagedType.BStr)] string password); /// <summary><para><c>ProxyIEConfig</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(5)] int ProxyIEConfig(); /// <summary><para><c>ProxyWinHttpConfig</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(6)] int ProxyWinHttpConfig(); /// <summary><para><c>ProxyAutoDetect</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(7)] int ProxyAutoDetect(); /// <summary><para><c>ProxyNoProxyServer</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(8)] int ProxyNoProxyServer(); /// <summary><para><c>ProxyAuthenticationUseNegotiate</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(9)] int ProxyAuthenticationUseNegotiate(); /// <summary><para><c>ProxyAuthenticationUseBasic</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(10)] int ProxyAuthenticationUseBasic(); /// <summary><para><c>ProxyAuthenticationUseDigest</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary> [DispId(11)] int ProxyAuthenticationUseDigest(); }; #endregion IWSManConnectionOptions #region IWSManEnumerator /// <summary><para><c>IWSManEnumerator</c> interface.</para></summary> [Guid("F3457CA9-ABB9-4FA5-B850-90E8CA300E7F")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif public interface IWSManEnumerator { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>ReadItem</c> method of <c>IWSManEnumerator</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>ReadItem</c> method was the following: <c>HRESULT ReadItem ([out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT ReadItem ([out, retval] BSTR* ReturnValue); [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] string ReadItem(); /// <summary><para><c>AtEndOfStream</c> property of <c>IWSManEnumerator</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>AtEndOfStream</c> property was the following: <c>BOOL AtEndOfStream</c>;</para></remarks> // IDL: BOOL AtEndOfStream; bool AtEndOfStream { // IDL: HRESULT AtEndOfStream ([out, retval] BOOL* ReturnValue); [DispId(2)] [return: MarshalAs(UnmanagedType.Bool)] get; } /// <summary><para><c>Error</c> property of <c>IWSManEnumerator</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(8)] [return: MarshalAs(UnmanagedType.BStr)] get; } } #endregion IWSManEnumerator #region IWSManEx /// <summary><para><c>IWSManEx</c> interface.</para></summary> [Guid("2D53BDAA-798E-49E6-A1AA-74D01256F411")] [ComImport] [TypeLibType((short)4304)] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "str")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] public interface IWSManEx { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>CreateSession</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateSession</c> method was the following: <c>HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateSession ([optional, defaultvalue(string.Empty)] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue); [DispId(1)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IUnknown)] object connectionOptions); #else [return: MarshalAs(UnmanagedType.IDispatch)] object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IDispatch)] object connectionOptions); #endif /// <summary><para><c>CreateConnectionOptions</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateConnectionOptions</c> method was the following: <c>HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue); [DispId(2)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] #else [return: MarshalAs(UnmanagedType.IDispatch)] #endif object CreateConnectionOptions(); /// <summary> /// </summary> /// <returns></returns> string CommandLine { // IDL: HRESULT CommandLine ([out, retval] BSTR* ReturnValue); [DispId(3)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>Error</c> property of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(4)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>CreateResourceLocator</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CreateResourceLocator</c> method was the following: <c>HRESULT CreateResourceLocator ([optional, defaultvalue(string.Empty)] BSTR strResourceLocator, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT CreateResourceLocator ([optional, defaultvalue(string.Empty)] BSTR strResourceLocator, [out, retval] IDispatch** ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "str")] [DispId(5)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] #else [return: MarshalAs(UnmanagedType.IDispatch)] #endif object CreateResourceLocator([MarshalAs(UnmanagedType.BStr)] string strResourceLocator); /// <summary><para><c>SessionFlagUTF8</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUTF8</c> method was the following: <c>HRESULT SessionFlagUTF8 ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUTF8 ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")] [DispId(6)] int SessionFlagUTF8(); /// <summary><para><c>SessionFlagCredUsernamePassword</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagCredUsernamePassword</c> method was the following: <c>HRESULT SessionFlagCredUsernamePassword ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagCredUsernamePassword ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [DispId(7)] int SessionFlagCredUsernamePassword(); /// <summary><para><c>SessionFlagSkipCACheck</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagSkipCACheck</c> method was the following: <c>HRESULT SessionFlagSkipCACheck ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagSkipCACheck ([out, retval] long* ReturnValue); [DispId(8)] int SessionFlagSkipCACheck(); /// <summary><para><c>SessionFlagSkipCNCheck</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagSkipCNCheck</c> method was the following: <c>HRESULT SessionFlagSkipCNCheck ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagSkipCNCheck ([out, retval] long* ReturnValue); [DispId(9)] int SessionFlagSkipCNCheck(); /// <summary><para><c>SessionFlagUseDigest</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseDigest</c> method was the following: <c>HRESULT SessionFlagUseDigest ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseDigest ([out, retval] long* ReturnValue); [DispId(10)] int SessionFlagUseDigest(); /// <summary><para><c>SessionFlagUseNegotiate</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseNegotiate</c> method was the following: <c>HRESULT SessionFlagUseNegotiate ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseNegotiate ([out, retval] long* ReturnValue); [DispId(11)] int SessionFlagUseNegotiate(); /// <summary><para><c>SessionFlagUseBasic</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseBasic</c> method was the following: <c>HRESULT SessionFlagUseBasic ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseBasic ([out, retval] long* ReturnValue); [DispId(12)] int SessionFlagUseBasic(); /// <summary><para><c>SessionFlagUseKerberos</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseKerberos</c> method was the following: <c>HRESULT SessionFlagUseKerberos ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseKerberos ([out, retval] long* ReturnValue); [DispId(13)] int SessionFlagUseKerberos(); /// <summary><para><c>SessionFlagNoEncryption</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagNoEncryption</c> method was the following: <c>HRESULT SessionFlagNoEncryption ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagNoEncryption ([out, retval] long* ReturnValue); [DispId(14)] int SessionFlagNoEncryption(); /// <summary><para><c>SessionFlagEnableSPNServerPort</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagEnableSPNServerPort</c> method was the following: <c>HRESULT SessionFlagEnableSPNServerPort ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagEnableSPNServerPort ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] [DispId(15)] int SessionFlagEnableSPNServerPort(); /// <summary><para><c>SessionFlagUseNoAuthentication</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>SessionFlagUseNoAuthentication</c> method was the following: <c>HRESULT SessionFlagUseNoAuthentication ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT SessionFlagUseNoAuthentication ([out, retval] long* ReturnValue); [DispId(16)] int SessionFlagUseNoAuthentication(); /// <summary><para><c>EnumerationFlagNonXmlText</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagNonXmlText</c> method was the following: <c>HRESULT EnumerationFlagNonXmlText ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagNonXmlText ([out, retval] long* ReturnValue); [DispId(17)] int EnumerationFlagNonXmlText(); /// <summary><para><c>EnumerationFlagReturnEPR</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnEPR</c> method was the following: <c>HRESULT EnumerationFlagReturnEPR ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagReturnEPR ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] [DispId(18)] int EnumerationFlagReturnEPR(); /// <summary><para><c>EnumerationFlagReturnObjectAndEPR</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnObjectAndEPR</c> method was the following: <c>HRESULT EnumerationFlagReturnObjectAndEPR ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagReturnObjectAndEPR ([out, retval] long* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")] [DispId(19)] int EnumerationFlagReturnObjectAndEPR(); /// <summary><para><c>GetErrorMessage</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>GetErrorMessage</c> method was the following: <c>HRESULT GetErrorMessage (unsigned long errorNumber, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT GetErrorMessage (unsigned long errorNumber, [out, retval] BSTR* ReturnValue); [DispId(20)] [return: MarshalAs(UnmanagedType.BStr)] string GetErrorMessage(uint errorNumber); /// <summary><para><c>EnumerationFlagHierarchyDeep</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyDeep</c> method was the following: <c>HRESULT EnumerationFlagHierarchyDeep ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagHierarchyDeep ([out, retval] long* ReturnValue); [DispId(21)] int EnumerationFlagHierarchyDeep(); /// <summary><para><c>EnumerationFlagHierarchyShallow</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyShallow</c> method was the following: <c>HRESULT EnumerationFlagHierarchyShallow ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagHierarchyShallow ([out, retval] long* ReturnValue); [DispId(22)] int EnumerationFlagHierarchyShallow(); /// <summary><para><c>EnumerationFlagHierarchyDeepBasePropsOnly</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyDeepBasePropsOnly</c> method was the following: <c>HRESULT EnumerationFlagHierarchyDeepBasePropsOnly ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagHierarchyDeepBasePropsOnly ([out, retval] long* ReturnValue); [DispId(23)] int EnumerationFlagHierarchyDeepBasePropsOnly(); /// <summary><para><c>EnumerationFlagReturnObject</c> method of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnObject</c> method was the following: <c>HRESULT EnumerationFlagReturnObject ([out, retval] long* ReturnValue)</c>;</para></remarks> // IDL: HRESULT EnumerationFlagReturnObject ([out, retval] long* ReturnValue); [DispId(24)] int EnumerationFlagReturnObject(); /// <summary><para><c>CommandLine</c> property of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks> // IDL: BSTR CommandLine; [DispId(28)] int EnumerationFlagAssociationInstance(); /// <summary><para><c>CommandLine</c> property of <c>IWSManEx</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks> // IDL: BSTR CommandLine; [DispId(29)] int EnumerationFlagAssociatedInstance(); } #endregion IWsManEx #region IWsManResourceLocator /// <summary><para><c>IWSManResourceLocator</c> interface.</para></summary> [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sel")] [Guid("A7A1BA28-DE41-466A-AD0A-C4059EAD7428")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif public interface IWSManResourceLocator { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>resourceUri</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Set the resource URI. Must contain path only -- query string is not allowed here.</para></summary> /// <remarks><para>An original IDL definition of <c>resourceUri</c> property was the following: <c>BSTR resourceUri</c>;</para></remarks> // Set the resource URI. Must contain path only -- query string is not allowed here. // IDL: BSTR resourceUri; [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] string ResourceUri { // IDL: HRESULT resourceUri (BSTR value); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] [DispId(1)] set; // IDL: HRESULT resourceUri ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>AddSelector</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Add selector to resource locator</para></summary> /// <remarks><para>An original IDL definition of <c>AddSelector</c> method was the following: <c>HRESULT AddSelector (BSTR resourceSelName, VARIANT selValue)</c>;</para></remarks> // Add selector to resource locator // IDL: HRESULT AddSelector (BSTR resourceSelName, VARIANT selValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "sel")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sel")] [DispId(2)] void AddSelector([MarshalAs(UnmanagedType.BStr)] string resourceSelName, object selValue); /// <summary><para><c>ClearSelectors</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Clear all selectors</para></summary> /// <remarks><para>An original IDL definition of <c>ClearSelectors</c> method was the following: <c>HRESULT ClearSelectors (void)</c>;</para></remarks> // Clear all selectors // IDL: HRESULT ClearSelectors (void); [DispId(3)] void ClearSelectors(); /// <summary><para><c>FragmentPath</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Gets the fragment path</para></summary> /// <remarks><para>An original IDL definition of <c>FragmentPath</c> property was the following: <c>BSTR FragmentPath</c>;</para></remarks> // Gets the fragment path // IDL: BSTR FragmentPath; string FragmentPath { // IDL: HRESULT FragmentPath ([out, retval] BSTR* ReturnValue); [DispId(4)] [return: MarshalAs(UnmanagedType.BStr)] get; // IDL: HRESULT FragmentPath (BSTR value); [DispId(4)] set; } /// <summary><para><c>FragmentDialect</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Gets the Fragment dialect</para></summary> /// <remarks><para>An original IDL definition of <c>FragmentDialect</c> property was the following: <c>BSTR FragmentDialect</c>;</para></remarks> // Gets the Fragment dialect // IDL: BSTR FragmentDialect; string FragmentDialect { // IDL: HRESULT FragmentDialect ([out, retval] BSTR* ReturnValue); [DispId(5)] [return: MarshalAs(UnmanagedType.BStr)] get; // IDL: HRESULT FragmentDialect (BSTR value); [DispId(5)] set; } /// <summary><para><c>AddOption</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Add option to resource locator</para></summary> /// <remarks><para>An original IDL definition of <c>AddOption</c> method was the following: <c>HRESULT AddOption (BSTR OptionName, VARIANT OptionValue, [optional, defaultvalue(0)] long mustComply)</c>;</para></remarks> // Add option to resource locator // IDL: HRESULT AddOption (BSTR OptionName, VARIANT OptionValue, [optional, defaultvalue(0)] long mustComply); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Option")] [DispId(6)] void AddOption([MarshalAs(UnmanagedType.BStr)] string OptionName, object OptionValue, int mustComply); /// <summary><para><c>MustUnderstandOptions</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Sets the MustUnderstandOptions value</para></summary> /// <remarks><para>An original IDL definition of <c>MustUnderstandOptions</c> property was the following: <c>long MustUnderstandOptions</c>;</para></remarks> // Sets the MustUnderstandOptions value // IDL: long MustUnderstandOptions; int MustUnderstandOptions { // IDL: HRESULT MustUnderstandOptions ([out, retval] long* ReturnValue); [DispId(7)] get; // IDL: HRESULT MustUnderstandOptions (long value); [DispId(7)] set; } /// <summary><para><c>ClearOptions</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Clear all options</para></summary> /// <remarks><para>An original IDL definition of <c>ClearOptions</c> method was the following: <c>HRESULT ClearOptions (void)</c>;</para></remarks> // Clear all options // IDL: HRESULT ClearOptions (void); [DispId(8)] void ClearOptions(); /// <summary><para><c>Error</c> property of <c>IWSManResourceLocator</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(9)] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [return: MarshalAs(UnmanagedType.BStr)] get; } } #endregion IWsManResourceLocator #region IWSManSession /// <summary><para><c>IWSManSession</c> interface.</para></summary> [Guid("FC84FC58-1286-40C4-9DA0-C8EF6EC241E0")] [ComImport] [TypeLibType((short)4288)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public interface IWSManSession { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif /// <summary><para><c>Get</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Get</c> method was the following: <c>HRESULT Get (VARIANT resourceUri, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT Get (VARIANT resourceUri, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] string Get(object resourceUri, int flags); /// <summary><para><c>Put</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Put</c> method was the following: <c>HRESULT Put (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT Put (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); [DispId(2)] [return: MarshalAs(UnmanagedType.BStr)] string Put(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string resource, int flags); /// <summary><para><c>Create</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Create</c> method was the following: <c>HRESULT Create (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT Create (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); [DispId(3)] [return: MarshalAs(UnmanagedType.BStr)] string Create(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string resource, int flags); /// <summary><para><c>Delete</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Delete</c> method was the following: <c>HRESULT Delete (VARIANT resourceUri, [optional, defaultvalue(0)] long flags)</c>;</para></remarks> // IDL: HRESULT Delete (VARIANT resourceUri, [optional, defaultvalue(0)] long flags); [DispId(4)] void Delete(object resourceUri, int flags); /// <summary> /// </summary> /// <param name="actionURI"></param> /// <param name="resourceUri"></param> /// <param name="parameters"></param> /// <param name="flags"></param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] [DispId(5)] string Invoke([MarshalAs(UnmanagedType.BStr)] string actionURI, [In] object resourceUri, [MarshalAs(UnmanagedType.BStr)] string parameters, [In] int flags); /// <summary><para><c>Enumerate</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Enumerate</c> method was the following: <c>HRESULT Enumerate (VARIANT resourceUri, [optional, defaultvalue(string.Empty)] BSTR filter, [optional, defaultvalue(string.Empty)] BSTR dialect, [optional, defaultvalue(0)] long flags, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks> // IDL: HRESULT Enumerate (VARIANT resourceUri, [optional, defaultvalue(string.Empty)] BSTR filter, [optional, defaultvalue(string.Empty)] BSTR dialect, [optional, defaultvalue(0)] long flags, [out, retval] IDispatch** ReturnValue); [DispId(6)] #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] #else [return: MarshalAs(UnmanagedType.IDispatch)] #endif object Enumerate(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string filter, [MarshalAs(UnmanagedType.BStr)] string dialect, int flags); /// <summary><para><c>Identify</c> method of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Identify</c> method was the following: <c>HRESULT Identify ([optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks> // IDL: HRESULT Identify ([optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue); [DispId(7)] [return: MarshalAs(UnmanagedType.BStr)] string Identify(int flags); /// <summary><para><c>Error</c> property of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks> // IDL: BSTR Error; [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] string Error { // IDL: HRESULT Error ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")] [DispId(8)] [return: MarshalAs(UnmanagedType.BStr)] get; } /// <summary><para><c>BatchItems</c> property of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>BatchItems</c> property was the following: <c>long BatchItems</c>;</para></remarks> // IDL: long BatchItems; int BatchItems { // IDL: HRESULT BatchItems ([out, retval] long* ReturnValue); [DispId(9)] get; // IDL: HRESULT BatchItems (long value); [DispId(9)] set; } /// <summary><para><c>Timeout</c> property of <c>IWSManSession</c> interface.</para></summary> /// <remarks><para>An original IDL definition of <c>Timeout</c> property was the following: <c>long Timeout</c>;</para></remarks> // IDL: long Timeout; int Timeout { // IDL: HRESULT Timeout ([out, retval] long* ReturnValue); [DispId(10)] get; // IDL: HRESULT Timeout (long value); [DispId(10)] set; } } #endregion IWSManSession #region IWSManResourceLocatorInternal /// <summary><para><c>IWSManResourceLocatorInternal</c> interface.</para></summary> [Guid("EFFAEAD7-7EC8-4716-B9BE-F2E7E9FB4ADB")] [ComImport] [TypeLibType((short)400)] #if CORECLR [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] public interface IWSManResourceLocatorInternal { #if CORECLR [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetTypeInfo(); [return: MarshalAs(UnmanagedType.IUnknown)] object GetIDsOfNames(); [return: MarshalAs(UnmanagedType.IUnknown)] object Invoke(); #endif } #endregion IWSManResourceLocatorInternal /// <summary><para><c>WSMan</c> interface.</para></summary> [Guid("BCED617B-EC03-420b-8508-977DC7A686BD")] [ComImport] #if CORECLR [ClassInterface(ClassInterfaceType.None)] #else [ClassInterface(ClassInterfaceType.AutoDual)] #endif public class WSManClass { } #region IGroupPolicyObject /// <summary><para><c>GPClass</c> interface.</para></summary> [Guid("EA502722-A23D-11d1-A7D3-0000F87571E3")] [ComImport] [ClassInterface(ClassInterfaceType.None)] public class GPClass { } [ComImport, Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IGroupPolicyObject { void New( [MarshalAs(UnmanagedType.LPWStr)] string pszDomainName, [MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, uint dwFlags); void OpenDSGPO( [MarshalAs(UnmanagedType.LPWStr)] string pszPath, uint dwFlags); void OpenLocalMachineGPO(uint dwFlags); void OpenRemoteMachineGPO( [MarshalAs(UnmanagedType.LPWStr)] string pszComputerName, uint dwFlags); void Save( [MarshalAs(UnmanagedType.Bool)] bool bMachine, [MarshalAs(UnmanagedType.Bool)] bool bAdd, [MarshalAs(UnmanagedType.LPStruct)] Guid pGuidExtension, [MarshalAs(UnmanagedType.LPStruct)] Guid pGuid); void Delete(); void GetName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxLength); void GetDisplayName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxLength); void SetDisplayName( [MarshalAs(UnmanagedType.LPWStr)] string pszName); void GetPath( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, int cchMaxPath); void GetDSPath( uint dwSection, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, int cchMaxPath); void GetFileSysPath( uint dwSection, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath, int cchMaxPath); IntPtr GetRegistryKey(uint dwSection); uint GetOptions(); void SetOptions(uint dwOptions, uint dwMask); void GetMachineName( [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxLength); uint GetPropertySheetPages(out IntPtr hPages); } #endregion IGroupPolicyObject /// <summary><para><c>GpoNativeApi</c></para></summary> public sealed class GpoNativeApi { private GpoNativeApi() { } [DllImport("Userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern System.IntPtr EnterCriticalPolicySection( [In, MarshalAs(UnmanagedType.Bool)] bool bMachine); [DllImport("Userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LeaveCriticalPolicySection( [In] System.IntPtr hSection); } #endregion } #pragma warning restore 1591
// 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.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { /// <summary> /// Async thin tagger implementation. /// /// Actual tag information is stored in TagSource and shared between multiple taggers created for same views or buffers. /// /// It's responsibility is on interaction between host and tagger. TagSource has responsibility on how to provide information for this tagger. /// </summary> internal sealed partial class AsynchronousTagger<TTag> : ITagger<TTag>, IDisposable where TTag : ITag { private const int MaxNumberOfRequestedSpans = 100; #region Fields that can be accessed from either thread private readonly ITextBuffer _subjectBuffer; private readonly TagSource<TTag> _tagSource; private readonly int _uiUpdateDelayInMS; #endregion #region Fields that can only be accessed from the foreground thread /// <summary> /// The batch change notifier that we use to throttle update to the UI. /// </summary> private readonly BatchChangeNotifier _batchChangeNotifier; #endregion public event EventHandler<SnapshotSpanEventArgs> TagsChanged; public AsynchronousTagger( IAsynchronousOperationListener listener, IForegroundNotificationService notificationService, TagSource<TTag> tagSource, ITextBuffer subjectBuffer, TimeSpan uiUpdateDelay) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; _uiUpdateDelayInMS = (int)uiUpdateDelay.TotalMilliseconds; _batchChangeNotifier = new BatchChangeNotifier(subjectBuffer, listener, notificationService, ReportChangedSpan); _tagSource = tagSource; _tagSource.OnTaggerAdded(this); _tagSource.TagsChangedForBuffer += OnTagsChangedForBuffer; _tagSource.Paused += OnPaused; _tagSource.Resumed += OnResumed; } public void Dispose() { _tagSource.Resumed -= OnResumed; _tagSource.Paused -= OnPaused; _tagSource.TagsChangedForBuffer -= OnTagsChangedForBuffer; _tagSource.OnTaggerDisposed(this); } private void ReportChangedSpan(SnapshotSpan changeSpan) { var tagsChanged = TagsChanged; if (tagsChanged != null) { tagsChanged(this, new SnapshotSpanEventArgs(changeSpan)); } } private void OnPaused(object sender, EventArgs e) { _batchChangeNotifier.Pause(); } private void OnResumed(object sender, EventArgs e) { _batchChangeNotifier.Resume(); } private void OnTagsChangedForBuffer(object sender, TagsChangedForBufferEventArgs args) { if (args.Buffer != _subjectBuffer) { return; } // Note: This operation is uncancellable. Once we've been notified here, our cached tags // in the tag source are new. If we don't update the UI of the editor then we will end // up in an inconsistent state between us and the editor where we have new tags but the // editor will never know. var spansChanged = args.Spans; _tagSource.RegisterNotification(() => { _tagSource.WorkQueue.AssertIsForeground(); // Now report them back to the UI on the main thread. _batchChangeNotifier.EnqueueChanges(spansChanged.First().Snapshot, spansChanged); }, _uiUpdateDelayInMS, CancellationToken.None); } public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans) { if (requestedSpans.Count == 0) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } var buffer = requestedSpans.First().Snapshot.TextBuffer; var tags = _tagSource.GetTagIntervalTreeForBuffer(buffer); if (tags == null) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } var result = GetTags(requestedSpans, tags); DebugVerifyTags(requestedSpans, result); return result; } private static IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans, ITagSpanIntervalTree<TTag> tags) { // Special case the case where there is only one requested span. In that case, we don't // need to allocate any intermediate collections return requestedSpans.Count == 1 ? tags.GetIntersectingSpans(requestedSpans[0]) : requestedSpans.Count < MaxNumberOfRequestedSpans ? GetTagsForSmallNumberOfSpans(requestedSpans, tags) : GetTagsForLargeNumberOfSpans(requestedSpans, tags); } private static IEnumerable<ITagSpan<TTag>> GetTagsForSmallNumberOfSpans( NormalizedSnapshotSpanCollection requestedSpans, ITagSpanIntervalTree<TTag> tags) { var result = new List<ITagSpan<TTag>>(); foreach (var s in requestedSpans) { result.AddRange(tags.GetIntersectingSpans(s)); } return result; } private static IEnumerable<ITagSpan<TTag>> GetTagsForLargeNumberOfSpans( NormalizedSnapshotSpanCollection requestedSpans, ITagSpanIntervalTree<TTag> tags) { // we are asked with bunch of spans. rather than asking same question again and again, ask once with big span // which will return superset of what we want. and then filter them out in O(m+n) cost. // m == number of requested spans, n = number of returned spans var mergedSpan = new SnapshotSpan(requestedSpans[0].Start, requestedSpans[requestedSpans.Count - 1].End); var result = tags.GetIntersectingSpans(mergedSpan); int requestIndex = 0; var enumerator = result.GetEnumerator(); try { if (!enumerator.MoveNext()) { return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } var hashSet = new HashSet<ITagSpan<TTag>>(); while (true) { var currentTag = enumerator.Current; var currentRequestSpan = requestedSpans[requestIndex]; var currentTagSpan = currentTag.Span; if (currentRequestSpan.Start > currentTagSpan.End) { if (!enumerator.MoveNext()) { break; } } else if (currentTagSpan.Start > currentRequestSpan.End) { requestIndex++; if (requestIndex >= requestedSpans.Count) { break; } } else { if (currentTagSpan.Length > 0) { hashSet.Add(currentTag); } if (!enumerator.MoveNext()) { break; } } } return hashSet; } finally { enumerator.Dispose(); } } [Conditional("DEBUG")] private static void DebugVerifyTags(NormalizedSnapshotSpanCollection requestedSpans, IEnumerable<ITagSpan<TTag>> tags) { if (tags == null) { return; } foreach (var tag in tags) { var span = tag.Span; if (!requestedSpans.Any(s => s.IntersectsWith(span))) { Contract.Fail(tag + " doesn't intersects with any requested span"); } } } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using pb = Google.Protobuf; using pbwkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Dialogflow.V2 { /// <summary> /// Settings for a <see cref="SessionsClient"/>. /// </summary> public sealed partial class SessionsSettings : gaxgrpc::ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="SessionsSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="SessionsSettings"/>. /// </returns> public static SessionsSettings GetDefault() => new SessionsSettings(); /// <summary> /// Constructs a new <see cref="SessionsSettings"/> object with default settings. /// </summary> public SessionsSettings() { } private SessionsSettings(SessionsSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); DetectIntentSettings = existing.DetectIntentSettings; StreamingDetectIntentSettings = existing.StreamingDetectIntentSettings; StreamingDetectIntentStreamingSettings = existing.StreamingDetectIntentStreamingSettings; OnCopy(existing); } partial void OnCopy(SessionsSettings existing); /// <summary> /// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="SessionsClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="grpccore::StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="SessionsClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="grpccore::StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="SessionsClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="SessionsClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="SessionsClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(100), maxDelay: sys::TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="SessionsClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="SessionsClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="SessionsClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 20000 milliseconds</description></item> /// </list> /// </remarks> public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(20000), maxDelay: sys::TimeSpan.FromMilliseconds(20000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>SessionsClient.DetectIntent</c> and <c>SessionsClient.DetectIntentAsync</c>. /// </summary> /// <remarks> /// The default <c>SessionsClient.DetectIntent</c> and /// <c>SessionsClient.DetectIntentAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public gaxgrpc::CallSettings DetectIntentSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for calls to <c>SessionsClient.StreamingDetectIntent</c>. /// </summary> /// <remarks> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public gaxgrpc::CallSettings StreamingDetectIntentSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))); /// <summary> /// <see cref="gaxgrpc::BidirectionalStreamingSettings"/> for calls to /// <c>SessionsClient.StreamingDetectIntent</c>. /// </summary> /// <remarks> /// The default local send queue size is 100. /// </remarks> public gaxgrpc::BidirectionalStreamingSettings StreamingDetectIntentStreamingSettings { get; set; } = new gaxgrpc::BidirectionalStreamingSettings(100); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="SessionsSettings"/> object.</returns> public SessionsSettings Clone() => new SessionsSettings(this); } /// <summary> /// Sessions client wrapper, for convenient use. /// </summary> public abstract partial class SessionsClient { /// <summary> /// The default endpoint for the Sessions service, which is a host of "dialogflow.googleapis.com" and a port of 443. /// </summary> public static gaxgrpc::ServiceEndpoint DefaultEndpoint { get; } = new gaxgrpc::ServiceEndpoint("dialogflow.googleapis.com", 443); /// <summary> /// The default Sessions scopes. /// </summary> /// <remarks> /// The default Sessions scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); private static readonly gaxgrpc::ChannelPool s_channelPool = new gaxgrpc::ChannelPool(DefaultScopes); /// <summary> /// Asynchronously creates a <see cref="SessionsClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. See the example for how to use custom credentials. /// </summary> /// <example> /// This sample shows how to create a client using default credentials: /// <code> /// using Google.Cloud.Dialogflow.V2; /// ... /// // When running on Google Cloud Platform this will use the project Compute Credential. /// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON /// // credential file to use that credential. /// SessionsClient client = await SessionsClient.CreateAsync(); /// </code> /// This sample shows how to create a client using credentials loaded from a JSON file: /// <code> /// using Google.Cloud.Dialogflow.V2; /// using Google.Apis.Auth.OAuth2; /// using Grpc.Auth; /// using Grpc.Core; /// ... /// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json"); /// Channel channel = new Channel( /// SessionsClient.DefaultEndpoint.Host, SessionsClient.DefaultEndpoint.Port, cred.ToChannelCredentials()); /// SessionsClient client = SessionsClient.Create(channel); /// ... /// // Shutdown the channel when it is no longer required. /// await channel.ShutdownAsync(); /// </code> /// </example> /// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="SessionsSettings"/>.</param> /// <returns>The task representing the created <see cref="SessionsClient"/>.</returns> public static async stt::Task<SessionsClient> CreateAsync(gaxgrpc::ServiceEndpoint endpoint = null, SessionsSettings settings = null) { grpccore::Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="SessionsClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. See the example for how to use custom credentials. /// </summary> /// <example> /// This sample shows how to create a client using default credentials: /// <code> /// using Google.Cloud.Dialogflow.V2; /// ... /// // When running on Google Cloud Platform this will use the project Compute Credential. /// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON /// // credential file to use that credential. /// SessionsClient client = SessionsClient.Create(); /// </code> /// This sample shows how to create a client using credentials loaded from a JSON file: /// <code> /// using Google.Cloud.Dialogflow.V2; /// using Google.Apis.Auth.OAuth2; /// using Grpc.Auth; /// using Grpc.Core; /// ... /// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json"); /// Channel channel = new Channel( /// SessionsClient.DefaultEndpoint.Host, SessionsClient.DefaultEndpoint.Port, cred.ToChannelCredentials()); /// SessionsClient client = SessionsClient.Create(channel); /// ... /// // Shutdown the channel when it is no longer required. /// channel.ShutdownAsync().Wait(); /// </code> /// </example> /// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="SessionsSettings"/>.</param> /// <returns>The created <see cref="SessionsClient"/>.</returns> public static SessionsClient Create(gaxgrpc::ServiceEndpoint endpoint = null, SessionsSettings settings = null) { grpccore::Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="SessionsClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="grpccore::Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="SessionsSettings"/>.</param> /// <returns>The created <see cref="SessionsClient"/>.</returns> public static SessionsClient Create(grpccore::Channel channel, SessionsSettings settings = null) { gax::GaxPreconditions.CheckNotNull(channel, nameof(channel)); return Create(new grpccore::DefaultCallInvoker(channel), settings); } /// <summary> /// Creates a <see cref="SessionsClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker">The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="SessionsSettings"/>.</param> /// <returns>The created <see cref="SessionsClient"/>.</returns> public static SessionsClient Create(grpccore::CallInvoker callInvoker, SessionsSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpccore::Interceptors.Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpccore::Interceptors.CallInvokerExtensions.Intercept(callInvoker, interceptor); } Sessions.SessionsClient grpcClient = new Sessions.SessionsClient(callInvoker); return new SessionsClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(gaxgrpc::ServiceEndpoint, SessionsSettings)"/> /// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, SessionsSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(gaxgrpc::ServiceEndpoint, SessionsSettings)"/> /// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, SessionsSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC Sessions client. /// </summary> public virtual Sessions.SessionsClient GrpcClient { get { throw new sys::NotImplementedException(); } } /// <summary> /// Processes a natural language query and returns structured, actionable data /// as a result. This method is not idempotent, because it may cause contexts /// and session entity types to be updated, which in turn might affect /// results of future queries. /// </summary> /// <param name="session"> /// Required. The name of the session this query is sent to. Format: /// `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;`. It's up to the API /// caller to choose an appropriate session ID. It can be a random number or /// some type of user identifier (preferably hashed). The length of the session /// ID must not exceed 36 bytes. /// </param> /// <param name="queryInput"> /// Required. The input specification. It can be set to: /// /// 1. an audio config /// which instructs the speech recognizer how to process the speech audio, /// /// 2. a conversational query in the form of text, or /// /// 3. an event that specifies which intent to trigger. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<DetectIntentResponse> DetectIntentAsync( SessionName session, QueryInput queryInput, gaxgrpc::CallSettings callSettings = null) => DetectIntentAsync( new DetectIntentRequest { SessionAsSessionName = gax::GaxPreconditions.CheckNotNull(session, nameof(session)), QueryInput = gax::GaxPreconditions.CheckNotNull(queryInput, nameof(queryInput)), }, callSettings); /// <summary> /// Processes a natural language query and returns structured, actionable data /// as a result. This method is not idempotent, because it may cause contexts /// and session entity types to be updated, which in turn might affect /// results of future queries. /// </summary> /// <param name="session"> /// Required. The name of the session this query is sent to. Format: /// `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;`. It's up to the API /// caller to choose an appropriate session ID. It can be a random number or /// some type of user identifier (preferably hashed). The length of the session /// ID must not exceed 36 bytes. /// </param> /// <param name="queryInput"> /// Required. The input specification. It can be set to: /// /// 1. an audio config /// which instructs the speech recognizer how to process the speech audio, /// /// 2. a conversational query in the form of text, or /// /// 3. an event that specifies which intent to trigger. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<DetectIntentResponse> DetectIntentAsync( SessionName session, QueryInput queryInput, st::CancellationToken cancellationToken) => DetectIntentAsync( session, queryInput, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Processes a natural language query and returns structured, actionable data /// as a result. This method is not idempotent, because it may cause contexts /// and session entity types to be updated, which in turn might affect /// results of future queries. /// </summary> /// <param name="session"> /// Required. The name of the session this query is sent to. Format: /// `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;`. It's up to the API /// caller to choose an appropriate session ID. It can be a random number or /// some type of user identifier (preferably hashed). The length of the session /// ID must not exceed 36 bytes. /// </param> /// <param name="queryInput"> /// Required. The input specification. It can be set to: /// /// 1. an audio config /// which instructs the speech recognizer how to process the speech audio, /// /// 2. a conversational query in the form of text, or /// /// 3. an event that specifies which intent to trigger. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual DetectIntentResponse DetectIntent( SessionName session, QueryInput queryInput, gaxgrpc::CallSettings callSettings = null) => DetectIntent( new DetectIntentRequest { SessionAsSessionName = gax::GaxPreconditions.CheckNotNull(session, nameof(session)), QueryInput = gax::GaxPreconditions.CheckNotNull(queryInput, nameof(queryInput)), }, callSettings); /// <summary> /// Processes a natural language query and returns structured, actionable data /// as a result. This method is not idempotent, because it may cause contexts /// and session entity types to be updated, which in turn might affect /// results of future queries. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<DetectIntentResponse> DetectIntentAsync( DetectIntentRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Processes a natural language query and returns structured, actionable data /// as a result. This method is not idempotent, because it may cause contexts /// and session entity types to be updated, which in turn might affect /// results of future queries. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<DetectIntentResponse> DetectIntentAsync( DetectIntentRequest request, st::CancellationToken cancellationToken) => DetectIntentAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Processes a natural language query and returns structured, actionable data /// as a result. This method is not idempotent, because it may cause contexts /// and session entity types to be updated, which in turn might affect /// results of future queries. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual DetectIntentResponse DetectIntent( DetectIntentRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Processes a natural language query in audio format in a streaming fashion /// and returns structured, actionable data as a result. This method is only /// available via the gRPC API (not REST). /// </summary> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <param name="streamingSettings"> /// If not null, applies streaming overrides to this RPC call. /// </param> /// <returns> /// The client-server stream. /// </returns> public virtual StreamingDetectIntentStream StreamingDetectIntent( gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Bidirectional streaming methods for <c>StreamingDetectIntent</c>. /// </summary> public abstract partial class StreamingDetectIntentStream : gaxgrpc::BidirectionalStreamingBase<StreamingDetectIntentRequest, StreamingDetectIntentResponse> { } } /// <summary> /// Sessions client wrapper implementation, for convenient use. /// </summary> public sealed partial class SessionsClientImpl : SessionsClient { private readonly gaxgrpc::ApiCall<DetectIntentRequest, DetectIntentResponse> _callDetectIntent; private readonly gaxgrpc::ApiBidirectionalStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> _callStreamingDetectIntent; /// <summary> /// Constructs a client wrapper for the Sessions service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="SessionsSettings"/> used within this client </param> public SessionsClientImpl(Sessions.SessionsClient grpcClient, SessionsSettings settings) { GrpcClient = grpcClient; SessionsSettings effectiveSettings = settings ?? SessionsSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callDetectIntent = clientHelper.BuildApiCall<DetectIntentRequest, DetectIntentResponse>( GrpcClient.DetectIntentAsync, GrpcClient.DetectIntent, effectiveSettings.DetectIntentSettings); _callStreamingDetectIntent = clientHelper.BuildApiCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse>( GrpcClient.StreamingDetectIntent, effectiveSettings.StreamingDetectIntentSettings, effectiveSettings.StreamingDetectIntentStreamingSettings); Modify_ApiCall(ref _callDetectIntent); Modify_DetectIntentApiCall(ref _callDetectIntent); Modify_ApiCall(ref _callStreamingDetectIntent); Modify_StreamingDetectIntentApiCall(ref _callStreamingDetectIntent); OnConstruction(grpcClient, effectiveSettings, clientHelper); } // Partial methods are named to (mostly) ensure there cannot be conflicts with RPC method names. // Partial methods called for every ApiCall on construction. // Allows modification of all the underlying ApiCall objects. partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, pb::IMessage<TRequest> where TResponse : class, pb::IMessage<TResponse>; partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiBidirectionalStreamingCall<TRequest, TResponse> call) where TRequest : class, pb::IMessage<TRequest> where TResponse : class, pb::IMessage<TResponse>; // Partial methods called for each ApiCall on construction. // Allows per-RPC-method modification of the underlying ApiCall object. partial void Modify_DetectIntentApiCall(ref gaxgrpc::ApiCall<DetectIntentRequest, DetectIntentResponse> call); partial void Modify_StreamingDetectIntentApiCall(ref gaxgrpc::ApiBidirectionalStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> call); partial void OnConstruction(Sessions.SessionsClient grpcClient, SessionsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary> /// The underlying gRPC Sessions client. /// </summary> public override Sessions.SessionsClient GrpcClient { get; } // Partial methods called on each request. // Allows per-RPC-call modification to the request and CallSettings objects, // before the underlying RPC is performed. partial void Modify_DetectIntentRequest(ref DetectIntentRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_StreamingDetectIntentRequestCallSettings(ref gaxgrpc::CallSettings settings); partial void Modify_StreamingDetectIntentRequestRequest(ref StreamingDetectIntentRequest request); /// <summary> /// Processes a natural language query and returns structured, actionable data /// as a result. This method is not idempotent, because it may cause contexts /// and session entity types to be updated, which in turn might affect /// results of future queries. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override stt::Task<DetectIntentResponse> DetectIntentAsync( DetectIntentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DetectIntentRequest(ref request, ref callSettings); return _callDetectIntent.Async(request, callSettings); } /// <summary> /// Processes a natural language query and returns structured, actionable data /// as a result. This method is not idempotent, because it may cause contexts /// and session entity types to be updated, which in turn might affect /// results of future queries. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override DetectIntentResponse DetectIntent( DetectIntentRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DetectIntentRequest(ref request, ref callSettings); return _callDetectIntent.Sync(request, callSettings); } /// <summary> /// Processes a natural language query in audio format in a streaming fashion /// and returns structured, actionable data as a result. This method is only /// available via the gRPC API (not REST). /// </summary> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <param name="streamingSettings"> /// If not null, applies streaming overrides to this RPC call. /// </param> /// <returns> /// The client-server stream. /// </returns> public override StreamingDetectIntentStream StreamingDetectIntent( gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) { Modify_StreamingDetectIntentRequestCallSettings(ref callSettings); gaxgrpc::BidirectionalStreamingSettings effectiveStreamingSettings = streamingSettings ?? _callStreamingDetectIntent.StreamingSettings; grpccore::AsyncDuplexStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> call = _callStreamingDetectIntent.Call(callSettings); gaxgrpc::BufferedClientStreamWriter<StreamingDetectIntentRequest> writeBuffer = new gaxgrpc::BufferedClientStreamWriter<StreamingDetectIntentRequest>( call.RequestStream, effectiveStreamingSettings.BufferedClientWriterCapacity); return new StreamingDetectIntentStreamImpl(this, call, writeBuffer); } internal sealed partial class StreamingDetectIntentStreamImpl : StreamingDetectIntentStream { /// <summary> /// Construct the bidirectional streaming method for <c>StreamingDetectIntent</c>. /// </summary> /// <param name="service">The service containing this streaming method.</param> /// <param name="call">The underlying gRPC duplex streaming call.</param> /// <param name="writeBuffer">The <see cref="gaxgrpc::BufferedClientStreamWriter{StreamingDetectIntentRequest}"/> /// instance associated with this streaming call.</param> public StreamingDetectIntentStreamImpl( SessionsClientImpl service, grpccore::AsyncDuplexStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> call, gaxgrpc::BufferedClientStreamWriter<StreamingDetectIntentRequest> writeBuffer) { _service = service; GrpcCall = call; _writeBuffer = writeBuffer; } private SessionsClientImpl _service; private gaxgrpc::BufferedClientStreamWriter<StreamingDetectIntentRequest> _writeBuffer; private StreamingDetectIntentRequest ModifyRequest(StreamingDetectIntentRequest request) { _service.Modify_StreamingDetectIntentRequestRequest(ref request); return request; } /// <inheritdoc/> public override grpccore::AsyncDuplexStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> GrpcCall { get; } /// <inheritdoc/> public override stt::Task TryWriteAsync(StreamingDetectIntentRequest message) => _writeBuffer.TryWriteAsync(ModifyRequest(message)); /// <inheritdoc/> public override stt::Task WriteAsync(StreamingDetectIntentRequest message) => _writeBuffer.WriteAsync(ModifyRequest(message)); /// <inheritdoc/> public override stt::Task TryWriteAsync(StreamingDetectIntentRequest message, grpccore::WriteOptions options) => _writeBuffer.TryWriteAsync(ModifyRequest(message), options); /// <inheritdoc/> public override stt::Task WriteAsync(StreamingDetectIntentRequest message, grpccore::WriteOptions options) => _writeBuffer.WriteAsync(ModifyRequest(message), options); /// <inheritdoc/> public override stt::Task TryWriteCompleteAsync() => _writeBuffer.TryWriteCompleteAsync(); /// <inheritdoc/> public override stt::Task WriteCompleteAsync() => _writeBuffer.WriteCompleteAsync(); /// <inheritdoc/> public override scg::IAsyncEnumerator<StreamingDetectIntentResponse> ResponseStream => GrpcCall.ResponseStream; } } // Partial classes to enable page-streaming }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Description { using System.Collections.Generic; using System.ServiceModel.Channels; using System.ServiceModel; using System.Xml; using System.Runtime.Serialization; using System.Diagnostics; using System.Net.Security; using System.ServiceModel.Security; using System.ComponentModel; [DebuggerDisplay("Action={action}, Direction={direction}, MessageType={messageType}")] public class MessageDescription { static Type typeOfUntypedMessage; string action; MessageDirection direction; MessageDescriptionItems items; XmlName messageName; Type messageType; XmlQualifiedName xsdType; ProtectionLevel protectionLevel; bool hasProtectionLevel; public MessageDescription(string action, MessageDirection direction) : this(action, direction, null) { } internal MessageDescription(string action, MessageDirection direction, MessageDescriptionItems items) { if (!MessageDirectionHelper.IsDefined(direction)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("direction")); this.action = action; this.direction = direction; this.items = items; } internal MessageDescription(MessageDescription other) { this.action = other.action; this.direction = other.direction; this.Items.Body = other.Items.Body.Clone(); foreach (MessageHeaderDescription mhd in other.Items.Headers) { this.Items.Headers.Add(mhd.Clone() as MessageHeaderDescription); } foreach (MessagePropertyDescription mpd in other.Items.Properties) { this.Items.Properties.Add(mpd.Clone() as MessagePropertyDescription); } this.MessageName = other.MessageName; this.MessageType = other.MessageType; this.XsdTypeName = other.XsdTypeName; this.hasProtectionLevel = other.hasProtectionLevel; this.ProtectionLevel = other.ProtectionLevel; } internal MessageDescription Clone() { return new MessageDescription(this); } public string Action { get { return action; } internal set { action = value; } } public MessageBodyDescription Body { get { return Items.Body; } } public MessageDirection Direction { get { return direction; } } public MessageHeaderDescriptionCollection Headers { get { return Items.Headers; } } public MessagePropertyDescriptionCollection Properties { get { return Items.Properties; } } internal MessageDescriptionItems Items { get { if (items == null) items = new MessageDescriptionItems(); return items; } } public ProtectionLevel ProtectionLevel { get { return this.protectionLevel; } set { if (!ProtectionLevelHelper.IsDefined(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); this.protectionLevel = value; this.hasProtectionLevel = true; } } public bool ShouldSerializeProtectionLevel() { return this.HasProtectionLevel; } public bool HasProtectionLevel { get { return this.hasProtectionLevel; } } internal static Type TypeOfUntypedMessage { get { if (typeOfUntypedMessage == null) { typeOfUntypedMessage = typeof(Message); } return typeOfUntypedMessage; } } internal XmlName MessageName { get { return messageName; } set { messageName = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime [DefaultValue(null)] public Type MessageType { get { return messageType; } set { messageType = value; } } internal bool IsTypedMessage { get { return messageType != null; } } internal bool IsUntypedMessage { get { return (Body.ReturnValue != null && Body.Parts.Count == 0 && Body.ReturnValue.Type == TypeOfUntypedMessage) || (Body.ReturnValue == null && Body.Parts.Count == 1 && Body.Parts[0].Type == TypeOfUntypedMessage); } } internal bool IsVoid { get { return !IsTypedMessage && Body.Parts.Count == 0 && (Body.ReturnValue == null || Body.ReturnValue.Type == typeof(void)); } } internal XmlQualifiedName XsdTypeName { get { return xsdType; } set { xsdType = value; } } internal void ResetProtectionLevel() { this.protectionLevel = ProtectionLevel.None; this.hasProtectionLevel = false; } } internal class MessageDescriptionItems { MessageHeaderDescriptionCollection headers; MessageBodyDescription body; MessagePropertyDescriptionCollection properties; internal MessageBodyDescription Body { get { if (body == null) body = new MessageBodyDescription(); return body; } set { this.body = value; } } internal MessageHeaderDescriptionCollection Headers { get { if (headers == null) headers = new MessageHeaderDescriptionCollection(); return headers; } } internal MessagePropertyDescriptionCollection Properties { get { if (properties == null) properties = new MessagePropertyDescriptionCollection(); return properties; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Reflection; using System.IO; using System.Data; using MySql.Data.MySqlClient; using System.Diagnostics; using classes; using System.Configuration; using System.Drawing; namespace kzstats { public partial class map : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string lpanMapName = Request.QueryString["id"]; lpanMapName = StaticMethods.CheckSqlReqValidity(lpanMapName, "kz_bhop_ocean"); Panel4.EnableViewState = false; if (Page.IsPostBack == false) { SetUpDropDown(); } if (HttpContext.Current.Request.UserAgent.Contains("Chrome") == true || HttpContext.Current.Request.UserAgent.Contains("Firefox") == true) { gcBody.Attributes.Add("style", tcBgStyler.Instance.GetBgImageStyle()); } DoPageLoad(); } private void DoPageLoad() { Stopwatch lcStopWatch = new Stopwatch(); lcStopWatch.Reset(); lcStopWatch.Start(); tcGridViewType lcGridViewType = new tcGridViewType(teGridViewType.eeMapPage,teSubPageType.eeSubPageNone); HyperLink lcCourseName; string lpanMapName = Request.QueryString["id"]; lpanMapName = StaticMethods.CheckSqlReqValidity(lpanMapName, "kz_bhop_ocean"); gcLabelMapName.Text = lpanMapName; tcMySqlCommand lcMySqlCommand = new tcMySqlCommand(@"SELECT id,name FROM kzs_courses WHERE map = (SELECT id FROM kzs_maps WHERE name = ?map LIMIT 1) ORDER BY id ASC;"); lcMySqlCommand.mcMySqlCommand.Parameters.Add("?map", lpanMapName); MySqlDataReader lcMySqlReader = lcMySqlCommand.mcMySqlCommand.ExecuteReader(); int lnIndex = 0; int lnCourseId = 0; //Loop over courses to add labels and records while (lcMySqlReader.HasRows && !lcMySqlReader.IsClosed && lcMySqlReader.Read()) { Debug.WriteLine(lcMySqlReader.GetString(0) + " " + lcMySqlReader.GetString(1)); lnCourseId = lcMySqlReader.GetInt32(0); if (lnCourseId < 1) { lnCourseId = 1; } //Set properties for the hyperlink to the course page lcCourseName = GetCourseHyperLink(lcMySqlReader.GetString(1), "~/course.aspx?id=" + lnCourseId); //Indent course hyperlink and add to the panel Panel4.Controls.AddAt(lnIndex++, new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")); Panel4.Controls.AddAt(lnIndex++, lcCourseName); Panel4.Controls.AddAt(lnIndex++, new LiteralControl("&nbsp;")); Label lcWr = GetWrLabel(lnCourseId); Panel4.Controls.AddAt(lnIndex++, lcWr); string lpanCp = Request.QueryString["cp"]; //Handle requests for checkpoints that are not postbacks from dropdown state change if (Page.IsPostBack == false && lpanCp != null && lpanCp.Equals("1")) { gcDropDown.SelectedValue = "cp"; } string lpanQuery = GetQueryFromDropDownState(lnCourseId); lcGridViewType.meSub = GetGridTypeFromDropDownState(); tcMySqlDataSource lcMySqlDataSource = new tcMySqlDataSource(lpanQuery); DataTable lcDataTable = lcMySqlDataSource.GetDataTable(); //If the course has records if (lcDataTable != null && lcDataTable.Rows.Count > 0) { tcGridView lcGridView = GridViewFactory.Create(lcDataTable, lcGridViewType); Panel4.Controls.AddAt(lnIndex++, new LiteralControl("<br>")); Panel4.Controls.AddAt(lnIndex++, lcGridView); Panel4.Controls.AddAt(lnIndex++, new LiteralControl("<br>")); } else //Else the course has no records { Label lcNoRecords = new Label(); lcNoRecords.Text = " - No records!"; Panel4.Controls.AddAt(lnIndex++, lcNoRecords); Panel4.Controls.AddAt(lnIndex++, new LiteralControl("<br><br>")); } } lcMySqlCommand.Close(); tcLinkPanel.AddLinkPanel(this); //Refresh all the gridviews with data contents Page.DataBind(); Page.MaintainScrollPositionOnPostBack = true; lcStopWatch.Stop(); gcPageLoad.Text = lcStopWatch.ElapsedMilliseconds.ToString(); } private void SetUpDropDown() { string[] lacText = { "Nocheck records", "Checkpoint records", "World records" }; string[] lacKeyword = { "nocheck", "cp", "wr" }; gcDropDown.AutoPostBack = true; gcDropDown.SelectedIndexChanged += new EventHandler(cb_DropDownTextChange); //Add options to dropdown for (int i = 0; i < lacText.Length; i++) { gcDropDown.Items.Add(new ListItem(lacText[i], lacKeyword[i])); } string lpanSel = Request.QueryString["sel"]; if (HttpContext.Current.Request.UserAgent.Contains("Chrome") == false && HttpContext.Current.Request.UserAgent.Contains("Firefox") == false) { gcDropDown.Visible = false; //TODO //Panel3.Width = Unit.Percentage(100); Panel3.Height = 425; Panel3.ScrollBars = ScrollBars.Vertical; if (lpanSel == null) { lpanSel = lacKeyword[0]; } } if (lpanSel != null) { gcDropDown.SelectedValue = lpanSel; Panel3.Controls.Remove(gcDropDown); string lpanMapName = Request.QueryString["id"]; for (int i = 0; i < lacText.Length; i++) { HyperLink lcLink = new HyperLink(); lcLink.Text = lacText[i]; lcLink.NavigateUrl = "~/map.aspx?id=" + lpanMapName + "&sel=" + lacKeyword[i]; lcLink.Font.Name = "Arial"; lcLink.Font.Size = 11; lcLink.Font.Bold = true; lcLink.ForeColor = teColors.eeLink; gcLinks.Controls.Add(lcLink); if (i + 1 < lacText.Length) { gcLinks.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")); } else { gcLinks.Controls.Add(new LiteralControl("<br><br>")); } } } } private void cb_DropDownTextChange(object acSender, EventArgs e) { while (Panel4.Controls.Count > 0) { Panel4.Controls.RemoveAt(0); } DoPageLoad(); } private HyperLink GetCourseHyperLink(string apanText, string apanUrl) { HyperLink lcReturn = new HyperLink(); lcReturn.Text = apanText; lcReturn.NavigateUrl = apanUrl; lcReturn.ForeColor = Color.FromName("#A40000"); lcReturn.Style.Value = "text-decoration:none"; //Remove underline lcReturn.Font.Bold = true; lcReturn.Font.Size = 12; lcReturn.Font.Name = "Arial"; return lcReturn; } private Label GetWrLabel(int anCourseId) { Label lcReturn = new Label(); string lpanPlayer = ""; string lpanTime = ""; string lpanDate = ""; tcMySqlCommand lcMySqlCommand = new tcMySqlCommand(@"SELECT WR.time,P.name,DATE_FORMAT(WR.date,'%Y-%m-%d') AS Date FROM (SELECT player,course,time,date FROM kzs_wrs WHERE course = ?courseid) AS WR LEFT JOIN (SELECT name,id FROM kzs_players) AS P ON P.id = WR.player LEFT JOIN (SELECT id,invert FROM kzs_courses) AS C ON C.id = WR.course ORDER BY Date DESC, CASE 1 WHEN C.invert THEN Time ELSE -Time END DESC LIMIT 1"); lcMySqlCommand.mcMySqlCommand.Parameters.Add("?courseid", anCourseId.ToString()); MySqlDataReader lcMySqlReader = lcMySqlCommand.mcMySqlCommand.ExecuteReader(); lcMySqlReader.Read(); if(lcMySqlReader.HasRows) { lpanTime = StaticMethods.TimeToString(lcMySqlReader.GetFloat(0)); lpanPlayer = lcMySqlReader.GetString(1); lpanDate = lcMySqlReader.GetString(2); } lcMySqlCommand.Close(); lcReturn.Font.Name = "Arial"; lcReturn.Font.Bold = true; lcReturn.ForeColor = teColors.eeText; lcReturn.Font.Size = 11; if (lpanDate != "" && lpanPlayer != "" && lpanTime != "") { if (lpanPlayer.Length > 18) { lcReturn.ToolTip = lpanPlayer; lpanPlayer = lpanPlayer.Substring(0, 17); } lcReturn.Text = "(World record " + lpanTime + " by " + lpanPlayer + " on " + lpanDate + ")"; } return lcReturn; } private teSubPageType GetGridTypeFromDropDownState() { switch (gcDropDown.SelectedValue) { case "cp": return teSubPageType.eeMapPageCheck; case "wr": return teSubPageType.eeMapPageWr; default: return teSubPageType.eeMapPageNocheck; } } private string GetQueryFromDropDownState(int anCourseId) { switch (gcDropDown.SelectedValue) { case "cp": return @"SELECT @rank := @rank + 1 AS Rank, F.* FROM (SELECT P.name AS Player, P.auth AS SteamID, CASE 1 WHEN C.invert THEN Rtimes.maxtime ELSE Rtimes.mintime END AS Time, CASE 1 WHEN C.invert THEN Rmax.cp ELSE Rmin.cp END AS Checks, CASE 1 WHEN C.invert THEN Rmax.tele ELSE Rmin.tele END AS Teles, CASE 1 WHEN C.invert THEN Smax.name ELSE Smin.name END AS Server, P.country AS Country FROM (SELECT course, min(time) AS mintime, max(time) AS maxtime, player FROM kzs_recordscp WHERE course = " + anCourseId + @" GROUP BY player) AS Rtimes LEFT JOIN (SELECT name,auth,id,country FROM kzs_players) AS P ON P.id = Rtimes.player LEFT JOIN (SELECT cp,tele,time AS ptime,server,player,course FROM kzs_recordscp) AS Rmin ON Rmin.ptime = Rtimes.mintime AND Rmin.player = P.id AND Rmin.course = Rtimes.course LEFT JOIN (SELECT cp,tele,time AS ptime,server,player,course FROM kzs_recordscp) AS Rmax ON Rmax.ptime = Rtimes.maxtime AND Rmax.player = P.id AND Rmax.course = Rtimes.course LEFT JOIN (SELECT id,invert FROM kzs_courses) AS C ON C.id = Rtimes.course LEFT JOIN (SELECT id,name FROM kzs_servers) AS Smin ON Smin.id = Rmin.server LEFT JOIN (SELECT id,name FROM kzs_servers) AS Smax ON Smax.id = Rmin.server ORDER BY CASE 1 WHEN C.invert THEN Time ELSE -Time END DESC) AS F, (SELECT @rank := 0) AS RNK LIMIT 10"; case "wr": return @"SELECT @rank := @rank + 1 AS Rank, F.* FROM (SELECT P.name AS Player, P.country AS Country, P.auth AS SteamId, WR.time AS Time, DATE_FORMAT(WR.date,'%Y-%m-%d') AS Date FROM (SELECT player,time,date FROM kzs_wrs WHERE course = " + anCourseId + @") AS WR LEFT JOIN (SELECT id,name,country,auth FROM kzs_players) AS P ON P.id = WR.player LEFT JOIN (SELECT invert FROM kzs_courses WHERE id = " + anCourseId + @") AS C ON C.invert ORDER BY date DESC, CASE 1 WHEN C.invert THEN Time ELSE -Time END DESC) AS F, (SELECT @rank := 0) AS RNK LIMIT 10"; default: return @"SELECT @rank := @rank + 1 AS Rank, F.* FROM (SELECT P.name AS Player, P.auth AS SteamID, CASE 1 WHEN C.invert THEN Rtimes.maxtime ELSE Rtimes.mintime END AS Time, CASE 1 WHEN C.invert THEN Smax.name ELSE Smin.name END AS Server, P.country AS Country FROM (SELECT course, min(time) AS mintime, max(time) AS maxtime, player FROM kzs_records WHERE course = " + anCourseId + @" GROUP BY player) AS Rtimes LEFT JOIN (SELECT name,auth,id,country FROM kzs_players) AS P ON P.id = Rtimes.player LEFT JOIN (SELECT time AS ptime,server,player,course FROM kzs_records) AS Rmin ON Rmin.ptime = Rtimes.mintime AND Rmin.player = P.id AND Rmin.course = Rtimes.course LEFT JOIN (SELECT time AS ptime,server,player,course FROM kzs_records) AS Rmax ON Rmax.ptime = Rtimes.maxtime AND Rmax.player = P.id AND Rmax.course = Rtimes.course LEFT JOIN (SELECT id,invert FROM kzs_courses) AS C ON C.id = Rtimes.course LEFT JOIN (SELECT id,name FROM kzs_servers) AS Smin ON Smin.id = Rmin.server LEFT JOIN (SELECT id,name FROM kzs_servers) AS Smax ON Smax.id = Rmin.server ORDER BY CASE 1 WHEN C.invert THEN Time ELSE -Time END DESC) AS F, (SELECT @rank := 0) AS RNK LIMIT 10"; } } } }
using System; using NSimulate; using System.Linq; using System.Collections.Generic; namespace NSimulate.Instruction { /// <summary> /// Instruction used to allocate resources /// </summary> public class AllocateInstruction<TResource> : InstructionBase where TResource : Resource { /// <summary> /// A function used to test whether a resource matches the request /// </summary> private Func<TResource, bool> _resourceMatchFunction = (o)=>true; /// <summary> /// A function used to determine a priority of a resource, used to prioritise resource selections /// </summary> private Func<TResource, int> _resourcePriorityFunction = null; /// <summary> /// Gets the set of allocations made whe completing this instruction /// </summary> /// <value> /// The allocations made /// </value> public List<KeyValuePair<TResource, int>> Allocations{ get; private set; } /// <summary> /// Gets the number of resources requested. /// </summary> /// <value> /// The number requested. /// </value> public int NumberRequested{ get; private set; } /// <summary> /// Gets a value indicating whether the allocations associated with this instruction have been mae /// </summary> /// <value> /// <c>true</c> if resources are allocated; otherwise, <c>false</c>. /// </value> public bool IsAllocated{ get; private set; } /// <summary> /// Gets a value indicating whether the resources associated with this instructions have been released /// </summary> /// <value> /// <c>true</c> if resources are released; otherwise, <c>false</c>. /// </value> public bool IsReleased{ get; private set; } /// <summary> /// Initializes a new instance of the <see cref="NSimulate.Instruction.AllocateInstruction`1"/> class. /// </summary> /// <param name='number'> /// Number of resources to allocate. /// </param> /// <param name='resourceMatchFunction'> /// An optional function used to match resources for allocation. /// </param> /// <param name='resourcePriorityFunction'> /// An optional function used to prioritise resources for allocation where multiple resources match /// </param> public AllocateInstruction (int number, Func<TResource, bool> resourceMatchFunction = null, Func<TResource, int> resourcePriorityFunction = null) { Priority = Priority.Low; // reduce priority so that allocate is processed after any releases NumberRequested = number; if (resourceMatchFunction != null){ _resourceMatchFunction = resourceMatchFunction; } if (resourcePriorityFunction!=null){ _resourcePriorityFunction = resourcePriorityFunction; } } /// <summary> /// Determines whether this instruction can complete in the current time period /// </summary> /// <returns> /// <c>true</c> if this instance can complete. /// </returns> /// <param name='context'> /// Context providing state information for the current simulation /// </param> /// <param name='skipFurtherChecksUntilTimePeriod'> /// Output parameter used to specify a time period at which this instruction should be checked again. This should be left null if it is not possible to determine when this instruction can complete. /// </param> public override bool CanComplete(SimulationContext context, out long? skipFurtherChecksUntilTimePeriod){ skipFurtherChecksUntilTimePeriod = null; // build a set or resources for possible allocation, filtering and prioritising as appropriate IEnumerable<TResource> resources = null; if (_resourcePriorityFunction == null){ resources = context.GetByType<TResource>() .Where(_resourceMatchFunction); } else{ resources = context.GetByType<TResource>() .Where(_resourceMatchFunction) .OrderBy(_resourcePriorityFunction); } // check if the are enough resources available for allocation bool enoughAvailable = false; int available = 0; foreach(TResource resource in resources){ int stillAvailable = resource.Capacity - resource.Allocated; if (stillAvailable > 0){ available += stillAvailable; } if (available >= NumberRequested){ enoughAvailable = true; break; } } // if there are currently enough resources available, the instruction can complete return enoughAvailable; } /// <summary> /// Complete the instruction. For this instruction type, allocates the requested resources /// </summary> /// <param name='context'> /// Context providing state information for the current simulation. /// </param> public override void Complete (SimulationContext context) { base.Complete(context); IEnumerable<TResource> resources = null; if (_resourcePriorityFunction == null){ resources = context.GetByType<TResource>() .Where(_resourceMatchFunction); } else{ resources = context.GetByType<TResource>() .Where(_resourceMatchFunction) .OrderBy(_resourcePriorityFunction); } Allocations = new List<KeyValuePair<TResource, int>>(); int allocated = 0; foreach(TResource resource in resources){ int available = resource.Capacity - resource.Allocated; if (available > 0){ int amountToAllocate = Math.Min(available, NumberRequested - allocated); Allocations.Add(new KeyValuePair<TResource, int>(resource, amountToAllocate)); resource.Allocated += amountToAllocate; allocated += amountToAllocate; if (allocated == NumberRequested){ break; } } } IsAllocated = true; IsReleased = false; CompletedAtTimePeriod = context.TimePeriod; } /// <summary> /// Release the resources previously allocated wen completing tis instruction. /// </summary> public void Release(){ if (IsAllocated && !IsReleased){ foreach(var allocation in Allocations){ allocation.Key.Allocated -= allocation.Value; } IsAllocated = false; IsReleased = true; } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapObjectClassSchema.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap { /// <summary> The schema definition of an object class in a directory server. /// /// The LdapObjectClassSchema class represents the definition of an object /// class. It is used to query the syntax of an object class. /// /// </summary> /// <seealso cref="LdapSchemaElement"> /// </seealso> /// <seealso cref="LdapSchema"> /// </seealso> public class LdapObjectClassSchema : LdapSchemaElement { /// <summary> Returns the object classes from which this one derives. /// /// </summary> /// <returns> The object classes superior to this class. /// </returns> virtual public string[] Superiors { get { return superiors; } } /// <summary> Returns a list of attributes required for an entry with this object /// class. /// /// </summary> /// <returns> The list of required attributes defined for this class. /// </returns> virtual public string[] RequiredAttributes { get { return required; } } /// <summary> Returns a list of optional attributes but not required of an entry /// with this object class. /// /// </summary> /// <returns> The list of optional attributes defined for this class. /// </returns> virtual public string[] OptionalAttributes { get { return optional; } } /// <summary> Returns the type of object class. /// /// The getType method returns one of the following constants defined in /// LdapObjectClassSchema: /// <ul> /// <li>ABSTRACT</li> /// <li>AUXILIARY</li> /// <li>STRUCTURAL</li> /// </ul> /// See the LdapSchemaElement.getQualifier method for information on /// obtaining the X-NDS flags. /// /// </summary> /// <returns> The type of object class. /// </returns> virtual public int Type { get { return type; } } internal string[] superiors; internal string[] required; internal string[] optional; internal int type = -1; /// <summary> This class definition defines an abstract schema class. /// /// This is equivalent to setting the Novell eDirectory effective class /// flag to true. /// </summary> public const int ABSTRACT = 0; /// <summary> This class definition defines a structural schema class. /// /// This is equivalent to setting the Novell eDirectory effective class /// flag to true. /// </summary> public const int STRUCTURAL = 1; /// <summary> This class definition defines an auxiliary schema class.</summary> public const int AUXILIARY = 2; /// <summary> Constructs an object class definition for adding to or deleting from /// a directory's schema. /// /// </summary> /// <param name="names"> Name(s) of the object class. /// /// </param> /// <param name="oid"> Object Identifer of the object class - in /// dotted-decimal format. /// /// </param> /// <param name="description"> Optional description of the object class. /// /// </param> /// <param name="superiors"> The object classes from which this one derives. /// /// </param> /// <param name="required"> A list of attributes required /// for an entry with this object class. /// /// </param> /// <param name="optional"> A list of attributes acceptable but not required /// for an entry with this object class. /// /// </param> /// <param name="type"> One of ABSTRACT, AUXILIARY, or STRUCTURAL. These /// constants are defined in LdapObjectClassSchema. /// /// </param> /// <param name="obsolete"> true if this object is obsolete /// /// </param> public LdapObjectClassSchema(string[] names, string oid, string[] superiors, string description, string[] required, string[] optional, int type, bool obsolete) : base(LdapSchema.schemaTypeNames[LdapSchema.OBJECT_CLASS]) { this.names = new string[names.Length]; names.CopyTo(this.names, 0); this.oid = oid; this.description = description; this.type = type; this.obsolete = obsolete; if (superiors != null) { this.superiors = new string[superiors.Length]; superiors.CopyTo(this.superiors, 0); } if (required != null) { this.required = new string[required.Length]; required.CopyTo(this.required, 0); } if (optional != null) { this.optional = new string[optional.Length]; optional.CopyTo(this.optional, 0); } Value = formatString(); } /// <summary> Constructs an object class definition from the raw string value /// returned from a directory query for "objectClasses". /// /// </summary> /// <param name="raw"> The raw string value returned from a directory /// query for "objectClasses". /// </param> public LdapObjectClassSchema(string raw) : base(LdapSchema.schemaTypeNames[LdapSchema.OBJECT_CLASS]) { try { SchemaParser parser = new SchemaParser(raw); if (parser.Names != null) { names = new string[parser.Names.Length]; parser.Names.CopyTo(names, 0); } if ((object)parser.ID != null) oid = parser.ID; if ((object)parser.Description != null) description = parser.Description; obsolete = parser.Obsolete; if (parser.Required != null) { required = new string[parser.Required.Length]; parser.Required.CopyTo(required, 0); } if (parser.Optional != null) { optional = new string[parser.Optional.Length]; parser.Optional.CopyTo(optional, 0); } if (parser.Superiors != null) { superiors = new string[parser.Superiors.Length]; parser.Superiors.CopyTo(superiors, 0); } type = parser.Type; System.Collections.IEnumerator qualifiers = parser.Qualifiers; AttributeQualifier attrQualifier; while (qualifiers.MoveNext()) { attrQualifier = (AttributeQualifier)qualifiers.Current; setQualifier(attrQualifier.Name, attrQualifier.Values); } Value = formatString(); } catch (System.IO.IOException e) { } } /// <summary> Returns a string in a format suitable for directly adding to a /// directory, as a value of the particular schema element class. /// /// </summary> /// <returns> A string representation of the class' definition. /// </returns> protected internal override string formatString() { System.Text.StringBuilder valueBuffer = new System.Text.StringBuilder("( "); string token; string[] strArray; if ((object)(token = ID) != null) { valueBuffer.Append(token); } strArray = Names; if (strArray != null) { valueBuffer.Append(" NAME "); if (strArray.Length == 1) { valueBuffer.Append("'" + strArray[0] + "'"); } else { valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { valueBuffer.Append(" '" + strArray[i] + "'"); } valueBuffer.Append(" )"); } } if ((object)(token = Description) != null) { valueBuffer.Append(" DESC "); valueBuffer.Append("'" + token + "'"); } if (Obsolete) { valueBuffer.Append(" OBSOLETE"); } if ((strArray = Superiors) != null) { valueBuffer.Append(" SUP "); if (strArray.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { if (i > 0) valueBuffer.Append(" $ "); valueBuffer.Append(strArray[i]); } if (strArray.Length > 1) valueBuffer.Append(" )"); } if (Type != -1) { if (Type == ABSTRACT) valueBuffer.Append(" ABSTRACT"); else if (Type == AUXILIARY) valueBuffer.Append(" AUXILIARY"); else if (Type == STRUCTURAL) valueBuffer.Append(" STRUCTURAL"); } if ((strArray = RequiredAttributes) != null) { valueBuffer.Append(" MUST "); if (strArray.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { if (i > 0) valueBuffer.Append(" $ "); valueBuffer.Append(strArray[i]); } if (strArray.Length > 1) valueBuffer.Append(" )"); } if ((strArray = OptionalAttributes) != null) { valueBuffer.Append(" MAY "); if (strArray.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { if (i > 0) valueBuffer.Append(" $ "); valueBuffer.Append(strArray[i]); } if (strArray.Length > 1) valueBuffer.Append(" )"); } System.Collections.IEnumerator en; if ((en = QualifierNames) != null) { string qualName; string[] qualValue; while (en.MoveNext()) { qualName = ((string)en.Current); valueBuffer.Append(" " + qualName + " "); if ((qualValue = getQualifier(qualName)) != null) { if (qualValue.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < qualValue.Length; i++) { if (i > 0) valueBuffer.Append(" "); valueBuffer.Append("'" + qualValue[i] + "'"); } if (qualValue.Length > 1) valueBuffer.Append(" )"); } } } valueBuffer.Append(" )"); return valueBuffer.ToString(); } } }
// // Copyright (c) Microsoft. 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. // using System.IO; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Microsoft.Azure.Test; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Runtime.Serialization.Formatters; using System.Threading; using Xunit; namespace ResourceGroups.Tests { public class LiveDeploymentTests : TestBase { const string DummyTemplateUri = "https://testtemplates.blob.core.windows.net/templates/dummytemplate.js"; const string GoodWebsiteTemplateUri = "https://testtemplates.blob.core.windows.net/templates/good-website.js"; const string BadTemplateUri = "https://testtemplates.blob.core.windows.net/templates/bad-website-1.js"; public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler) { handler.IsPassThrough = true; return this.GetResourceManagementClient().WithHandler(handler); } [Fact] public void CreateDummyDeploymentTemplateWorks() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; var dictionary = new Dictionary<string, object> { {"string", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"securestring", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"int", new Dictionary<string, object>() { {"value", 42}, }}, {"bool", new Dictionary<string, object>() { {"value", true}, }} }; var serializedDictionary = JsonConvert.SerializeObject(dictionary, new JsonSerializerSettings { TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, TypeNameHandling = TypeNameHandling.None }); using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri(DummyTemplateUri) }, Parameters = serializedDictionary, Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); JObject json = JObject.Parse(handler.Request); Assert.Equal(HttpStatusCode.OK, client.Deployments.Get(groupName, deploymentName).StatusCode); } } [Fact] public void CreateDeploymentAndValidateProperties() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri(GoodWebsiteTemplateUri), }, Parameters = @"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}", Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" }); var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); Assert.NotNull(deploymentCreateResult.Deployment.Id); Assert.Equal(deploymentName, deploymentCreateResult.Deployment.Name); TestUtilities.Wait(1000); var deploymentListResult = client.Deployments.List(groupName, null); var deploymentGetResult = client.Deployments.Get(groupName, deploymentName); Assert.NotEmpty(deploymentListResult.Deployments); Assert.Equal(deploymentName, deploymentGetResult.Deployment.Name); Assert.Equal(deploymentName, deploymentListResult.Deployments[0].Name); Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Deployment.Properties.TemplateLink.Uri.AbsoluteUri); Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.Deployments[0].Properties.TemplateLink.Uri.AbsoluteUri); Assert.NotNull(deploymentGetResult.Deployment.Properties.ProvisioningState); Assert.NotNull(deploymentListResult.Deployments[0].Properties.ProvisioningState); Assert.NotNull(deploymentGetResult.Deployment.Properties.CorrelationId); Assert.NotNull(deploymentListResult.Deployments[0].Properties.CorrelationId); Assert.True(deploymentGetResult.Deployment.Properties.Parameters.Contains("mctest0101")); Assert.True(deploymentListResult.Deployments[0].Properties.Parameters.Contains("mctest0101")); //stop the deployment client.Deployments.Cancel(groupName, deploymentName); TestUtilities.Wait(2000); //Delete deployment Assert.Equal(HttpStatusCode.NoContent, client.Deployments.Delete(groupName, deploymentName).StatusCode); } } [Fact] public void ValidateGoodDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri(GoodWebsiteTemplateUri), }, Parameters = @"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}", Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" }); //Action DeploymentValidateResponse validationResult = client.Deployments.Validate(groupName, deploymentName, parameters); //Assert Assert.True(validationResult.IsValid); Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); Assert.Equal(1, validationResult.Properties.Providers.Count); Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].Namespace); } } [Fact] public void ValidateGoodDeploymentWithInlineTemplate() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = File.ReadAllText("ScenarioTests\\good-website.js"), Parameters = @"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}", Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" }); //Action DeploymentValidateResponse validationResult = client.Deployments.Validate(groupName, deploymentName, parameters); //Assert Assert.True(validationResult.IsValid); Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); Assert.Equal(1, validationResult.Properties.Providers.Count); Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].Namespace); } } [Fact] public void ValidateBadDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri(BadTemplateUri), }, Parameters = @"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}", Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" }); var result = client.Deployments.Validate(groupName, deploymentName, parameters); Assert.False(result.IsValid); Assert.Equal("InvalidTemplate", result.Error.Code); } } [Fact] public void CreateDummyDeploymentProducesOperations() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; var dictionary = new Dictionary<string, object> { {"string", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"securestring", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"int", new Dictionary<string, object>() { {"value", 42}, }}, {"bool", new Dictionary<string, object>() { {"value", true}, }} }; var serializedDictionary = JsonConvert.SerializeObject(dictionary, new JsonSerializerSettings { TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, TypeNameHandling = TypeNameHandling.None }); using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri(DummyTemplateUri) }, Parameters = serializedDictionary, Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csmr"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); // Wait until deployment completes TestUtilities.Wait(30000); var operations = client.DeploymentOperations.List(groupName, deploymentName, null); Assert.True(operations.Operations.Any()); Assert.NotNull(operations.Operations[0].Id); Assert.NotNull(operations.Operations[0].OperationId); Assert.NotNull(operations.Operations[0].Properties); } } [Fact] public void ListDeploymentsWorksWithFilter() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri(GoodWebsiteTemplateUri), }, Parameters = @"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}", Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); var deploymentListResult = client.Deployments.List(groupName, new DeploymentListParameters { ProvisioningState = ProvisioningState.Running }); if (null == deploymentListResult.Deployments || deploymentListResult.Deployments.Count < 1) { deploymentListResult = client.Deployments.List(groupName, new DeploymentListParameters { ProvisioningState = ProvisioningState.Accepted }); } var deploymentGetResult = client.Deployments.Get(groupName, deploymentName); Assert.NotEmpty(deploymentListResult.Deployments); Assert.Equal(deploymentName, deploymentGetResult.Deployment.Name); Assert.Equal(deploymentName, deploymentListResult.Deployments[0].Name); Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Deployment.Properties.TemplateLink.Uri.AbsoluteUri); Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.Deployments[0].Properties.TemplateLink.Uri.AbsoluteUri); Assert.NotNull(deploymentGetResult.Deployment.Properties.ProvisioningState); Assert.NotNull(deploymentListResult.Deployments[0].Properties.ProvisioningState); Assert.NotNull(deploymentGetResult.Deployment.Properties.CorrelationId); Assert.NotNull(deploymentListResult.Deployments[0].Properties.CorrelationId); Assert.True(deploymentGetResult.Deployment.Properties.Parameters.Contains("mctest0101")); Assert.True(deploymentListResult.Deployments[0].Properties.Parameters.Contains("mctest0101")); } } [Fact] public void CreateLargeWebDeploymentTemplateWorks() { var handler = new RecordedDelegatingHandler(); using (UndoContext context = UndoContext.Current) { context.Start(); string resourceName = TestUtilities.GenerateName("csmr"); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri(GoodWebsiteTemplateUri), }, Parameters = "{ 'siteName': {'value': '" + resourceName + "'},'hostingPlanName': {'value': '" + resourceName + "'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}", Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "South Central US" }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); // Wait until deployment completes TestUtilities.Wait(30000); var operations = client.DeploymentOperations.List(groupName, deploymentName, null); Assert.True(operations.Operations.Any()); } } [Fact] public void CheckExistenceReturnsCorrectValue() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetResourceManagementClient(handler); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = new Uri(GoodWebsiteTemplateUri), }, Parameters = @"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}", Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" }); var checkExistenceFirst = client.Deployments.CheckExistence(groupName, deploymentName); Assert.False(checkExistenceFirst.Exists); var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); var checkExistenceSecond = client.Deployments.CheckExistence(groupName, deploymentName); Assert.True(checkExistenceSecond.Exists); } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: ErrorMailModule.cs 923 2011-12-23 22:02:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Diagnostics; using System.Globalization; using System.Web; using System.IO; using System.Net.Mail; using MailAttachment = System.Net.Mail.Attachment; using IDictionary = System.Collections.IDictionary; using ThreadPool = System.Threading.ThreadPool; using WaitCallback = System.Threading.WaitCallback; using Encoding = System.Text.Encoding; using NetworkCredential = System.Net.NetworkCredential; #endregion public sealed class ErrorMailEventArgs : EventArgs { private readonly Error _error; private readonly MailMessage _mail; public ErrorMailEventArgs(Error error, MailMessage mail) { if (error == null) throw new ArgumentNullException("error"); if (mail == null) throw new ArgumentNullException("mail"); _error = error; _mail = mail; } public Error Error { get { return _error; } } public MailMessage Mail { get { return _mail; } } } public delegate void ErrorMailEventHandler(object sender, ErrorMailEventArgs args); /// <summary> /// HTTP module that sends an e-mail whenever an unhandled exception /// occurs in an ASP.NET web application. /// </summary> public class ErrorMailModule : HttpModuleBase, IExceptionFiltering { private string _mailSender; private string _mailRecipient; private string _mailCopyRecipient; private string _mailSubjectFormat; private MailPriority _mailPriority; private bool _reportAsynchronously; private string _smtpServer; private int _smtpPort; private string _authUserName; private string _authPassword; private bool _noYsod; private bool _useSsl; public event ExceptionFilterEventHandler Filtering; public event ErrorMailEventHandler Mailing; public event ErrorMailEventHandler Mailed; public event ErrorMailEventHandler DisposingMail; /// <summary> /// Initializes the module and prepares it to handle requests. /// </summary> protected override void OnInit(HttpApplication application) { if (application == null) throw new ArgumentNullException("application"); // // Get the configuration section of this module. // If it's not there then there is nothing to initialize or do. // In this case, the module is as good as mute. // var config = (IDictionary) GetConfig(); if (config == null) return; // // Extract the settings. // var mailRecipient = GetSetting(config, "to"); var mailSender = GetSetting(config, "from", mailRecipient); var mailCopyRecipient = GetSetting(config, "cc", string.Empty); var mailSubjectFormat = GetSetting(config, "subject", string.Empty); var mailPriority = (MailPriority) Enum.Parse(typeof(MailPriority), GetSetting(config, "priority", MailPriority.Normal.ToString()), true); var reportAsynchronously = Convert.ToBoolean(GetSetting(config, "async", bool.TrueString)); var smtpServer = GetSetting(config, "smtpServer", string.Empty); var smtpPort = Convert.ToUInt16(GetSetting(config, "smtpPort", "0"), CultureInfo.InvariantCulture); var authUserName = GetSetting(config, "userName", string.Empty); var authPassword = GetSetting(config, "password", string.Empty); var sendYsod = Convert.ToBoolean(GetSetting(config, "noYsod", bool.FalseString)); var useSsl = Convert.ToBoolean(GetSetting(config, "useSsl", bool.FalseString)); // // Hook into the Error event of the application. // application.Error += new EventHandler(OnError); ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled); // // Finally, commit the state of the module if we got this far. // Anything beyond this point should not cause an exception. // _mailRecipient = mailRecipient; _mailSender = mailSender; _mailCopyRecipient = mailCopyRecipient; _mailSubjectFormat = mailSubjectFormat; _mailPriority = mailPriority; _reportAsynchronously = reportAsynchronously; _smtpServer = smtpServer; _smtpPort = smtpPort; _authUserName = authUserName; _authPassword = authPassword; _noYsod = sendYsod; _useSsl = useSsl; } /// <summary> /// Determines whether the module will be registered for discovery /// in partial trust environments or not. /// </summary> protected override bool SupportDiscoverability { get { return true; } } /// <summary> /// Gets the e-mail address of the sender. /// </summary> protected virtual string MailSender { get { return _mailSender; } } /// <summary> /// Gets the e-mail address of the recipient, or a /// comma-/semicolon-delimited list of e-mail addresses in case of /// multiple recipients. /// </summary> /// <remarks> /// When using System.Web.Mail components under .NET Framework 1.x, /// multiple recipients must be semicolon-delimited. /// When using System.Net.Mail components under .NET Framework 2.0 /// or later, multiple recipients must be comma-delimited. /// </remarks> protected virtual string MailRecipient { get { return _mailRecipient; } } /// <summary> /// Gets the e-mail address of the recipient for mail carbon /// copy (CC), or a comma-/semicolon-delimited list of e-mail /// addresses in case of multiple recipients. /// </summary> /// <remarks> /// When using System.Web.Mail components under .NET Framework 1.x, /// multiple recipients must be semicolon-delimited. /// When using System.Net.Mail components under .NET Framework 2.0 /// or later, multiple recipients must be comma-delimited. /// </remarks> protected virtual string MailCopyRecipient { get { return _mailCopyRecipient; } } /// <summary> /// Gets the text used to format the e-mail subject. /// </summary> /// <remarks> /// The subject text specification may include {0} where the /// error message (<see cref="Error.Message"/>) should be inserted /// and {1} <see cref="Error.Type"/> where the error type should /// be insert. /// </remarks> protected virtual string MailSubjectFormat { get { return _mailSubjectFormat; } } /// <summary> /// Gets the priority of the e-mail. /// </summary> protected virtual MailPriority MailPriority { get { return _mailPriority; } } /// <summary> /// Gets the SMTP server host name used when sending the mail. /// </summary> protected string SmtpServer { get { return _smtpServer; } } /// <summary> /// Gets the SMTP port used when sending the mail. /// </summary> protected int SmtpPort { get { return _smtpPort; } } /// <summary> /// Gets the user name to use if the SMTP server requires authentication. /// </summary> protected string AuthUserName { get { return _authUserName; } } /// <summary> /// Gets the clear-text password to use if the SMTP server requires /// authentication. /// </summary> protected string AuthPassword { get { return _authPassword; } } /// <summary> /// Indicates whether <a href="http://en.wikipedia.org/wiki/Screens_of_death#ASP.NET">YSOD</a> /// is attached to the e-mail or not. If <c>true</c>, the YSOD is /// not attached. /// </summary> protected bool NoYsod { get { return _noYsod; } } /// <summary> /// Determines if SSL will be used to encrypt communication with the /// mail server. /// </summary> protected bool UseSsl { get { return _useSsl; } } /// <summary> /// The handler called when an unhandled exception bubbles up to /// the module. /// </summary> protected virtual void OnError(object sender, EventArgs e) { var context = new HttpContextWrapper(((HttpApplication) sender).Context); OnError(context.Server.GetLastError(), context); } /// <summary> /// The handler called when an exception is explicitly signaled. /// </summary> protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args) { using (args.Exception.TryScopeCallerInfo(args.CallerInfo)) OnError(args.Exception, args.Context); } /// <summary> /// Reports the exception. /// </summary> protected virtual void OnError(Exception e, HttpContextBase context) { if (e == null) throw new ArgumentNullException("e"); // // Fire an event to check if listeners want to filter out // reporting of the uncaught exception. // var args = new ExceptionFilterEventArgs(e, context); OnFiltering(args); if (args.Dismissed) return; // // Get the last error and then report it synchronously or // asynchronously based on the configuration. // var error = new Error(e, context); if (_reportAsynchronously) ReportErrorAsync(error); else ReportError(error); } /// <summary> /// Raises the <see cref="Filtering"/> event. /// </summary> protected virtual void OnFiltering(ExceptionFilterEventArgs args) { var handler = Filtering; if (handler != null) handler(this, args); } /// <summary> /// Schedules the error to be e-mailed asynchronously. /// </summary> /// <remarks> /// The default implementation uses the <see cref="ThreadPool"/> /// to queue the reporting. /// </remarks> protected virtual void ReportErrorAsync(Error error) { if (error == null) throw new ArgumentNullException("error"); // // Schedule the reporting at a later time using a worker from // the system thread pool. This makes the implementation // simpler, but it might have an impact on reducing the // number of workers available for processing ASP.NET // requests in the case where lots of errors being generated. // ThreadPool.QueueUserWorkItem(new WaitCallback(ReportError), error); } private void ReportError(object state) { try { ReportError((Error) state); } // // Catch and trace COM/SmtpException here because this // method will be called on a thread pool thread and // can either fail silently in 1.x or with a big band in // 2.0. For latter, see the following MS KB article for // details: // // Unhandled exceptions cause ASP.NET-based applications // to unexpectedly quit in the .NET Framework 2.0 // http://support.microsoft.com/kb/911816 // catch (SmtpException e) { Trace.TraceError(e.ToString()); } } /// <summary> /// Schedules the error to be e-mailed synchronously. /// </summary> protected virtual void ReportError(Error error) { if (error == null) throw new ArgumentNullException("error"); // // Start by checking if we have a sender and a recipient. // These values may be null if someone overrides the // implementation of OnInit but does not override the // MailSender and MailRecipient properties. // var sender = this.MailSender ?? string.Empty; var recipient = this.MailRecipient ?? string.Empty; var copyRecipient = this.MailCopyRecipient ?? string.Empty; if (recipient.Length == 0) return; // // Create the mail, setting up the sender and recipient and priority. // var mail = new MailMessage(); mail.Priority = this.MailPriority; mail.From = new MailAddress(sender); mail.To.Add(recipient); if (copyRecipient.Length > 0) mail.CC.Add(copyRecipient); // // Format the mail subject. // var subjectFormat = Mask.EmptyString(this.MailSubjectFormat, "Error ({1}): {0}"); mail.Subject = string.Format(subjectFormat, error.Message, error.Type). Replace('\r', ' ').Replace('\n', ' '); // // Format the mail body. // var formatter = CreateErrorFormatter(); var bodyWriter = new StringWriter(); formatter.Format(bodyWriter, error); mail.Body = bodyWriter.ToString(); switch (formatter.MimeType) { case "text/html": mail.IsBodyHtml = true; break; case "text/plain": mail.IsBodyHtml = false; break; default : { throw new ApplicationException(string.Format( "The error mail module does not know how to handle the {1} media type that is created by the {0} formatter.", formatter.GetType().FullName, formatter.MimeType)); } } var args = new ErrorMailEventArgs(error, mail); try { // // If an HTML message was supplied by the web host then attach // it to the mail if not explicitly told not to do so. // if (!NoYsod && error.WebHostHtmlMessage.Length > 0) { var ysodAttachment = CreateHtmlAttachment("YSOD", error.WebHostHtmlMessage); if (ysodAttachment != null) mail.Attachments.Add(ysodAttachment); } // // Send off the mail with some chance to pre- or post-process // using event. // OnMailing(args); SendMail(mail); OnMailed(args); } finally { OnDisposingMail(args); mail.Dispose(); } } protected static MailAttachment CreateHtmlAttachment(string name, string html) { Debug.AssertStringNotEmpty(name); Debug.AssertStringNotEmpty(html); return MailAttachment.CreateAttachmentFromString(html, name + ".html", Encoding.UTF8, "text/html"); } /// <summary> /// Creates the <see cref="ErrorTextFormatter"/> implementation to /// be used to format the body of the e-mail. /// </summary> protected virtual ErrorTextFormatter CreateErrorFormatter() { return new ErrorMailHtmlFormatter(); } /// <summary> /// Sends the e-mail using SmtpMail or SmtpClient. /// </summary> protected virtual void SendMail(MailMessage mail) { if (mail == null) throw new ArgumentNullException("mail"); // // Under .NET Framework 2.0, the authentication settings // go on the SmtpClient object rather than mail message // so these have to be set up here. // var client = new SmtpClient(); var host = SmtpServer ?? string.Empty; if (host.Length > 0) { client.Host = host; client.DeliveryMethod = SmtpDeliveryMethod.Network; } var port = SmtpPort; if (port > 0) client.Port = port; var userName = AuthUserName ?? string.Empty; var password = AuthPassword ?? string.Empty; if (userName.Length > 0 && password.Length > 0) client.Credentials = new NetworkCredential(userName, password); client.EnableSsl = UseSsl; try { client.Send(mail); } catch (Exception ex) { // an exception here would cause the app pool to terminate! // unfortunately there's not much we can do other than swallow it // we'll send it off to any trace listeners we may have though. Trace.TraceError("Error sending mail! {0}\n{1}", ex.Message, ex.StackTrace); } } /// <summary> /// Fires the <see cref="Mailing"/> event. /// </summary> protected virtual void OnMailing(ErrorMailEventArgs args) { if (args == null) throw new ArgumentNullException("args"); var handler = Mailing; if (handler != null) handler(this, args); } /// <summary> /// Fires the <see cref="Mailed"/> event. /// </summary> protected virtual void OnMailed(ErrorMailEventArgs args) { if (args == null) throw new ArgumentNullException("args"); var handler = Mailed; if (handler != null) handler(this, args); } /// <summary> /// Fires the <see cref="DisposingMail"/> event. /// </summary> protected virtual void OnDisposingMail(ErrorMailEventArgs args) { if (args == null) throw new ArgumentNullException("args"); var handler = DisposingMail; if (handler != null) handler(this, args); } /// <summary> /// Gets the configuration object used by <see cref="OnInit"/> to read /// the settings for module. /// </summary> protected virtual object GetConfig() { return Configuration.GetSubsection("errorMail"); } private static string GetSetting(IDictionary config, string name) { return GetSetting(config, name, null); } private static string GetSetting(IDictionary config, string name, string defaultValue) { Debug.Assert(config != null); Debug.AssertStringNotEmpty(name); var value = ((string) config[name]) ?? string.Empty; if (value.Length == 0) { if (defaultValue == null) { throw new ApplicationException(string.Format( "The required configuration setting '{0}' is missing for the error mailing module.", name)); } value = defaultValue; } return value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using Task = System.Threading.Tasks.Task; namespace Microsoft.DotNet.Build.Tasks.Utility { public class UploadClient { private TaskLoggingHelper log; public UploadClient(TaskLoggingHelper loggingHelper) { log = loggingHelper; } public string EncodeBlockIds(int numberOfBlocks, int lengthOfId) { string numberOfBlocksString = numberOfBlocks.ToString("D" + lengthOfId); if (Encoding.UTF8.GetByteCount(numberOfBlocksString) <= 64) { byte[] bytes = Encoding.UTF8.GetBytes(numberOfBlocksString); return Convert.ToBase64String(bytes); } else { throw new Exception("Task failed - Could not encode block id."); } } public async Task UploadBlockBlobAsync( CancellationToken ct, string AccountName, string AccountKey, string ContainerName, string filePath, string destinationBlob) { string resourceUrl = string.Format("https://{0}.blob.core.windows.net/{1}", AccountName, ContainerName); string fileName = destinationBlob; fileName = fileName.Replace("\\", "/"); string blobUploadUrl = resourceUrl + "/" + fileName; int size = (int)new FileInfo(filePath).Length; int blockSize = 4 * 1024 * 1024; //4MB max size of a block blob int bytesLeft = size; List<string> blockIds = new List<string>(); int numberOfBlocks = (size / blockSize) + 1; int countForId = 0; using (FileStream fileStreamTofilePath = new FileStream(filePath, FileMode.Open)) { int offset = 0; while (bytesLeft > 0) { int nextBytesToRead = (bytesLeft < blockSize) ? bytesLeft : blockSize; byte[] fileBytes = new byte[blockSize]; int read = fileStreamTofilePath.Read(fileBytes, 0, nextBytesToRead); if (nextBytesToRead != read) { throw new Exception(string.Format( "Number of bytes read ({0}) from file {1} isn't equal to the number of bytes expected ({2}) .", read, fileName, nextBytesToRead)); } string blockId = EncodeBlockIds(countForId, numberOfBlocks.ToString().Length); blockIds.Add(blockId); string blockUploadUrl = blobUploadUrl + "?comp=block&blockid=" + WebUtility.UrlEncode(blockId); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Clear(); Func<HttpRequestMessage> createRequest = () => { DateTime dt = DateTime.UtcNow; var req = new HttpRequestMessage(HttpMethod.Put, blockUploadUrl); req.Headers.Add(AzureHelper.DateHeaderString, dt.ToString("R", CultureInfo.InvariantCulture)); req.Headers.Add(AzureHelper.VersionHeaderString, AzureHelper.StorageApiVersion); req.Headers.Add( AzureHelper.AuthorizationHeaderString, AzureHelper.AuthorizationHeader( AccountName, AccountKey, "PUT", dt, req, string.Empty, string.Empty, nextBytesToRead.ToString(), string.Empty)); Stream postStream = new MemoryStream(); postStream.Write(fileBytes, 0, nextBytesToRead); postStream.Seek(0, SeekOrigin.Begin); req.Content = new StreamContent(postStream); return req; }; log.LogMessage(MessageImportance.Low, "Sending request to upload part {0} of file {1}", countForId, fileName); using (HttpResponseMessage response = await AzureHelper.RequestWithRetry(log, client, createRequest)) { log.LogMessage( MessageImportance.Low, "Received response to upload part {0} of file {1}: Status Code:{2} Status Desc: {3}", countForId, fileName, response.StatusCode, await response.Content.ReadAsStringAsync()); } } offset += read; bytesLeft -= nextBytesToRead; countForId += 1; } } string blockListUploadUrl = blobUploadUrl + "?comp=blocklist"; using (HttpClient client = new HttpClient()) { Func<HttpRequestMessage> createRequest = () => { DateTime dt1 = DateTime.UtcNow; var req = new HttpRequestMessage(HttpMethod.Put, blockListUploadUrl); req.Headers.Add(AzureHelper.DateHeaderString, dt1.ToString("R", CultureInfo.InvariantCulture)); req.Headers.Add(AzureHelper.VersionHeaderString, AzureHelper.StorageApiVersion); string contentType = DetermineContentTypeBasedOnFileExtension(filePath); if (!string.IsNullOrEmpty(contentType)) { req.Headers.Add(AzureHelper.ContentTypeString, contentType); } string cacheControl = DetermineCacheControlBasedOnFileExtension(filePath); if (!string.IsNullOrEmpty(cacheControl)) { req.Headers.Add(AzureHelper.CacheControlString, cacheControl); } var body = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><BlockList>"); foreach (object item in blockIds) body.AppendFormat("<Latest>{0}</Latest>", item); body.Append("</BlockList>"); byte[] bodyData = Encoding.UTF8.GetBytes(body.ToString()); req.Headers.Add( AzureHelper.AuthorizationHeaderString, AzureHelper.AuthorizationHeader( AccountName, AccountKey, "PUT", dt1, req, string.Empty, string.Empty, bodyData.Length.ToString(), string.Empty)); Stream postStream = new MemoryStream(); postStream.Write(bodyData, 0, bodyData.Length); postStream.Seek(0, SeekOrigin.Begin); req.Content = new StreamContent(postStream); return req; }; using (HttpResponseMessage response = await AzureHelper.RequestWithRetry(log, client, createRequest)) { log.LogMessage( MessageImportance.Low, "Received response to combine block list for file {0}: Status Code:{1} Status Desc: {2}", fileName, response.StatusCode, await response.Content.ReadAsStringAsync()); } } } private string DetermineContentTypeBasedOnFileExtension(string filename) { if(Path.GetExtension(filename) == ".svg") { return "image/svg+xml"; } else if(Path.GetExtension(filename) == ".version") { return "text/plain"; } return string.Empty; } private string DetermineCacheControlBasedOnFileExtension(string filename) { if(Path.GetExtension(filename) == ".svg") { return "No-Cache"; } return string.Empty; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Wintellect.PowerCollections; public static class Messages { private static StringBuilder output = new StringBuilder(); public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } public class Event : IComparable { private DateTime date; private string title; private string location; public Event(DateTime date, string title, string location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int byDate = this.date.CompareTo(other.date); int byTitle = this.title.CompareTo(other.title); int byLocation = this.location.CompareTo(other.location); if (byDate == 0) { if (byTitle == 0) { return byLocation; } else { return byTitle; } } else { return byDate; } } public override string ToString() { StringBuilder toString = new StringBuilder(); toString.Append(this.date.ToString("yyyy-MM-ddTHH:mm:ss")); toString.Append(" | " + this.title); if (this.location != null && this.location != string.Empty) { toString.Append(" | " + this.location); } return toString.ToString(); } } public class EventHolder { private MultiDictionary<string, Event> byTitle = new MultiDictionary<string, Event>(true); private OrderedBag<Event> byDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); this.byTitle.Add(title.ToLower(), newEvent); this.byDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { string title = titleToDelete.ToLower(); int removed = 0; foreach (var eventToRemove in this.byTitle[title]) { removed++; this.byDate.Remove(eventToRemove); } this.byTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { OrderedBag<Event>.View eventsToShow = this.byDate.RangeFrom(new Event(date, string.Empty, string.Empty), true); int showed = 0; foreach (var eventToShow in eventsToShow) { if (showed == count) { break; } Messages.PrintEvent(eventToShow); showed++; } if (showed == 0) { Messages.NoEventsFound(); } } } public class Program { private static EventHolder events = new EventHolder(); public static void Main(string[] args) { while (ExecuteNextCommand()) { Console.WriteLine(output); } } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); if (command[0] == 'A') { AddEvent(command); return true; } if (command[0] == 'D') { DeleteEvents(command); return true; } if (command[0] == 'L') { ListEvents(command); return true; } if (command[0] == 'E') { return false; } return false; } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate(command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters(string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim(); eventLocation = string.Empty; } else { eventTitle = commandForExecution.Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1).Trim(); eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using Microsoft.PythonTools.Editor; using Microsoft.PythonTools.Editor.Core; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; using Microsoft.PythonTools.Projects; using Microsoft.VisualStudio; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.IncrementalSearch; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.TextManager.Interop; using VSConstants = Microsoft.VisualStudio.VSConstants; namespace Microsoft.PythonTools.Intellisense { internal sealed class IntellisenseController : IIntellisenseController, IOleCommandTarget, IPythonTextBufferInfoEventSink { private readonly PythonEditorServices _services; private readonly ITextView _textView; private readonly IntellisenseControllerProvider _provider; private readonly IIncrementalSearch _incSearch; private readonly ExpansionClient _expansionClient; private readonly IVsExpansionManager _expansionMgr; private ICompletionSession _activeSession; private ISignatureHelpSession _sigHelpSession; private IAsyncQuickInfoSession _quickInfoSession; internal IOleCommandTarget _oldTarget; private IEditorOperations _editOps; private static readonly string[] _allStandardSnippetTypes = { ExpansionClient.Expansion, ExpansionClient.SurroundsWith }; private static readonly string[] _surroundsWithSnippetTypes = { ExpansionClient.SurroundsWith, ExpansionClient.SurroundsWithStatement }; public static readonly object SuppressErrorLists = new object(); public static readonly object FollowDefaultEnvironment = new object(); /// <summary> /// Attaches events for invoking Statement completion /// </summary> public IntellisenseController(IntellisenseControllerProvider provider, ITextView textView) { _textView = textView; _provider = provider; _services = _provider.Services; _editOps = _services.EditOperationsFactory.GetEditorOperations(textView); _incSearch = _services.IncrementalSearch.GetIncrementalSearch(textView); _textView.MouseHover += TextViewMouseHover; _services.Python.InterpreterOptionsService.DefaultInterpreterChanged += InterpreterOptionsService_DefaultInterpreterChanged; if (textView.TextBuffer.IsPythonContent()) { try { _expansionClient = new ExpansionClient(textView, _services); _services.VsTextManager2.GetExpansionManager(out _expansionMgr); } catch (ArgumentException) { // No expansion client for this buffer, but we can continue without it } } textView.Properties.AddProperty(typeof(IntellisenseController), this); // added so our key processors can get back to us _textView.Closed += TextView_Closed; } private void TextView_Closed(object sender, EventArgs e) { Close(); } internal void Close() { _textView.MouseHover -= TextViewMouseHover; _textView.Closed -= TextView_Closed; _textView.Properties.RemoveProperty(typeof(IntellisenseController)); _services.Python.InterpreterOptionsService.DefaultInterpreterChanged -= InterpreterOptionsService_DefaultInterpreterChanged; // Do not disconnect subject buffers here - VS will handle that for us } private void TextViewMouseHover(object sender, MouseHoverEventArgs e) { TextViewMouseHoverWorker(e) .HandleAllExceptions(_services.Site, GetType()) .DoNotWait(); } private static async Task DismissQuickInfo(IAsyncQuickInfoSession session) { if (session != null && session.State != QuickInfoSessionState.Dismissed) { await session.DismissAsync(); } } private async Task TextViewMouseHoverWorker(MouseHoverEventArgs e) { var pt = e.TextPosition.GetPoint(EditorExtensions.IsPythonContent, PositionAffinity.Successor); if (pt == null) { return; } if (_textView.TextBuffer.GetInteractiveWindow() != null && pt.Value.Snapshot.Length > 1 && pt.Value.Snapshot[0] == '$') { // don't provide quick info on help, the content type doesn't switch until we have // a complete command otherwise we shouldn't need to do this. await DismissQuickInfo(Interlocked.Exchange(ref _quickInfoSession, null)); return; } var entry = await e.View.TextBuffer.GetAnalysisEntryAsync(_services); if (entry == null) { await DismissQuickInfo(Interlocked.Exchange(ref _quickInfoSession, null)); return; } var session = _quickInfoSession; if (session != null) { try { var span = session.ApplicableToSpan?.GetSpan(pt.Value.Snapshot); if (span != null && span.Value.Contains(pt.Value)) { return; } } catch (ArgumentException) { } } var t = entry.Analyzer.GetQuickInfoAsync(entry, _textView, pt.Value); var quickInfo = await Task.Run(() => entry.Analyzer.WaitForRequest(t, "GetQuickInfo", null, 2)); AsyncQuickInfoSource.AddQuickInfo(_textView, quickInfo); if (quickInfo == null) { await DismissQuickInfo(Interlocked.Exchange(ref _quickInfoSession, null)); return; } var viewPoint = _textView.BufferGraph.MapUpToBuffer( pt.Value, PointTrackingMode.Positive, PositionAffinity.Successor, _textView.TextBuffer ); if (viewPoint != null) { _quickInfoSession = await _services.QuickInfoBroker.TriggerQuickInfoAsync( _textView, viewPoint.Value.Snapshot.CreateTrackingPoint(viewPoint.Value, PointTrackingMode.Positive), QuickInfoSessionOptions.TrackMouse ); } } internal async Task TriggerQuickInfoAsync() { if (_quickInfoSession != null && _quickInfoSession.State != QuickInfoSessionState.Dismissed) { await _quickInfoSession.DismissAsync(); } _quickInfoSession = await _services.QuickInfoBroker.TriggerQuickInfoAsync(_textView); } private static object _intellisenseAnalysisEntry = new object(); public async void ConnectSubjectBuffer(ITextBuffer subjectBuffer) { var buffer = _services.GetBufferInfo(subjectBuffer); for (int retries = 5; retries > 0; --retries) { try { await ConnectSubjectBufferAsync(buffer); return; } catch (InvalidOperationException) { // Analysis entry changed, so we should retry } } Debug.Fail("Failed to connect subject buffer after multiple retries"); } private static async Task<AnalysisEntry> AnalyzeBufferAsync(ITextView textView, PythonTextBufferInfo bufferInfo) { ProjectAnalyzer analyzer; var services = bufferInfo.Services; bool isTemporaryFile = false, followDefaultEnvironment = false; analyzer = await services.Site.FindAnalyzerAsync(bufferInfo); if (analyzer == null) { // there's no analyzer for this file, but we can analyze it against either // the default analyzer or some other analyzer (e.g. if it's a diff view, we want // to analyze against the project we're diffing from). But in either case this // is just a temporary file which should be closed when the view is closed. isTemporaryFile = true; analyzer = await services.Site.FindAnalyzerAsync(textView); if (analyzer == null) { var pytoolsSvc = services.Python; if (pytoolsSvc != null) { analyzer = await pytoolsSvc.GetSharedAnalyzerAsync(); } followDefaultEnvironment = true; } } var vsAnalyzer = analyzer as VsProjectAnalyzer; if (vsAnalyzer == null) { return null; } bool suppressErrorList = textView.Properties.ContainsProperty(SuppressErrorLists); var entry = await vsAnalyzer.AnalyzeFileAsync(bufferInfo.DocumentUri, bufferInfo.Filename, isTemporaryFile, suppressErrorList); if (entry != null && followDefaultEnvironment) { entry.Properties[FollowDefaultEnvironment] = true; } return entry; } private async Task ConnectSubjectBufferAsync(PythonTextBufferInfo buffer) { buffer.AddSink(this, this); // Cannot analyze buffers without a URI if (buffer.DocumentUri == null) { return; } var entry = buffer.AnalysisEntry; if (entry == null) { for (int retries = 3; retries > 0 && entry == null; --retries) { // Likely in the process of changing analyzer, so we'll delay slightly and retry. await Task.Delay(100); entry = await AnalyzeBufferAsync(_textView, buffer); } if (entry == null) { Debug.Fail($"Failed to analyze {buffer.DocumentUri}"); return; } entry = buffer.TrySetAnalysisEntry(entry, null); if (entry == null) { Debug.Fail("Analysis entry should never be null here"); return; } } var parser = entry.GetOrCreateBufferParser(_services); // This may raise InvalidOperationException if we have raced with // an analyzer being closed. Our caller will retry in this case. parser.AddBuffer(buffer.Buffer); await parser.EnsureCodeSyncedAsync(buffer.Buffer); // AnalysisEntry will be cleared automatically if the analyzer closes if (buffer.AnalysisEntry == null) { throw new InvalidOperationException("Analyzer was closed"); } } public void DisconnectSubjectBuffer(ITextBuffer subjectBuffer) { var bi = PythonTextBufferInfo.TryGetForBuffer(subjectBuffer); bi?.RemoveSink(this); bi?.AnalysisEntry?.TryGetBufferParser()?.RemoveBuffer(subjectBuffer); } private void InterpreterOptionsService_DefaultInterpreterChanged(object sender, EventArgs e) { DefaultInterpreterChanged().HandleAllExceptions(_services.Site, GetType()).DoNotWait(); } private async Task DefaultInterpreterChanged() { VsProjectAnalyzer analyzer = null; foreach (var bi in PythonTextBufferInfo.GetAllFromView(_textView)) { var currentEntry = bi.AnalysisEntry; if (currentEntry != null && currentEntry.Properties.ContainsKey(FollowDefaultEnvironment)) { var oldAnalyzer = currentEntry.Analyzer; if (analyzer == null) { analyzer = await _services.Python.GetSharedAnalyzerAsync(); } if (analyzer == oldAnalyzer) { continue; } if (bi.TrySetAnalysisEntry(null, currentEntry) != null) { continue; } if (oldAnalyzer.RemoveUser()) { oldAnalyzer.Dispose(); } var newEntry = await analyzer.AnalyzeFileAsync(bi.DocumentUri, bi.Filename, true, bi.Buffer.Properties.ContainsProperty(SuppressErrorLists)); newEntry.Properties[FollowDefaultEnvironment] = true; bi.TrySetAnalysisEntry(newEntry, null); } } } public async Task PythonTextBufferEventAsync(PythonTextBufferInfo sender, PythonTextBufferInfoEventArgs e) { if (e.Event == PythonTextBufferInfoEvents.AnalyzerExpired) { // Analysis entry has been cleared. Allow a short pause before // trying to create a new one. await Task.Delay(500); if (sender.AnalysisEntry == null) { for (int retries = 3; retries > 0; --retries) { try { await ConnectSubjectBufferAsync(sender); break; } catch (InvalidOperationException) { } } } } } /// <summary> /// Detaches the events /// </summary> /// <param name="textView"></param> public void Detach(ITextView textView) { if (_textView == null) { throw new InvalidOperationException(Strings.IntellisenseControllerAlreadyDetachedException); } if (textView != _textView) { throw new ArgumentException(Strings.IntellisenseControllerNotAttachedToSpecifiedTextViewException, nameof(textView)); } _textView.MouseHover -= TextViewMouseHover; _textView.Properties.RemoveProperty(typeof(IntellisenseController)); DetachKeyboardFilter(); } private string GetTextBeforeCaret(int includeCharsAfter = 0) { var maybePt = _textView.Caret.Position.Point.GetPoint(_textView.TextBuffer, PositionAffinity.Predecessor); if (!maybePt.HasValue) { return string.Empty; } var pt = maybePt.Value + includeCharsAfter; var span = new SnapshotSpan(pt.GetContainingLine().Start, pt); return span.GetText(); } private void HandleChar(char ch) { // We trigger completions when the user types . or space. Called via our IOleCommandTarget filter // on the text view. // // We trigger signature help when we receive a "(". We update our current sig when // we receive a "," and we close sig help when we receive a ")". if (!_incSearch.IsActive) { var prefs = _services.Python.LangPrefs; var session = Volatile.Read(ref _activeSession); var sigHelpSession = Volatile.Read(ref _sigHelpSession); var literalSpan = GetStringLiteralSpan(); if (literalSpan.HasValue && // UNDONE: Do not automatically trigger file path completions github#2352 //ShouldTriggerStringCompletionSession(prefs, literalSpan.Value) && (session?.IsDismissed ?? true)) { //TriggerCompletionSession(false); return; } switch (ch) { case '@': if (!string.IsNullOrWhiteSpace(GetTextBeforeCaret(-1))) { break; } goto case '.'; case '.': case ' ': if (prefs.AutoListMembers && GetStringLiteralSpan() == null) { TriggerCompletionSession(false, ch).DoNotWait(); } break; case '(': if (prefs.AutoListParams && GetStringLiteralSpan() == null) { OpenParenStartSignatureSession(); } break; case ')': if (sigHelpSession != null) { sigHelpSession.Dismiss(); } if (prefs.AutoListParams) { // trigger help for outer call if there is one TriggerSignatureHelp(); } break; case '=': case ',': if (sigHelpSession == null) { if (prefs.AutoListParams) { CommaStartSignatureSession(); } } else { UpdateCurrentParameter(); } break; default: // Note: Don't call CompletionSets property if session is dismissed to avoid NRE if (Tokenizer.IsIdentifierStartChar(ch) && ((session?.IsDismissed ?? false ? 0 : session?.CompletionSets.Count ?? 0) == 0)) { bool commitByDefault; if (ShouldTriggerIdentifierCompletionSession(out commitByDefault)) { TriggerCompletionSession(false, ch, commitByDefault).DoNotWait(); } } break; } } } private SnapshotSpan? GetStringLiteralSpan() { var pyCaret = _textView.GetPythonCaret(); var classifier = pyCaret?.Snapshot.TextBuffer.GetPythonClassifier(); if (classifier == null) { return null; } var spans = classifier.GetClassificationSpans(new SnapshotSpan(pyCaret.Value.GetContainingLine().Start, pyCaret.Value)); var token = spans.LastOrDefault(); if (!(token?.ClassificationType.IsOfType(PredefinedClassificationTypeNames.String) ?? false)) { return null; } return token.Span; } private bool ShouldTriggerIdentifierCompletionSession(out bool commitByDefault) { commitByDefault = true; if (!_services.Python.AdvancedOptions.AutoListIdentifiers || !_services.Python.AdvancedOptions.AutoListMembers) { return false; } var caretPoint = _textView.GetPythonCaret(); if (!caretPoint.HasValue) { return false; } var snapshot = caretPoint.Value.Snapshot; var statement = new ReverseExpressionParser( snapshot, snapshot.TextBuffer, snapshot.CreateTrackingSpan(caretPoint.Value.Position, 0, SpanTrackingMode.EdgeNegative) ).GetStatementRange(); if (!statement.HasValue || caretPoint.Value <= statement.Value.Start) { return false; } var text = new SnapshotSpan(statement.Value.Start, caretPoint.Value).GetText(); if (string.IsNullOrEmpty(text)) { return false; } var entry = snapshot.TextBuffer.TryGetAnalysisEntry(); if (entry == null) { return false; } var languageVersion = entry.Analyzer.LanguageVersion; var parser = Parser.CreateParser(new StringReader(text), languageVersion, new ParserOptions()); var ast = parser.ParseSingleStatement(); var walker = new ExpressionCompletionWalker(caretPoint.Value.Position - statement.Value.Start.Position); ast.Walk(walker); commitByDefault = walker.CommitByDefault; return walker.CanComplete; } private class ExpressionCompletionWalker : PythonWalker { public bool CanComplete = false; public bool CommitByDefault = true; private readonly int _caretIndex; public ExpressionCompletionWalker(int caretIndex) { _caretIndex = caretIndex; } private static bool IsActualExpression(Expression node) { return node != null && !(node is ErrorExpression); } private static bool IsActualExpression(IList<NameExpression> expressions) { return expressions != null && expressions.Count > 0; } private static bool IsActualExpression(IList<Expression> expressions) { return expressions != null && expressions.Count > 0 && !(expressions[0] is ErrorExpression); } private bool HasCaret(Node node) { return node.StartIndex <= _caretIndex && _caretIndex <= node.EndIndex; } public override bool Walk(ErrorExpression node) { return false; } public override bool Walk(AssignmentStatement node) { CanComplete = true; CommitByDefault = true; if (node.Right != null) { node.Right.Walk(this); } return false; } public override bool Walk(Arg node) { CanComplete = true; CommitByDefault = true; return base.Walk(node); } public override bool Walk(ClassDefinition node) { CanComplete = false; return base.Walk(node); } public override bool Walk(FunctionDefinition node) { CommitByDefault = true; if (node.Parameters != null) { CanComplete = false; foreach (var p in node.Parameters) { p.Walk(this); } } if (node.Decorators != null) { node.Decorators.Walk(this); } if (node.ReturnAnnotation != null) { CanComplete = true; node.ReturnAnnotation.Walk(this); } if (node.Body != null && !(node.Body is ErrorStatement)) { CanComplete = node.IsLambda; node.Body.Walk(this); } return false; } public override bool Walk(Parameter node) { CommitByDefault = true; var afterName = node.Annotation ?? node.DefaultValue; CanComplete = afterName != null && afterName.StartIndex <= _caretIndex; return base.Walk(node); } public override bool Walk(ComprehensionFor node) { if (!IsActualExpression(node.Left) || HasCaret(node.Left)) { CanComplete = false; CommitByDefault = false; } else if (IsActualExpression(node.List)) { CanComplete = true; CommitByDefault = true; node.List.Walk(this); } return false; } public override bool Walk(ComprehensionIf node) { CanComplete = true; CommitByDefault = true; return base.Walk(node); } private bool WalkCollection(Expression node, IEnumerable<Expression> items) { CanComplete = HasCaret(node); int count = 0; Expression last = null; foreach (var e in items) { count += 1; last = e; } if (count == 0) { CommitByDefault = false; } else if (count == 1) { last.Walk(this); CommitByDefault = false; } else { CommitByDefault = true; last.Walk(this); } return false; } public override bool Walk(ListExpression node) { return WalkCollection(node, node.Items); } public override bool Walk(DictionaryExpression node) { return WalkCollection(node, node.Items); } public override bool Walk(SetExpression node) { return WalkCollection(node, node.Items); } public override bool Walk(TupleExpression node) { return WalkCollection(node, node.Items); } public override bool Walk(ParenthesisExpression node) { CanComplete = HasCaret(node); CommitByDefault = false; return base.Walk(node); } public override bool Walk(AssertStatement node) { CanComplete = IsActualExpression(node.Test); CommitByDefault = true; return base.Walk(node); } public override bool Walk(AugmentedAssignStatement node) { CanComplete = IsActualExpression(node.Right); CommitByDefault = true; return base.Walk(node); } public override bool Walk(AwaitExpression node) { CanComplete = IsActualExpression(node.Expression); CommitByDefault = true; return base.Walk(node); } public override bool Walk(DelStatement node) { CanComplete = IsActualExpression(node.Expressions); CommitByDefault = true; return base.Walk(node); } public override bool Walk(ExecStatement node) { CanComplete = IsActualExpression(node.Code); CommitByDefault = true; return base.Walk(node); } public override bool Walk(ExpressionStatement node) { if (node.Expression is TupleExpression) { node.Expression.Walk(this); CommitByDefault = false; return false; } else if (node.Expression is ConstantExpression) { node.Expression.Walk(this); return false; } else if (node.Expression is ErrorExpression) { // Might be an unfinished string literal, which we care about node.Expression.Walk(this); return false; } CanComplete = true; CommitByDefault = false; return base.Walk(node); } public override bool Walk(ForStatement node) { if (!IsActualExpression(node.Left) || HasCaret(node.Left)) { CanComplete = false; CommitByDefault = false; } else if (IsActualExpression(node.List)) { CanComplete = true; CommitByDefault = true; node.List.Walk(this); } return false; } public override bool Walk(IfStatementTest node) { CanComplete = IsActualExpression(node.Test); CommitByDefault = true; return base.Walk(node); } public override bool Walk(GlobalStatement node) { CanComplete = IsActualExpression(node.Names); CommitByDefault = true; return base.Walk(node); } public override bool Walk(NonlocalStatement node) { CanComplete = IsActualExpression(node.Names); CommitByDefault = true; return base.Walk(node); } public override bool Walk(PrintStatement node) { CanComplete = IsActualExpression(node.Expressions); CommitByDefault = true; return base.Walk(node); } public override bool Walk(ReturnStatement node) { CanComplete = IsActualExpression(node.Expression); CommitByDefault = true; return base.Walk(node); } public override bool Walk(WhileStatement node) { CanComplete = IsActualExpression(node.Test); CommitByDefault = true; return base.Walk(node); } public override bool Walk(WithStatement node) { CanComplete = true; CommitByDefault = true; if (node.Items != null) { var item = node.Items.LastOrDefault(); if (item != null) { if (item.Variable != null) { CanComplete = false; } else { item.Walk(this); } } } if (node.Body != null) { node.Body.Walk(this); } return false; } public override bool Walk(YieldExpression node) { CommitByDefault = true; if (IsActualExpression(node.Expression)) { // "yield" is valid and has implied None following it var ce = node.Expression as ConstantExpression; CanComplete = ce == null || ce.Value != null; } return base.Walk(node); } public override bool Walk(ConstantExpression node) { return false; } } private bool Backspace() { var sigHelpSession = Volatile.Read(ref _sigHelpSession); if (sigHelpSession != null) { if (_textView.Selection.IsActive && !_textView.Selection.IsEmpty) { // when deleting a selection don't do anything to pop up signature help again sigHelpSession.Dismiss(); return false; } SnapshotPoint? caretPoint = _textView.BufferGraph.MapDownToFirstMatch( _textView.Caret.Position.BufferPosition, PointTrackingMode.Positive, EditorExtensions.IsPythonContent, PositionAffinity.Predecessor ); if (caretPoint != null && caretPoint.Value.Position != 0) { var deleting = caretPoint.Value.Snapshot[caretPoint.Value.Position - 1]; if (deleting == ',') { caretPoint.Value.Snapshot.TextBuffer.Delete(new Span(caretPoint.Value.Position - 1, 1)); UpdateCurrentParameter(); return true; } else if (deleting == '(' || deleting == ')') { sigHelpSession.Dismiss(); // delete the ( before triggering help again caretPoint.Value.Snapshot.TextBuffer.Delete(new Span(caretPoint.Value.Position - 1, 1)); // Pop to an outer nesting of signature help if (_services.Python.LangPrefs.AutoListParams) { TriggerSignatureHelp(); } return true; } } } return false; } private void OpenParenStartSignatureSession() { Volatile.Read(ref _activeSession)?.Dismiss(); Volatile.Read(ref _sigHelpSession)?.Dismiss(); TriggerSignatureHelp(); } private void CommaStartSignatureSession() { TriggerSignatureHelp(); } /// <summary> /// Updates the current parameter for the caret's current position. /// /// This will analyze the buffer for where we are currently located, find the current /// parameter that we're entering, and then update the signature. If our current /// signature does not have enough parameters we'll find a signature which does. /// </summary> private void UpdateCurrentParameter() { var sigHelpSession = Volatile.Read(ref _sigHelpSession); if (sigHelpSession == null) { // we moved out of the original span for sig help, re-trigger based upon the position TriggerSignatureHelp(); return; } int position = _textView.Caret.Position.BufferPosition.Position; // we advance to the next parameter // TODO: Take into account params arrays // TODO: need to parse and see if we have keyword arguments entered into the current signature yet PythonSignature sig = sigHelpSession.SelectedSignature as PythonSignature; if (sig == null) { return; } var prevBuffer = sig.ApplicableToSpan.TextBuffer; var targetPt = _textView.BufferGraph.MapDownToFirstMatch( new SnapshotPoint(_textView.TextBuffer.CurrentSnapshot, position), PointTrackingMode.Positive, EditorExtensions.IsPythonContent, PositionAffinity.Successor ); if (targetPt == null) { return; } var span = targetPt.Value.Snapshot.CreateTrackingSpan(targetPt.Value.Position, 0, SpanTrackingMode.EdgeInclusive); var sigs = _services.Python.GetSignatures(_textView, targetPt.Value.Snapshot, span); if (sigs == null) { return; } bool retrigger = false; if (sigs.Signatures.Count == sigHelpSession.Signatures.Count) { for (int i = 0; i < sigs.Signatures.Count && !retrigger; i++) { var leftSig = sigs.Signatures[i]; var rightSig = sigHelpSession.Signatures[i]; if (leftSig.Parameters.Count == rightSig.Parameters.Count) { for (int j = 0; j < leftSig.Parameters.Count; j++) { var leftParam = leftSig.Parameters[j]; var rightParam = rightSig.Parameters[j]; if (leftParam == null || rightParam == null) { continue; } if (leftParam.Name != rightParam.Name || leftParam.Documentation != rightParam.Documentation) { retrigger = true; break; } } } if (leftSig.Content != rightSig.Content || leftSig.Documentation != rightSig.Documentation) { retrigger = true; } } } else { retrigger = true; } if (retrigger) { sigHelpSession.Dismiss(); TriggerSignatureHelp(); } else { CommaFindBestSignature(sigHelpSession, sigs.ParameterIndex, sigs.LastKeywordArgument); } } private static void CommaFindBestSignature(ISignatureHelpSession sigHelpSession, int curParam, string lastKeywordArg) { // see if we have a signature which accomodates this... // TODO: We should also get the types of the arguments and use that to // pick the best signature when the signature includes types. var bestSig = sigHelpSession.SelectedSignature as PythonSignature; if (bestSig != null) { if (bestSig.SelectBestParameter(curParam, lastKeywordArg) >= 0) { sigHelpSession.SelectedSignature = bestSig; return; } } PythonSignature fallback = null; foreach (var sig in sigHelpSession.Signatures.OfType<PythonSignature>().OrderBy(s => s.Parameters.Count)) { fallback = sig; if (sig.SelectBestParameter(curParam, lastKeywordArg) >= 0) { sigHelpSession.SelectedSignature = sig; return; } } if (fallback != null) { fallback.ClearParameter(); sigHelpSession.SelectedSignature = fallback; } else { sigHelpSession.Dismiss(); } } private bool SelectSingleBestCompletion(ICompletionSession session) { if (session.CompletionSets.Count != 1) { return false; } var set = session.CompletionSets[0] as FuzzyCompletionSet; if (set == null) { return false; } if (set.SelectSingleBest()) { session.Commit(); return true; } return false; } internal async Task TriggerCompletionSession(bool completeWord, char triggerChar, bool? commitByDefault = null) { var caretPoint = _textView.TextBuffer.CurrentSnapshot.CreateTrackingPoint(_textView.Caret.Position.BufferPosition, PointTrackingMode.Positive); var session = _services.CompletionBroker.CreateCompletionSession(_textView, caretPoint, true); if (session == null) { // Session is null when text view has multiple carets return; } session.SetTriggerCharacter(triggerChar); if (completeWord) { session.SetCompleteWordMode(); } var oldSession = Interlocked.Exchange(ref _activeSession, session); if (oldSession != null && !oldSession.IsDismissed) { oldSession.Dismiss(); } if (triggerChar == ' ' || triggerChar == '.') { var bi = _textView.TextBuffer.TryGetInfo(); if (bi == null) { bi = _textView.MapDownToPythonBuffer(_textView.Caret.Position.BufferPosition)?.Snapshot.TextBuffer.TryGetInfo(); } var bp = bi?.AnalysisEntry?.TryGetBufferParser(); if (bp != null) { await bp.EnsureCodeSyncedAsync(bi.Buffer); } } if (session.IsStarted || session.IsDismissed) { return; } session.Start(); if (!session.IsStarted) { Volatile.Write(ref _activeSession, null); return; } if (completeWord && SelectSingleBestCompletion(session)) { session.Commit(); return; } if (commitByDefault.HasValue) { foreach (var s in session.CompletionSets.OfType<FuzzyCompletionSet>()) { s.CommitByDefault = commitByDefault.GetValueOrDefault(); } } session.Filter(); session.Dismissed += OnCompletionSessionDismissedOrCommitted; session.Committed += OnCompletionSessionDismissedOrCommitted; } internal void TriggerSignatureHelp() { Volatile.Read(ref _sigHelpSession)?.Dismiss(); ISignatureHelpSession sigHelpSession = null; try { sigHelpSession = _services.SignatureHelpBroker.TriggerSignatureHelp(_textView); } catch (ObjectDisposedException) { } if (sigHelpSession != null) { sigHelpSession.Dismissed += OnSignatureSessionDismissed; ISignature sig; if (sigHelpSession.Properties.TryGetProperty(typeof(PythonSignature), out sig)) { sigHelpSession.SelectedSignature = sig; } _sigHelpSession = sigHelpSession; } } private void OnCompletionSessionDismissedOrCommitted(object sender, EventArgs e) { // We've just been told that our active session was dismissed. We should remove all references to it. var session = sender as ICompletionSession; if (session == null) { Debug.Fail("invalid type passed to event"); return; } session.Committed -= OnCompletionSessionDismissedOrCommitted; session.Dismissed -= OnCompletionSessionDismissedOrCommitted; Interlocked.CompareExchange(ref _activeSession, null, session); } private void OnSignatureSessionDismissed(object sender, EventArgs e) { // We've just been told that our active session was dismissed. We should remove all references to it. var session = sender as ISignatureHelpSession; if (session == null) { Debug.Fail("invalid type passed to event"); return; } session.Dismissed -= OnSignatureSessionDismissed; Interlocked.CompareExchange(ref _sigHelpSession, null, session); } private void DeleteSelectedSpans() { if (!_textView.Selection.IsEmpty) { _editOps.Delete(); } } internal bool DismissCompletionSession() { var session = Interlocked.Exchange(ref _activeSession, null); if (session != null && !session.IsDismissed) { session.Dismiss(); return true; } return false; } #region IOleCommandTarget Members // we need this because VS won't give us certain keyboard events as they're handled before our key processor. These // include enter and tab both of which we want to complete. internal void AttachKeyboardFilter() { if (_oldTarget == null) { var viewAdapter = _services.EditorAdaptersFactoryService.GetViewAdapter(_textView); if (viewAdapter != null) { ErrorHandler.ThrowOnFailure(viewAdapter.AddCommandFilter(this, out _oldTarget)); } } } private void DetachKeyboardFilter() { if (_oldTarget != null) { ErrorHandler.ThrowOnFailure(_services.EditorAdaptersFactoryService.GetViewAdapter(_textView).RemoveCommandFilter(this)); _oldTarget = null; } } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { var session = Volatile.Read(ref _activeSession); ISignatureHelpSession sigHelpSession; if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (int)VSConstants.VSStd2KCmdID.TYPECHAR) { var ch = (char)(ushort)System.Runtime.InteropServices.Marshal.GetObjectForNativeVariant(pvaIn); bool suppressChar = false; if (session != null && !session.IsDismissed) { if (session.SelectedCompletionSet != null && session.SelectedCompletionSet.SelectionStatus.IsSelected && _services.Python.AdvancedOptions.CompletionCommittedBy.IndexOf(ch) != -1) { if ((ch == '\\' || ch == '/') && session.SelectedCompletionSet.Moniker == "PythonFilenames") { // We want to dismiss filename completions on slashes // rather than committing them. Then it will probably // be retriggered after the slash is inserted. session.Dismiss(); } else { if (ch == session.SelectedCompletionSet.SelectionStatus.Completion.InsertionText.LastOrDefault()) { suppressChar = true; } session.Commit(); } } else if (!Tokenizer.IsIdentifierChar(ch)) { session.Dismiss(); } } int res = VSConstants.S_OK; if (!suppressChar) { res = _oldTarget != null ? _oldTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut) : VSConstants.S_OK; HandleChar(ch); if (session != null && session.IsStarted && !session.IsDismissed) { session.Filter(); } } return res; } if (session != null) { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.RETURN: if (_services.Python.AdvancedOptions.EnterCommitsIntellisense && !session.IsDismissed && (session.SelectedCompletionSet?.SelectionStatus.IsSelected ?? false)) { // If the user has typed all of the characters as the completion and presses // enter we should dismiss & let the text editor receive the enter. For example // when typing "import sys[ENTER]" completion starts after the space. After typing // sys the user wants a new line and doesn't want to type enter twice. bool enterOnComplete = _services.Python.AdvancedOptions.AddNewLineAtEndOfFullyTypedWord && EnterOnCompleteText(session); session.Commit(); if (!enterOnComplete) { return VSConstants.S_OK; } } else { session.Dismiss(); } break; case VSConstants.VSStd2KCmdID.TAB: if (!session.IsDismissed) { session.Commit(); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.BACKSPACE: case VSConstants.VSStd2KCmdID.DELETE: case VSConstants.VSStd2KCmdID.DELETEWORDLEFT: case VSConstants.VSStd2KCmdID.DELETEWORDRIGHT: int res = _oldTarget != null ? _oldTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut) : VSConstants.S_OK; if (session != null && session.IsStarted && !session.IsDismissed) { session.Filter(); } return res; } } } else if ((sigHelpSession = Volatile.Read(ref _sigHelpSession)) != null) { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.BACKSPACE: bool fDeleted = Backspace(); if (fDeleted) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.LEFT: _editOps.MoveToPreviousCharacter(false); UpdateCurrentParameter(); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.RIGHT: _editOps.MoveToNextCharacter(false); UpdateCurrentParameter(); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.HOME: case VSConstants.VSStd2KCmdID.BOL: case VSConstants.VSStd2KCmdID.BOL_EXT: case VSConstants.VSStd2KCmdID.EOL: case VSConstants.VSStd2KCmdID.EOL_EXT: case VSConstants.VSStd2KCmdID.END: case VSConstants.VSStd2KCmdID.WORDPREV: case VSConstants.VSStd2KCmdID.WORDPREV_EXT: case VSConstants.VSStd2KCmdID.DELETEWORDLEFT: sigHelpSession.Dismiss(); break; } } } else { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.RETURN: if (_expansionMgr != null && _expansionClient.InSession && ErrorHandler.Succeeded(_expansionClient.EndCurrentExpansion(false))) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.TAB: if (_expansionMgr != null && _expansionClient.InSession && ErrorHandler.Succeeded(_expansionClient.NextField())) { return VSConstants.S_OK; } if (_textView.Selection.IsEmpty && _textView.Caret.Position.BufferPosition > 0) { if (TryTriggerExpansion()) { return VSConstants.S_OK; } } break; case VSConstants.VSStd2KCmdID.BACKTAB: if (_expansionMgr != null && _expansionClient.InSession && ErrorHandler.Succeeded(_expansionClient.PreviousField())) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.SURROUNDWITH: case VSConstants.VSStd2KCmdID.INSERTSNIPPET: TriggerSnippet(nCmdID); return VSConstants.S_OK; } } } if (_oldTarget != null) { return _oldTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } return (int)Constants.OLECMDERR_E_UNKNOWNGROUP; } private void TriggerSnippet(uint nCmdID) { if (_expansionMgr != null) { string prompt; string[] snippetTypes; if ((VSConstants.VSStd2KCmdID)nCmdID == VSConstants.VSStd2KCmdID.SURROUNDWITH) { prompt = Strings.SurroundWith; snippetTypes = _surroundsWithSnippetTypes; } else { prompt = Strings.InsertSnippet; snippetTypes = _allStandardSnippetTypes; } _expansionMgr.InvokeInsertionUI( GetViewAdapter(), _expansionClient, GuidList.guidPythonLanguageServiceGuid, snippetTypes, snippetTypes.Length, 0, null, 0, 0, prompt, ">" ); } } private bool TryTriggerExpansion() { if (_expansionMgr != null) { var snapshot = _textView.TextBuffer.CurrentSnapshot; var span = new SnapshotSpan(snapshot, new Span(_textView.Caret.Position.BufferPosition.Position - 1, 1)); var classification = _textView.TextBuffer.GetPythonClassifier().GetClassificationSpans(span); if (classification.Count == 1) { var clsSpan = classification.First().Span; var text = classification.First().Span.GetText(); TextSpan[] textSpan = new TextSpan[1]; textSpan[0].iStartLine = clsSpan.Start.GetContainingLine().LineNumber; textSpan[0].iStartIndex = clsSpan.Start.Position - clsSpan.Start.GetContainingLine().Start; textSpan[0].iEndLine = clsSpan.End.GetContainingLine().LineNumber; textSpan[0].iEndIndex = clsSpan.End.Position - clsSpan.End.GetContainingLine().Start; string expansionPath, title; int hr = _expansionMgr.GetExpansionByShortcut( _expansionClient, GuidList.guidPythonLanguageServiceGuid, text, GetViewAdapter(), textSpan, 1, out expansionPath, out title ); if (ErrorHandler.Succeeded(hr)) { // hr may be S_FALSE if there are multiple expansions, // so we don't want to InsertNamedExpansion yet. VS will // pop up a selection dialog in this case. if (hr == VSConstants.S_OK) { return ErrorHandler.Succeeded(_expansionClient.InsertNamedExpansion(title, expansionPath, textSpan[0])); } return true; } } } return false; } private IVsTextView GetViewAdapter() { return _services.EditorAdaptersFactoryService.GetViewAdapter(_textView); } private bool EnterOnCompleteText(ICompletionSession session) { var selectionStatus = session.SelectedCompletionSet.SelectionStatus; var mcaret = session.TextView.MapDownToPythonBuffer(session.TextView.Caret.Position.BufferPosition); if (!mcaret.HasValue) { return false; } var caret = mcaret.Value; var span = session.SelectedCompletionSet.ApplicableTo.GetSpan(caret.Snapshot); return caret == span.End && span.Length == selectionStatus.Completion?.InsertionText.Length && span.GetText() == selectionStatus.Completion.InsertionText; } public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == VSConstants.VSStd2K) { for (int i = 0; i < cCmds; i++) { switch ((VSConstants.VSStd2KCmdID)prgCmds[i].cmdID) { case VSConstants.VSStd2KCmdID.SURROUNDWITH: case VSConstants.VSStd2KCmdID.INSERTSNIPPET: if (_expansionMgr != null) { prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); return VSConstants.S_OK; } break; } } } if (_oldTarget != null) { return _oldTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } return (int)Constants.OLECMDERR_E_UNKNOWNGROUP; } #endregion } }
/* * TestXmlTextReader.cs - Tests for the * "System.Xml.TestXmlTextReader" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using CSUnit; using System; using System.IO; using System.Text; using System.Xml; public class TestXmlTextReader : TestCase { private XmlTextReader xr; private StringReader sr; private String[] xml = { "<soda caffeine=\"yes\">\n<size>medium</size>\n</soda>", "<soda><size>medium</size></soda>", "<free>software's freedom</free>", ("<?xml version='1.0' ?>" + "<bookstore>" + " <book>" + " <title>Understanding The Linux Kernel</title>" + " <author>Daniel P. Bovet and Marco Cesati</author>" + " </book>" + " <book>" + " <title>Learning Perl</title>" + " <author>Randal L. Schwartz and Tom Christiansen</author>" + " </book>" + "</bookstore>"), ("<?xml version='1.0'?>" + "<!DOCTYPE test [" + " <!ELEMENT test (#PCDATA) >" + " <!ENTITY % foo '&#37;bar;'>" + " <!ENTITY % bar '&#60;!ENTITY GNU \"GNU&#39;s NOT UNIX\" >' >" + " <!ENTITY fu '&#37;bar;'>" + " %foo;" + "]>" + "<test>Brave &GNU; World... &fu;<![CDATA[bar]]></test>"), ("<?xml version='1.0'?>" + "<!DOCTYPE test [" + " <!ELEMENT test (#PCDATA) >" + " <!ENTITY hello 'hello world'>" + "]>" + "<!-- a sample comment -->" + "<test>Brave GNU <![CDATA[World]]> &hello;</test>" + " " + "<?pi HeLlO wOrLd ?>"), "<doc><text/></doc>" }; // Constructor. public TestXmlTextReader(String name) : base(name) { // Nothing to do here. } // Set up for the tests. protected override void Setup() { // Nothing to do here. } // Clean up after the tests. protected override void Cleanup() { // Nothing to do here. } // Clear the current output. private void Clear() { sr = null; xr = null; } // Reset the entire XML text reader. private void Reset(int index) { sr = new StringReader(xml[index]); xr = new XmlTextReader(sr); } private void Reset(TextReader tr) { sr = null; xr = new XmlTextReader(tr); } // Test the constructors public void TestXmlTextReaderCtor() { // TODO: Test each constructor } // Test the GetRemainder method. public void TestXmlTextReaderGetRemainder() { Reset(3); xr.WhitespaceHandling = WhitespaceHandling.None; AssertEquals("GetRemainder (1)", true, xr.Read()); AssertEquals("GetRemainder (2)", true, xr.Read()); AssertEquals("GetRemainder (3)", true, xr.Read()); AssertEquals("GetRemainder (4)", "book", xr.Name); AssertEquals("GetRemainder (5)", true, xr.Read()); AssertEquals("GetRemainder (6)", "title", xr.Name); AssertEquals("GetRemainder (7)", true, xr.Read()); AssertEquals("GetRemainder (8)", "Understanding The Linux Kernel", xr.Value); AssertEquals("GetRemainder (9)", true, xr.Read()); AssertEquals("GetRemainder (10)", "title", xr.Name); AssertEquals("GetRemainder (11)", true, xr.Read()); AssertEquals("GetRemainder (12)", "author", xr.Name); AssertEquals("GetRemainder (13)", true, xr.Read()); AssertEquals("GetRemainder (14)", "Daniel P. Bovet and Marco Cesati", xr.Value); AssertEquals("GetRemainder (15)", true, xr.Read()); AssertEquals("GetRemainder (16)", "author", xr.Name); AssertEquals("GetRemainder (17)", true, xr.Read()); AssertEquals("GetRemainder (18)", "book", xr.Name); Reset(xr.GetRemainder()); xr.WhitespaceHandling = WhitespaceHandling.None; AssertEquals("GetRemainder (19)", true, xr.Read()); AssertEquals("GetRemainder (20)", "book", xr.Name); AssertEquals("GetRemainder (21)", true, xr.Read()); AssertEquals("GetRemainder (22)", "title", xr.Name); AssertEquals("GetRemainder (23)", true, xr.Read()); AssertEquals("GetRemainder (24)", "Learning Perl", xr.Value); AssertEquals("GetRemainder (25)", true, xr.Read()); AssertEquals("GetRemainder (26)", "title", xr.Name); AssertEquals("GetRemainder (27)", true, xr.Read()); AssertEquals("GetRemainder (28)", "author", xr.Name); AssertEquals("GetRemainder (29)", true, xr.Read()); AssertEquals("GetRemainder (30)", "Randal L. Schwartz and Tom Christiansen", xr.Value); AssertEquals("GetRemainder (31)", true, xr.Read()); AssertEquals("GetRemainder (32)", "author", xr.Name); AssertEquals("GetRemainder (33)", true, xr.Read()); AssertEquals("GetRemainder (34)", "book", xr.Name); Clear(); } // Test the Read method. public void TestXmlTextReaderRead() { Reset(0); AssertEquals("Read (1)", true, xr.Read()); AssertEquals("Read (2)", "soda", xr.Name); AssertEquals("Read (3)", "soda", xr.LocalName); AssertEquals("Read (4)", true, xr.Read()); AssertEquals("Read (5)", true, xr.Read()); AssertEquals("Read (6)", "size", xr.Name); AssertEquals("Read (7)", "size", xr.LocalName); AssertEquals("Read (8)", true, xr.Read()); AssertEquals("Read (9)", "medium", xr.Value); Reset(2); AssertEquals("Read (10)", true, xr.Read()); AssertEquals("Read (11)", "free", xr.Name); AssertEquals("Read (12)", true, xr.Read()); AssertEquals("Read (13)", "software's freedom", xr.Value); Reset(4); AssertEquals("Read (14)", true, xr.Read()); AssertEquals("Read (15)", "xml", xr.Name); AssertEquals("Read (16)", "1.0", xr["version"]); AssertEquals("Read (17)", true, xr.Read()); AssertEquals("Read (18)", "test", xr.Name); AssertEquals("Read (19)", true, xr.Read()); AssertEquals("Read (20)", "test", xr.Name); AssertEquals("Read (21)", true, xr.Read()); AssertEquals("Read (22)", "Brave ", xr.Value); AssertEquals("Read (23)", true, xr.Read()); AssertEquals("Read (24)", "GNU", xr.Name); AssertEquals("Read (25)", true, xr.Read()); AssertEquals("Read (26)", " World... ", xr.Value); AssertEquals("Read (27)", true, xr.Read()); AssertEquals("Read (28)", "fu", xr.Name); AssertEquals("Read (29)", true, xr.Read()); AssertEquals("Read (30)", "bar", xr.Value); AssertEquals("Read (31)", true, xr.Read()); AssertEquals("Read (32)", "test", xr.Name); Clear(); } // Test the ReadAttributeValue method. public void TestXmlTextReaderReadAttributeValue() { Reset(0); AssertEquals("ReadAttributeValue (1)", true, xr.Read()); AssertEquals("ReadAttributeValue (2)", true, xr.MoveToFirstAttribute()); AssertEquals("ReadAttributeValue (3)", true, xr.ReadAttributeValue()); AssertEquals("ReadAttributeValue (4)", XmlNodeType.Text, xr.NodeType); Clear(); } // Test the ReadOuterXml method. public void TestXmlTextReaderReadOuterXml() { Reset(0); AssertEquals("ReadOuterXml (1)", true, xr.Read()); AssertEquals("ReadOuterXml (2)", xml[0], xr.ReadOuterXml()); Reset(1); AssertEquals("ReadOuterXml (3)", true, xr.Read()); AssertEquals("ReadOuterXml (4)", xml[1], xr.ReadOuterXml()); Reset(new StringReader("<outer><inner></inner></outer>")); AssertEquals("ReadOuterXml (5)", true, xr.Read()); AssertEquals("ReadOuterXml (6)", true, xr.Read()); AssertEquals("ReadOuterXml (7)", "<inner></inner>", xr.ReadOuterXml()); Reset(new StringReader(@"<foo bar=""' '"" />")); AssertEquals("ReadOuterXml (8)", true, xr.Read()); AssertEquals("ReadOuterXml (9)", @"<foo bar=""' '"" />", xr.ReadOuterXml()); Clear(); } // Test the ReadString method. public void TestXmlTextReaderReadString() { Reset(5); AssertEquals("ReadString (1)", XmlNodeType.Element, xr.MoveToContent()); AssertEquals("ReadString (2)", "Brave GNU World ", xr.ReadString()); } // Test if NodeType after reading empty element with ReadElementString() is XmlNodeType.EndElement (bug #14261). public void TestXmlTextReaderReadElementStringOnEmpyElement() { Reset(6); AssertEquals("ReadElementStringOnEmpyElement (1)", XmlNodeType.Element, xr.MoveToContent()); AssertEquals("ReadElementStringOnEmpyElement (2)", true, xr.Read()); AssertEquals("ReadElementStringOnEmpyElement (3)", String.Empty, xr.ReadElementString()); AssertEquals("ReadElementStringOnEmpyElement (4)", XmlNodeType.EndElement, xr.NodeType); } // Test the Depth property. public void TestXmlTextReaderDepth() { Reset(new StringReader("<node attr=\"1\" />")); AssertEquals("Depth (1)", 0, xr.Depth); AssertEquals("Depth (2)", XmlNodeType.Element, xr.MoveToContent()); AssertEquals("Depth (3)", 0, xr.Depth); AssertEquals("Depth (4)", true, xr.MoveToFirstAttribute()); AssertEquals("Depth (5)", 1, xr.Depth); AssertEquals("Depth (6)", false, xr.Read()); AssertEquals("Depth (7)", 0, xr.Depth); Clear(); } // Test XML with char references &amp; and entities &xxx; in attributes. public void TestXmlTextReaderCharReferenceAndEntityInAttr() { string xmlText = "<doc a=\"C &amp;&amp; D\" b=\"C &xxx; D\" />"; Reset(new StringReader(xmlText)); xr.MoveToContent(); AssertEquals("CharReferenceAndEntityInAttr (1)", "doc", xr.Name); xr.MoveToFirstAttribute(); AssertEquals("CharReferenceAndEntityInAttr (2)", "a", xr.Name); AssertEquals("CharReferenceAndEntityInAttr (3)", "C && D", xr.Value); xr.MoveToNextAttribute(); AssertEquals("CharReferenceAndEntityInAttr (4)", "b", xr.Name); AssertEquals("CharReferenceAndEntityInAttr (5)", "C &xxx; D", xr.Value); } }; // class TestXmlTextReader
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // 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. // #if MINIMAL using System; namespace OpenTK { /// <summary> /// Represents a rectangular region on a two-dimensional plane. /// </summary> public struct Rectangle : IEquatable<Rectangle> { Point location; Size size; /// <summary> /// Constructs a new Rectangle instance. /// </summary> /// <param name="location">The top-left corner of the Rectangle.</param> /// <param name="size">The width and height of the Rectangle.</param> public Rectangle(Point location, Size size) : this() { Location = location; Size = size; } /// <summary> /// Constructs a new Rectangle instance. /// </summary> /// <param name="x">The x coordinate of the Rectangle.</param> /// <param name="y">The y coordinate of the Rectangle.</param> /// <param name="width">The width coordinate of the Rectangle.</param> /// <param name="height">The height coordinate of the Rectangle.</param> public Rectangle(int x, int y, int width, int height) : this(new Point(x, y), new Size(width, height)) { } /// <summary> /// Gets or sets the x coordinate of the Rectangle. /// </summary> public int X { get { return Location.X; } set { Location = new Point (value, Y); } } /// <summary> /// Gets or sets the y coordinate of the Rectangle. /// </summary> public int Y { get { return Location.Y; } set { Location = new Point (X, value); } } /// <summary> /// Gets or sets the width of the Rectangle. /// </summary> public int Width { get { return Size.Width; } set { Size = new Size (value, Height); } } /// <summary> /// Gets or sets the height of the Rectangle. /// </summary> public int Height { get { return Size.Height; } set { Size = new Size(Width, value); } } /// <summary> /// Gets or sets a <see cref="Point"/> representing the x and y coordinates /// of the Rectangle. /// </summary> public Point Location { get { return location; } set { location = value; } } /// <summary> /// Gets or sets a <see cref="Size"/> representing the width and height /// of the Rectangle. /// </summary> public Size Size { get { return size; } set { size = value; } } /// <summary> /// Gets the y coordinate of the top edge of this Rectangle. /// </summary> public int Top { get { return Y; } } /// <summary> /// Gets the x coordinate of the right edge of this Rectangle. /// </summary> public int Right { get { return X + Width; } } /// <summary> /// Gets the y coordinate of the bottom edge of this Rectangle. /// </summary> public int Bottom { get { return Y + Height; } } /// <summary> /// Gets the x coordinate of the left edge of this Rectangle. /// </summary> public int Left { get { return X; } } /// <summary> /// Gets a <see cref="System.Boolean"/> that indicates whether this /// Rectangle is equal to the empty Rectangle. /// </summary> public bool IsEmpty { get { return Location.IsEmpty && Size.IsEmpty; } } /// <summary> /// Defines the empty Rectangle. /// </summary> public static readonly Rectangle Zero = new Rectangle(); /// <summary> /// Defines the empty Rectangle. /// </summary> public static readonly Rectangle Empty = new Rectangle(); /// <summary> /// Constructs a new instance with the specified edges. /// </summary> /// <param name="left">The left edge of the Rectangle.</param> /// <param name="top">The top edge of the Rectangle.</param> /// <param name="right">The right edge of the Rectangle.</param> /// <param name="bottom">The bottom edge of the Rectangle.</param> /// <returns>A new Rectangle instance with the specified edges.</returns> public static Rectangle FromLTRB(int left, int top, int right, int bottom) { return new Rectangle(new Point(left, top), new Size(right - left, bottom - top)); } /// <summary> /// Tests whether this instance contains the specified x, y coordinates. /// </summary> /// <param name="x">The x coordinate to test.</param> /// <param name="y">The y coordinate to test.</param> /// <returns>True if this instance contains the x, y coordinates; false otherwise.</returns> /// <remarks>The left and top edges are inclusive. The right and bottom edges /// are exclusive.</remarks> public bool Contains(int x, int y) { return x >= Left && x < Right && y >= Top && y < Bottom; } /// <summary> /// Tests whether this instance contains the specified Point. /// </summary> /// <param name="point">The <see cref="Point"/> to test.</param> /// <returns>True if this instance contains point; false otherwise.</returns> /// <remarks>The left and top edges are inclusive. The right and bottom edges /// are exclusive.</remarks> public bool Contains(Point point) { return point.X >= Left && point.X < Right && point.Y >= Top && point.Y < Bottom; } /// <summary> /// Tests whether this instance contains the specified Rectangle. /// </summary> /// <param name="rect">The <see cref="Rectangle"/> to test.</param> /// <returns>True if this instance contains rect; false otherwise.</returns> /// <remarks>The left and top edges are inclusive. The right and bottom edges /// are exclusive.</remarks> public bool Contains(Rectangle rect) { return Contains(rect.Location) && Contains(rect.Location + rect.Size); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left is equal to right; false otherwise.</returns> public static bool operator ==(Rectangle left, Rectangle right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left is not equal to right; false otherwise.</returns> public static bool operator !=(Rectangle left, Rectangle right) { return !left.Equals(right); } /// <summary> /// Union the specified a and b. /// </summary> /// <param name="a">The alpha component.</param> /// <param name="b">The blue component.</param> public static Rectangle Union (Rectangle a, Rectangle b) { int x1 = Math.Min(a.X, b.X); int x2 = Math.Max(a.X + a.Width, b.X + b.Width); int y1 = Math.Min(a.Y, b.Y); int y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new Rectangle(x1, y1, x2 - x1, y2 - y1); } /// <summary> /// Indicates whether this instance is equal to the specified object. /// </summary> /// <param name="obj">The object instance to compare to.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (obj is Rectangle) return Equals((Rectangle)obj); return false; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A <see cref="System.Int32"/> that represents the hash code for this instance./></returns> public override int GetHashCode() { return Location.GetHashCode() & Size.GetHashCode(); } /// <summary> /// Returns a <see cref="System.String"/> that describes this instance. /// </summary> /// <returns>A <see cref="System.String"/> that describes this instance.</returns> public override string ToString() { return String.Format("{{{0}-{1}}}", Location, Location + Size); } /// <summary> /// Indicates whether this instance is equal to the specified Rectangle. /// </summary> /// <param name="other">The instance to compare to.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public bool Equals(Rectangle other) { return Location.Equals(other.Location) && Size.Equals(other.Size); } } } #endif
using System; using NUnit.Framework; using SimpleContainer.Configuration; using SimpleContainer.Infection; using SimpleContainer.Interface; using SimpleContainer.Tests.Helpers; namespace SimpleContainer.Tests.Contracts { public abstract class ContractsReuseTest : SimpleContainerTestBase { public class ContractUsageViaCache : ContractsReuseTest { public class Client { public readonly ServiceWrap wrap; public readonly OtherService otherService; public Client([TestContract("c1")] ServiceWrap wrap, OtherService otherService) { this.wrap = wrap; this.otherService = otherService; } } public class ServiceWrap { public readonly Service service; public readonly OtherService otherService; public ServiceWrap(Service service, OtherService otherService) { this.service = service; this.otherService = otherService; } } public class OtherService { public readonly Service service; public OtherService(Service service) { this.service = service; } } public class Service { public readonly IInterface @interface; public Service(IInterface @interface) { this.@interface = @interface; } } public interface IInterface { } public class Impl : IInterface { } [Test] public void Test() { var container = Container(c => c.Contract("c1").Bind<IInterface, Impl>()); var client = container.Get<Client>(); Assert.That(client.wrap.otherService, Is.Not.SameAs(client.otherService)); } } public class UsedContractsForReusedServices : ContractsReuseTest { public class A { public readonly B b; public readonly D d1; public readonly D d2; public A([TestContract("c1")] B b, [TestContract("c2")] D d1, D d2) { this.b = b; this.d1 = d1; this.d2 = d2; } } public class B { public readonly C c; public B([TestContract("c2")] C c) { this.c = c; } } public class C { public readonly int parameter; public C(int parameter) { this.parameter = parameter; } } public class D { public readonly C c; public D(C c) { this.c = c; } } [Test] public void Test() { var container = Container(delegate(ContainerConfigurationBuilder builder) { builder.BindDependency<C>("parameter", 41); builder.Contract("c2").BindDependency<C>("parameter", 42); }); var a = container.Get<A>(); Assert.That(a.b.c.parameter, Is.EqualTo(42)); Assert.That(a.d1.c, Is.SameAs(a.b.c)); Assert.That(a.d2.c.parameter, Is.EqualTo(41)); } } public class UsedContractsForServiceCreatedUsingFinalContracts : ContractsReuseTest { public class A { public readonly Wrap wrap; public readonly C c1; public readonly C c2; public A([TestContract("x")] Wrap wrap, [TestContract("x")] C c1, C c2) { this.wrap = wrap; this.c1 = c1; this.c2 = c2; } } [TestContract("not-used")] public class Wrap { public readonly B b; public Wrap(B b) { this.b = b; } } public class B { public readonly int parameter; public B(int parameter) { this.parameter = parameter; } } public class C { public readonly B b; public C(B b) { this.b = b; } } [Test] public void Test() { var container = Container(delegate(ContainerConfigurationBuilder builder) { builder.Contract("not-used"); builder.BindDependency<B>("parameter", 1); builder.Contract("x").BindDependency<B>("parameter", 2); }); var a = container.Get<A>(); Assert.That(a.wrap.b.parameter, Is.EqualTo(2)); Assert.That(a.c1.b.parameter, Is.EqualTo(2)); Assert.That(a.c2.b.parameter, Is.EqualTo(1)); } } public class ContractsSequenceIsImportant : ContractsReuseTest { public class A { public readonly B b; public readonly C c; public A([TestContract("x")] B b, [TestContract("y")] C c) { this.b = b; this.c = c; } } [TestContract("not-used")] public class B { public readonly U u; public B([TestContract("y")] U u) { this.u = u; } } public class C { public readonly U u; public C([TestContract("x")] U u) { this.u = u; } } public class U { public readonly IInterface s; public U(IInterface s) { this.s = s; } } public interface IInterface { } public class Impl1 : IInterface { public readonly int parameter; public Impl1(int parameter) { this.parameter = parameter; } } public class Impl2 : IInterface { public readonly int parameter; public Impl2(int parameter) { this.parameter = parameter; } } [Test] public void Test() { var container = Container(delegate(ContainerConfigurationBuilder builder) { builder.Contract("not-used"); builder.Contract("x") .Bind<IInterface, Impl2>() .BindDependency<Impl1>("parameter", 1); builder.Contract("y") .BindDependency<Impl2>("parameter", 2) .Bind<IInterface, Impl1>(); }); var a = container.Get<A>(); Assert.That(a.b.u.s, Is.InstanceOf<Impl1>()); Assert.That(((Impl1)a.b.u.s).parameter, Is.EqualTo(1)); Assert.That(a.c.u.s, Is.InstanceOf<Impl2>()); Assert.That(((Impl2)a.c.u.s).parameter, Is.EqualTo(2)); } } public class FinalUsedContractsForSkippedServices : ContractsReuseTest { public class Wrap { public readonly A a; public Wrap([TestContract("x")] A a) { this.a = a; } } public class A { public readonly B b; public A([Optional] B b) { this.b = b; } } public class B { } [Test] public void Test() { var container = Container(b => b.Contract("x").DontUse<B>()); Assert.That(container.Get<Wrap>().a.b, Is.Null); Assert.That(container.Resolve<A>("x").GetConstructionLog(), Is.EqualTo(TestHelpers.FormatMessage(@" A[x] B[x] - DontUse -> <null>"))); } } public class ConstructionLogForReusedService : ContractsReuseTest { public class A { public readonly B b1; public readonly B b2; public A([TestContract("x")] B b1, [TestContract("y")] B b2) { this.b1 = b1; this.b2 = b2; } } public class B { } [Test] public void Test() { var container = Container(b => { b.Contract("x"); b.Contract("y"); }); var a = container.Get<A>(); Assert.That(a.b1, Is.SameAs(a.b2)); Assert.That(container.Resolve<A>().GetConstructionLog(), Is.EqualTo(TestHelpers.FormatMessage(@" A B B"))); } } public class CrashInConstructorOfServiceForUsedContracts : ContractsReuseTest { public class A { public A() { throw new InvalidOperationException("test crash"); } } [Test] public void Test() { var container = Container(b => b.Contract("a")); var error = Assert.Throws<SimpleContainerException>(() => container.Get<A>("a")); Assert.That(error.Message, Does.Contain("construction exception")); Assert.That(error.InnerException.Message, Is.EqualTo("test crash")); } } public class ServicesAreBoundToUsedContractPath : ContractsReuseTest { public class A { public readonly B b; public readonly C c; public A([TestContract("x1")] B b, [TestContract("x2")] C c) { this.b = b; this.c = c; } } public class B { public readonly C c; public B([TestContract("x2")] C c) { this.c = c; } } public class C { public readonly int p; public C(int p) { this.p = p; } } [Test] public void Test() { var container = Container(b => { b.Contract("x1"); b.Contract("x2").BindDependency<C>("p", 42); }); var a = container.Get<A>(); Assert.That(a.b.c, Is.SameAs(a.c)); } } } }
using System; using System.Collections.Generic; using System.Data; using bv.common.Core; using DevExpress.Utils; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Controls; using eidss.avr.BaseComponents.Views; using eidss.avr.ChartForm; using eidss.avr.db.AvrEventArgs.AvrEventArgs; using eidss.avr.db.CacheReceiver; using eidss.avr.db.Common; using eidss.avr.db.DBService.DataTableCopier; using eidss.avr.db.Interfaces; using eidss.avr.LayoutForm; using eidss.avr.MainForm; using eidss.avr.MapForm; using eidss.avr.PivotComponents; using eidss.avr.PivotForm; using eidss.avr.QueryBuilder; using eidss.avr.QueryLayoutTree; using eidss.avr.ViewForm; using eidss.model.Avr.Commands.Models; using eidss.model.AVR.SourceData; using eidss.model.Reports.OperationContext; using eidss.model.Resources; using StructureMap; namespace eidss.avr.BaseComponents { public class SharedPresenter : IDisposable { private readonly SharedModel m_SharedModel; private readonly IContextKeeper m_ContextKeeper; private readonly Dictionary<IBaseAvrView, BaseAvrPresenter> m_ChildPresenters; private IContainer m_Container; public SharedPresenter(IContainer container, IPostable parentForm) { Utils.CheckNotNull(parentForm, "parentForm"); Utils.CheckNotNull(container, "container"); m_Container = container; m_SharedModel = new SharedModel(parentForm, new ExportDialogStrategy()); m_ContextKeeper = new ContextKeeper(); m_ChildPresenters = new Dictionary<IBaseAvrView, BaseAvrPresenter>(); TableCopier = new AvrDataTableCopier(); } public void Dispose() { m_ChildPresenters.Clear(); DisposeTableCopier(); m_SharedModel.Dispose(); } public IContextKeeper ContextKeeper { get { return m_ContextKeeper; } } public SharedModel SharedModel { get { return m_SharedModel; } } public AvrDataTableCopier TableCopier { get; private set; } public bool IsQueryResultNull { get; private set; } public BaseAvrPresenter this[IBaseAvrView view] { get { Utils.CheckNotNull(view, "view"); if (!m_ChildPresenters.ContainsKey(view)) { RegisterPresenterFor(view); } return m_ChildPresenters[view]; } } public void UnregisterView(IBaseAvrView view) { Utils.CheckNotNull(view, "view"); if (m_ChildPresenters.ContainsKey(view)) { m_ChildPresenters.Remove(view); } } public void SetQueryResult(CachedQueryResult result) { DisposeTableCopier(); if (result != null) { IsQueryResultNull = false; TableCopier = new AvrDataTableCopier(result); } else { IsQueryResultNull = true; TableCopier = new AvrDataTableCopier(); } } public AvrDataTable GetQueryResultCopy(string filter) { CheckQueryResultAndTableCopier(); AvrDataTable copy = TableCopier.GetCopy(filter); return copy; } public AvrDataTable GetQueryResultClone() { CheckQueryResultAndTableCopier(); return TableCopier.GetClone(); } private void CheckQueryResultAndTableCopier() { if (IsQueryResultNull) { throw new InvalidOperationException("Canot create copy of QueryResult because it is null"); } if (TableCopier == null) { throw new AvrException("SharedModel.TableCopier is not initialized"); } } public void BindAggregateFunctionsInternal(LookUpEdit lookUp, AggregateFunctionTarget target) { lookUp.DataBindings.Clear(); lookUp.Properties.Columns.Clear(); var info = new LookUpColumnInfo(AggrFunctionLookupHelper.ColumnName, EidssMessages.Get("colCaption", "Caption"), 200, FormatType.None, "", true, HorzAlignment.Near); lookUp.Properties.Columns.AddRange(new[] {info}); lookUp.Properties.PopupWidth = lookUp.Width; lookUp.Properties.NullText = string.Empty; lookUp.Properties.DataSource = AggrFunctionLookupHelper.GetLookupTable(target); lookUp.Properties.ValueMember = AggrFunctionLookupHelper.ColumnId; lookUp.Properties.DisplayMember = AggrFunctionLookupHelper.ColumnName; lookUp.EditValue = DBNull.Value; lookUp.Enabled = false; } public static string GetSelectedAdministrativeFieldAlias(DataView dataView, IAvrPivotGridField field) { string fieldAlias = null; if (dataView != null && dataView.Count > 0) { if (field != null && !string.IsNullOrEmpty(field.UnitSearchFieldAlias) && field.UnitLayoutSearchFieldId.HasValue && field.UnitLayoutSearchFieldId.Value != -1) { fieldAlias = AvrPivotGridFieldHelper.CreateFieldName(field.UnitSearchFieldAlias, field.UnitLayoutSearchFieldId.Value); } if (fieldAlias == null && field != null && field.UnitLayoutSearchFieldId.HasValue && field.UnitLayoutSearchFieldId.Value == -1) { string oldFilter = dataView.RowFilter; dataView.RowFilter = string.Format("Alias = '{0}'", AvrPivotGridFieldHelper.VirtualCountryFieldName); if (dataView.Count > 0) { fieldAlias = AvrPivotGridFieldHelper.VirtualCountryFieldName; } dataView.RowFilter = oldFilter; } if (fieldAlias == null) { fieldAlias = Utils.Str(dataView[0]["Alias"]); } } return fieldAlias; } public bool TryGetStartUpParameter(string key, out object value) { value = null; Dictionary<string, object> parameters = SharedModel.StartUpParameters; if ((parameters != null) && (parameters.ContainsKey(key))) { value = parameters[key]; return true; } return false; } private void RegisterPresenterFor(IBaseAvrView view) { BaseAvrPresenter avrPresenter; if (view is IMapView) { avrPresenter = new MapPresenter(this, (IMapView) view); } else if (view is IChartView) { avrPresenter = new ChartPresenter(this, (IChartView) view); } else if (view is IPivotDetailView) { avrPresenter = new PivotDetailPresenter(this, (IPivotDetailView) view); } else if (view is ILayoutDetailView) { avrPresenter = new LayoutDetailPresenter(this, (ILayoutDetailView) view); } else if (view is IAvrPivotGridView) { avrPresenter = new AvrPivotGridPresenter(this, (IAvrPivotGridView) view); } else if (view is IAvrMainFormView) { avrPresenter = new AvrMainFormPresenter(this, (IAvrMainFormView) view); } else if (view is IQueryLayoutTreeView) { avrPresenter = new QueryLayoutTreePresenter(this, (IQueryLayoutTreeView) view); } else if (view is IPivotInfoDetailView) { avrPresenter = new PivotInfoPresenter(this, (IPivotInfoDetailView) view); } else if (view is IViewDetailView) { avrPresenter = new ViewDetailPresenter(this, (IViewDetailView) view); } else if (view is IQueryDetailView) { avrPresenter = new QueryDetailPresenter(this, (IQueryDetailView) view); } else { throw new NotSupportedException(string.Format("Not supported view {0}", view)); } view.SendCommand += View_SendCommand; m_ChildPresenters.Add(view, avrPresenter); } private void View_SendCommand(object sender, CommandEventArgs e) { Utils.CheckNotNull(e, "e"); Utils.CheckNotNull(e.Command, "e.Command"); foreach (BaseAvrPresenter value in m_ChildPresenters.Values) { value.Process(e.Command); } } private void DisposeTableCopier() { if (TableCopier != null) { TableCopier.Dispose(); TableCopier = null; } } } }
// 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.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; #if !MSBUILD12 using Microsoft.Build.Construction; #endif using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A workspace that can be populated by opening MSBuild solution and project files. /// </summary> public sealed class MSBuildWorkspace : Workspace { // used to serialize access to public methods private readonly NonReentrantLock _serializationLock = new NonReentrantLock(); // used to protect access to mutable state private readonly NonReentrantLock _dataGuard = new NonReentrantLock(); private readonly Dictionary<string, string> _extensionToLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, ProjectId> _projectPathToProjectIdMap = new Dictionary<string, ProjectId>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, IProjectFileLoader> _projectPathToLoaderMap = new Dictionary<string, IProjectFileLoader>(StringComparer.OrdinalIgnoreCase); private string _solutionFilePath; private ImmutableDictionary<string, string> _properties; private MSBuildWorkspace( HostServices hostServices, ImmutableDictionary<string, string> properties) : base(hostServices, "MSBuildWorkspace") { // always make a copy of these build properties (no mutation please!) _properties = properties ?? ImmutableDictionary<string, string>.Empty; this.SetSolutionProperties(solutionFilePath: null); this.LoadMetadataForReferencedProjects = false; this.SkipUnrecognizedProjects = true; } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> public static MSBuildWorkspace Create() { return Create(ImmutableDictionary<string, string>.Empty); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">An optional set of MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties) { return Create(properties, DesktopMefHostServices.DefaultServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties, HostServices hostServices) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } if (hostServices == null) { throw new ArgumentNullException(nameof(hostServices)); } return new MSBuildWorkspace(hostServices, properties.ToImmutableDictionary()); } /// <summary> /// The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument. /// </summary> public ImmutableDictionary<string, string> Properties { get { return _properties; } } /// <summary> /// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects. /// If the referenced project is already opened, the metadata will not be loaded. /// If the metadata assembly cannot be found the referenced project will be opened instead. /// </summary> public bool LoadMetadataForReferencedProjects { get; set; } /// <summary> /// Determines if unrecognized projects are skipped when solutions or projects are opened. /// /// An project is unrecognized if it either has /// a) an invalid file path, /// b) a non-existent project file, /// c) has an unrecognized file extension or /// d) a file extension associated with an unsupported language. /// /// If unrecognized projects cannot be skipped a corresponding exception is thrown. /// </summary> public bool SkipUnrecognizedProjects { get; set; } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language) { if (language == null) { throw new ArgumentNullException(nameof(language)); } if (projectFileExtension == null) { throw new ArgumentNullException(nameof(projectFileExtension)); } using (_dataGuard.DisposableWait()) { _extensionToLanguageMap[projectFileExtension] = language; } } /// <summary> /// Close the open solution, and reset the workspace to a new empty solution. /// </summary> public void CloseSolution() { using (_serializationLock.DisposableWait()) { this.ClearSolution(); } } protected override void ClearSolutionData() { base.ClearSolutionData(); using (_dataGuard.DisposableWait()) { this.SetSolutionProperties(solutionFilePath: null); // clear project related data _projectPathToProjectIdMap.Clear(); _projectPathToLoaderMap.Clear(); } } private const string SolutionDirProperty = "SolutionDir"; private void SetSolutionProperties(string solutionFilePath) { _solutionFilePath = solutionFilePath; if (!string.IsNullOrEmpty(solutionFilePath)) { // When MSBuild is building an individual project, it doesn't define $(SolutionDir). // However when building an .sln file, or when working inside Visual Studio, // $(SolutionDir) is defined to be the directory where the .sln file is located. // Some projects out there rely on $(SolutionDir) being set (although the best practice is to // use MSBuildProjectDirectory which is always defined). if (!string.IsNullOrEmpty(solutionFilePath)) { string solutionDirectory = Path.GetDirectoryName(solutionFilePath); if (!solutionDirectory.EndsWith(@"\", StringComparison.Ordinal)) { solutionDirectory += @"\"; } if (Directory.Exists(solutionDirectory)) { _properties = _properties.SetItem(SolutionDirProperty, solutionDirectory); } } } } private ProjectId GetProjectId(string fullProjectPath) { using (_dataGuard.DisposableWait()) { ProjectId id; _projectPathToProjectIdMap.TryGetValue(fullProjectPath, out id); return id; } } private ProjectId GetOrCreateProjectId(string fullProjectPath) { using (_dataGuard.DisposableWait()) { ProjectId id; if (!_projectPathToProjectIdMap.TryGetValue(fullProjectPath, out id)) { id = ProjectId.CreateNewId(debugName: fullProjectPath); _projectPathToProjectIdMap.Add(fullProjectPath, id); } return id; } } private bool TryGetLoaderFromProjectPath(string projectFilePath, ReportMode mode, out IProjectFileLoader loader) { using (_dataGuard.DisposableWait()) { // check to see if we already know the loader if (!_projectPathToLoaderMap.TryGetValue(projectFilePath, out loader)) { // otherwise try to figure it out from extension var extension = Path.GetExtension(projectFilePath); if (extension.Length > 0 && extension[0] == '.') { extension = extension.Substring(1); } string language; if (_extensionToLanguageMap.TryGetValue(extension, out language)) { if (this.Services.SupportedLanguages.Contains(language)) { loader = this.Services.GetLanguageServices(language).GetService<IProjectFileLoader>(); } else { this.ReportFailure(mode, string.Format(WorkspacesResources.CannotOpenProjectUnsupportedLanguage, projectFilePath, language)); return false; } } else { loader = ProjectFileLoader.GetLoaderForProjectFileExtension(this, extension); if (loader == null) { this.ReportFailure(mode, string.Format(WorkspacesResources.CannotOpenProjectUnrecognizedFileExtension, projectFilePath, Path.GetExtension(projectFilePath))); return false; } } if (loader != null) { _projectPathToLoaderMap[projectFilePath] = loader; } } return loader != null; } } private bool TryGetAbsoluteProjectPath(string path, string baseDirectory, ReportMode mode, out string absolutePath) { try { absolutePath = this.GetAbsolutePath(path, baseDirectory); } catch (Exception) { ReportFailure(mode, string.Format(WorkspacesResources.InvalidProjectFilePath, path)); absolutePath = null; return false; } if (!File.Exists(absolutePath)) { ReportFailure( mode, string.Format(WorkspacesResources.ProjectFileNotFound, absolutePath), msg => new FileNotFoundException(msg)); return false; } return true; } private string GetAbsoluteSolutionPath(string path, string baseDirectory) { string absolutePath; try { absolutePath = GetAbsolutePath(path, baseDirectory); } catch (Exception) { throw new InvalidOperationException(string.Format(WorkspacesResources.InvalidSolutionFilePath, path)); } if (!File.Exists(absolutePath)) { throw new FileNotFoundException(string.Format(WorkspacesResources.SolutionFileNotFound, absolutePath)); } return absolutePath; } private enum ReportMode { Throw, Log, Ignore } private void ReportFailure(ReportMode mode, string message, Func<string, Exception> createException = null) { switch (mode) { case ReportMode.Throw: if (createException != null) { throw createException(message); } else { throw new InvalidOperationException(message); } case ReportMode.Log: this.OnWorkspaceFailed(new WorkspaceDiagnostic(WorkspaceDiagnosticKind.Failure, message)); break; case ReportMode.Ignore: default: break; } } private string GetAbsolutePath(string path, string baseDirectoryPath) { return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path); } #region Open Solution & Project /// <summary> /// Open a solution file and all referenced projects. /// </summary> public async Task<Solution> OpenSolutionAsync(string solutionFilePath, CancellationToken cancellationToken = default(CancellationToken)) { if (solutionFilePath == null) { throw new ArgumentNullException(nameof(solutionFilePath)); } this.ClearSolution(); var absoluteSolutionPath = this.GetAbsoluteSolutionPath(solutionFilePath, Directory.GetCurrentDirectory()); using (_dataGuard.DisposableWait(cancellationToken)) { this.SetSolutionProperties(absoluteSolutionPath); } VersionStamp version = default(VersionStamp); #if !MSBUILD12 Microsoft.Build.Construction.SolutionFile solutionFile = Microsoft.Build.Construction.SolutionFile.Parse(absoluteSolutionPath); var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw; var invalidProjects = new List<ProjectInSolution>(); // seed loaders from known project types using (_dataGuard.DisposableWait(cancellationToken)) { foreach (var project in solutionFile.ProjectsInOrder) { if (project.ProjectType == SolutionProjectType.SolutionFolder) { continue; } var projectAbsolutePath = TryGetAbsolutePath(project.AbsolutePath, reportMode); if (projectAbsolutePath != null) { var extension = Path.GetExtension(projectAbsolutePath); if (extension.Length > 0 && extension[0] == '.') { extension = extension.Substring(1); } var loader = ProjectFileLoader.GetLoaderForProjectFileExtension(this, extension); if (loader != null) { _projectPathToLoaderMap[projectAbsolutePath] = loader; } } else { invalidProjects.Add(project); } } } // a list to accumulate all the loaded projects var loadedProjects = new Dictionary<ProjectId, ProjectInfo>(); // load all the projects foreach (var project in solutionFile.ProjectsInOrder) { cancellationToken.ThrowIfCancellationRequested(); if (project.ProjectType != SolutionProjectType.SolutionFolder && !invalidProjects.Contains(project)) { var projectAbsolutePath = TryGetAbsolutePath(project.AbsolutePath, reportMode); if (projectAbsolutePath != null) { IProjectFileLoader loader; if (TryGetLoaderFromProjectPath(projectAbsolutePath, reportMode, out loader)) { // projects get added to 'loadedProjects' as side-effect // never perfer metadata when loading solution, all projects get loaded if they can. var tmp = await GetOrLoadProjectAsync(projectAbsolutePath, loader, preferMetadata: false, loadedProjects: loadedProjects, cancellationToken: cancellationToken).ConfigureAwait(false); } } } } #else SolutionFile solutionFile = null; using (var reader = new StreamReader(absoluteSolutionPath)) { version = VersionStamp.Create(File.GetLastWriteTimeUtc(absoluteSolutionPath)); var text = await reader.ReadToEndAsync().ConfigureAwait(false); solutionFile = SolutionFile.Parse(new StringReader(text)); } var solutionFolder = Path.GetDirectoryName(absoluteSolutionPath); // seed loaders from known project types using (_dataGuard.DisposableWait()) { foreach (var projectBlock in solutionFile.ProjectBlocks) { string absoluteProjectPath; if (TryGetAbsoluteProjectPath(projectBlock.ProjectPath, solutionFolder, ReportMode.Ignore, out absoluteProjectPath)) { var loader = ProjectFileLoader.GetLoaderForProjectTypeGuid(this, projectBlock.ProjectTypeGuid); if (loader != null) { _projectPathToLoaderMap[absoluteProjectPath] = loader; } } } } // a list to accumulate all the loaded projects var loadedProjects = new Dictionary<ProjectId, ProjectInfo>(); var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw; // load all the projects foreach (var projectBlock in solutionFile.ProjectBlocks) { cancellationToken.ThrowIfCancellationRequested(); string absoluteProjectPath; if (TryGetAbsoluteProjectPath(projectBlock.ProjectPath, solutionFolder, reportMode, out absoluteProjectPath)) { IProjectFileLoader loader; if (TryGetLoaderFromProjectPath(absoluteProjectPath, reportMode, out loader)) { // projects get added to 'loadedProjects' as side-effect // never perfer metadata when loading solution, all projects get loaded if they can. var tmp = await GetOrLoadProjectAsync(absoluteProjectPath, loader, preferMetadata: false, loadedProjects: loadedProjects, cancellationToken: cancellationToken).ConfigureAwait(false); } } } #endif // construct workspace from loaded project infos this.OnSolutionAdded(SolutionInfo.Create(SolutionId.CreateNewId(debugName: absoluteSolutionPath), version, absoluteSolutionPath, loadedProjects.Values)); this.UpdateReferencesAfterAdd(); return this.CurrentSolution; } /// <summary> /// Open a project file and all referenced projects. /// </summary> public async Task<Project> OpenProjectAsync(string projectFilePath, CancellationToken cancellationToken = default(CancellationToken)) { if (projectFilePath == null) { throw new ArgumentNullException(nameof(projectFilePath)); } string fullPath; if (this.TryGetAbsoluteProjectPath(projectFilePath, Directory.GetCurrentDirectory(), ReportMode.Throw, out fullPath)) { IProjectFileLoader loader; if (this.TryGetLoaderFromProjectPath(projectFilePath, ReportMode.Throw, out loader)) { var loadedProjects = new Dictionary<ProjectId, ProjectInfo>(); var projectId = await GetOrLoadProjectAsync(fullPath, loader, this.LoadMetadataForReferencedProjects, loadedProjects, cancellationToken).ConfigureAwait(false); // add projects to solution foreach (var project in loadedProjects.Values) { this.OnProjectAdded(project); } this.UpdateReferencesAfterAdd(); return this.CurrentSolution.GetProject(projectId); } } // unreachable return null; } private string TryGetAbsolutePath(string path, ReportMode mode) { try { path = Path.GetFullPath(path); } catch (Exception) { ReportFailure(mode, string.Format(WorkspacesResources.InvalidProjectFilePath, path)); return null; } if (!File.Exists(path)) { ReportFailure( mode, string.Format(WorkspacesResources.ProjectFileNotFound, path), msg => new FileNotFoundException(msg)); return null; } return path; } private void UpdateReferencesAfterAdd() { using (_serializationLock.DisposableWait()) { var oldSolution = this.CurrentSolution; var newSolution = this.UpdateReferencesAfterAdd(oldSolution); if (newSolution != oldSolution) { newSolution = this.SetCurrentSolution(newSolution); var ignore = this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, oldSolution, newSolution); } } } // Updates all projects to properly reference other existing projects via project references instead of using references to built metadata. private Solution UpdateReferencesAfterAdd(Solution solution) { // Build map from output assembly path to ProjectId // Use explicit loop instead of ToDictionary so we don't throw if multiple projects have same output assembly path. var outputAssemblyToProjectIdMap = new Dictionary<string, ProjectId>(); foreach (var p in solution.Projects) { if (!string.IsNullOrEmpty(p.OutputFilePath)) { outputAssemblyToProjectIdMap[p.OutputFilePath] = p.Id; } } // now fix each project if necessary foreach (var pid in solution.ProjectIds) { var project = solution.GetProject(pid); // convert metadata references to project references if the metadata reference matches some project's output assembly. foreach (var meta in project.MetadataReferences) { var pemeta = meta as PortableExecutableReference; if (pemeta != null) { ProjectId matchingProjectId; // check both Display and FilePath. FilePath points to the actually bits, but Display should match output path if // the metadata reference is shadow copied. if ((!string.IsNullOrEmpty(pemeta.Display) && outputAssemblyToProjectIdMap.TryGetValue(pemeta.Display, out matchingProjectId)) || (!string.IsNullOrEmpty(pemeta.FilePath) && outputAssemblyToProjectIdMap.TryGetValue(pemeta.FilePath, out matchingProjectId))) { var newProjRef = new ProjectReference(matchingProjectId, pemeta.Properties.Aliases, pemeta.Properties.EmbedInteropTypes); if (!project.ProjectReferences.Contains(newProjRef)) { project = project.WithProjectReferences(project.ProjectReferences.Concat(newProjRef)); } project = project.WithMetadataReferences(project.MetadataReferences.Where(mr => mr != meta)); } } } solution = project.Solution; } return solution; } private async Task<ProjectId> GetOrLoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, Dictionary<ProjectId, ProjectInfo> loadedProjects, CancellationToken cancellationToken) { var projectId = GetProjectId(projectFilePath); if (projectId == null) { projectId = await this.LoadProjectAsync(projectFilePath, loader, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false); } return projectId; } private async Task<ProjectId> LoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, Dictionary<ProjectId, ProjectInfo> loadedProjects, CancellationToken cancellationToken) { System.Diagnostics.Debug.Assert(projectFilePath != null); System.Diagnostics.Debug.Assert(loader != null); var projectId = this.GetOrCreateProjectId(projectFilePath); var projectName = Path.GetFileNameWithoutExtension(projectFilePath); var projectFile = await loader.LoadProjectFileAsync(projectFilePath, _properties, cancellationToken).ConfigureAwait(false); var projectFileInfo = await projectFile.GetProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); VersionStamp version; if (!string.IsNullOrEmpty(projectFilePath) && File.Exists(projectFilePath)) { version = VersionStamp.Create(File.GetLastWriteTimeUtc(projectFilePath)); } else { version = VersionStamp.Create(); } // Documents var docFileInfos = projectFileInfo.Documents.ToImmutableArrayOrEmpty(); CheckDocuments(docFileInfos, projectFilePath, projectId); Encoding defaultEncoding = GetDefaultEncoding(projectFileInfo.CodePage); var docs = new List<DocumentInfo>(); foreach (var docFileInfo in docFileInfos) { string name; ImmutableArray<string> folders; GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders); docs.Add(DocumentInfo.Create( DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath), name, folders, projectFile.GetSourceCodeKind(docFileInfo.FilePath), new FileTextLoader(docFileInfo.FilePath, defaultEncoding), docFileInfo.FilePath, docFileInfo.IsGenerated)); } var additonalDocs = new List<DocumentInfo>(); foreach (var docFileInfo in projectFileInfo.AdditionalDocuments) { string name; ImmutableArray<string> folders; GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders); additonalDocs.Add(DocumentInfo.Create( DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath), name, folders, SourceCodeKind.Regular, new FileTextLoader(docFileInfo.FilePath, defaultEncoding), docFileInfo.FilePath, docFileInfo.IsGenerated)); } // project references var resolvedReferences = await this.ResolveProjectReferencesAsync( projectId, projectFilePath, projectFileInfo.ProjectReferences, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false); var metadataReferences = projectFileInfo.MetadataReferences .Concat(resolvedReferences.MetadataReferences); var outputFilePath = projectFileInfo.OutputFilePath; var assemblyName = projectFileInfo.AssemblyName; // if the project file loader couldn't figure out an assembly name, make one using the project's file path. if (string.IsNullOrWhiteSpace(assemblyName)) { assemblyName = Path.GetFileNameWithoutExtension(projectFilePath); // if this is still unreasonable, use a fixed name. if (string.IsNullOrWhiteSpace(assemblyName)) { assemblyName = "assembly"; } } loadedProjects.Add( projectId, ProjectInfo.Create( projectId, version, projectName, assemblyName, loader.Language, projectFilePath, outputFilePath, projectFileInfo.CompilationOptions, projectFileInfo.ParseOptions, docs, resolvedReferences.ProjectReferences, metadataReferences, analyzerReferences: projectFileInfo.AnalyzerReferences, additionalDocuments: additonalDocs, isSubmission: false, hostObjectType: null)); return projectId; } private static Encoding GetDefaultEncoding(int codePage) { // If no CodePage was specified in the project file, then the FileTextLoader will // attempt to use UTF8 before falling back on Encoding.Default. if (codePage == 0) { return null; } try { return Encoding.GetEncoding(codePage); } catch (ArgumentOutOfRangeException) { return null; } } private static readonly char[] s_directorySplitChars = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; private static void GetDocumentNameAndFolders(string logicalPath, out string name, out ImmutableArray<string> folders) { var pathNames = logicalPath.Split(s_directorySplitChars, StringSplitOptions.RemoveEmptyEntries); if (pathNames.Length > 0) { if (pathNames.Length > 1) { folders = pathNames.Take(pathNames.Length - 1).ToImmutableArray(); } else { folders = ImmutableArray.Create<string>(); } name = pathNames[pathNames.Length - 1]; } else { name = logicalPath; folders = ImmutableArray.Create<string>(); } } private void CheckDocuments(IEnumerable<DocumentFileInfo> docs, string projectFilePath, ProjectId projectId) { var paths = new HashSet<string>(); foreach (var doc in docs) { if (paths.Contains(doc.FilePath)) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Warning, string.Format(WorkspacesResources.DuplicateSourceFileInProject, doc.FilePath, projectFilePath), projectId)); } paths.Add(doc.FilePath); } } private class ResolvedReferences { public readonly List<ProjectReference> ProjectReferences = new List<ProjectReference>(); public readonly List<MetadataReference> MetadataReferences = new List<MetadataReference>(); } private async Task<ResolvedReferences> ResolveProjectReferencesAsync( ProjectId thisProjectId, string thisProjectPath, IReadOnlyList<ProjectFileReference> projectFileReferences, bool preferMetadata, Dictionary<ProjectId, ProjectInfo> loadedProjects, CancellationToken cancellationToken) { var resolvedReferences = new ResolvedReferences(); var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw; foreach (var projectFileReference in projectFileReferences) { string fullPath; if (TryGetAbsoluteProjectPath(projectFileReference.Path, Path.GetDirectoryName(thisProjectPath), reportMode, out fullPath)) { // if the project is already loaded, then just reference the one we have var existingProjectId = this.GetProjectId(fullPath); if (existingProjectId != null) { resolvedReferences.ProjectReferences.Add(new ProjectReference(existingProjectId, projectFileReference.Aliases)); continue; } IProjectFileLoader loader; TryGetLoaderFromProjectPath(fullPath, ReportMode.Ignore, out loader); // get metadata if preferred or if loader is unknown if (preferMetadata || loader == null) { var projectMetadata = await this.GetProjectMetadata(fullPath, projectFileReference.Aliases, _properties, cancellationToken).ConfigureAwait(false); if (projectMetadata != null) { resolvedReferences.MetadataReferences.Add(projectMetadata); continue; } } // must load, so we really need loader if (TryGetLoaderFromProjectPath(fullPath, reportMode, out loader)) { // load the project var projectId = await this.GetOrLoadProjectAsync(fullPath, loader, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false); // If that other project already has a reference on us, this will cause a circularity. // This check doesn't need to be in the "already loaded" path above, since in any circularity this path // must be taken at least once. if (ProjectAlreadyReferencesProject(loadedProjects, projectId, targetProject: thisProjectId)) { // We'll try to make this metadata if we can var projectMetadata = await this.GetProjectMetadata(fullPath, projectFileReference.Aliases, _properties, cancellationToken).ConfigureAwait(false); if (projectMetadata != null) { resolvedReferences.MetadataReferences.Add(projectMetadata); } continue; } else { resolvedReferences.ProjectReferences.Add(new ProjectReference(projectId, projectFileReference.Aliases)); continue; } } } else { fullPath = projectFileReference.Path; } // cannot find metadata and project cannot be loaded, so leave a project reference to a non-existent project. var id = this.GetOrCreateProjectId(fullPath); resolvedReferences.ProjectReferences.Add(new ProjectReference(id, projectFileReference.Aliases)); } return resolvedReferences; } /// <summary> /// Returns true if the project identified by <paramref name="fromProject"/> has a reference (even indirectly) /// on the project identified by <paramref name="targetProject"/>. /// </summary> private bool ProjectAlreadyReferencesProject(Dictionary<ProjectId, ProjectInfo> loadedProjects, ProjectId fromProject, ProjectId targetProject) { ProjectInfo info; return loadedProjects.TryGetValue(fromProject, out info) && info.ProjectReferences.Any(pr => pr.ProjectId == targetProject || ProjectAlreadyReferencesProject(loadedProjects, pr.ProjectId, targetProject)); } /// <summary> /// Gets a MetadataReference to a project's output assembly. /// </summary> private async Task<MetadataReference> GetProjectMetadata(string projectFilePath, ImmutableArray<string> aliases, IDictionary<string, string> globalProperties, CancellationToken cancellationToken) { // use loader service to determine output file for project if possible string outputFilePath = null; try { outputFilePath = await ProjectFileLoader.GetOutputFilePathAsync(projectFilePath, globalProperties, cancellationToken).ConfigureAwait(false); } catch (Exception e) { this.OnWorkspaceFailed(new WorkspaceDiagnostic(WorkspaceDiagnosticKind.Failure, e.Message)); } if (outputFilePath != null && File.Exists(outputFilePath)) { if (Workspace.TestHookStandaloneProjectsDoNotHoldReferences) { var documentationService = this.Services.GetService<IDocumentationProviderService>(); var docProvider = documentationService.GetDocumentationProvider(outputFilePath); var metadata = AssemblyMetadata.CreateFromImage(File.ReadAllBytes(outputFilePath)); return metadata.GetReference( documentation: docProvider, aliases: aliases, display: outputFilePath); } else { var metadataService = this.Services.GetService<IMetadataService>(); return metadataService.GetReference(outputFilePath, new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases)); } } return null; } #endregion #region Apply Changes public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: return true; default: return false; } } private bool HasProjectFileChanges(ProjectChanges changes) { return changes.GetAddedDocuments().Any() || changes.GetRemovedDocuments().Any() || changes.GetAddedMetadataReferences().Any() || changes.GetRemovedMetadataReferences().Any() || changes.GetAddedProjectReferences().Any() || changes.GetRemovedProjectReferences().Any() || changes.GetAddedAnalyzerReferences().Any() || changes.GetRemovedAnalyzerReferences().Any(); } private IProjectFile _applyChangesProjectFile; public override bool TryApplyChanges(Solution newSolution) { using (_serializationLock.DisposableWait()) { return base.TryApplyChanges(newSolution); } } protected override void ApplyProjectChanges(ProjectChanges projectChanges) { System.Diagnostics.Debug.Assert(_applyChangesProjectFile == null); var project = projectChanges.OldProject ?? projectChanges.NewProject; try { // if we need to modify the project file, load it first. if (this.HasProjectFileChanges(projectChanges)) { var projectPath = project.FilePath; IProjectFileLoader loader; if (this.TryGetLoaderFromProjectPath(projectPath, ReportMode.Ignore, out loader)) { try { _applyChangesProjectFile = loader.LoadProjectFileAsync(projectPath, _properties, CancellationToken.None).Result; } catch (System.IO.IOException exception) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } // do normal apply operations base.ApplyProjectChanges(projectChanges); // save project file if (_applyChangesProjectFile != null) { try { _applyChangesProjectFile.Save(); } catch (System.IO.IOException exception) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } finally { _applyChangesProjectFile = null; } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text) { var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { Encoding encoding = DetermineEncoding(text, document); this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); this.OnDocumentTextChanged(documentId, text, PreservationMode.PreserveValue); } } private static Encoding DetermineEncoding(SourceText text, Document document) { if (text.Encoding != null) { return text.Encoding; } try { using (ExceptionHelpers.SuppressFailFast()) { using (var stream = new FileStream(document.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var onDiskText = EncodedStringText.Create(stream); return onDiskText.Encoding; } } } catch (IOException) { } catch (InvalidDataException) { } return null; } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { System.Diagnostics.Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(info.Id.ProjectId); IProjectFileLoader loader; if (this.TryGetLoaderFromProjectPath(project.FilePath, ReportMode.Ignore, out loader)) { var extension = _applyChangesProjectFile.GetDocumentExtension(info.SourceCodeKind); var fileName = Path.ChangeExtension(info.Name, extension); var relativePath = (info.Folders != null && info.Folders.Count > 0) ? Path.Combine(Path.Combine(info.Folders.ToArray()), fileName) : fileName; var fullPath = GetAbsolutePath(relativePath, Path.GetDirectoryName(project.FilePath)); var newDocumentInfo = info.WithName(fileName) .WithFilePath(fullPath) .WithTextLoader(new FileTextLoader(fullPath, text.Encoding)); // add document to project file _applyChangesProjectFile.AddDocument(relativePath); // add to solution this.OnDocumentAdded(newDocumentInfo); // save text to disk if (text != null) { this.SaveDocumentText(info.Id, fullPath, text, text.Encoding ?? Encoding.UTF8); } } } private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding) { try { using (ExceptionHelpers.SuppressFailFast()) { var dir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Debug.Assert(encoding != null); using (var writer = new StreamWriter(fullPath, append: false, encoding: encoding)) { newText.Write(writer); } } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, id)); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { Debug.Assert(_applyChangesProjectFile != null); var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { _applyChangesProjectFile.RemoveDocument(document.FilePath); this.DeleteDocumentFile(document.Id, document.FilePath); this.OnDocumentRemoved(documentId); } } private void DeleteDocumentFile(DocumentId documentId, string fullPath) { try { if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (NotSupportedException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (UnauthorizedAccessException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.AddMetadataReference(metadataReference, identity); this.OnMetadataReferenceAdded(projectId, metadataReference); } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.RemoveMetadataReference(metadataReference, identity); this.OnMetadataReferenceRemoved(projectId, metadataReference); } private AssemblyIdentity GetAssemblyIdentity(ProjectId projectId, MetadataReference metadataReference) { var project = this.CurrentSolution.GetProject(projectId); if (!project.MetadataReferences.Contains(metadataReference)) { project = project.AddMetadataReference(metadataReference); } var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference) as IAssemblySymbol; return symbol != null ? symbol.Identity : null; } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project != null) { _applyChangesProjectFile.AddProjectReference(project.Name, new ProjectFileReference(project.FilePath, projectReference.Aliases)); } this.OnProjectReferenceAdded(projectId, projectReference); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project != null) { _applyChangesProjectFile.RemoveProjectReference(project.Name, project.FilePath); } this.OnProjectReferenceRemoved(projectId, projectReference); } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.AddAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceAdded(projectId, analyzerReference); } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.RemoveAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class ProductHeaderValueTest { [Fact] public void Ctor_SetValidHeaderValues_InstanceCreatedCorrectly() { ProductHeaderValue product = new ProductHeaderValue("HTTP", "2.0"); Assert.Equal("HTTP", product.Name); Assert.Equal("2.0", product.Version); product = new ProductHeaderValue("HTTP"); Assert.Equal("HTTP", product.Name); Assert.Null(product.Version); product = new ProductHeaderValue("HTTP", ""); // null and string.Empty are equivalent Assert.Equal("HTTP", product.Name); Assert.Null(product.Version); } [Fact] public void Ctor_UseInvalidValues_Throw() { Assert.Throws<ArgumentException>(() => { new ProductHeaderValue(null); }); Assert.Throws<ArgumentException>(() => { new ProductHeaderValue(string.Empty); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue(" x"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x "); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x y"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", " y"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", "y "); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", "y z"); }); } [Fact] public void ToString_UseDifferentRanges_AllSerializedCorrectly() { ProductHeaderValue product = new ProductHeaderValue("IRC", "6.9"); Assert.Equal("IRC/6.9", product.ToString()); product = new ProductHeaderValue("product"); Assert.Equal("product", product.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes() { ProductHeaderValue product1 = new ProductHeaderValue("custom", "1.0"); ProductHeaderValue product2 = new ProductHeaderValue("custom"); ProductHeaderValue product3 = new ProductHeaderValue("CUSTOM", "1.0"); ProductHeaderValue product4 = new ProductHeaderValue("RTA", "x11"); ProductHeaderValue product5 = new ProductHeaderValue("rta", "X11"); Assert.NotEqual(product1.GetHashCode(), product2.GetHashCode()); Assert.Equal(product1.GetHashCode(), product3.GetHashCode()); Assert.NotEqual(product1.GetHashCode(), product4.GetHashCode()); Assert.Equal(product4.GetHashCode(), product5.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { ProductHeaderValue product1 = new ProductHeaderValue("custom", "1.0"); ProductHeaderValue product2 = new ProductHeaderValue("custom"); ProductHeaderValue product3 = new ProductHeaderValue("CUSTOM", "1.0"); ProductHeaderValue product4 = new ProductHeaderValue("RTA", "x11"); ProductHeaderValue product5 = new ProductHeaderValue("rta", "X11"); Assert.False(product1.Equals(null), "custom/1.0 vs. <null>"); Assert.False(product1.Equals(product2), "custom/1.0 vs. custom"); Assert.False(product2.Equals(product1), "custom/1.0 vs. custom"); Assert.True(product1.Equals(product3), "custom/1.0 vs. CUSTOM/1.0"); Assert.False(product1.Equals(product4), "custom/1.0 vs. rta/X11"); Assert.True(product4.Equals(product5), "RTA/x11 vs. rta/X11"); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { ProductHeaderValue source = new ProductHeaderValue("SHTTP", "1.3"); ProductHeaderValue clone = (ProductHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Name, clone.Name); Assert.Equal(source.Version, clone.Version); source = new ProductHeaderValue("SHTTP", null); clone = (ProductHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Name, clone.Name); Assert.Null(clone.Version); } [Fact] public void GetProductLength_DifferentValidScenarios_AllReturnNonZero() { ProductHeaderValue result = null; CallGetProductLength(" custom", 1, 6, out result); Assert.Equal("custom", result.Name); Assert.Null(result.Version); CallGetProductLength(" custom, ", 1, 6, out result); Assert.Equal("custom", result.Name); Assert.Null(result.Version); CallGetProductLength(" custom / 5.6 ", 1, 13, out result); Assert.Equal("custom", result.Name); Assert.Equal("5.6", result.Version); CallGetProductLength("RTA / x58 ,", 0, 10, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); CallGetProductLength("RTA / x58", 0, 9, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); CallGetProductLength("RTA / x58 XXX", 0, 10, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); } [Fact] public void GetProductLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetProductLength(" custom", 0); // no leading whitespaces allowed CheckInvalidGetProductLength("custom/", 0); CheckInvalidGetProductLength("custom/[", 0); CheckInvalidGetProductLength("=", 0); CheckInvalidGetProductLength("", 0); CheckInvalidGetProductLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse(" y/1 ", new ProductHeaderValue("y", "1")); CheckValidParse(" custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidParse("custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidParse("custom / 1.0", new ProductHeaderValue("custom", "1.0")); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("product/version="); // only delimiter ',' allowed after last product CheckInvalidParse("product otherproduct"); CheckInvalidParse("product["); CheckInvalidParse("="); CheckInvalidParse(null); CheckInvalidParse(string.Empty); CheckInvalidParse(" "); CheckInvalidParse(" ,,"); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse(" y/1 ", new ProductHeaderValue("y", "1")); CheckValidTryParse(" custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidTryParse("custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidTryParse("custom / 1.0", new ProductHeaderValue("custom", "1.0")); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("product/version="); // only delimiter ',' allowed after last product CheckInvalidTryParse("product otherproduct"); CheckInvalidTryParse("product["); CheckInvalidTryParse("="); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); CheckInvalidTryParse(" "); CheckInvalidTryParse(" ,,"); } #region Helper methods private void CheckValidParse(string input, ProductHeaderValue expectedResult) { ProductHeaderValue result = ProductHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { ProductHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, ProductHeaderValue expectedResult) { ProductHeaderValue result = null; Assert.True(ProductHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { ProductHeaderValue result = null; Assert.False(ProductHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetProductLength(string input, int startIndex, int expectedLength, out ProductHeaderValue result) { Assert.Equal(expectedLength, ProductHeaderValue.GetProductLength(input, startIndex, out result)); } private static void CheckInvalidGetProductLength(string input, int startIndex) { ProductHeaderValue result = null; Assert.Equal(0, ProductHeaderValue.GetProductLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.3.5.2. Information about a request for supplies /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(EntityID))] [XmlInclude(typeof(SupplyQuantity))] public partial class ResupplyOfferPdu : LogisticsPdu, IEquatable<ResupplyOfferPdu> { /// <summary> /// Entity that is receiving service /// </summary> private EntityID _receivingEntityID = new EntityID(); /// <summary> /// Entity that is supplying /// </summary> private EntityID _supplyingEntityID = new EntityID(); /// <summary> /// how many supplies are being offered /// </summary> private byte _numberOfSupplyTypes; /// <summary> /// padding /// </summary> private short _padding1; /// <summary> /// padding /// </summary> private byte _padding2; private List<SupplyQuantity> _supplies = new List<SupplyQuantity>(); /// <summary> /// Initializes a new instance of the <see cref="ResupplyOfferPdu"/> class. /// </summary> public ResupplyOfferPdu() { PduType = (byte)6; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(ResupplyOfferPdu left, ResupplyOfferPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(ResupplyOfferPdu left, ResupplyOfferPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += this._receivingEntityID.GetMarshalledSize(); // this._receivingEntityID marshalSize += this._supplyingEntityID.GetMarshalledSize(); // this._supplyingEntityID marshalSize += 1; // this._numberOfSupplyTypes marshalSize += 2; // this._padding1 marshalSize += 1; // this._padding2 for (int idx = 0; idx < this._supplies.Count; idx++) { SupplyQuantity listElement = (SupplyQuantity)this._supplies[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the Entity that is receiving service /// </summary> [XmlElement(Type = typeof(EntityID), ElementName = "receivingEntityID")] public EntityID ReceivingEntityID { get { return this._receivingEntityID; } set { this._receivingEntityID = value; } } /// <summary> /// Gets or sets the Entity that is supplying /// </summary> [XmlElement(Type = typeof(EntityID), ElementName = "supplyingEntityID")] public EntityID SupplyingEntityID { get { return this._supplyingEntityID; } set { this._supplyingEntityID = value; } } /// <summary> /// Gets or sets the how many supplies are being offered /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfSupplyTypes method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(byte), ElementName = "numberOfSupplyTypes")] public byte NumberOfSupplyTypes { get { return this._numberOfSupplyTypes; } set { this._numberOfSupplyTypes = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(short), ElementName = "padding1")] public short Padding1 { get { return this._padding1; } set { this._padding1 = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(byte), ElementName = "padding2")] public byte Padding2 { get { return this._padding2; } set { this._padding2 = value; } } /// <summary> /// Gets the supplies /// </summary> [XmlElement(ElementName = "suppliesList", Type = typeof(List<SupplyQuantity>))] public List<SupplyQuantity> Supplies { get { return this._supplies; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { this._receivingEntityID.Marshal(dos); this._supplyingEntityID.Marshal(dos); dos.WriteUnsignedByte((byte)this._supplies.Count); dos.WriteShort((short)this._padding1); dos.WriteByte((byte)this._padding2); for (int idx = 0; idx < this._supplies.Count; idx++) { SupplyQuantity aSupplyQuantity = (SupplyQuantity)this._supplies[idx]; aSupplyQuantity.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._receivingEntityID.Unmarshal(dis); this._supplyingEntityID.Unmarshal(dis); this._numberOfSupplyTypes = dis.ReadUnsignedByte(); this._padding1 = dis.ReadShort(); this._padding2 = dis.ReadByte(); for (int idx = 0; idx < this.NumberOfSupplyTypes; idx++) { SupplyQuantity anX = new SupplyQuantity(); anX.Unmarshal(dis); this._supplies.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<ResupplyOfferPdu>"); base.Reflection(sb); try { sb.AppendLine("<receivingEntityID>"); this._receivingEntityID.Reflection(sb); sb.AppendLine("</receivingEntityID>"); sb.AppendLine("<supplyingEntityID>"); this._supplyingEntityID.Reflection(sb); sb.AppendLine("</supplyingEntityID>"); sb.AppendLine("<supplies type=\"byte\">" + this._supplies.Count.ToString(CultureInfo.InvariantCulture) + "</supplies>"); sb.AppendLine("<padding1 type=\"short\">" + this._padding1.ToString(CultureInfo.InvariantCulture) + "</padding1>"); sb.AppendLine("<padding2 type=\"byte\">" + this._padding2.ToString(CultureInfo.InvariantCulture) + "</padding2>"); for (int idx = 0; idx < this._supplies.Count; idx++) { sb.AppendLine("<supplies" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"SupplyQuantity\">"); SupplyQuantity aSupplyQuantity = (SupplyQuantity)this._supplies[idx]; aSupplyQuantity.Reflection(sb); sb.AppendLine("</supplies" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</ResupplyOfferPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as ResupplyOfferPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(ResupplyOfferPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (!this._receivingEntityID.Equals(obj._receivingEntityID)) { ivarsEqual = false; } if (!this._supplyingEntityID.Equals(obj._supplyingEntityID)) { ivarsEqual = false; } if (this._numberOfSupplyTypes != obj._numberOfSupplyTypes) { ivarsEqual = false; } if (this._padding1 != obj._padding1) { ivarsEqual = false; } if (this._padding2 != obj._padding2) { ivarsEqual = false; } if (this._supplies.Count != obj._supplies.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._supplies.Count; idx++) { if (!this._supplies[idx].Equals(obj._supplies[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._receivingEntityID.GetHashCode(); result = GenerateHash(result) ^ this._supplyingEntityID.GetHashCode(); result = GenerateHash(result) ^ this._numberOfSupplyTypes.GetHashCode(); result = GenerateHash(result) ^ this._padding1.GetHashCode(); result = GenerateHash(result) ^ this._padding2.GetHashCode(); if (this._supplies.Count > 0) { for (int idx = 0; idx < this._supplies.Count; idx++) { result = GenerateHash(result) ^ this._supplies[idx].GetHashCode(); } } return result; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using System.Threading; using Aurora.Simulation.Base; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using Aurora.Framework.Capabilities; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Services.MessagingService { public class AgentProcessing : ConnectorBase, IService, IAgentProcessing { #region Declares protected int MaxVariableRegionSight = 512; protected bool VariableRegionSight; protected bool m_enabled = true; protected string _capsURL = "", _capsURLPassword = ""; protected IConfigSource _config; #endregion #region IService Members public virtual void Initialize(IConfigSource config, IRegistryCore registry) { _config = config; m_registry = registry; IConfig agentConfig = config.Configs["AgentProcessing"]; if (agentConfig != null) { m_enabled = agentConfig.GetString("Module", "AgentProcessing") == "AgentProcessing"; VariableRegionSight = agentConfig.GetBoolean("UseVariableRegionSightDistance", VariableRegionSight); MaxVariableRegionSight = agentConfig.GetInt("MaxDistanceVariableRegionSightDistance", MaxVariableRegionSight); } if (m_enabled) { m_registry.RegisterModuleInterface<IAgentProcessing>(this); IConfig auroraConfig = _config.Configs["AuroraConnectors"]; IGenericsConnector genericsConnector = Aurora.DataManager.DataManager.RequestPlugin<IGenericsConnector>(); if (!auroraConfig.GetBoolean("CapsServiceDoRemoteCalls", false)) { genericsConnector.AddGeneric(UUID.Zero, "CapsServiceURL", "CapsURL", new OSDWrapper { Info = MainServer.Instance.ServerURI }.ToOSD()); genericsConnector.AddGeneric(UUID.Zero, "CapsServiceURL", "CapsPassword", new OSDWrapper { Info = new System.Random().NextDouble() * 1000 }.ToOSD()); } Init(registry, "CapsService"); } } public virtual void Start(IConfigSource config, IRegistryCore registry) { } public virtual void FinishedStartup() { //Also look for incoming messages to display if (m_enabled) { m_registry.RequestModuleInterface<IAsyncMessageRecievedService>().OnMessageReceived += OnMessageReceived; ReadRemoteCapsPassword(); } } private void ReadRemoteCapsPassword() { IConfig handlerConfig = _config.Configs["AuroraConnectors"]; IGenericsConnector genericsConnector = Aurora.DataManager.DataManager.RequestPlugin<IGenericsConnector>(); if (handlerConfig.GetBoolean("CapsServiceDoRemoteCalls", false)) { OSDWrapper wrapper = genericsConnector.GetGeneric<OSDWrapper>(UUID.Zero, "CapsServiceURL", "CapsURL"); if (wrapper != null) { _capsURL = wrapper.Info.AsString(); OSDWrapper w = genericsConnector.GetGeneric<OSDWrapper>(UUID.Zero, "CapsServiceURL", "CapsPassword"); _capsURLPassword = w.Info.AsString(); base.SetPassword(_capsURLPassword); } } } #endregion #region Message Received protected virtual OSDMap OnMessageReceived(OSDMap message) { if (!message.ContainsKey("Method")) return null; UUID AgentID = message["AgentID"].AsUUID(); ulong requestingRegion = message["RequestingRegion"].AsULong(); ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); if (capsService == null) return new OSDMap(); IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID); IRegionClientCapsService regionCaps = null; if (clientCaps != null) regionCaps = clientCaps.GetCapsService(requestingRegion); if (message["Method"] == "LogoutRegionAgents") { LogOutAllAgentsForRegion(requestingRegion); } else if (message["Method"] == "RegionIsOnline") //This gets fired when the scene is fully finished starting up { //Log out all the agents first, then add any child agents that should be in this region LogOutAllAgentsForRegion(requestingRegion); IGridService GridService = m_registry.RequestModuleInterface<IGridService>(); if (GridService != null) { int x, y; Util.UlongToInts(requestingRegion, out x, out y); GridRegion requestingGridRegion = GridService.GetRegionByPosition(null, x, y); if (requestingGridRegion != null) Util.FireAndForget((o) => EnableChildAgentsForRegion(requestingGridRegion)); } } else if (message["Method"] == "DisableSimulator") { //KILL IT! if (regionCaps == null || clientCaps == null) return null; IEventQueueService eventQueue = m_registry.RequestModuleInterface<IEventQueueService>(); eventQueue.DisableSimulator(regionCaps.AgentID, regionCaps.RegionHandle); //regionCaps.Close(); //clientCaps.RemoveCAPS(requestingRegion); regionCaps.Disabled = true; } else if (message["Method"] == "ArrivedAtDestination") { if (regionCaps == null || clientCaps == null) return null; //Recieved a callback if (clientCaps.InTeleport) //Only set this if we are in a teleport, // otherwise (such as on login), this won't check after the first tp! clientCaps.CallbackHasCome = true; regionCaps.Disabled = false; //The agent is getting here for the first time (eg. login) OSDMap body = ((OSDMap) message["Message"]); //Parse the OSDMap int DrawDistance = body["DrawDistance"].AsInteger(); AgentCircuitData circuitData = new AgentCircuitData(); circuitData.UnpackAgentCircuitData((OSDMap) body["Circuit"]); //Now do the creation EnableChildAgents(AgentID, requestingRegion, DrawDistance, circuitData); } else if (message["Method"] == "CancelTeleport") { if (regionCaps == null || clientCaps == null) return null; //Only the region the client is root in can do this IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService(); if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle) { //The user has requested to cancel the teleport, stop them. clientCaps.RequestToCancelTeleport = true; regionCaps.Disabled = false; } } else if (message["Method"] == "AgentLoggedOut") { //ONLY if the agent is root do we even consider it if (regionCaps != null) { if (regionCaps.RootAgent) { LogoutAgent(regionCaps, false); //The root is killing itself } } } else if (message["Method"] == "SendChildAgentUpdate") { if (regionCaps == null || clientCaps == null) return null; IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService(); if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle) //Has to be root { OSDMap body = ((OSDMap) message["Message"]); AgentPosition pos = new AgentPosition(); pos.Unpack((OSDMap) body["AgentPos"]); SendChildAgentUpdate(pos, regionCaps); regionCaps.Disabled = false; } } else if (message["Method"] == "TeleportAgent") { if (regionCaps == null || clientCaps == null) return null; IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService(); if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle) { OSDMap body = ((OSDMap) message["Message"]); GridRegion destination = new GridRegion(); destination.FromOSD((OSDMap) body["Region"]); uint TeleportFlags = body["TeleportFlags"].AsUInteger(); int DrawDistance = body["DrawDistance"].AsInteger(); AgentCircuitData Circuit = new AgentCircuitData(); Circuit.UnpackAgentCircuitData((OSDMap) body["Circuit"]); AgentData AgentData = new AgentData(); AgentData.Unpack((OSDMap) body["AgentData"]); regionCaps.Disabled = false; string ResponseURL = message["ResponseURL"].AsString(); if (ResponseURL == "") { OSDMap result = new OSDMap(); string reason = ""; result["success"] = TeleportAgent(ref destination, TeleportFlags, DrawDistance, Circuit, AgentData, AgentID, requestingRegion, out reason); result["Reason"] = reason; //Remove the region flags, not the regions problem destination.Flags = 0; result["Destination"] = destination.ToOSD(); //Send back the new destination return result; } else { Util.FireAndForget(delegate { OSDMap result = new OSDMap(); string reason = ""; result["success"] = TeleportAgent(ref destination, TeleportFlags, DrawDistance, Circuit, AgentData, AgentID, requestingRegion, out reason); result["Reason"] = reason; //Remove the region flags, not the regions problem destination.Flags = 0; result["Destination"] = destination.ToOSD(); //Send back the new destination WebUtils.PostToService(ResponseURL, result); }); return new OSDMap() { new KeyValuePair<string, OSD>("WillHaveResponse", true) }; } } } else if (message["Method"] == "CrossAgent") { if (regionCaps == null || clientCaps == null) return null; IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService(); if (rootCaps == null || rootCaps.RegionHandle == regionCaps.RegionHandle) { //This is a simulator message that tells us to cross the agent OSDMap body = ((OSDMap) message["Message"]); Vector3 pos = body["Pos"].AsVector3(); Vector3 Vel = body["Vel"].AsVector3(); GridRegion Region = new GridRegion(); Region.FromOSD((OSDMap) body["Region"]); AgentCircuitData Circuit = new AgentCircuitData(); Circuit.UnpackAgentCircuitData((OSDMap) body["Circuit"]); AgentData AgentData = new AgentData(); AgentData.Unpack((OSDMap) body["AgentData"]); regionCaps.Disabled = false; string ResponseURL = message["ResponseURL"].AsString(); if (ResponseURL == "") { OSDMap result = new OSDMap(); string reason = ""; result["success"] = CrossAgent(Region, pos, Vel, Circuit, AgentData, AgentID, requestingRegion, out reason); result["reason"] = reason; return result; } else { Util.FireAndForget(delegate { OSDMap result = new OSDMap(); string reason = ""; result["success"] = CrossAgent(Region, pos, Vel, Circuit, AgentData, AgentID, requestingRegion, out reason); result["reason"] = reason; if (ResponseURL != null) WebUtils.PostToService(ResponseURL, result); }); return new OSDMap() { new KeyValuePair<string, OSD>("WillHaveResponse", true) }; } } else if (clientCaps.InTeleport) { OSDMap result = new OSDMap(); result["success"] = false; result["Note"] = false; return result; } else { OSDMap result = new OSDMap(); result["success"] = false; result["Note"] = false; return result; } } return null; } #region Logout Agent public virtual void LogoutAgent(IRegionClientCapsService regionCaps, bool kickRootAgent) { //Close all neighbor agents as well, the root is closing itself, so don't call them ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>(); if (SimulationService != null) { IGridService GridService = m_registry.RequestModuleInterface<IGridService>(); if (GridService != null) { #if (!ISWIN) foreach (IRegionClientCapsService regionClient in regionCaps.ClientCaps.GetCapsServices()) { if (regionClient.RegionHandle != regionCaps.RegionHandle && regionClient.Region != null) { SimulationService.CloseAgent(regionClient.Region, regionCaps.AgentID); } } #else foreach (IRegionClientCapsService regionClient in regionCaps.ClientCaps.GetCapsServices().Where(regionClient => regionClient.RegionHandle != regionCaps.RegionHandle && regionClient.Region != null)) { SimulationService.CloseAgent(regionClient.Region, regionCaps.AgentID); } #endif } } if (kickRootAgent && regionCaps.Region != null) //Kick the root agent then SimulationService.CloseAgent(regionCaps.Region, regionCaps.AgentID); //Close all caps regionCaps.ClientCaps.Close(); IAgentInfoService agentInfoService = m_registry.RequestModuleInterface<IAgentInfoService>(); if (agentInfoService != null) agentInfoService.SetLoggedIn(regionCaps.AgentID.ToString(), false, true, UUID.Zero); ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); if (capsService != null) capsService.RemoveCAPS(regionCaps.AgentID); } public virtual void LogOutAllAgentsForRegion(ulong requestingRegion) { IRegionCapsService fullregionCaps = m_registry.RequestModuleInterface<ICapsService>().GetCapsForRegion(requestingRegion); if (fullregionCaps != null) { IEventQueueService eqs = m_registry.RequestModuleInterface<IEventQueueService>(); if (eqs != null) { foreach (IRegionClientCapsService regionClientCaps in fullregionCaps.GetClients()) { //We can send this here, because we ONLY send this when the region is going down for a loong time eqs.DisableSimulator(regionClientCaps.AgentID, regionClientCaps.RegionHandle); } } //Now kill the region in the caps Service, DO THIS FIRST, otherwise you get an infinite loop later in the IClientCapsService when it tries to remove itself from the IRegionCapsService m_registry.RequestModuleInterface<ICapsService>().RemoveCapsForRegion(requestingRegion); //Close all regions and remove them from the region fullregionCaps.Close(); } } #endregion #region EnableChildAgents public virtual bool EnableChildAgentsForRegion(GridRegion requestingRegion) { int count = 0; bool informed = true; List<GridRegion> neighbors = GetNeighbors(null, requestingRegion, 0); foreach (GridRegion neighbor in neighbors) { //MainConsole.Instance.WarnFormat("--> Going to send child agent to {0}, new agent {1}", neighbour.RegionName, newAgent); IRegionCapsService regionCaps = m_registry.RequestModuleInterface<ICapsService>().GetCapsForRegion(neighbor.RegionHandle); if (regionCaps == null) //If there isn't a region caps, there isn't an agent in this sim continue; List<UUID> usersInformed = new List<UUID>(); foreach (IRegionClientCapsService regionClientCaps in regionCaps.GetClients()) { if (usersInformed.Contains(regionClientCaps.AgentID) || !regionClientCaps.RootAgent || AllScopeIDImpl.CheckScopeIDs(regionClientCaps.ClientCaps.AccountInfo.AllScopeIDs, neighbor) == null) //Only inform agents once continue; AgentCircuitData regionCircuitData = regionClientCaps.CircuitData.Copy(); regionCircuitData.child = true; //Fix child agent status regionCircuitData.roothandle = requestingRegion.RegionHandle; regionCircuitData.reallyischild = true; string reason; //Tell the region about it bool useCallbacks = false; if (!InformClientOfNeighbor(regionClientCaps.AgentID, regionClientCaps.RegionHandle, regionCircuitData, ref requestingRegion, (uint) TeleportFlags.Default, null, out reason, out useCallbacks)) informed = false; else usersInformed.Add(regionClientCaps.AgentID); } count++; } return informed; } public virtual void EnableChildAgents(UUID AgentID, ulong requestingRegion, int DrawDistance, AgentCircuitData circuit) { Util.FireAndForget((o) => { int count = 0; int x, y; ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID); Util.UlongToInts(requestingRegion, out x, out y); GridRegion ourRegion = m_registry.RequestModuleInterface<IGridService>().GetRegionByPosition( clientCaps.AccountInfo.AllScopeIDs, x, y); if (ourRegion == null) { MainConsole.Instance.Info( "[AgentProcessing]: Failed to inform neighbors about new agent, could not find our region."); return; } List<GridRegion> neighbors = GetNeighbors(clientCaps.AccountInfo.AllScopeIDs, ourRegion, DrawDistance); clientCaps.GetRootCapsService().CircuitData.DrawDistance = DrawDistance; //Fix the root agents dd foreach (GridRegion neighbor in neighbors) { if (neighbor.RegionHandle != requestingRegion && clientCaps.GetCapsService(neighbor.RegionHandle) == null) { string reason; AgentCircuitData regionCircuitData = clientCaps.GetRootCapsService().CircuitData.Copy(); GridRegion nCopy = neighbor; regionCircuitData.child = true; //Fix child agent status regionCircuitData.roothandle = requestingRegion; regionCircuitData.reallyischild = true; regionCircuitData.DrawDistance = DrawDistance; bool useCallbacks = false; InformClientOfNeighbor(AgentID, requestingRegion, regionCircuitData, ref nCopy, (uint) TeleportFlags.Default, null, out reason, out useCallbacks); } count++; } }); } public virtual void EnableChildAgentsForPosition(IRegionClientCapsService caps, Vector3 position) { Util.FireAndForget((o) => { int count = 0; IGridService gridService = m_registry.RequestModuleInterface<IGridService>(); int xMin = (caps.Region.RegionLocX) + (int)(position.X) - ((gridService != null ? gridService.GetRegionViewSize() : 1) * caps.Region.RegionSizeX); int xMax = (caps.Region.RegionLocX) + (int) (position.X) + 256; int yMin = (caps.Region.RegionLocY) + (int)(position.Y) - ((gridService != null ? gridService.GetRegionViewSize() : 1) * caps.Region.RegionSizeY); int yMax = (caps.Region.RegionLocY) + (int) (position.Y) + 256; //Ask the grid service about the range List<GridRegion> neighbors = m_registry.RequestModuleInterface<IGridService>().GetRegionRange(caps.ClientCaps.AccountInfo.AllScopeIDs, xMin, xMax, yMin, yMax); ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); IClientCapsService clientCaps = capsService.GetClientCapsService(caps.AgentID); foreach (GridRegion neighbor in neighbors) { if (neighbor.RegionHandle != caps.RegionHandle && clientCaps.GetCapsService(neighbor.RegionHandle) == null) { string reason; AgentCircuitData regionCircuitData = caps.CircuitData.Copy(); GridRegion nCopy = neighbor; regionCircuitData.child = true; //Fix child agent status regionCircuitData.roothandle = caps.RegionHandle; regionCircuitData.reallyischild = true; bool useCallbacks = false; InformClientOfNeighbor(caps.AgentID, caps.RegionHandle, regionCircuitData, ref nCopy, (uint) TeleportFlags.Default, null, out reason, out useCallbacks); } count++; } }); } #endregion #region Inform Client Of Neighbor /// <summary> /// Async component for informing client of which neighbors exist /// </summary> /// <remarks> /// This needs to run asynchronously, as a network timeout may block the thread for a long while /// </remarks> /// <param name = "remoteClient"></param> /// <param name = "a"></param> /// <param name = "regionHandle"></param> /// <param name = "endPoint"></param> public virtual bool InformClientOfNeighbor(UUID AgentID, ulong requestingRegion, AgentCircuitData circuitData, ref GridRegion neighbor, uint TeleportFlags, AgentData agentData, out string reason, out bool useCallbacks) { useCallbacks = true; if (neighbor == null || neighbor.RegionHandle == 0) { reason = "Could not find neighbor to inform"; return false; } /*if ((neighbor.Flags & (int)Aurora.Framework.RegionFlags.RegionOnline) == 0 && (neighbor.Flags & (int)(Aurora.Framework.RegionFlags.Foreign | Aurora.Framework.RegionFlags.Hyperlink)) == 0) { reason = "The region you are attempting to teleport to is offline"; return false; }*/ MainConsole.Instance.Info("[AgentProcessing]: Starting to inform client about neighbor " + neighbor.RegionName); //Notes on this method // 1) the SimulationService.CreateAgent MUST have a fixed CapsUrl for the region, so we have to create (if needed) // a new Caps handler for it. // 2) Then we can call the methods (EnableSimulator and EstatablishAgentComm) to tell the client the new Urls // 3) This allows us to make the Caps on the grid server without telling any other regions about what the // Urls are. ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>(); if (SimulationService != null) { ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID); IRegionClientCapsService oldRegionService = clientCaps.GetCapsService(neighbor.RegionHandle); //If its disabled, it should be removed, so kill it! if (oldRegionService != null && oldRegionService.Disabled) { clientCaps.RemoveCAPS(neighbor.RegionHandle); oldRegionService = null; } bool newAgent = oldRegionService == null; IRegionClientCapsService otherRegionService = clientCaps.GetOrCreateCapsService(neighbor.RegionHandle, CapsUtil.GetCapsSeedPath (CapsUtil. GetRandomCapsObjectPath ()), circuitData, 0); if (!newAgent) { //Note: if the agent is already there, send an agent update then bool result = true; if (agentData != null) { agentData.IsCrossing = false; result = SimulationService.UpdateAgent(neighbor, agentData); } if (result) oldRegionService.Disabled = false; reason = ""; return result; } ICommunicationService commsService = m_registry.RequestModuleInterface<ICommunicationService>(); if (commsService != null) commsService.GetUrlsForUser(neighbor, circuitData.AgentID); //Make sure that we make userURLs if we need to circuitData.CapsPath = CapsUtil.GetCapsPathFromCapsSeed(otherRegionService.CapsUrl); //For OpenSim circuitData.firstname = clientCaps.AccountInfo.FirstName; circuitData.lastname = clientCaps.AccountInfo.LastName; int requestedPort = 0; if (circuitData.child) circuitData.reallyischild = true; bool regionAccepted = CreateAgent(neighbor, otherRegionService, ref circuitData, SimulationService, ref requestedPort, out reason); if (regionAccepted) { IPAddress ipAddress = neighbor.ExternalEndPoint.Address; string otherRegionsCapsURL; //If the region accepted us, we should get a CAPS url back as the reason, if not, its not updated or not an Aurora region, so don't touch it. if (reason != "" && reason != "authorized") { OSDMap responseMap = (OSDMap) OSDParser.DeserializeJson(reason); OSDMap SimSeedCaps = (OSDMap) responseMap["CapsUrls"]; if (responseMap.ContainsKey("OurIPForClient")) { string ip = responseMap["OurIPForClient"].AsString(); if (!IPAddress.TryParse(ip, out ipAddress)) #pragma warning disable 618 ipAddress = Dns.GetHostByName(ip).AddressList[0]; #pragma warning restore 618 } otherRegionService.AddCAPS(SimSeedCaps); otherRegionsCapsURL = otherRegionService.CapsUrl; } else { //We are assuming an OpenSim region now! #region OpenSim teleport compatibility! useCallbacks = false; //OpenSim can't send us back a message, don't try it! otherRegionsCapsURL = otherRegionService.Region.ServerURI + CapsUtil.GetCapsSeedPath(circuitData.CapsPath); otherRegionService.CapsUrl = otherRegionsCapsURL; #endregion } if (ipAddress == null) ipAddress = neighbor.ExternalEndPoint.Address; if (requestedPort == 0) requestedPort = neighbor.ExternalEndPoint.Port; otherRegionService = clientCaps.GetCapsService(neighbor.RegionHandle); otherRegionService.LoopbackRegionIP = ipAddress; otherRegionService.CircuitData.RegionUDPPort = requestedPort; circuitData.RegionUDPPort = requestedPort; //Fix the port IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>(); EQService.EnableSimulator(neighbor.RegionHandle, ipAddress.GetAddressBytes(), requestedPort, AgentID, neighbor.RegionSizeX, neighbor.RegionSizeY, requestingRegion); // EnableSimulator makes the client send a UseCircuitCode message to the destination, // which triggers a bunch of things there. // So let's wait Thread.Sleep(300); EQService.EstablishAgentCommunication(AgentID, neighbor.RegionHandle, ipAddress.GetAddressBytes(), requestedPort, otherRegionsCapsURL, neighbor.RegionSizeX, neighbor.RegionSizeY, requestingRegion); if (!useCallbacks) Thread.Sleep(3000); //Give it a bit of time, only for OpenSim... MainConsole.Instance.Info("[AgentProcessing]: Completed inform client about neighbor " + neighbor.RegionName); } else { clientCaps.RemoveCAPS(neighbor.RegionHandle); MainConsole.Instance.Error("[AgentProcessing]: Failed to inform client about neighbor " + neighbor.RegionName + ", reason: " + reason); return false; } return true; } reason = "SimulationService does not exist"; MainConsole.Instance.Error("[AgentProcessing]: Failed to inform client about neighbor " + neighbor.RegionName + ", reason: " + reason + "!"); return false; } #endregion #region Teleporting private int CloseNeighborCall; public virtual bool TeleportAgent(ref GridRegion destination, uint TeleportFlags, int DrawDistance, AgentCircuitData circuit, AgentData agentData, UUID AgentID, ulong requestingRegion, out string reason) { IClientCapsService clientCaps = m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID); IRegionClientCapsService regionCaps = clientCaps.GetCapsService(requestingRegion); if (regionCaps == null || !regionCaps.RootAgent) { reason = ""; ResetFromTransit(AgentID); return false; } bool result = false; try { bool callWasCanceled = false; ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>(); if (SimulationService != null) { //Set the user in transit so that we block duplicate tps and reset any cancelations if (!SetUserInTransit(AgentID)) { reason = "Already in a teleport"; return false; } bool useCallbacks = false; //Note: we have to pull the new grid region info as the one from the region cannot be trusted GridRegion oldRegion = destination; IGridService GridService = m_registry.RequestModuleInterface<IGridService>(); if (GridService != null) { destination = GridService.GetRegionByUUID(clientCaps.AccountInfo.AllScopeIDs, destination.RegionID); if (destination == null) //If its not in this grid destination = oldRegion; //Inform the client of the neighbor if needed circuit.child = false; //Force child status to the correct type circuit.roothandle = destination.RegionHandle; if (!InformClientOfNeighbor(AgentID, requestingRegion, circuit, ref destination, TeleportFlags, agentData, out reason, out useCallbacks)) { ResetFromTransit(AgentID); return false; } } else { reason = "Could not find the grid service"; ResetFromTransit(AgentID); return false; } IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>(); IRegionClientCapsService otherRegion = clientCaps.GetCapsService(destination.RegionHandle); EQService.TeleportFinishEvent(destination.RegionHandle, destination.Access, otherRegion.LoopbackRegionIP, otherRegion.CircuitData.RegionUDPPort, otherRegion.CapsUrl, 4, AgentID, TeleportFlags, destination.RegionSizeX, destination.RegionSizeY, requestingRegion); // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation // that the client contacted the destination before we send the attachments and close things here. result = !useCallbacks || WaitForCallback(AgentID, out callWasCanceled); if (!result) { //It says it failed, lets call the sim and check AgentData data = null; AgentCircuitData circuitData; result = SimulationService.RetrieveAgent(destination, AgentID, false, out data, out circuitData); } if (!result) { if (!callWasCanceled) { MainConsole.Instance.Warn("[AgentProcessing]: Callback never came for teleporting agent " + AgentID + ". Resetting."); } //Close the agent at the place we just created if it isn't a neighbor // 7/22 -- Kill the agent no matter what, it obviously is having issues getting there //if (IsOutsideView (regionCaps.RegionX, destination.RegionLocX, regionCaps.Region.RegionSizeX, destination.RegionSizeX, // regionCaps.RegionY, destination.RegionLocY, regionCaps.Region.RegionSizeY, destination.RegionSizeY)) { SimulationService.CloseAgent(destination, AgentID); clientCaps.RemoveCAPS(destination.RegionHandle); } reason = !callWasCanceled ? "The teleport timed out" : "Cancelled"; } else { //Fix the root agent status otherRegion.RootAgent = true; regionCaps.RootAgent = false; // Next, let's close the child agent connections that are too far away. //if (useCallbacks || oldRegion != destination)//Only close it if we are using callbacks (Aurora region) //Why? OpenSim regions need closed too, even if the protocol is kinda stupid CloseNeighborAgents(regionCaps.Region, destination, AgentID); reason = ""; } } else reason = "No SimulationService found!"; } catch (Exception ex) { MainConsole.Instance.WarnFormat("[AgentProcessing]: Exception occured during agent teleport, {0}", ex); reason = "Exception occured."; } //All done ResetFromTransit(AgentID); return result; } public virtual void CloseNeighborAgents(GridRegion oldRegion, GridRegion destination, UUID AgentID) { CloseNeighborCall++; int CloseNeighborCallNum = CloseNeighborCall; Util.FireAndForget(delegate { //Sleep for 15 seconds to give the agents a chance to cross and get everything right Thread.Sleep(15000); if (CloseNeighborCall != CloseNeighborCallNum) return; //Another was enqueued, kill this one //Now do a sanity check on the avatar IClientCapsService clientCaps = m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService( AgentID); if (clientCaps == null) return; IRegionClientCapsService rootRegionCaps = clientCaps.GetRootCapsService(); if (rootRegionCaps == null) return; IRegionClientCapsService ourRegionCaps = clientCaps.GetCapsService(destination.RegionHandle); if (ourRegionCaps == null) return; //If they handles arn't the same, the agent moved, and we can't be sure that we should close these agents if (rootRegionCaps.RegionHandle != ourRegionCaps.RegionHandle && !clientCaps.InTeleport) return; IGridService service = m_registry.RequestModuleInterface<IGridService>(); if (service != null) { List<GridRegion> NeighborsOfOldRegion = service.GetNeighbors(clientCaps.AccountInfo.AllScopeIDs, oldRegion); List<GridRegion> NeighborsOfDestinationRegion = service.GetNeighbors(clientCaps.AccountInfo.AllScopeIDs, destination); List<GridRegion> byebyeRegions = new List<GridRegion>(NeighborsOfOldRegion) {oldRegion}; //Add the old region, because it might need closed too byebyeRegions.RemoveAll(delegate(GridRegion r) { if (r.RegionID == destination.RegionID) return true; else if ( NeighborsOfDestinationRegion.Contains (r)) return true; return false; }); if (byebyeRegions.Count > 0) { MainConsole.Instance.Info("[AgentProcessing]: Closing " + byebyeRegions.Count + " child agents around " + oldRegion.RegionName); SendCloseChildAgent(AgentID, byebyeRegions); } } }); } public virtual void SendCloseChildAgent(UUID agentID, IEnumerable<GridRegion> regionsToClose) { IClientCapsService clientCaps = m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(agentID); //Close all agents that we've been given regions for foreach (GridRegion region in regionsToClose) { MainConsole.Instance.Info("[AgentProcessing]: Closing child agent in " + region.RegionName); IRegionClientCapsService regionClientCaps = clientCaps.GetCapsService(region.RegionHandle); if (regionClientCaps != null) { m_registry.RequestModuleInterface<ISimulationService>().CloseAgent(region, agentID); clientCaps.RemoveCAPS(region.RegionHandle); } } } protected void ResetFromTransit(UUID AgentID) { IClientCapsService clientCaps = m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID); if (clientCaps != null) { clientCaps.InTeleport = false; clientCaps.RequestToCancelTeleport = false; clientCaps.CallbackHasCome = false; } } protected bool SetUserInTransit(UUID AgentID) { IClientCapsService clientCaps = m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID); if (clientCaps.InTeleport) { MainConsole.Instance.Warn("[AgentProcessing]: Got a request to teleport during another teleport for agent " + AgentID + "!"); return false; //What??? Stop here and don't go forward } clientCaps.InTeleport = true; clientCaps.RequestToCancelTeleport = false; clientCaps.CallbackHasCome = false; return true; } #region Callbacks protected bool WaitForCallback(UUID AgentID, out bool callWasCanceled) { IClientCapsService clientCaps = m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID); int count = 1000; while (!clientCaps.CallbackHasCome && count > 0) { //MainConsole.Instance.Debug(" >>> Waiting... " + count); if (clientCaps.RequestToCancelTeleport) { //If the call was canceled, we need to break here // now and tell the code that called us about it callWasCanceled = true; return true; } Thread.Sleep(10); count--; } //If we made it through the whole loop, we havn't been canceled, // as we either have timed out or made it, so no checks are needed callWasCanceled = false; return clientCaps.CallbackHasCome; } protected bool WaitForCallback(UUID AgentID) { IClientCapsService clientCaps = m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID); int count = 100; while (!clientCaps.CallbackHasCome && count > 0) { //MainConsole.Instance.Debug(" >>> Waiting... " + count); Thread.Sleep(100); count--; } return clientCaps.CallbackHasCome; } #endregion #endregion #region View Size /// <summary> /// Check if the new position is outside of the range for the old position /// </summary> /// <param name = "x">old X pos (in meters)</param> /// <param name = "newRegionX">new X pos (in meters)</param> /// <param name = "y">old Y pos (in meters)</param> /// <param name = "newRegionY">new Y pos (in meters)</param> /// <returns></returns> public virtual bool IsOutsideView(int oldRegionX, int newRegionX, int oldRegionSizeX, int newRegionSizeX, int oldRegionY, int newRegionY, int oldRegionSizeY, int newRegionSizeY) { if (!CheckViewSize(oldRegionX, newRegionX, oldRegionSizeX, newRegionSizeX)) return true; if (!CheckViewSize(oldRegionY, newRegionY, oldRegionSizeY, newRegionSizeY)) return true; return false; } private bool CheckViewSize(int oldr, int newr, int oldSize, int newSize) { if (oldr - newr < 0) { if ( !(Math.Abs(oldr - newr + newSize) <= m_registry.RequestModuleInterface<IGridService>().GetRegionViewSize())) return false; } else { if ( !(Math.Abs(newr - oldr + oldSize) <= m_registry.RequestModuleInterface<IGridService>().GetRegionViewSize())) return false; } return true; } public virtual List<GridRegion> GetNeighbors(List<UUID> scopeIDs, GridRegion region, int userDrawDistance) { List<GridRegion> neighbors = new List<GridRegion>(); if (VariableRegionSight && userDrawDistance != 0) { //Enforce the max draw distance if (userDrawDistance > MaxVariableRegionSight) userDrawDistance = MaxVariableRegionSight; //Query how many regions fit in this size int xMin = (region.RegionLocX) - (userDrawDistance); int xMax = (region.RegionLocX) + (userDrawDistance); int yMin = (region.RegionLocY) - (userDrawDistance); int yMax = (region.RegionLocY) + (userDrawDistance); //Ask the grid service about the range neighbors = m_registry.RequestModuleInterface<IGridService>().GetRegionRange(scopeIDs, xMin, xMax, yMin, yMax); } else neighbors = m_registry.RequestModuleInterface<IGridService>().GetNeighbors(scopeIDs, region); return neighbors; } #endregion #region Crossing public virtual bool CrossAgent(GridRegion crossingRegion, Vector3 pos, Vector3 velocity, AgentCircuitData circuit, AgentData cAgent, UUID AgentID, ulong requestingRegion, out string reason) { try { IClientCapsService clientCaps = m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID); IRegionClientCapsService requestingRegionCaps = clientCaps.GetCapsService(requestingRegion); ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>(); if (SimulationService != null) { //Note: we have to pull the new grid region info as the one from the region cannot be trusted IGridService GridService = m_registry.RequestModuleInterface<IGridService>(); if (GridService != null) { //Set the user in transit so that we block duplicate tps and reset any cancelations if (!SetUserInTransit(AgentID)) { reason = "Already in a teleport"; return false; } bool result = false; //We need to get it from the grid service again so that we can get the simulation service urls correctly // as regions don't get that info crossingRegion = GridService.GetRegionByUUID(clientCaps.AccountInfo.AllScopeIDs, crossingRegion.RegionID); cAgent.IsCrossing = true; if (!SimulationService.UpdateAgent(crossingRegion, cAgent)) { MainConsole.Instance.Warn("[AgentProcessing]: Failed to cross agent " + AgentID + " because region did not accept it. Resetting."); reason = "Failed to update an agent"; } else { IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>(); //Add this for the viewer, but not for the sim, seems to make the viewer happier int XOffset = crossingRegion.RegionLocX - requestingRegionCaps.RegionX; pos.X += XOffset; int YOffset = crossingRegion.RegionLocY - requestingRegionCaps.RegionY; pos.Y += YOffset; IRegionClientCapsService otherRegion = clientCaps.GetCapsService(crossingRegion.RegionHandle); //Tell the client about the transfer EQService.CrossRegion(crossingRegion.RegionHandle, pos, velocity, otherRegion.LoopbackRegionIP, otherRegion.CircuitData.RegionUDPPort, otherRegion.CapsUrl, AgentID, circuit.SessionID, crossingRegion.RegionSizeX, crossingRegion.RegionSizeY, requestingRegion); result = WaitForCallback(AgentID); if (!result) { MainConsole.Instance.Warn("[AgentProcessing]: Callback never came in crossing agent " + circuit.AgentID + ". Resetting."); reason = "Crossing timed out"; } else { // Next, let's close the child agent connections that are too far away. //Fix the root agent status otherRegion.RootAgent = true; requestingRegionCaps.RootAgent = false; CloseNeighborAgents(requestingRegionCaps.Region, crossingRegion, AgentID); reason = ""; } } //All done ResetFromTransit(AgentID); return result; } else reason = "Could not find the GridService"; } else reason = "Could not find the SimulationService"; } catch (Exception ex) { MainConsole.Instance.WarnFormat("[AgentProcessing]: Failed to cross an agent into a new region. {0}", ex); } ResetFromTransit(AgentID); reason = "Exception occured"; return false; } #endregion #region Agent Update public virtual void SendChildAgentUpdate(AgentPosition agentpos, IRegionClientCapsService regionCaps) { Util.FireAndForget(delegate { SendChildAgentUpdateAsync(agentpos, regionCaps); }); } public virtual void SendChildAgentUpdateAsync(AgentPosition agentpos, IRegionClientCapsService regionCaps) { //We need to send this update out to all the child agents this region has IGridService service = m_registry.RequestModuleInterface<IGridService>(); if (service != null) { ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>(); if (SimulationService != null) { //Set the last location in the database IAgentInfoService agentInfoService = m_registry.RequestModuleInterface<IAgentInfoService>(); if (agentInfoService != null) { //Find the lookAt vector Vector3 lookAt = new Vector3(agentpos.AtAxis.X, agentpos.AtAxis.Y, 0); if (lookAt != Vector3.Zero) lookAt = Util.GetNormalizedVector(lookAt); //Update the database agentInfoService.SetLastPosition(regionCaps.AgentID.ToString(), regionCaps.Region.RegionID, agentpos.Position, lookAt); } //Also update the service itself regionCaps.LastPosition = agentpos.Position; if (agentpos.UserGoingOffline) return; //It just needed a last pos update //Tell all neighbor regions about the new position as well List<GridRegion> ourNeighbors = GetRegions(regionCaps.ClientCaps); foreach (GridRegion region in ourNeighbors.Where(region => region != null && !SimulationService.UpdateAgent(region, agentpos))) { MainConsole.Instance.Info("[AgentProcessing]: Failed to inform " + region.RegionName + " about updating agent. "); } EnableChildAgentsForPosition(regionCaps, agentpos.Position); } } } private List<GridRegion> GetRegions(IClientCapsService iClientCapsService) { #if(!ISWIN) List<GridRegion> regions = new List<GridRegion>(); foreach(IRegionClientCapsService rcc in iClientCapsService.GetCapsServices()) regions.Add(rcc.Region); return regions; #else return iClientCapsService.GetCapsServices().Select(rccs => rccs.Region).ToList(); #endif } #endregion #region Login initial agent [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.None, UsePassword = true)] public virtual LoginAgentArgs LoginAgent(GridRegion region, AgentCircuitData aCircuit) { object retVal = base.DoRemoteByHTTP(_capsURL, region, aCircuit); if (retVal != null || m_doRemoteOnly) { if (retVal == null) { ReadRemoteCapsPassword(); retVal = base.DoRemoteByHTTP(_capsURL, region, aCircuit); } return retVal == null ? null : (LoginAgentArgs)retVal; } bool success = false; string seedCap = ""; string reason = "Could not find the simulation service"; ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>(); if (SimulationService != null) { // The client is in the region, we need to make sure it gets the right Caps // If CreateAgent is successful, it passes back a OSDMap of params that the client // wants to inform us about, and it includes the Caps SEED url for the region IRegionClientCapsService regionClientCaps = null; IClientCapsService clientCaps = null; if (capsService != null) { //Remove any previous users seedCap = capsService.CreateCAPS(aCircuit.AgentID, CapsUtil.GetCapsSeedPath(aCircuit.CapsPath), region.RegionHandle, true, aCircuit, 0); clientCaps = capsService.GetClientCapsService(aCircuit.AgentID); regionClientCaps = clientCaps.GetCapsService(region.RegionHandle); } ICommunicationService commsService = m_registry.RequestModuleInterface<ICommunicationService>(); if (commsService != null) commsService.GetUrlsForUser(region, aCircuit.AgentID); //Make sure that we make userURLs if we need to int requestedUDPPort = 0; // As we are creating the agent, we must also initialize the CapsService for the agent success = CreateAgent(region, regionClientCaps, ref aCircuit, SimulationService, ref requestedUDPPort, out reason); if (requestedUDPPort == 0) requestedUDPPort = region.ExternalEndPoint.Port; aCircuit.RegionUDPPort = requestedUDPPort; if (!success) // If it failed, do not set up any CapsService for the client { if (reason != "") { try { OSDMap reasonMap = OSDParser.DeserializeJson(reason) as OSDMap; if (reasonMap != null && reasonMap.ContainsKey("Reason")) reason = reasonMap["Reason"].AsString(); } catch { //If its already not JSON, it'll throw an exception, catch it } } //Delete the Caps! IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>(); if (agentProcessor != null && capsService != null) agentProcessor.LogoutAgent(regionClientCaps, true); else if (capsService != null) capsService.RemoveCAPS(aCircuit.AgentID); return new LoginAgentArgs { Success = success, CircuitData = aCircuit, Reason = reason, SeedCap = seedCap }; } IPAddress ipAddress = regionClientCaps.Region.ExternalEndPoint.Address; if (capsService != null && reason != "") { try { OSDMap responseMap = (OSDMap) OSDParser.DeserializeJson(reason); OSDMap SimSeedCaps = (OSDMap) responseMap["CapsUrls"]; if (responseMap.ContainsKey("OurIPForClient")) { string ip = responseMap["OurIPForClient"].AsString(); if (!IPAddress.TryParse(ip, out ipAddress)) #pragma warning disable 618 ipAddress = Dns.GetHostByName(ip).AddressList[0]; #pragma warning restore 618 } region.ExternalEndPoint.Address = ipAddress; //Fix this so that it gets sent to the client that way regionClientCaps.AddCAPS(SimSeedCaps); regionClientCaps = clientCaps.GetCapsService(region.RegionHandle); regionClientCaps.LoopbackRegionIP = ipAddress; regionClientCaps.CircuitData.RegionUDPPort = requestedUDPPort; regionClientCaps.RootAgent = true; } catch { //Delete the Caps! IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>(); if (agentProcessor != null && capsService != null) agentProcessor.LogoutAgent(regionClientCaps, true); else if (capsService != null) capsService.RemoveCAPS(aCircuit.AgentID); success = false; } } } return new LoginAgentArgs { Success = success, CircuitData = aCircuit, Reason = reason, SeedCap = seedCap }; } private bool CreateAgent(GridRegion region, IRegionClientCapsService regionCaps, ref AgentCircuitData aCircuit, ISimulationService SimulationService, ref int requestedUDPPort, out string reason) { CachedUserInfo info = new CachedUserInfo(); IAgentConnector con = Aurora.DataManager.DataManager.RequestPlugin<IAgentConnector>(); if (con != null) info.AgentInfo = con.GetAgent(aCircuit.AgentID); info.UserAccount = regionCaps.ClientCaps.AccountInfo; IGroupsServiceConnector groupsConn = Aurora.DataManager.DataManager.RequestPlugin<IGroupsServiceConnector>(); if (groupsConn != null) { info.ActiveGroup = groupsConn.GetGroupMembershipData(aCircuit.AgentID, UUID.Zero, aCircuit.AgentID); info.GroupMemberships = groupsConn.GetAgentGroupMemberships(aCircuit.AgentID, aCircuit.AgentID); } aCircuit.OtherInformation["CachedUserInfo"] = info.ToOSD(); return SimulationService.CreateAgent(region, aCircuit, aCircuit.teleportFlags, null, out requestedUDPPort, out reason); } #endregion #endregion } }
using Innovator.Client; using Innovator.Client.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Xml; namespace InnovatorAdmin { public class ArasMetadataProvider : IArasMetadataProvider { private IAsyncConnection _conn; private Dictionary<ItemProperty, ItemReference> _customProps = new Dictionary<ItemProperty, ItemReference>(); private Dictionary<string, ItemType> _itemTypesByName = new Dictionary<string, ItemType>(StringComparer.OrdinalIgnoreCase); private Dictionary<string, ItemType> _itemTypesById; private Task<bool[]> _metadataComplete; private IEnumerable<Method> _methods = Enumerable.Empty<Method>(); private IEnumerable<ItemReference> _polyItemLists = Enumerable.Empty<ItemReference>(); private IEnumerable<ItemReference> _sequences = Enumerable.Empty<ItemReference>(); private Dictionary<string, Sql> _sql; private Dictionary<string, ItemReference> _systemIdentities; private Dictionary<string, IEnumerable<ListValue>> _listValues = new Dictionary<string, IEnumerable<ListValue>>(); private Dictionary<string, IEnumerable<IListValue>> _serverReports = new Dictionary<string, IEnumerable<IListValue>>(); private readonly Dictionary<string, IEnumerable<IListValue>> _serverActions = new Dictionary<string, IEnumerable<IListValue>>(); private HashSet<string> _cmfGeneratedTypes = new HashSet<string>(); private Dictionary<string, ItemReference> _cmfLinkedTypes = new Dictionary<string, ItemReference>(); /// <summary> /// Enumerable of methods where core = 1 /// </summary> public IEnumerable<ItemReference> CoreMethods { get { return _methods.Where(m => m.IsCore); } } /// <summary> /// Enumerable of methods where core = 1 /// </summary> public IEnumerable<ItemReference> AllMethods { get { return _methods; } } /// <summary> /// Enumerable of all item types /// </summary> public IEnumerable<ItemType> ItemTypes { get { return _itemTypesByName.Values; } } /// <summary> /// Enumerable of all method names /// </summary> public IEnumerable<string> MethodNames { get { return _methods.Select(i => i.KeyedName); } } /// <summary> /// Enumerable of all lists that are auto-generated for a polyitem item type /// </summary> public IEnumerable<ItemReference> PolyItemLists { get { return _polyItemLists; } } /// <summary> /// Enumerable of all sequences /// </summary> public IEnumerable<ItemReference> Sequences { get { return _sequences; } } /// <summary> /// Enumerable of all system identities /// </summary> public IEnumerable<ItemReference> SystemIdentities { get { return _systemIdentities.Values; } } /// <summary> /// Hashset of all CMF-generated ItemType IDs /// </summary> public HashSet<string> CmfGeneratedTypes => _cmfGeneratedTypes; /// <summary> /// Dictionary of all ItemTypes linked from contentTypes /// </summary> public Dictionary<string, ItemReference> CmfLinkedTypes => _cmfLinkedTypes; /// <summary> /// Gets a reference to a system identity given the ID (if the ID matches a system identity; /// otherwise <c>null</c>) /// </summary> /// <param name="id">ID of the identity to check</param> /// <returns>An <see cref="ItemReference"/> if the ID matches a system identity; otherwise /// <c>null</c></returns> public ItemReference GetSystemIdentity(string id) { ItemReference result; if (!_systemIdentities.TryGetValue(id, out result)) result = null; return result; } /// <summary> /// Get an Item Type by ID /// </summary> public ItemType ItemTypeById(string id) { return _itemTypesById[id]; } /// <summary> /// Try to get an Item Type by ID /// </summary> public bool ItemTypeById(string id, out ItemType type) { return _itemTypesById.TryGetValue(id, out type); } /// <summary> /// Get an Item Type by name /// </summary> public ItemType ItemTypeByName(string name) { return _itemTypesByName[name]; } /// <summary> /// Try to get an Item Type by name /// </summary> public bool ItemTypeByName(string name, out ItemType type) { return _itemTypesByName.TryGetValue(name, out type); } /// <summary> /// Try to get a custom property by the Item Type and name information /// </summary> public bool CustomPropertyByPath(ItemProperty path, out ItemReference propRef) { return _customProps.TryGetValue(path, out propRef); } /// <summary> /// Try to get SQL information from a name /// </summary> public bool SqlRefByName(string name, out ItemReference sql) { Sql buffer; sql = null; if (_sql.TryGetValue(name, out buffer)) { sql = buffer; return true; } return false; } public IEnumerable<Sql> Sqls() { return _sql.Values; } public IPromise<IEnumerable<ListValue>> ListValues(string id) { IEnumerable<ListValue> result; if (_listValues.TryGetValue(id, out result)) return Promises.Resolved(result); return _conn.ApplyAsync("<Item type='List' action='get' id='@0' select='id'><Relationships><Item type='Value' action='get' select='label,value' /><Item type='Filter Value' action='get' select='label,value' /></Relationships></Item>" , true, false, id) .Convert(r => { var values = (IEnumerable<ListValue>)r.AssertItem().Relationships() .Select(i => new ListValue() { Label = i.Property("label").Value, Value = i.Property("value").Value }).ToArray(); _listValues[id] = values; return values; }); } public async Task<IEnumerable<string>> ItemTypeStates(ItemType itemtype) { if (itemtype.States != null) return itemtype.States; var result = await _conn.ApplyAsync(@"<Item type='ItemType Life Cycle' action='get' select='related_id'> <related_id> <Item type='Life Cycle Map' action='get' select='id'> <Relationships> <Item action='get' type='Life Cycle State' select='name'> </Item> </Relationships> </Item> </related_id> <source_id>@0</source_id> </Item>", true, false, itemtype.Id); var states = result.Items() .SelectMany(i => i.RelatedItem().Relationships().OfType<LifeCycleState>()) .Select(i => i.NameProp().Value).ToArray(); itemtype.States = states; return states; } public IEnumerable<IListValue> ServerReports(string typeName) { IEnumerable<IListValue> result; if (_serverReports.TryGetValue(typeName, out result)) return result; var items = _conn.Apply(@"<Item type='Item Report' action='get' select='related_id(name,label)'> <related_id> <Item type='Report' action='get'> <location>server</location> <type>item</type> </Item> </related_id> <source_id> <Item type='ItemType' action='get'> <name>@0</name> </Item> </source_id> </Item>", typeName).Items(); result = items.Select(r => new ListValue() { Label = r.RelatedItem().Property("label").Value, Value = r.RelatedItem().Property("name").Value }).ToArray(); _serverReports[typeName] = result; return result; } public IEnumerable<IListValue> ServerItemActions(string typeName) { IEnumerable<IListValue> result; if (_serverActions.TryGetValue(typeName, out result)) return result; var items = _conn.Apply(@"<Item type='Item Action' action='get' select='related_id(label,method(name))'> <related_id> <Item type='Action' action='get'> <location>server</location> <type>item</type> </Item> </related_id> <source_id> <Item type='ItemType' action='get'> <name>@0</name> </Item> </source_id> </Item>", typeName).Items(); result = items.Select(r => new ListValue() { Label = r.RelatedItem().Property("label").Value, Value = r.RelatedItem().Property("method").AsItem().Property("name").Value }).ToArray(); _serverActions[typeName] = result; return result; } /// <summary> /// Constructor for the ArasMetadataProvider class /// </summary> private ArasMetadataProvider(IAsyncConnection conn) { _conn = conn; Reset(); } /// <summary> /// Wait synchronously for the asynchronous data loads to complete /// </summary> public Task ReloadTask() { return _metadataComplete; } public IPromise ReloadPromise() { return _metadataComplete.ToPromise(); } /// <summary> /// Clear all the metadata and stard asynchronously reloading it. /// </summary> public void Reset() { if (_metadataComplete == null || _metadataComplete.IsCompleted) _metadataComplete = Task.WhenAll(ReloadItemTypeMetadata(), ReloadSecondaryMetadata()); } private async Task<bool> ReloadItemTypeMetadata() { var itemTypes = _conn.ApplyAsync("<Item type='ItemType' action='get' select='is_versionable,is_dependent,implementation_type,core,name,label'></Item>", true, true).ToTask(); var relTypes = _conn.ApplyAsync("<Item action='get' type='RelationshipType' related_expand='0' select='related_id,source_id,relationship_id,name,label' />", true, true).ToTask(); var sortedProperties = _conn.ApplyAsync(@"<Item type='Property' action='get' select='source_id'> <order_by condition='is not null'></order_by> </Item>", true, false).ToTask(); var floatProps = _conn.ApplyAsync(@"<Item type='Property' action='get' select='source_id,item_behavior,name' related_expand='0'> <data_type>item</data_type> <data_source> <Item type='ItemType' action='get'> <is_versionable>1</is_versionable> </Item> </data_source> <item_behavior>float</item_behavior> <name condition='not in'>'config_id','id'</name> </Item>", true, false).ToTask(); // Load in the item types var r = await itemTypes; ItemType result; foreach (var itemTypeData in r.Items()) { result = new ItemType() { Id = itemTypeData.Id(), IsCore = itemTypeData.Property("core").AsBoolean(false), IsDependent = itemTypeData.Property("is_dependent").AsBoolean(false), IsFederated = itemTypeData.Property("implementation_type").Value == "federated", IsPolymorphic = itemTypeData.Property("implementation_type").Value == "polymorphic", IsVersionable = itemTypeData.Property("is_versionable").AsBoolean(false), Label = itemTypeData.Property("label").Value, Name = itemTypeData.Property("name").Value, Reference = ItemReference.FromFullItem(itemTypeData, true) }; _itemTypesByName[result.Name] = result; } _itemTypesById = _itemTypesByName.Values.ToDictionary(i => i.Id); // Load in the relationship types r = await relTypes; ItemType relType; ItemType source; ItemType related; foreach (var rel in r.Items()) { if (rel.SourceId().Attribute("name").HasValue() && _itemTypesByName.TryGetValue(rel.SourceId().Attribute("name").Value, out source) && rel.Property("relationship_id").Attribute("name").HasValue() && _itemTypesByName.TryGetValue(rel.Property("relationship_id").Attribute("name").Value, out relType)) { source.Relationships.Add(relType); relType.Source = source; relType.TabLabel = rel.Property("label").AsString(null); if (rel.RelatedId().Attribute("name").HasValue() && _itemTypesByName.TryGetValue(rel.RelatedId().Attribute("name").Value, out related)) { relType.Related = related; } } } // Sorted Types r = await sortedProperties; foreach (var prop in r.Items()) { if (_itemTypesByName.TryGetValue(prop.SourceId().Attribute("name").Value, out result)) { result.IsSorted = true; } } // Float props r = await floatProps; foreach (var floatProp in r.Items()) { if (_itemTypesByName.TryGetValue(floatProp.SourceId().Attribute("name").Value.ToLowerInvariant(), out result)) { result.FloatProperties.Add(floatProp.Property("name").AsString("")); } } return true; } private async Task<bool> ReloadSecondaryMetadata() { var methods = _conn.ApplyAsync("<Item type='Method' action='get' select='config_id,core,name'></Item>", true, false).ToTask(); var sysIdents = _conn.ApplyAsync(@"<Item type='Identity' action='get' select='id,name'> <name condition='in'>'World', 'Creator', 'Owner', 'Manager', 'Innovator Admin', 'Super User'</name> </Item>", true, true).ToTask(); var sqls = _conn.ApplyAsync("<Item type='SQL' action='get' select='id,name,type'></Item>", true, false).ToTask(); var customProps = _conn.ApplyAsync(@"<Item type='Property' action='get' select='name,source_id(id,name)'> <created_by_id condition='ne'>AD30A6D8D3B642F5A2AFED1A4B02BEFA</created_by_id> <source_id> <Item type='ItemType' action='get'> <core>1</core> <created_by_id>AD30A6D8D3B642F5A2AFED1A4B02BEFA</created_by_id> </Item> </source_id> </Item>", true, false).ToTask(); var polyLists = _conn.ApplyAsync(@"<Item type='Property' action='get' select='data_source(id)'> <name>itemtype</name> <data_type>list</data_type> <source_id> <Item type='ItemType' action='get'> <implementation_type>polymorphic</implementation_type> </Item> </source_id> </Item>", true, false).ToTask(); var sequences = _conn.ApplyAsync(@"<Item type='Sequence' action='get' select='name'></Item>", true, false).ToTask(); var elementTypes = _conn.ApplyAsync(@"<Item action='get' type='cmf_ElementType' select='generated_type'> <Relationships> <Item action='get' type='cmf_PropertyType' select='generated_type'> </Item> </Relationships> </Item>", true, false).ToTask(); var contentTypes = _conn.ApplyAsync(@"<Item action='get' type='cmf_ContentType' select='linked_item_type'> <linked_item_type> <Item type='ItemType' action='get'> </Item> </linked_item_type> </Item>", true, false).ToTask(); _methods = (await methods).Items().Select(i => { var method = Method.FromFullItem(i, false); method.KeyedName = i.Property("name").AsString(""); method.IsCore = i.Property("core").AsBoolean(false); return method; }).ToArray(); _systemIdentities = (await sysIdents).Items() .Select(i => { var itemRef = ItemReference.FromFullItem(i, false); itemRef.KeyedName = i.Property("name").AsString(""); return itemRef; }).ToDictionary(i => i.Unique); _sql = (await sqls).Items() .Select(i => { var itemRef = Sql.FromFullItem(i, false); itemRef.KeyedName = i.Property("name").AsString(""); itemRef.Type = i.Property("type").AsString(""); return itemRef; }).ToDictionary(i => i.KeyedName.ToLowerInvariant(), StringComparer.OrdinalIgnoreCase); var r = (await customProps); IReadOnlyItem itemType; foreach (var customProp in r.Items()) { itemType = customProp.SourceItem(); _customProps[new ItemProperty() { ItemType = itemType.Property("name").Value, ItemTypeId = itemType.Id(), Property = customProp.Property("name").Value, PropertyId = customProp.Id() }] = new ItemReference("Property", customProp.Id()) { KeyedName = customProp.Property("name").Value }; } _polyItemLists = (await polyLists).Items() .OfType<Innovator.Client.Model.Property>() .Select(i => new ItemReference("List", i.DataSource().Value) { KeyedName = i.DataSource().KeyedName().Value }).ToArray(); _sequences = (await sequences).Items().Select(i => ItemReference.FromFullItem(i, true)).ToArray(); try { _cmfGeneratedTypes = new HashSet<string>((await elementTypes).Items().SelectMany(x => { var relations = x.Relationships().Select(y => y.Property("generated_type").Value).ToList(); relations.Add(x.Property("generated_type").Value); return relations; })); _cmfLinkedTypes = (await contentTypes).Items().ToDictionary(x => x.Property("linked_item_type").Value, y => ItemReference.FromFullItem(y, true)); } catch (ServerException) { //TODO: Do something when cmf types don't exist } return true; } public IPromise<IEnumerable<Property>> GetPropertiesByTypeId(string id) { ItemType itemType; if (!_itemTypesById.TryGetValue(id, out itemType)) return Promises.Rejected<IEnumerable<Property>>(new KeyNotFoundException()); return GetProperties(itemType); } public IPromise<IEnumerable<string>> GetClassPaths(ItemType itemType) { if (_conn == null || itemType.ClassPaths != null) return Promises.Resolved(itemType.ClassPaths); return _conn.ApplyAsync("<AML><Item action=\"get\" type=\"ItemType\" id=\"@0\" select='class_structure'></Item></AML>" , true, true, itemType.Id) .Convert(r => { var structure = r.AssertItem().Property("class_structure").Value; if (string.IsNullOrEmpty(structure)) { itemType.ClassPaths = Enumerable.Empty<string>(); } else { try { itemType.ClassPaths = ParseClassStructure(new System.IO.StringReader(structure)).ToArray(); } catch (XmlException) { itemType.ClassPaths = Enumerable.Empty<string>(); } } return itemType.ClassPaths; }); } private IEnumerable<string> ParseClassStructure(System.IO.TextReader structure) { var path = new List<string>(); var returned = 0; using (var reader = XmlReader.Create(structure)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "class") { if (reader.IsEmptyElement) { returned = path.Count; yield return path.Concat(Enumerable.Repeat(reader.GetAttribute("name"), 1)).GroupConcat("/"); } else { var name = reader.GetAttribute("name"); if (!string.IsNullOrEmpty(name)) path.Add(name); } } else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "class") { if (returned < path.Count) yield return path.GroupConcat("/"); if (path.Count > 0) path.RemoveAt(path.Count - 1); returned = path.Count; } } } } /// <summary> /// Gets a promise to return information about all properties of a given Item Type /// </summary> public IPromise<IEnumerable<Property>> GetProperties(ItemType itemType) { if (_conn == null || itemType.Properties.Count > 0) return Promises.Resolved<IEnumerable<Property>>(itemType.Properties.Values); var xPropQuery = default(string); if (_itemTypesById.ContainsKey("A253DB1415194344AEFB5E6A2029AB3A")) { xPropQuery = @"<Item type='ItemType_xPropertyDefinition' action='get' select='related_id(name,label,data_type,data_source,stored_length,prec,scale,default_value,column_width,is_required,readonly)'></Item>"; } var aml = $@"<AML> <Item action='get' type='ItemType' select='name'> <name>@0</name> <Relationships> <Item action='get' type='Property' select='name,label,data_type,data_source,stored_length,prec,scale,foreign_property(name,source_id),is_hidden,is_hidden2,sort_order,default_value,column_width,is_required,readonly' /> {xPropQuery} </Relationships> </Item> </AML>"; var promise = _conn.ApplyAsync(aml, true, true, itemType.Name) .Convert(r => { LoadProperties(itemType, r.AssertItem()); return (IEnumerable<Property>)itemType.Properties.Values; }).Fail(ex => System.Diagnostics.Debug.Print("PROPLOAD: " + ex.ToString())); if (!string.IsNullOrEmpty(xPropQuery)) { promise = promise.Continue(p => { return _conn.ApplyAsync(@"<Item type='xClassificationTree' action='get' select='id'> <Relationships> <Item type='xClassificationTree_ItemType' action='get' select='id'> <related_id>@0</related_id> </Item> <Item action='get' type='xClass' select='id'> <Relationships> <Item action='get' type='xClass_xPropertyDefinition' select='related_id(name,label,data_type,data_source,stored_length,prec,scale,default_value,column_width,is_required,readonly)'> <is_current>1</is_current> </Item> </Relationships> </Item> </Relationships> </Item>", true, false, itemType.Id); }).Convert(r => { foreach (var prop in r.Items() .SelectMany(i => i.Relationships("xClass")) .SelectMany(i => i.Relationships("xClass_xPropertyDefinition")) .Select(i => i.RelatedItem())) { var newProp = Property.FromItem(prop, itemType); itemType.Properties[newProp.Name] = newProp; } return (IEnumerable<Property>)itemType.Properties.Values; }).Fail(ex => System.Diagnostics.Debug.Print("PROPLOAD: " + ex.ToString())); } return promise; } /// <summary> /// Gets a promise to return information about property of a given Item Type and name /// </summary> public IPromise<Property> GetProperty(ItemType itemType, string name) { if (_conn == null || itemType.Properties.Count > 0) return LoadedProperty(itemType, name); return GetProperties(itemType) .Continue(r => { return LoadedProperty(itemType, name); }); } private IPromise<Property> LoadedProperty(ItemType itemType, string name) { Property prop; if (itemType.Properties.TryGetValue(name, out prop)) { return Promises.Resolved(prop); } else { return Promises.Rejected<Property>(new KeyNotFoundException()); } } /// <summary> /// Loads the property metadata for the current type into the schema. /// </summary> /// <param name="type">The type.</param> /// <param name="itemTypeMeta">The properties.</param> private void LoadProperties(ItemType type, IReadOnlyItem itemTypeMeta) { var props = itemTypeMeta.Relationships("Property") .Concat(itemTypeMeta.Relationships("ItemType_xPropertyDefinition").Select(i => i.RelatedItem())); foreach (var prop in props) { var newProp = Property.FromItem(prop, type); type.Properties[newProp.Name] = newProp; } } private static Dictionary<string, ArasMetadataProvider> _cache = new Dictionary<string, ArasMetadataProvider>(); /// <summary> /// Return a cached metadata object for a given connection /// </summary> public static ArasMetadataProvider Cached(IAsyncConnection conn) { ArasMetadataProvider result; var key = conn.Database + "|" + conn.UserId; var remote = conn as IRemoteConnection; if (remote != null) key += "|" + remote.Url; if (!_cache.TryGetValue(key, out result) || string.IsNullOrEmpty(result._conn.UserId)) { result = new ArasMetadataProvider(conn); _cache[key] = result; } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ServerAsyncAuthenticateTest { private readonly ITestOutputHelper _log; private readonly X509Certificate2 _serverCertificate; public ServerAsyncAuthenticateTest() { _log = TestLogging.GetInstance(); _serverCertificate = TestConfiguration.GetServerCertificate(); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ServerAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol) { await ServerAsyncSslHelper(protocol, protocol); } [Theory] [ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))] public async Task ServerAsyncAuthenticate_EachServerUnsupportedProtocol_Fail(SslProtocols protocol) { await Assert.ThrowsAsync<NotSupportedException>(() => { return ServerAsyncSslHelper( SslProtocolSupport.SupportedSslProtocols, protocol, expectedToFail: true); }); } [Theory] [MemberData(nameof(ProtocolMismatchData))] public async Task ServerAsyncAuthenticate_MismatchProtocols_Fails( SslProtocols serverProtocol, SslProtocols clientProtocol, Type expectedException) { await Assert.ThrowsAsync( expectedException, () => { return ServerAsyncSslHelper( serverProtocol, clientProtocol, expectedToFail: true); }); } [Fact] public async Task ServerAsyncAuthenticate_UnsuportedAllServer_Fail() { await Assert.ThrowsAsync<NotSupportedException>(() => { return ServerAsyncSslHelper( SslProtocolSupport.SupportedSslProtocols, SslProtocolSupport.UnsupportedSslProtocols, expectedToFail: true); }); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ServerAsyncAuthenticate_AllClientVsIndividualServerSupportedProtocols_Success( SslProtocols serverProtocol) { await ServerAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol); } private static IEnumerable<object[]> ProtocolMismatchData() { yield return new object[] { SslProtocols.Tls, SslProtocols.Tls11, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls, typeof(TimeoutException) }; yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls12, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls, typeof(TimeoutException) }; yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls11, typeof(TimeoutException) }; } #region Helpers private async Task ServerAsyncSslHelper( SslProtocols clientSslProtocols, SslProtocols serverSslProtocols, bool expectedToFail = false) { _log.WriteLine( "Server: " + serverSslProtocols + "; Client: " + clientSslProtocols + " expectedToFail: " + expectedToFail); int timeOut = expectedToFail ? TestConfiguration.FailingTestTimeoutMiliseconds : TestConfiguration.PassingTestTimeoutMilliseconds; IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0); var server = new TcpListener(endPoint); server.Start(); using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6)) { IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint; Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port); Task<TcpClient> serverAccept = server.AcceptTcpClientAsync(); // We expect that the network-level connect will always complete. Task.WaitAll( new Task[] { clientConnect, serverAccept }, TestConfiguration.PassingTestTimeoutMilliseconds); using (TcpClient serverConnection = await serverAccept) using (SslStream sslClientStream = new SslStream(clientConnection.GetStream())) using (SslStream sslServerStream = new SslStream( serverConnection.GetStream(), false, AllowAnyServerCertificate)) { string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false); Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync( serverName, null, clientSslProtocols, false); Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync( _serverCertificate, true, serverSslProtocols, false); try { clientAuthentication.Wait(timeOut); } catch (AggregateException ex) { // Ignore client-side errors: we're only interested in server-side behavior. _log.WriteLine("Client exception: " + ex.InnerException); } bool serverAuthenticationCompleted = false; try { serverAuthenticationCompleted = serverAuthentication.Wait(timeOut); } catch (AggregateException ex) { throw ex.InnerException; } if (!serverAuthenticationCompleted) { throw new TimeoutException(); } _log.WriteLine( "Server({0}) authenticated with encryption cipher: {1} {2}-bit strength", serverEndPoint, sslServerStream.CipherAlgorithm, sslServerStream.CipherStrength); Assert.True( sslServerStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(sslServerStream.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } // The following method is invoked by the RemoteCertificateValidationDelegate. private bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Assert.True( (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable, "Client didn't supply a cert, the server required one, yet sslPolicyErrors is " + sslPolicyErrors); return true; // allow everything } #endregion Helpers } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Avalonia.Controls.Generators; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Layout; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Controls.UnitTests.Presenters { public class ItemsPresenterTests_Virtualization { [Fact] public void Should_Return_IsLogicalScrollEnabled_False_When_Has_No_Virtualizing_Panel() { var target = CreateTarget(); target.ClearValue(ItemsPresenter.ItemsPanelProperty); target.ApplyTemplate(); Assert.False(((ILogicalScrollable)target).IsLogicalScrollEnabled); } [Fact] public void Should_Return_IsLogicalScrollEnabled_False_When_VirtualizationMode_None() { var target = CreateTarget(ItemVirtualizationMode.None); target.ApplyTemplate(); Assert.False(((ILogicalScrollable)target).IsLogicalScrollEnabled); } [Fact] public void Should_Return_IsLogicalScrollEnabled_False_When_Doesnt_Have_ScrollPresenter_Parent() { var target = new ItemsPresenter { ItemsPanel = VirtualizingPanelTemplate(), ItemTemplate = ItemTemplate(), VirtualizationMode = ItemVirtualizationMode.Simple, }; target.ApplyTemplate(); Assert.False(((ILogicalScrollable)target).IsLogicalScrollEnabled); } [Fact] public void Should_Return_IsLogicalScrollEnabled_True() { var target = CreateTarget(); target.ApplyTemplate(); Assert.True(((ILogicalScrollable)target).IsLogicalScrollEnabled); } [Fact] public void Parent_ScrollContentPresenter_Properties_Should_Be_Set() { var target = CreateTarget(); target.ApplyTemplate(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); var scroll = (ScrollContentPresenter)target.Parent; Assert.Equal(new Size(0, 20), scroll.Extent); Assert.Equal(new Size(0, 10), scroll.Viewport); } [Fact] public void Should_Fill_Panel_With_Containers() { var target = CreateTarget(); target.ApplyTemplate(); target.Measure(new Size(100, 100)); Assert.Equal(10, target.Panel.Children.Count); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(10, target.Panel.Children.Count); } [Fact] public void Should_Only_Create_Enough_Containers_To_Display_All_Items() { var target = CreateTarget(itemCount: 2); target.ApplyTemplate(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(2, target.Panel.Children.Count); } [Fact] public void Should_Expand_To_Fit_Containers_When_Flexible_Size() { var target = CreateTarget(); target.ApplyTemplate(); target.Measure(Size.Infinity); target.Arrange(new Rect(target.DesiredSize)); Assert.Equal(new Size(10, 200), target.DesiredSize); Assert.Equal(new Size(10, 200), target.Bounds.Size); Assert.Equal(20, target.Panel.Children.Count); } [Fact] public void Initial_Item_DataContexts_Should_Be_Correct() { var target = CreateTarget(); var items = (IList<string>)target.Items; target.ApplyTemplate(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); for (var i = 0; i < target.Panel.Children.Count; ++i) { Assert.Equal(items[i], target.Panel.Children[i].DataContext); } } [Fact] public void Should_Add_New_Items_When_Control_Is_Enlarged() { var target = CreateTarget(); var items = (IList<string>)target.Items; target.ApplyTemplate(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(10, target.Panel.Children.Count); target.Measure(new Size(120, 120)); target.Arrange(new Rect(0, 0, 100, 120)); Assert.Equal(12, target.Panel.Children.Count); for (var i = 0; i < target.Panel.Children.Count; ++i) { Assert.Equal(items[i], target.Panel.Children[i].DataContext); } } [Fact] public void Changing_VirtualizationMode_None_To_Simple_Should_Update_Control() { var target = CreateTarget(mode: ItemVirtualizationMode.None); var scroll = (ScrollContentPresenter)target.Parent; scroll.Measure(new Size(100, 100)); scroll.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(20, target.Panel.Children.Count); Assert.Equal(new Size(10, 200), scroll.Extent); Assert.Equal(new Size(100, 100), scroll.Viewport); target.VirtualizationMode = ItemVirtualizationMode.Simple; target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(10, target.Panel.Children.Count); Assert.Equal(new Size(0, 20), scroll.Extent); Assert.Equal(new Size(0, 10), scroll.Viewport); } [Fact] public void Changing_VirtualizationMode_None_To_Simple_Should_Add_Correct_Number_Of_Controls() { using (UnitTestApplication.Start(TestServices.RealLayoutManager)) { var target = CreateTarget(mode: ItemVirtualizationMode.None); var scroll = (ScrollContentPresenter)target.Parent; scroll.Measure(new Size(100, 100)); scroll.Arrange(new Rect(0, 0, 100, 100)); // Ensure than an intermediate measure pass doesn't add more controls than it // should. This can happen if target gets measured with Size.Infinity which // is what the available size should be when VirtualizationMode == None but not // what it should after VirtualizationMode is changed to Simple. target.Panel.Children.CollectionChanged += (s, e) => { Assert.InRange(target.Panel.Children.Count, 0, 10); }; target.VirtualizationMode = ItemVirtualizationMode.Simple; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Equal(10, target.Panel.Children.Count); } } [Fact] public void Changing_VirtualizationMode_Simple_To_None_Should_Update_Control() { var target = CreateTarget(); var scroll = (ScrollContentPresenter)target.Parent; scroll.Measure(new Size(100, 100)); scroll.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(10, target.Panel.Children.Count); Assert.Equal(new Size(0, 20), scroll.Extent); Assert.Equal(new Size(0, 10), scroll.Viewport); target.VirtualizationMode = ItemVirtualizationMode.None; target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); // Here - unlike changing the other way - we need to do a layout pass on the scroll // content presenter as non-logical scroll values are only updated on arrange. scroll.Measure(new Size(100, 100)); scroll.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(20, target.Panel.Children.Count); Assert.Equal(new Size(10, 200), scroll.Extent); Assert.Equal(new Size(100, 100), scroll.Viewport); } private static ItemsPresenter CreateTarget( ItemVirtualizationMode mode = ItemVirtualizationMode.Simple, Orientation orientation = Orientation.Vertical, bool useContainers = true, int itemCount = 20) { ItemsPresenter result; var items = Enumerable.Range(0, itemCount).Select(x => $"Item {x}").ToList(); var scroller = new ScrollContentPresenter { Content = result = new TestItemsPresenter(useContainers) { Items = items, ItemsPanel = VirtualizingPanelTemplate(orientation), ItemTemplate = ItemTemplate(), VirtualizationMode = mode, } }; scroller.UpdateChild(); return result; } private static IDataTemplate ItemTemplate() { return new FuncDataTemplate<string>(x => new Canvas { Width = 10, Height = 10, }); } private static ITemplate<IPanel> VirtualizingPanelTemplate( Orientation orientation = Orientation.Vertical) { return new FuncTemplate<IPanel>(() => new VirtualizingStackPanel { Orientation = orientation, }); } private class TestItemsPresenter : ItemsPresenter { private bool _useContainers; public TestItemsPresenter(bool useContainers) { _useContainers = useContainers; } protected override IItemContainerGenerator CreateItemContainerGenerator() { return _useContainers ? new ItemContainerGenerator<TestContainer>(this, TestContainer.ContentProperty, null) : new ItemContainerGenerator(this); } } private class TestContainer : ContentControl { public TestContainer() { Width = 10; Height = 10; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: crm/guests/guest_cancelled_reservation.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 HOLMS.Types.CRM.Guests { /// <summary>Holder for reflection information generated from crm/guests/guest_cancelled_reservation.proto</summary> public static partial class GuestCancelledReservationReflection { #region Descriptor /// <summary>File descriptor for crm/guests/guest_cancelled_reservation.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GuestCancelledReservationReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cixjcm0vZ3Vlc3RzL2d1ZXN0X2NhbmNlbGxlZF9yZXNlcnZhdGlvbi5wcm90", "bxIWaG9sbXMudHlwZXMuY3JtLmd1ZXN0cxouYm9va2luZy9pbmRpY2F0b3Jz", "L3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90bxogY3JtL2d1ZXN0cy9ndWVz", "dF9pbmRpY2F0b3IucHJvdG8i4wEKGUd1ZXN0Q2FuY2VsbGVkUmVzZXJ2YXRp", "b24SFwoPcGVuYWx0eV9hcHBsaWVkGAEgASgIEiUKHWRheXNfYmVmb3JlX3Jl", "c2VydmF0aW9uX3N0YXJ0GAIgASgFEkwKDnJlc2VydmF0aW9uX2lkGAMgASgL", "MjQuaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0aW9u", "SW5kaWNhdG9yEjgKCGd1ZXN0X2lkGAQgASgLMiYuaG9sbXMudHlwZXMuY3Jt", "Lmd1ZXN0cy5HdWVzdEluZGljYXRvckIlWgpjcm0vZ3Vlc3RzqgIWSE9MTVMu", "VHlwZXMuQ1JNLkd1ZXN0c2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.CRM.Guests.GuestIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.CRM.Guests.GuestCancelledReservation), global::HOLMS.Types.CRM.Guests.GuestCancelledReservation.Parser, new[]{ "PenaltyApplied", "DaysBeforeReservationStart", "ReservationId", "GuestId" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GuestCancelledReservation : pb::IMessage<GuestCancelledReservation> { private static readonly pb::MessageParser<GuestCancelledReservation> _parser = new pb::MessageParser<GuestCancelledReservation>(() => new GuestCancelledReservation()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GuestCancelledReservation> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.CRM.Guests.GuestCancelledReservationReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GuestCancelledReservation() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GuestCancelledReservation(GuestCancelledReservation other) : this() { penaltyApplied_ = other.penaltyApplied_; daysBeforeReservationStart_ = other.daysBeforeReservationStart_; ReservationId = other.reservationId_ != null ? other.ReservationId.Clone() : null; GuestId = other.guestId_ != null ? other.GuestId.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GuestCancelledReservation Clone() { return new GuestCancelledReservation(this); } /// <summary>Field number for the "penalty_applied" field.</summary> public const int PenaltyAppliedFieldNumber = 1; private bool penaltyApplied_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool PenaltyApplied { get { return penaltyApplied_; } set { penaltyApplied_ = value; } } /// <summary>Field number for the "days_before_reservation_start" field.</summary> public const int DaysBeforeReservationStartFieldNumber = 2; private int daysBeforeReservationStart_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int DaysBeforeReservationStart { get { return daysBeforeReservationStart_; } set { daysBeforeReservationStart_ = value; } } /// <summary>Field number for the "reservation_id" field.</summary> public const int ReservationIdFieldNumber = 3; private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservationId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.ReservationIndicator ReservationId { get { return reservationId_; } set { reservationId_ = value; } } /// <summary>Field number for the "guest_id" field.</summary> public const int GuestIdFieldNumber = 4; private global::HOLMS.Types.CRM.Guests.GuestIndicator guestId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.CRM.Guests.GuestIndicator GuestId { get { return guestId_; } set { guestId_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GuestCancelledReservation); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GuestCancelledReservation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (PenaltyApplied != other.PenaltyApplied) return false; if (DaysBeforeReservationStart != other.DaysBeforeReservationStart) return false; if (!object.Equals(ReservationId, other.ReservationId)) return false; if (!object.Equals(GuestId, other.GuestId)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (PenaltyApplied != false) hash ^= PenaltyApplied.GetHashCode(); if (DaysBeforeReservationStart != 0) hash ^= DaysBeforeReservationStart.GetHashCode(); if (reservationId_ != null) hash ^= ReservationId.GetHashCode(); if (guestId_ != null) hash ^= GuestId.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 (PenaltyApplied != false) { output.WriteRawTag(8); output.WriteBool(PenaltyApplied); } if (DaysBeforeReservationStart != 0) { output.WriteRawTag(16); output.WriteInt32(DaysBeforeReservationStart); } if (reservationId_ != null) { output.WriteRawTag(26); output.WriteMessage(ReservationId); } if (guestId_ != null) { output.WriteRawTag(34); output.WriteMessage(GuestId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (PenaltyApplied != false) { size += 1 + 1; } if (DaysBeforeReservationStart != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(DaysBeforeReservationStart); } if (reservationId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReservationId); } if (guestId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GuestId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GuestCancelledReservation other) { if (other == null) { return; } if (other.PenaltyApplied != false) { PenaltyApplied = other.PenaltyApplied; } if (other.DaysBeforeReservationStart != 0) { DaysBeforeReservationStart = other.DaysBeforeReservationStart; } if (other.reservationId_ != null) { if (reservationId_ == null) { reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } ReservationId.MergeFrom(other.ReservationId); } if (other.guestId_ != null) { if (guestId_ == null) { guestId_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator(); } GuestId.MergeFrom(other.GuestId); } } [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: { PenaltyApplied = input.ReadBool(); break; } case 16: { DaysBeforeReservationStart = input.ReadInt32(); break; } case 26: { if (reservationId_ == null) { reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } input.ReadMessage(reservationId_); break; } case 34: { if (guestId_ == null) { guestId_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator(); } input.ReadMessage(guestId_); break; } } } } } #endregion } #endregion Designer generated code
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.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. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Core { using System; using System.Xml; using System.Collections; using System.Collections.Generic; using Util; using Widgets; using Mono.Unix; using Basics; public class SaverTask : MesurableTask, IBoilProvider { // Translatable //////////////////////////////////////////////// readonly static string savingSS = Catalog.GetString ("Saving project"); // Enums /////////////////////////////////////////////////////// enum Step { StartXml, ProjectDetails, Deps, Boiling, Xmlize, Flush, Finished }; // Fields ////////////////////////////////////////////////////// static readonly string minVersion = "0.0.1"; // XML output backward compatibility string fileName; // Filename where we're saving XmlDocument xmlDocument; // Document we're creating XmlElement xmlRootElement; // Our root element XmlElement xmlProjectInfoElement; // Our info element ObjectListContainer objectList; // The container with the object list Project project; // The project we're saving int currentId; // Current ref id Dictionary <object, int> objectToId; // Object -> id Dictionary <int, object> idToObject; // id -> object Dictionary <object, string> objectToString; // Object -> canonical root name // Properties ////////////////////////////////////////////////// public override string Message { get { return savingSS; } } public override bool SuggestProgressBar { get { return true; } } public override bool SuggestCursor { get { return true; } } // Public methods ////////////////////////////////////////////// /* CONSTRUCTOR */ public SaverTask (Project project) { this.fileName = project.FileName; this.project = project; maxSteps = 6; } public override void Reset () { xmlDocument = new XmlDocument (); objectToId = new Dictionary <object, int> (); idToObject = new Dictionary <int, object> (); objectToString = new Dictionary <object, string> (); currentId = 1; base.Reset (); } /* IBoilProvider */ public int GetIdForObject (object o) { return objectToId [o]; } /* IBoilProvider */ public object GetObjectForId (int id) { return idToObject [id]; } /* IBoilProvider */ public bool Contains (int id) { return idToObject.ContainsKey (id); } // Private methods ///////////////////////////////////////////// protected override TaskStatus ExecuteStep (int s) { switch ((Step) s) { case Step.StartXml: CreateXmlDeclaration (); xmlRootElement = CreateRootElement (); xmlProjectInfoElement = CreateProjectInfoElement (); break; case Step.ProjectDetails: //xmlProjectInfoElement = CreateProjectInfoElement (); break; case Step.Deps: DepDownObject (project.Tracks, "tracklist"); DepDownObject (project.Tags, "taglist"); DepDownObject (project.Commander, "commander"); DepDownObject (project.Pipeline, "pipeline"); DepDownObject (project.Stuff, "stufflist"); DepDownObject (project.Clips, "cliplist"); DepDownObject (project.MediaItems, "mediaitemlist"); DepDownObject (project.Format, "projectformat"); break; case Step.Boiling: objectList = new ObjectListContainer ("objectlist"); IEnumerator objectEnumerator; objectEnumerator = GetObjectsEnumerator (); while (objectEnumerator.MoveNext ()) { object currentObject = objectEnumerator.Current; int refId = GetIdForObject (currentObject); string currentName = (objectToString.ContainsKey (currentObject)) ? objectToString [currentObject] : String.Format ("object_{0}", refId); ObjectContainer container = Basics.BoilFactory.Boil (currentName, currentObject, this); container.RefId = refId; objectList.Add (container); } break; case Step.Xmlize: xmlRootElement.AppendChild (xmlProjectInfoElement); xmlRootElement.AppendChild (objectList.ToXmlElement (xmlDocument)); break; case Step.Flush: xmlDocument.Save (fileName); break; case Step.Finished: return TaskStatus.Done; default: break; } return TaskStatus.Running; } void CreateXmlDeclaration () { XmlNode xmlNode = xmlDocument.CreateNode (XmlNodeType.XmlDeclaration, "", ""); xmlDocument.AppendChild (xmlNode); } XmlElement CreateRootElement () { XmlElement element = xmlDocument.CreateElement ("divaproject"); // Minimal version needed to open the file element.SetAttribute ("minversion", minVersion); // Software version element.SetAttribute ("version", VersionFu.GetCallingVersion ()); // Time this project was saved element.SetAttribute ("timestamp", DateTime.Now.ToFileTime ().ToString ()); xmlDocument.AppendChild (element); return element; } XmlElement CreateProjectInfoElement () { // Main XmlElement projectInfoElement = xmlDocument.CreateElement ("projectinfo"); // Name XmlElement nameElement = xmlDocument.CreateElement ("name"); XmlNode nameNode = xmlDocument.CreateTextNode (project.Name); nameElement.AppendChild (nameNode); // Directory XmlElement directoryElement = xmlDocument.CreateElement ("directory"); XmlNode directoryNode = xmlDocument.CreateTextNode (project.Directory); directoryElement.AppendChild (directoryNode); // Length XmlElement lengthElement = xmlDocument.CreateElement ("length"); XmlNode lengthNode = xmlDocument.CreateTextNode (TimeFu.ToShortString (project.Clips.GetMaximumOutPoint ())); lengthElement.AppendChild (lengthNode); projectInfoElement.AppendChild (nameElement); projectInfoElement.AppendChild (directoryElement); projectInfoElement.AppendChild (lengthElement); return projectInfoElement; } /* XmlElement CreateRootObjectsElement () { XmlElement element = xmlDocument.CreateElement ("root"); xmlObjectsElement.AppendChild (element); element.AppendChild (XmlFu.CreateElementRef (xmlDocument, "taglist", boilerStore.GetIdForObject (project.Tags))); element.AppendChild (XmlFu.CreateElementRef (xmlDocument, "stufflist", boilerStore.GetIdForObject (project.Stuff))); element.AppendChild (XmlFu.CreateElementRef (xmlDocument, "commander", boilerStore.GetIdForObject (project.Commander))); element.AppendChild (XmlFu.CreateElementRef (xmlDocument, "pipeline", boilerStore.GetIdForObject (project.Pipeline))); element.AppendChild (XmlFu.CreateElementRef (xmlDocument, "tracklist", boilerStore.GetIdForObject (project.Tracks))); element.AppendChild (XmlFu.CreateElementRef (xmlDocument, "mediaitemlist", boilerStore.GetIdForObject (project.MediaItems))); return element; }*/ /* Get the dependent objects. Recursive */ void DepDownObject (object obj) { // Put ourselves here if (! PutInTable (obj)) return; // Put references List <object> list = Basics.BoilFactory.GetDepObjects (obj); foreach (object o in list) DepDownObject (o); } /* As above, but with a name */ void DepDownObject (object obj, string objectName) { DepDownObject (obj); objectToString [obj] = objectName; } IEnumerator GetObjectsEnumerator () { return idToObject.Values.GetEnumerator (); } bool PutInTable (object o) { // Do nothing if we already have this object if (objectToId.ContainsKey (o)) return false; // Assign it an id objectToId [o] = currentId; idToObject [currentId] = o; currentId++; return true; } } }
#region License /* Copyright (c) 2005 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.ComponentModel; using System.Diagnostics; namespace Sanford.Multimedia.Midi { #region Channel Command Types /// <summary> /// Defines constants for ChannelMessage types. /// </summary> public enum ChannelCommand { /// <summary> /// Represents the note-off command type. /// </summary> NoteOff = 0x80, /// <summary> /// Represents the note-on command type. /// </summary> NoteOn = 0x90, /// <summary> /// Represents the poly pressure (aftertouch) command type. /// </summary> PolyPressure = 0xA0, /// <summary> /// Represents the controller command type. /// </summary> Controller = 0xB0, /// <summary> /// Represents the program change command type. /// </summary> ProgramChange = 0xC0, /// <summary> /// Represents the channel pressure (aftertouch) command /// type. /// </summary> ChannelPressure = 0xD0, /// <summary> /// Represents the pitch wheel command type. /// </summary> PitchWheel = 0xE0 } #endregion #region Controller Types /// <summary> /// Defines constants for controller types. /// </summary> public enum ControllerType { /// <summary> /// The Bank Select coarse. /// </summary> BankSelect, /// <summary> /// The Modulation Wheel coarse. /// </summary> ModulationWheel, /// <summary> /// The Breath Control coarse. /// </summary> BreathControl, /// <summary> /// The Foot Pedal coarse. /// </summary> FootPedal = 4, /// <summary> /// The Portamento Time coarse. /// </summary> PortamentoTime, /// <summary> /// The Data Entry Slider coarse. /// </summary> DataEntrySlider, /// <summary> /// The Volume coarse. /// </summary> Volume, /// <summary> /// The Balance coarse. /// </summary> Balance, /// <summary> /// The Pan position coarse. /// </summary> Pan = 10, /// <summary> /// The Expression coarse. /// </summary> Expression, /// <summary> /// The Effect Control 1 coarse. /// </summary> EffectControl1, /// <summary> /// The Effect Control 2 coarse. /// </summary> EffectControl2, /// <summary> /// The General Puprose Slider 1 /// </summary> GeneralPurposeSlider1 = 16, /// <summary> /// The General Puprose Slider 2 /// </summary> GeneralPurposeSlider2, /// <summary> /// The General Puprose Slider 3 /// </summary> GeneralPurposeSlider3, /// <summary> /// The General Puprose Slider 4 /// </summary> GeneralPurposeSlider4, /// <summary> /// The Bank Select fine. /// </summary> BankSelectFine = 32, /// <summary> /// The Modulation Wheel fine. /// </summary> ModulationWheelFine, /// <summary> /// The Breath Control fine. /// </summary> BreathControlFine, /// <summary> /// The Foot Pedal fine. /// </summary> FootPedalFine = 36, /// <summary> /// The Portamento Time fine. /// </summary> PortamentoTimeFine, /// <summary> /// The Data Entry Slider fine. /// </summary> DataEntrySliderFine, /// <summary> /// The Volume fine. /// </summary> VolumeFine, /// <summary> /// The Balance fine. /// </summary> BalanceFine, /// <summary> /// The Pan position fine. /// </summary> PanFine = 42, /// <summary> /// The Expression fine. /// </summary> ExpressionFine, /// <summary> /// The Effect Control 1 fine. /// </summary> EffectControl1Fine, /// <summary> /// The Effect Control 2 fine. /// </summary> EffectControl2Fine, /// <summary> /// The Hold Pedal 1. /// </summary> HoldPedal1 = 64, /// <summary> /// The Portamento. /// </summary> Portamento, /// <summary> /// The Sustenuto Pedal. /// </summary> SustenutoPedal, /// <summary> /// The Soft Pedal. /// </summary> SoftPedal, /// <summary> /// The Legato Pedal. /// </summary> LegatoPedal, /// <summary> /// The Hold Pedal 2. /// </summary> HoldPedal2, /// <summary> /// The Sound Variation. /// </summary> SoundVariation, /// <summary> /// The Sound Timbre. /// </summary> SoundTimbre, /// <summary> /// The Sound Release Time. /// </summary> SoundReleaseTime, /// <summary> /// The Sound Attack Time. /// </summary> SoundAttackTime, /// <summary> /// The Sound Brightness. /// </summary> SoundBrightness, /// <summary> /// The Sound Control 6. /// </summary> SoundControl6, /// <summary> /// The Sound Control 7. /// </summary> SoundControl7, /// <summary> /// The Sound Control 8. /// </summary> SoundControl8, /// <summary> /// The Sound Control 9. /// </summary> SoundControl9, /// <summary> /// The Sound Control 10. /// </summary> SoundControl10, /// <summary> /// The General Purpose Button 1. /// </summary> GeneralPurposeButton1, /// <summary> /// The General Purpose Button 2. /// </summary> GeneralPurposeButton2, /// <summary> /// The General Purpose Button 3. /// </summary> GeneralPurposeButton3, /// <summary> /// The General Purpose Button 4. /// </summary> GeneralPurposeButton4, /// <summary> /// The Effects Level. /// </summary> EffectsLevel = 91, /// <summary> /// The Tremelo Level. /// </summary> TremeloLevel, /// <summary> /// The Chorus Level. /// </summary> ChorusLevel, /// <summary> /// The Celeste Level. /// </summary> CelesteLevel, /// <summary> /// The Phaser Level. /// </summary> PhaserLevel, /// <summary> /// The Data Button Increment. /// </summary> DataButtonIncrement, /// <summary> /// The Data Button Decrement. /// </summary> DataButtonDecrement, /// <summary> /// The NonRegistered Parameter Fine. /// </summary> NonRegisteredParameterFine, /// <summary> /// The NonRegistered Parameter Coarse. /// </summary> NonRegisteredParameterCoarse, /// <summary> /// The Registered Parameter Fine. /// </summary> RegisteredParameterFine, /// <summary> /// The Registered Parameter Coarse. /// </summary> RegisteredParameterCoarse, /// <summary> /// The All Sound Off. /// </summary> AllSoundOff = 120, /// <summary> /// The All Controllers Off. /// </summary> AllControllersOff, /// <summary> /// The Local Keyboard. /// </summary> LocalKeyboard, /// <summary> /// The All Notes Off. /// </summary> AllNotesOff, /// <summary> /// The Omni Mode Off. /// </summary> OmniModeOff, /// <summary> /// The Omni Mode On. /// </summary> OmniModeOn, /// <summary> /// The Mono Operation. /// </summary> MonoOperation, /// <summary> /// The Poly Operation. /// </summary> PolyOperation } #endregion /// <summary> /// Represents MIDI channel messages. /// </summary> [ImmutableObject(true)] public sealed class ChannelMessage : ShortMessage { #region ChannelEventArgs Members #region Constants // // Bit manipulation constants. // private const int MidiChannelMask = ~15; private const int CommandMask = ~240; /// <summary> /// Maximum value allowed for MIDI channels. /// </summary> public const int MidiChannelMaxValue = 15; #endregion #region Construction /// <summary> /// Initializes a new instance of the ChannelEventArgs class with the /// specified command, MIDI channel, and data 1 values. /// </summary> /// <param name="command"> /// The command value. /// </param> /// <param name="midiChannel"> /// The MIDI channel. /// </param> /// <param name="data1"> /// The data 1 value. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// If midiChannel is less than zero or greater than 15. Or if /// data1 is less than zero or greater than 127. /// </exception> public ChannelMessage(ChannelCommand command, int midiChannel, int data1) { msg = 0; msg = PackCommand(msg, command); msg = PackMidiChannel(msg, midiChannel); msg = PackData1(msg, data1); #region Ensure Debug.Assert(Command == command); Debug.Assert(MidiChannel == midiChannel); Debug.Assert(Data1 == data1); #endregion } /// <summary> /// Initializes a new instance of the ChannelEventArgs class with the /// specified command, MIDI channel, data 1, and data 2 values. /// </summary> /// <param name="command"> /// The command value. /// </param> /// <param name="midiChannel"> /// The MIDI channel. /// </param> /// <param name="data1"> /// The data 1 value. /// </param> /// <param name="data2"> /// The data 2 value. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// If midiChannel is less than zero or greater than 15. Or if /// data1 or data 2 is less than zero or greater than 127. /// </exception> public ChannelMessage(ChannelCommand command, int midiChannel, int data1, int data2) { msg = 0; msg = PackCommand(msg, command); msg = PackMidiChannel(msg, midiChannel); msg = PackData1(msg, data1); msg = PackData2(msg, data2); #region Ensure Debug.Assert(Command == command); Debug.Assert(MidiChannel == midiChannel); Debug.Assert(Data1 == data1); Debug.Assert(Data2 == data2); #endregion } internal ChannelMessage(int message) { this.msg = message; } #endregion #region Methods /// <summary> /// Returns a value for the current ChannelEventArgs suitable for use in /// hashing algorithms. /// </summary> /// <returns> /// A hash code for the current ChannelEventArgs. /// </returns> public override int GetHashCode() { return msg; } /// <summary> /// Determines whether two ChannelEventArgs instances are equal. /// </summary> /// <param name="obj"> /// The ChannelMessageEventArgs to compare with the current ChannelEventArgs. /// </param> /// <returns> /// <b>true</b> if the specified object is equal to the current /// ChannelMessageEventArgs; otherwise, <b>false</b>. /// </returns> public override bool Equals(object obj) { #region Guard if(!(obj is ChannelMessage)) { return false; } #endregion ChannelMessage e = (ChannelMessage)obj; return this.msg == e.msg; } /// <summary> /// Returns a value indicating how many bytes are used for the /// specified ChannelCommand. /// </summary> /// <param name="command"> /// The ChannelCommand value to test. /// </param> /// <returns> /// The number of bytes used for the specified ChannelCommand. /// </returns> internal static int DataBytesPerType(ChannelCommand command) { int result; if(command == ChannelCommand.ChannelPressure || command == ChannelCommand.ProgramChange) { result = 1; } else { result = 2; } return result; } /// <summary> /// Unpacks the command value from the specified integer channel /// message. /// </summary> /// <param name="message"> /// The message to unpack. /// </param> /// <returns> /// The command value for the packed message. /// </returns> internal static ChannelCommand UnpackCommand(int message) { return (ChannelCommand)(message & DataMask & MidiChannelMask); } /// <summary> /// Unpacks the MIDI channel from the specified integer channel /// message. /// </summary> /// <param name="message"> /// The message to unpack. /// </param> /// <returns> /// The MIDI channel for the pack message. /// </returns> internal static int UnpackMidiChannel(int message) { return message & DataMask & CommandMask; } /// <summary> /// Packs the MIDI channel into the specified integer message. /// </summary> /// <param name="message"> /// The message into which the MIDI channel is packed. /// </param> /// <param name="midiChannel"> /// The MIDI channel to pack into the message. /// </param> /// <returns> /// An integer message. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// If midiChannel is less than zero or greater than 15. /// </exception> internal static int PackMidiChannel(int message, int midiChannel) { #region Preconditons if(midiChannel < 0 || midiChannel > MidiChannelMaxValue) { throw new ArgumentOutOfRangeException("midiChannel", midiChannel, "MIDI channel out of range."); } #endregion return (message & MidiChannelMask) | midiChannel; } /// <summary> /// Packs the command value into an integer message. /// </summary> /// <param name="message"> /// The message into which the command is packed. /// </param> /// <param name="command"> /// The command value to pack into the message. /// </param> /// <returns> /// An integer message. /// </returns> internal static int PackCommand(int message, ChannelCommand command) { return (message & CommandMask) | (int)command; } #endregion #region Properties /// <summary> /// Gets the channel command value. /// </summary> public ChannelCommand Command { get { return UnpackCommand(msg); } } /// <summary> /// Gets the MIDI channel. /// </summary> public int MidiChannel { get { return UnpackMidiChannel(msg); } } /// <summary> /// Gets the first data value. /// </summary> public int Data1 { get { return UnpackData1(msg); } } /// <summary> /// Gets the second data value. /// </summary> public int Data2 { get { return UnpackData2(msg); } } /// <summary> /// Gets the EventType. /// </summary> public override MessageType MessageType { get { return MessageType.Channel; } } #endregion #endregion } }
// Lucene version compatibility level: 4.8.1 using Lucene.Net.Diagnostics; using Lucene.Net.Support.Threading; using System; using System.Diagnostics; using System.Threading; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// <see cref="DocumentsWriterPerThreadPool"/> controls <see cref="ThreadState"/> instances /// and their thread assignments during indexing. Each <see cref="ThreadState"/> holds /// a reference to a <see cref="DocumentsWriterPerThread"/> that is once a /// <see cref="ThreadState"/> is obtained from the pool exclusively used for indexing a /// single document by the obtaining thread. Each indexing thread must obtain /// such a <see cref="ThreadState"/> to make progress. Depending on the /// <see cref="DocumentsWriterPerThreadPool"/> implementation <see cref="ThreadState"/> /// assignments might differ from document to document. /// <para/> /// Once a <see cref="DocumentsWriterPerThread"/> is selected for flush the thread pool /// is reusing the flushing <see cref="DocumentsWriterPerThread"/>s <see cref="ThreadState"/> with a /// new <see cref="DocumentsWriterPerThread"/> instance. /// </summary> internal sealed class DocumentsWriterPerThreadPool #if FEATURE_CLONEABLE : System.ICloneable #endif { /// <summary> /// <see cref="ThreadState"/> references and guards a /// <see cref="Index.DocumentsWriterPerThread"/> instance that is used during indexing to /// build a in-memory index segment. <see cref="ThreadState"/> also holds all flush /// related per-thread data controlled by <see cref="DocumentsWriterFlushControl"/>. /// <para/> /// A <see cref="ThreadState"/>, its methods and members should only accessed by one /// thread a time. Users must acquire the lock via <see cref="ReentrantLock.Lock()"/> /// and release the lock in a finally block via <see cref="ReentrantLock.Unlock()"/> /// (on the <see cref="ThreadState"/> instance) before accessing the state. /// </summary> internal sealed class ThreadState : ReentrantLock { internal DocumentsWriterPerThread dwpt; // TODO this should really be part of DocumentsWriterFlushControl // write access guarded by DocumentsWriterFlushControl internal volatile bool flushPending = false; // TODO this should really be part of DocumentsWriterFlushControl // write access guarded by DocumentsWriterFlushControl internal long bytesUsed = 0; // guarded by Reentrant lock internal bool isActive = true; internal ThreadState(DocumentsWriterPerThread dpwt) { this.dwpt = dpwt; } /// <summary> /// Resets the internal <see cref="DocumentsWriterPerThread"/> with the given one. /// if the given DWPT is <c>null</c> this <see cref="ThreadState"/> is marked as inactive and should not be used /// for indexing anymore. </summary> /// <seealso cref="IsActive"/> internal void Deactivate() // LUCENENET NOTE: Made internal because it is called outside of this context { if (Debugging.AssertsEnabled) Debugging.Assert(this.IsHeldByCurrentThread); isActive = false; Reset(); } internal void Reset() // LUCENENET NOTE: Made internal because it is called outside of this context { if (Debugging.AssertsEnabled) Debugging.Assert(this.IsHeldByCurrentThread); this.dwpt = null; this.bytesUsed = 0; this.flushPending = false; } /// <summary> /// Returns <c>true</c> if this <see cref="ThreadState"/> is still open. This will /// only return <c>false</c> iff the DW has been disposed and this /// <see cref="ThreadState"/> is already checked out for flush. /// </summary> internal bool IsActive { get { if (Debugging.AssertsEnabled) Debugging.Assert(this.IsHeldByCurrentThread); return isActive; } } internal bool IsInitialized { get { if (Debugging.AssertsEnabled) Debugging.Assert(this.IsHeldByCurrentThread); return IsActive && dwpt != null; } } /// <summary> /// Returns the number of currently active bytes in this ThreadState's /// <see cref="DocumentsWriterPerThread"/> /// </summary> public long BytesUsedPerThread { get { if (Debugging.AssertsEnabled) Debugging.Assert(this.IsHeldByCurrentThread); // public for FlushPolicy return bytesUsed; } } /// <summary> /// Returns this <see cref="ThreadState"/>s <see cref="DocumentsWriterPerThread"/> /// </summary> public DocumentsWriterPerThread DocumentsWriterPerThread { get { if (Debugging.AssertsEnabled) Debugging.Assert(this.IsHeldByCurrentThread); // public for FlushPolicy return dwpt; } } /// <summary> /// Returns <c>true</c> iff this <see cref="ThreadState"/> is marked as flush /// pending otherwise <c>false</c> /// </summary> public bool IsFlushPending => flushPending; } private readonly ThreadState[] threadStates; private volatile int numThreadStatesActive; private readonly ThreadState[] freeList; private volatile int freeCount; /// <summary> /// Creates a new <see cref="DocumentsWriterPerThreadPool"/> with a given maximum of <see cref="ThreadState"/>s. /// </summary> internal DocumentsWriterPerThreadPool(int maxNumThreadStates) { if (maxNumThreadStates < 1) { throw new ArgumentException("maxNumThreadStates must be >= 1 but was: " + maxNumThreadStates); } threadStates = new ThreadState[maxNumThreadStates]; numThreadStatesActive = 0; for (int i = 0; i < threadStates.Length; i++) { threadStates[i] = new ThreadState(null); } freeList = new ThreadState[maxNumThreadStates]; } public object Clone() { // We should only be cloned before being used: if (numThreadStatesActive != 0) { throw new InvalidOperationException("clone this object before it is used!"); } return new DocumentsWriterPerThreadPool(threadStates.Length); } /// <summary> /// Returns the max number of <see cref="ThreadState"/> instances available in this /// <see cref="DocumentsWriterPerThreadPool"/> /// </summary> public int MaxThreadStates => threadStates.Length; /// <summary> /// Returns the active number of <see cref="ThreadState"/> instances. /// </summary> public int NumThreadStatesActive => numThreadStatesActive; // LUCENENET NOTE: Changed from getActiveThreadState() because the name wasn't clear /// <summary> /// Returns a new <see cref="ThreadState"/> iff any new state is available otherwise /// <c>null</c>. /// <para/> /// NOTE: the returned <see cref="ThreadState"/> is already locked iff non-<c>null</c>. /// </summary> /// <returns> a new <see cref="ThreadState"/> iff any new state is available otherwise /// <c>null</c> </returns> public ThreadState NewThreadState() { if (Debugging.AssertsEnabled) Debugging.Assert(numThreadStatesActive < threadStates.Length); ThreadState threadState = threadStates[numThreadStatesActive]; threadState.Lock(); // lock so nobody else will get this ThreadState bool unlock = true; try { if (threadState.IsActive) { // unreleased thread states are deactivated during DW#close() numThreadStatesActive++; // increment will publish the ThreadState //System.out.println("activeCount=" + numThreadStatesActive); if (Debugging.AssertsEnabled) Debugging.Assert(threadState.dwpt == null); unlock = false; return threadState; } // we are closed: unlock since the threadstate is not active anymore if (Debugging.AssertsEnabled) Debugging.Assert(AssertUnreleasedThreadStatesInactive()); return null; } finally { if (unlock) { // in any case make sure we unlock if we fail threadState.Unlock(); } } } private bool AssertUnreleasedThreadStatesInactive() { lock (this) { for (int i = numThreadStatesActive; i < threadStates.Length; i++) { if (Debugging.AssertsEnabled) Debugging.Assert(threadStates[i].TryLock(), "unreleased threadstate should not be locked"); try { if (Debugging.AssertsEnabled) Debugging.Assert(!threadStates[i].IsInitialized, "expected unreleased thread state to be inactive"); } finally { threadStates[i].Unlock(); } } return true; } } /// <summary> /// Deactivate all unreleased threadstates /// </summary> internal void DeactivateUnreleasedStates() { lock (this) { for (int i = numThreadStatesActive; i < threadStates.Length; i++) { ThreadState threadState = threadStates[i]; threadState.@Lock(); try { threadState.Deactivate(); } finally { threadState.Unlock(); } } } } internal DocumentsWriterPerThread Reset(ThreadState threadState, bool closed) { if (Debugging.AssertsEnabled) Debugging.Assert(threadState.IsHeldByCurrentThread); DocumentsWriterPerThread dwpt = threadState.dwpt; if (!closed) { threadState.Reset(); } else { threadState.Deactivate(); } return dwpt; } internal void Recycle(DocumentsWriterPerThread dwpt) { // don't recycle DWPT by default } // you cannot subclass this without being in o.a.l.index package anyway, so // the class is already pkg-private... fix me: see LUCENE-4013 public ThreadState GetAndLock(Thread requestingThread, DocumentsWriter documentsWriter) { ThreadState threadState = null; lock (this) { for (;;) { if (freeCount > 0) { // Important that we are LIFO here! This way if number of concurrent indexing threads was once high, but has now reduced, we only use a // limited number of thread states: threadState = freeList[freeCount - 1]; if (threadState.dwpt == null) { // This thread-state is not initialized, e.g. it // was just flushed. See if we can instead find // another free thread state that already has docs // indexed. This way if incoming thread concurrency // has decreased, we don't leave docs // indefinitely buffered, tying up RAM. This // will instead get those thread states flushed, // freeing up RAM for larger segment flushes: for (int i = 0; i < freeCount; i++) { if (freeList[i].dwpt != null) { // Use this one instead, and swap it with // the un-initialized one: ThreadState ts = freeList[i]; freeList[i] = threadState; threadState = ts; break; } } } freeCount--; break; } else if (NumThreadStatesActive < threadStates.Length) { // ThreadState is already locked before return by this method: return NewThreadState(); } else { // Wait until a thread state frees up: Monitor.Wait(this); } } } // This could take time, e.g. if the threadState is [briefly] checked for flushing: threadState.Lock(); return threadState; } public void Release(ThreadState state) { state.Unlock(); lock (this) { Debug.Assert(freeCount < freeList.Length); freeList[freeCount++] = state; // In case any thread is waiting, wake one of them up since we just released a thread state; notify() should be sufficient but we do // notifyAll defensively: Monitor.PulseAll(this); } } /// <summary> /// Returns the <i>i</i>th active <seealso cref="ThreadState"/> where <i>i</i> is the /// given ord. /// </summary> /// <param name="ord"> /// the ordinal of the <seealso cref="ThreadState"/> </param> /// <returns> the <i>i</i>th active <seealso cref="ThreadState"/> where <i>i</i> is the /// given ord. </returns> internal ThreadState GetThreadState(int ord) { return threadStates[ord]; } /// <summary> /// Returns the <see cref="ThreadState"/> with the minimum estimated number of threads /// waiting to acquire its lock or <c>null</c> if no <see cref="ThreadState"/> /// is yet visible to the calling thread. /// </summary> internal ThreadState MinContendedThreadState() { ThreadState minThreadState = null; int limit = numThreadStatesActive; for (int i = 0; i < limit; i++) { ThreadState state = threadStates[i]; if (minThreadState == null || state.QueueLength < minThreadState.QueueLength) { minThreadState = state; } } return minThreadState; } /// <summary> /// Returns the number of currently deactivated <see cref="ThreadState"/> instances. /// A deactivated <see cref="ThreadState"/> should not be used for indexing anymore. /// </summary> /// <returns> the number of currently deactivated <see cref="ThreadState"/> instances. </returns> internal int NumDeactivatedThreadStates() { int count = 0; for (int i = 0; i < threadStates.Length; i++) { ThreadState threadState = threadStates[i]; threadState.@Lock(); try { if (!threadState.isActive) { count++; } } finally { threadState.Unlock(); } } return count; } /// <summary> /// Deactivates an active <see cref="ThreadState"/>. Inactive <see cref="ThreadState"/> can /// not be used for indexing anymore once they are deactivated. This method should only be used /// if the parent <see cref="DocumentsWriter"/> is closed or aborted. /// </summary> /// <param name="threadState"> the state to deactivate </param> internal void DeactivateThreadState(ThreadState threadState) { if (Debugging.AssertsEnabled) Debugging.Assert(threadState.IsActive); threadState.Deactivate(); } } }
// 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.Net.Mail.MailMessage.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.Net.Mail { public partial class MailMessage : IDisposable { #region Methods and constructors public void Dispose() { } protected virtual new void Dispose(bool disposing) { } public MailMessage(string from, string to) { } public MailMessage(string from, string to, string subject, string body) { } public MailMessage(MailAddress from, MailAddress to) { } public MailMessage() { } #endregion #region Properties and indexers public AlternateViewCollection AlternateViews { get { Contract.Ensures(Contract.Result<System.Net.Mail.AlternateViewCollection>() != null); return default(AlternateViewCollection); } } public AttachmentCollection Attachments { get { Contract.Ensures(Contract.Result<System.Net.Mail.AttachmentCollection>() != null); return default(AttachmentCollection); } } public MailAddressCollection Bcc { get { Contract.Ensures(Contract.Result<System.Net.Mail.MailAddressCollection>() != null); return default(MailAddressCollection); } } public string Body { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { } } public Encoding BodyEncoding { get { return default(Encoding); } set { } } public MailAddressCollection CC { get { Contract.Ensures(Contract.Result<System.Net.Mail.MailAddressCollection>() != null); return default(MailAddressCollection); } } public DeliveryNotificationOptions DeliveryNotificationOptions { get { return default(DeliveryNotificationOptions); } set { } } public MailAddress From { get { return default(MailAddress); } set { } } public System.Collections.Specialized.NameValueCollection Headers { get { Contract.Ensures(Contract.Result<System.Collections.Specialized.NameValueCollection>() != null); return default(System.Collections.Specialized.NameValueCollection); } } public Encoding HeadersEncoding { get { return default(Encoding); } set { } } public bool IsBodyHtml { get { return default(bool); } set { } } public MailPriority Priority { get { return default(MailPriority); } set { } } public MailAddress ReplyTo { get { return default(MailAddress); } set { } } public MailAddressCollection ReplyToList { get { Contract.Ensures(Contract.Result<System.Net.Mail.MailAddressCollection>() != null); return default(MailAddressCollection); } } public MailAddress Sender { get { return default(MailAddress); } set { } } public string Subject { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { } } public Encoding SubjectEncoding { get { return default(Encoding); } set { } } public MailAddressCollection To { get { Contract.Ensures(Contract.Result<System.Net.Mail.MailAddressCollection>() != null); return default(MailAddressCollection); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Http { /// <summary> /// A wrapper for the response Set-Cookie header. /// </summary> internal partial class ResponseCookies : IResponseCookies { internal const string EnableCookieNameEncoding = "Microsoft.AspNetCore.Http.EnableCookieNameEncoding"; internal bool _enableCookieNameEncoding = AppContext.TryGetSwitch(EnableCookieNameEncoding, out var enabled) && enabled; private readonly IFeatureCollection _features; private ILogger? _logger; /// <summary> /// Create a new wrapper. /// </summary> internal ResponseCookies(IFeatureCollection features) { _features = features; Headers = _features.Get<IHttpResponseFeature>()!.Headers; } private IHeaderDictionary Headers { get; set; } /// <inheritdoc /> public void Append(string key, string value) { var setCookieHeaderValue = new SetCookieHeaderValue( _enableCookieNameEncoding ? Uri.EscapeDataString(key) : key, Uri.EscapeDataString(value)) { Path = "/" }; var cookieValue = setCookieHeaderValue.ToString(); Headers.SetCookie = StringValues.Concat(Headers.SetCookie, cookieValue); } /// <inheritdoc /> public void Append(string key, string value, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } // SameSite=None cookies must be marked as Secure. if (!options.Secure && options.SameSite == SameSiteMode.None) { if (_logger == null) { var services = _features.Get<Features.IServiceProvidersFeature>()?.RequestServices; _logger = services?.GetService<ILogger<ResponseCookies>>(); } if (_logger != null) { Log.SameSiteCookieNotSecure(_logger, key); } } var setCookieHeaderValue = new SetCookieHeaderValue( _enableCookieNameEncoding ? Uri.EscapeDataString(key) : key, Uri.EscapeDataString(value)) { Domain = options.Domain, Path = options.Path, Expires = options.Expires, MaxAge = options.MaxAge, Secure = options.Secure, SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite, HttpOnly = options.HttpOnly }; var cookieValue = setCookieHeaderValue.ToString(); Headers.SetCookie = StringValues.Concat(Headers.SetCookie, cookieValue); } /// <inheritdoc /> public void Append(ReadOnlySpan<KeyValuePair<string, string>> keyValuePairs, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } // SameSite=None cookies must be marked as Secure. if (!options.Secure && options.SameSite == SameSiteMode.None) { if (_logger == null) { var services = _features.Get<IServiceProvidersFeature>()?.RequestServices; _logger = services?.GetService<ILogger<ResponseCookies>>(); } if (_logger != null) { foreach (var keyValuePair in keyValuePairs) { Log.SameSiteCookieNotSecure(_logger, keyValuePair.Key); } } } var setCookieHeaderValue = new SetCookieHeaderValue(string.Empty) { Domain = options.Domain, Path = options.Path, Expires = options.Expires, MaxAge = options.MaxAge, Secure = options.Secure, SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite, HttpOnly = options.HttpOnly }; var cookierHeaderValue = setCookieHeaderValue.ToString()[1..]; var cookies = new string[keyValuePairs.Length]; var position = 0; foreach (var keyValuePair in keyValuePairs) { var key = _enableCookieNameEncoding ? Uri.EscapeDataString(keyValuePair.Key) : keyValuePair.Key; cookies[position] = string.Concat(key, "=", Uri.EscapeDataString(keyValuePair.Value), cookierHeaderValue); position++; } // Can't use += as StringValues does not override operator+ // and the implict conversions will cause an incorrect string concat https://github.com/dotnet/runtime/issues/52507 Headers.SetCookie = StringValues.Concat(Headers.SetCookie, cookies); } /// <inheritdoc /> public void Delete(string key) { Delete(key, new CookieOptions() { Path = "/" }); } /// <inheritdoc /> public void Delete(string key, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var encodedKeyPlusEquals = (_enableCookieNameEncoding ? Uri.EscapeDataString(key) : key) + "="; var domainHasValue = !string.IsNullOrEmpty(options.Domain); var pathHasValue = !string.IsNullOrEmpty(options.Path); Func<string, string, CookieOptions, bool> rejectPredicate; if (domainHasValue && pathHasValue) { rejectPredicate = (value, encKeyPlusEquals, opts) => value.StartsWith(encKeyPlusEquals, StringComparison.OrdinalIgnoreCase) && value.IndexOf($"domain={opts.Domain}", StringComparison.OrdinalIgnoreCase) != -1 && value.IndexOf($"path={opts.Path}", StringComparison.OrdinalIgnoreCase) != -1; } else if (domainHasValue) { rejectPredicate = (value, encKeyPlusEquals, opts) => value.StartsWith(encKeyPlusEquals, StringComparison.OrdinalIgnoreCase) && value.IndexOf($"domain={opts.Domain}", StringComparison.OrdinalIgnoreCase) != -1; } else if (pathHasValue) { rejectPredicate = (value, encKeyPlusEquals, opts) => value.StartsWith(encKeyPlusEquals, StringComparison.OrdinalIgnoreCase) && value.IndexOf($"path={opts.Path}", StringComparison.OrdinalIgnoreCase) != -1; } else { rejectPredicate = (value, encKeyPlusEquals, opts) => value.StartsWith(encKeyPlusEquals, StringComparison.OrdinalIgnoreCase); } var existingValues = Headers.SetCookie; if (!StringValues.IsNullOrEmpty(existingValues)) { var values = existingValues.ToArray(); var newValues = new List<string>(); for (var i = 0; i < values.Length; i++) { var value = values[i] ?? string.Empty; if (!rejectPredicate(value, encodedKeyPlusEquals, options)) { newValues.Add(value); } } Headers.SetCookie = new StringValues(newValues.ToArray()); } Append(key, string.Empty, new CookieOptions { Path = options.Path, Domain = options.Domain, Expires = DateTimeOffset.UnixEpoch, Secure = options.Secure, HttpOnly = options.HttpOnly, SameSite = options.SameSite }); } private static partial class Log { [LoggerMessage(1, LogLevel.Warning, "The cookie '{name}' has set 'SameSite=None' and must also set 'Secure'.", EventName = "SameSiteNotSecure")] public static partial void SameSiteCookieNotSecure(ILogger logger, string name); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Authorization.Version2015_07_01 { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Authorization; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PermissionsOperations operations. /// </summary> internal partial class PermissionsOperations : IServiceOperations<AuthorizationManagementClient>, IPermissionsOperations { /// <summary> /// Initializes a new instance of the PermissionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PermissionsOperations(AuthorizationManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AuthorizationManagementClient /// </summary> public AuthorizationManagementClient Client { get; private set; } /// <summary> /// Gets all permissions the caller has for a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to get the permissions for. The name is case /// insensitive. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Permission>>> ListForResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListForResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Permission>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Permission>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all permissions the caller has for a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group containing the resource. The name is case /// insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> /// <param name='parentResourcePath'> /// The parent resource identity. /// </param> /// <param name='resourceType'> /// The resource type of the resource. /// </param> /// <param name='resourceName'> /// The name of the resource to get the permissions for. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Permission>>> ListForResourceWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceProviderNamespace == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceProviderNamespace"); } if (parentResourcePath == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parentResourcePath"); } if (resourceType == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceType"); } if (resourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("parentResourcePath", parentResourcePath); tracingParameters.Add("resourceType", resourceType); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListForResource", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{resourceProviderNamespace}", System.Uri.EscapeDataString(resourceProviderNamespace)); _url = _url.Replace("{parentResourcePath}", parentResourcePath); _url = _url.Replace("{resourceType}", resourceType); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Permission>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Permission>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all permissions the caller has for a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Permission>>> ListForResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListForResourceGroupNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Permission>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Permission>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all permissions the caller has for a resource. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Permission>>> ListForResourceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListForResourceNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Permission>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Permission>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Build.Collections; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; using Microsoft.Build.Execution; using Xunit; using Xunit.Abstractions; namespace Microsoft.Build.UnitTests { public class ExpressionTest : IDisposable { private readonly ITestOutputHelper output; private static readonly string[] FilesWithExistenceChecks = { "a", "a;b", "a'b", ";", "'" }; private readonly Expander<ProjectPropertyInstance, ProjectItemInstance> _expander; public static readonly IEnumerable<string[]> TrueTests = new [] { "true or (SHOULDNOTEVALTHIS)", // short circuit "(true and false) or true", "false or true or false", "(true) and (true)", "false or !false", "($(a) or true)", "('$(c)'==1 and (!false))", "@(z -> '%(filename).z', '$')=='xxx.z$yyy.z'", "@(w -> '%(definingprojectname).barproj') == 'foo.barproj'", "false or (false or (false or (false or (false or (true)))))", "!(true and false)", "$(and)=='and'", "0x1==1.0", "0xa==10", "0<0.1", "+4>-4", "'-$(c)'==-1", "$(a)==faLse", "$(a)==oFF", "$(a)==no", "$(a)!=true", "$(b)== True", "$(b)==on", "$(b)==yes", "$(b)!=1", "$(c)==1", "$(d)=='xxx'", "$(d)==$(e)", "$(d)=='$(e)'", "@(y)==$(d)", "'@(z)'=='xxx;yyy'", "$(a)==$(a)", "'1'=='1'", "'1'==1", "1\n==1", "1\t==\t\r\n1", "123=='0123.0'", "123==123", "123==0123", "123==0123.0", "123!=0123.01", "1.2.3<=1.2.3.0", "12.23.34==12.23.34", "0.8.0.0<8.0.0", "1.1.2>1.0.1.2", "8.1>8.0.16.23", "8.0.0>=8", "6<=6.0.0.1", "7>6.8.2", "4<5.9.9135.4", "3!=3.0.0", "1.2.3.4.5.6.7==1.2.3.4.5.6.7", "00==0", "0==0.0", "1\n\t==1", "+4==4", "44==+44.0 and -44==-44.0", "false==no", "true==yes", "true==!false", "yes!=no", "false!=1", "$(c)>0", "!$(a)", "$(b)", "($(d)==$(e))", "!true==false", "a_a==a_a", "a_a=='a_a'", "_a== _a", "@(y -> '%(filename)')=='xxx'", "@(z -> '%(filename)', '!')=='xxx!yyy'", "'xxx!yyy'==@(z -> '%(filename)', '!')", "'$(a)'==(false)", "('$(a)'==(false))", "1>0", "2<=2", "2<=3", "1>=1", "1>=-1", "-1==-1", "-1 < 0", "(1==1)and('a'=='a')", "(true) and ($(a)==off)", "(true) and ($(d)==xxx)", "(false) or($(d)==xxx)", "!(false)and!(false)", "'and'=='AND'", "$(d)=='XxX'", "true or true or false", "false or true or !true or'1'", "$(a) or $(b)", "$(a) or true", "!!true", "'$(e)1@(y)'=='xxx1xxx'", "0x11==17", "0x01a==26", "0xa==0x0A", "@(x)", "'%77'=='w'", "'%zz'=='%zz'", "true or 1", "true==!false", "(!(true))=='off'", "@(w)>0", "1<=@(w)", "%(culture)=='FRENCH'", "'%(culture) fries' == 'FRENCH FRIES' ", @"'%(HintPath)' == ''", @"%(HintPath) != 'c:\myassemblies\foo.dll'", "exists('a')", "exists(a)", "exists('a%3bb')", /* semicolon */ "exists('a%27b')", /* apostrophe */ "exists($(a_escapedsemi_b))", "exists('$(a_escapedsemi_b)')", "exists($(a_escapedapos_b))", "exists('$(a_escapedapos_b)')", "exists($(a_apos_b))", "exists('$(a_apos_b)')", "exists(@(v))", "exists('@(v)')", "exists('%3b')", "exists('%27')", "exists('@(v);@(nonexistent)')", @"HASTRAILINGSLASH('foo\')", @"!HasTrailingSlash('foo')", @"HasTrailingSlash('foo/')", @"HasTrailingSlash($(has_trailing_slash))", "'59264.59264' == '59264.59264'", "1" + new String('0', 500) + "==" + "1" + new String('0', 500), /* too big for double, eval as string */ "'1" + new String('0', 500) + "'=='" + "1" + new String('0', 500) + "'" /* too big for double, eval as string */ }.Select(s => new[] {s}); public static readonly IEnumerable<string[]> FalseTests = new [] { "false and SHOULDNOTEVALTHIS", // short circuit "$(a)!=no", "$(b)==1.1", "$(c)==$(a)", "$(d)!=$(e)", "!$(b)", "false or false or false", "false and !((true and false))", "on and off", "(true) and (false)", "false or (false or (false or (false or (false or (false)))))", "!$(b)and true", "1==a", "!($(d)==$(e))", "$(a) and true", "true==1", "false==0", "(!(true))=='x'", "oops==false", "oops==!false", "%(culture) == 'english'", "'%(culture) fries' == 'english fries' ", @"'%(HintPath)' == 'c:\myassemblies\foo.dll'", @"%(HintPath) == 'c:\myassemblies\foo.dll'", "exists('')", "exists(' ')", "exists($(nonexistent))", // DDB #141195 "exists('$(nonexistent)')", // DDB #141195 "exists(@(nonexistent))", // DDB #141195 "exists('@(nonexistent)')", // DDB #141195 "exists('\t')", "exists('@(u)')", "exists('$(foo_apos_foo)')", "!exists('a')", "!!!exists(a)", "exists('|||||')", @"hastrailingslash('foo')", @"hastrailingslash('')", @"HasTrailingSlash($(nonexistent))", "'59264.59264' == '59264.59265'", "1.2.0==1.2", "$(f)!=$(f)", "1.3.5.8>1.3.6.8", "0.8.0.0>=1.0", "8.0.0<=8.0", "8.1.2<8", "1" + new String('0', 500) + "==2", /* too big for double, eval as string */ "'1" + new String('0', 500) + "'=='2'", /* too big for double, eval as string */ "'1" + new String('0', 500) + "'=='01" + new String('0', 500) + "'" /* too big for double, eval as string */ }.Select(s => new[] { s }); public static readonly IEnumerable<object[]> ErrorTests = new [] { "$", "$(", "$()", "@", "@(", "@()", "%", "%(", "%()", "exists", "exists(", "exists()", "exists( )", "exists(,)", "@(x->'", "@(x->''", "@(x-", "@(x->'x','", "@(x->'x',''", "@(x->'x','')", "-1>x", "%00", "\n", "\t", "+-1==1", "1==-+1", "1==+0xa", "!$(c)", "'a'==('a'=='a')", "'a'!=('a'=='a')", "('a'=='a')!=a", "('a'=='a')==a", "!'x'", "!'$(d)'", "ab#==ab#", "#!=#", "$(d)$(e)=='xxxxxx'", "1=1=1", "'a'=='a'=='a'", "1 > 'x'", "x1<=1", "1<=x", "1>x", "x<x", "@(x)<x", "x>x", "x>=x", "x<=x", "x>1", "x>=1", "1>=x", "@(y)<=1", "1<=@(z)", "1>$(d)", "$(c)@(y)>1", "'$(c)@(y)'>1", "$(d)>=1", "1>=$(b)", "1> =0", "or true", "1 and", "and", "or", "not", "not true", "()", "(a)", "!", "or=or", "1==", "1= =1", "=", "'true", "'false''", "'a'=='a", "('a'=='a'", "('a'=='a'))", "'a'=='a')", "!and", "@(a)@(x)!=1", "@(a) @(x)!=1", "$(a==off", "=='x'", "==", "!0", ">", "true!=false==", "true!=false==true", "()", "!1", "1==(2", "$(a)==x>1==2", "'a'>'a'", "0", "$(a)>0", "!$(e)", "1<=1<=1", "true $(and) true", "--1==1", "$(and)==and", "!@#$%^&*", "-($(c))==-1", "a==b or $(d)", "false or $()", "$(d) or true", "%(Culture) or true", "@(nonexistent) and true", "$(nonexistent) and true", "@(nonexistent)", "$(nonexistent)", "@(z) and true", "@() and true", "@()", "$()", "1", "1 or true", "false or 1", "1 and true", "true and 1", "!1", "false or !1", "false or 'aa'", "true blah", "existsX", "!", "nonexistentfunction('xyz')", "exists('a;b')", /* non scalar */ "exists(@(z))", "exists('@(z)')", "exists($(a_semi_b))", "exists('$(a_semi_b)')", "exists(@(v)x)", "exists(@(v)$(nonexistent))", "exists('@(v)$(a)')", "exists(|||||)", "HasTrailingSlash(a,'b')", "HasTrailingSlash(,,)", "1.2.3==1,2,3" }.Select(s => new[] { s }); /// <summary> /// Set up expression tests by creating files for existence checks. /// </summary> public ExpressionTest(ITestOutputHelper output) { this.output = output; ItemDictionary<ProjectItemInstance> itemBag = new ItemDictionary<ProjectItemInstance>(); // Dummy project instance to own the items. ProjectRootElement xml = ProjectRootElement.Create(); xml.FullPath = @"c:\abc\foo.proj"; ProjectInstance parentProject = new ProjectInstance(xml); itemBag.Add(new ProjectItemInstance(parentProject, "u", "a'b;c", parentProject.FullPath)); itemBag.Add(new ProjectItemInstance(parentProject, "v", "a", parentProject.FullPath)); itemBag.Add(new ProjectItemInstance(parentProject, "w", "1", parentProject.FullPath)); itemBag.Add(new ProjectItemInstance(parentProject, "x", "true", parentProject.FullPath)); itemBag.Add(new ProjectItemInstance(parentProject, "y", "xxx", parentProject.FullPath)); itemBag.Add(new ProjectItemInstance(parentProject, "z", "xxx", parentProject.FullPath)); itemBag.Add(new ProjectItemInstance(parentProject, "z", "yyy", parentProject.FullPath)); PropertyDictionary<ProjectPropertyInstance> propertyBag = new PropertyDictionary<ProjectPropertyInstance>(); propertyBag.Set(ProjectPropertyInstance.Create("a", "no")); propertyBag.Set(ProjectPropertyInstance.Create("b", "true")); propertyBag.Set(ProjectPropertyInstance.Create("c", "1")); propertyBag.Set(ProjectPropertyInstance.Create("d", "xxx")); propertyBag.Set(ProjectPropertyInstance.Create("e", "xxx")); propertyBag.Set(ProjectPropertyInstance.Create("f", "1.9.5")); propertyBag.Set(ProjectPropertyInstance.Create("and", "and")); propertyBag.Set(ProjectPropertyInstance.Create("a_semi_b", "a;b")); propertyBag.Set(ProjectPropertyInstance.Create("a_apos_b", "a'b")); propertyBag.Set(ProjectPropertyInstance.Create("foo_apos_foo", "foo'foo")); propertyBag.Set(ProjectPropertyInstance.Create("a_escapedsemi_b", "a%3bb")); propertyBag.Set(ProjectPropertyInstance.Create("a_escapedapos_b", "a%27b")); propertyBag.Set(ProjectPropertyInstance.Create("has_trailing_slash", @"foo\")); Dictionary<string, string> metadataDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); metadataDictionary["Culture"] = "french"; StringMetadataTable itemMetadata = new StringMetadataTable(metadataDictionary); _expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(propertyBag, itemBag, itemMetadata); foreach (string file in FilesWithExistenceChecks) { using (StreamWriter sw = File.CreateText(file)) {; } } } /// <summary> /// Clean up files created for these tests. /// </summary> public void Dispose() { foreach (string file in FilesWithExistenceChecks) { if (File.Exists(file)) File.Delete(file); } } /// <summary> /// A whole bunch of conditionals that should be true /// (many coincidentally like existing QA tests) to give breadth coverage. /// Please add more cases as they arise. /// </summary> [Theory] [MemberData(nameof(TrueTests))] public void EvaluateAVarietyOfTrueExpressions(string expression) { Parser p = new Parser(); GenericExpressionNode tree; tree = p.Parse(expression, ParserOptions.AllowAll, ElementLocation.EmptyLocation); ConditionEvaluator.IConditionEvaluationState state = new ConditionEvaluator.ConditionEvaluationState<ProjectPropertyInstance, ProjectItemInstance> ( expression, _expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation ); Assert.True(tree.Evaluate(state), "expected true from '" + expression + "'"); } /// <summary> /// A whole bunch of conditionals that should be false /// (many coincidentally like existing QA tests) to give breadth coverage. /// Please add more cases as they arise. /// </summary> [Theory] [MemberData(nameof(FalseTests))] public void EvaluateAVarietyOfFalseExpressions(string expression) { Parser p = new Parser(); GenericExpressionNode tree; tree = p.Parse(expression, ParserOptions.AllowAll, ElementLocation.EmptyLocation); ConditionEvaluator.IConditionEvaluationState state = new ConditionEvaluator.ConditionEvaluationState<ProjectPropertyInstance, ProjectItemInstance> ( expression, _expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation ); Assert.False(tree.Evaluate(state), "expected false from '" + expression + "' and got true"); } /// <summary> /// A whole bunch of conditionals that should produce errors /// (many coincidentally like existing QA tests) to give breadth coverage. /// Please add more cases as they arise. /// </summary> [Theory] [MemberData(nameof(ErrorTests))] public void EvaluateAVarietyOfErrorExpressions(string expression) { // If an expression is invalid, // - Parse may throw, or // - Evaluate may throw, or // - Evaluate may return false causing its caller EvaluateCondition to throw bool caughtException = false; try { Parser p = new Parser(); var tree = p.Parse(expression, ParserOptions.AllowAll, ElementLocation.EmptyLocation); ConditionEvaluator.IConditionEvaluationState state = new ConditionEvaluator.ConditionEvaluationState<ProjectPropertyInstance, ProjectItemInstance> ( expression, _expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation ); var value = tree.Evaluate(state); } catch (InvalidProjectFileException ex) { output.WriteLine(expression + " caused '" + ex.Message + "'"); caughtException = true; } Assert.True(caughtException, "expected '" + expression + "' to not parse or not be evaluated"); } } }
// 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. //************************************************************************/ //*Test: LeakWheel //*Purpose: simulate real world objects allocating and deleting condation. //*Description: It create an object table with "iTable" items. Random number //* generator will generate number between 0 to iTable, that is ID in the //* Table. object will be added or deleted from that table item. //* Oject may be varied size, may create a new thread doing the same thing //* like main thread. may be a link list. Delete Object may delete single //* object, delete a list of object or delete all objects. While create //* object, if the table item has had one object, put this object as it's //* child object to make a link list. This tests covered link list, Variant //* array, Binary tree, finalize, multi_thread, collections, WeakReference. //*Arguments: Arg1:iMem(MB), Arg2: iIter(Number of iterations), Arg3:iTable, Arg4: iSeed //************************************************************************/ namespace DefaultNamespace { using System.Threading; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; internal class LeakWheel { internal static int iSeed; internal static int iIter; internal static int iTable; internal static int iMem; internal Node LstNode; public static int Main( String [] Args) { // console synchronization Console.SetOut(TextWriter.Synchronized(Console.Out)); /*max memory will be used. If heap size is bigger than this, */ // delete all the objects. Default 10MB iMem = 10; //How many iterations iIter = 1500000; //Max items number in the object table iTable = 500; //Seed for generate random iKey iSeed = (int)DateTime.Now.Ticks; switch( Args.Length ) { case 1: try{ iMem = Int32.Parse( Args[0] ); } catch(FormatException) { Console.WriteLine("FormatException is caught"); } break; case 2: try{ iMem = Int32.Parse( Args[0] ); iIter = Int32.Parse( Args[1] ); } catch(FormatException ) { Console.WriteLine("FormatException is caught"); } break; case 3: try{ iMem = Int32.Parse( Args[0] ); iIter = Int32.Parse( Args[1] ); iTable = Int32.Parse( Args[2] ); } catch(FormatException ) { Console.WriteLine("FormatException is caught"); } break; case 4: try { iMem = Int32.Parse(Args[0]); iIter = Int32.Parse(Args[1]); iTable = Int32.Parse(Args[2]); iSeed = Int32.Parse(Args[3]); } catch (FormatException) { Console.WriteLine("FormatException is caught"); } break; } Console.WriteLine("Repro with these values:"); Console.WriteLine("iMem= {0} MB, iIter= {1}, iTable={2} iSeed={3}", iMem, iIter, iTable, iSeed ); LeakWheel mv_obj = new LeakWheel(); if(mv_obj.RunGame()) { Console.WriteLine("Test Passed!"); return 100; } Console.WriteLine("Test Failed!"); return 1; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public void DestroyLstNode() { LstNode = null; } public bool RunGame() { Dictionary<int, WeakReference> oTable = new Dictionary<int, WeakReference>(10); DestroyLstNode(); //the last node in the node chain// Random r = new Random (LeakWheel.iSeed); for(int i=0; i<iIter; i++) { SpinWheel(oTable, LstNode, r); if( GC.GetTotalMemory(false)/(1024*1024) >= iMem ) { DestroyLstNode(); GC.Collect( ); GC.WaitForPendingFinalizers(); GC.Collect( ); Console.WriteLine( "After Delete and GCed all Objects: {0}", GC.GetTotalMemory(false) ); } } DestroyLstNode(); GC.Collect(); GC.WaitForPendingFinalizers(); Thread.Sleep(100); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.WriteLine("When test finished: {0}", GC.GetTotalMemory(false)); Console.WriteLine("Created VarAry objects: {0} Finalized VarAry Objects: {1}", Node.iVarAryCreat, Node.iVarAryFinal); Console.WriteLine("Created BitArray objects: {0} Finalized BitArray Objects: {1}", Node.iBitAryCreat, Node.iBitAryFinal); Console.WriteLine("Created small objects: {0} Finalized small Objects: {1}", Node.iSmallCreat, Node.iSmallFinal); Console.WriteLine("Created BinaryTree objects: {0} Finalized BinaryTree Objects: {1}", Node.iBiTreeCreat, Node.iBiTreeFinal); Console.WriteLine("Created Thread objects: {0} Finalized Thread Objects: {1}", Node.iThrdCreat, Node.iThrdFinal); return (Node.iBitAryCreat == Node.iBitAryFinal && Node.iBiTreeCreat == Node.iBiTreeFinal && Node.iSmallCreat == Node.iSmallFinal && Node.iThrdCreat == Node.iThrdFinal && Node.iVarAryCreat == Node.iVarAryFinal); } public void SpinWheel( Dictionary<int, WeakReference> oTable, Node node, Random r ) { int iKey;//the index which the new node will be set at Node nValue;//the new node bool bDel; //Console.WriteLine( "start spinwheel "); iKey = r.Next( 0, LeakWheel.iTable ); if( iKey%2 == 0 ) //decide whether delete or create a node. bDel = true; //delete else bDel = false; if( !bDel ) { nValue = CreateNode( iKey ); if( oTable.ContainsKey(iKey) && (oTable[iKey]).IsAlive ) { SetChildNode(oTable, iKey, nValue ); } else { LstNode = SetNodeInTable(iKey, nValue, node, oTable); } } else { DeleteNode( iKey, oTable); } //if (iKey % 100 == 0) //{ // Console.WriteLine("HeapSize: {0}", GC.GetTotalMemory(false)); //} } public void DeleteNode( int iKey, Dictionary<int, WeakReference> oTable) { //iSwitch is 0, delete one child Node at iKey; //is 1, del one object and its childred; //is 2, del the object at iKey and all the next objects; //is 3, del the all objects in object chain. int iSwitch = iKey%4; Node thisNode; if( oTable.ContainsKey( iKey ) ) { WeakReference wRef = oTable[iKey]; if( wRef.IsAlive ) { thisNode = (Node)wRef.Target; switch( iSwitch ) { case 0: Node childNode = thisNode; if( childNode.Child != null ) {//delete one child Node at iKey if there is, while( childNode.Child != null ) { childNode = childNode.Child; } childNode = childNode.Parent; childNode.Child = null; break; } else goto case 1; //otherwise del this Node in "case 1" (the node is shared with "case 1" ); case 1: //del one object and its childred from nodes chain; if( thisNode.Last != null ) { thisNode.Last.Next = thisNode.Next; if( thisNode.Next != null ) { thisNode.Next.Last = thisNode.Last; } } else { if( thisNode.Next != null ) thisNode.Next.Last = null; } break; case 2: //del the object at iKey and all the next objects; if( thisNode.Last != null ) thisNode.Last = null; else thisNode = null; break; case 3://del the all objects in object chain. Node Last = thisNode; while( Last.Last != null ) { Last = Last.Last; } Last = null; break; }//end of switch } else oTable[iKey] = null; } } public Node SetNodeInTable(int iKey, Node nValue, Node LstNode, Dictionary<int, WeakReference> oTable ) { /**************************************************/ /* save new node in a chain, all the node is */ /* refereced by this chain, Table only have their */ /* Weakreferece. So when delete a node, only need */ /* to delete the ref in this chain. */ /**************************************************/ if( LstNode == null ) LstNode = nValue; else { LstNode.Next = nValue ; LstNode.Next.Last = LstNode; LstNode = LstNode.Next; } WeakReference wRef = new WeakReference( LstNode, false ); if( oTable.ContainsKey(iKey) ) { oTable[iKey] = wRef; } else { oTable.Add( iKey, wRef ); } return LstNode; //keep the last node fresh in chain } public void SetChildNode( Dictionary<int, WeakReference> oTable, int iKey, Node nValue ) { WeakReference wRef= oTable[iKey]; WeakReference wRefChild = wRef; Node thisNode = (Node)wRefChild.Target; Node ChildNode = thisNode; while( ChildNode.Child != null ) { ChildNode = ChildNode.Child; } ChildNode.Child = nValue; ChildNode.Child.Parent = ChildNode; } public Node CreateNode( int iKey ) { Node newNode = new Node( ); switch( iKey%5 ) { //case 0://1 out of 4 nodes are thread node. // newNode.SetThread( ); //break; case 1://This node include a binary tree newNode.SettreeNode( iKey ); break; case 2: //This node with a Variant array. newNode.SetVararyNode( iKey ); break; case 3: //This node with a BitArray newNode.SetBitArrayNode( iKey ); break; case 0: case 4: //small node newNode.SetSmallNode( iKey ); break; } return newNode; } public void ThreadNode() { Dictionary<int, WeakReference> oTable = new Dictionary<int, WeakReference>( 10); DestroyLstNode(); //the last node in the node chain// Random r = new Random (LeakWheel.iSeed); LeakWheel mv_obj = new LeakWheel(); while (true) { mv_obj.SpinWheel( oTable, LstNode, r ); if( GC.GetTotalMemory(false) >= LeakWheel.iMem*60 ) { DestroyLstNode(); GC.Collect( ); GC.WaitForPendingFinalizers(); GC.Collect( ); Console.WriteLine( "After Delete and GCed all Objects: {0}", GC.GetTotalMemory(false) ); } } } } internal class Node { internal static int iVarAryCreat=0; internal static int iVarAryFinal=0; internal static int iBitAryCreat=0; internal static int iBitAryFinal=0; internal static int iSmallCreat=0; internal static int iSmallFinal=0; internal static int iBiTreeCreat=0; internal static int iBiTreeFinal=0; internal static int iThrdCreat=0; internal static int iThrdFinal=0; internal Node Last; internal Node Next; internal Node Parent; internal Node Child; // disabling unused variable warning #pragma warning disable 0414 internal Object vsMem; #pragma warning restore 0414 internal Thread ThrdNode; internal int itype; //0=VarAry;1=BitAry;2=small;3=binarytree;4=Thread public Node() { Last = null; Next = null; Parent = null; Child = null; ThrdNode = null; itype = -1; } public void SetVararyNode( int iKey ) { int iSize = iKey%30; if (iSize == 0) { iSize = 30; } Object [] VarAry = new Object[iSize]; double [] dmem; for( int i=0; i < iSize; i++ ) { dmem= new double[1+i]; dmem[0] = (double)0; dmem[i] = (double)i; VarAry[i] = ( dmem ); } vsMem = ( VarAry ); itype = 0; AddObjectToRecord(); } public void SetBitArrayNode( int iKey ) { vsMem = ( new BitArray( iKey, true ) ); itype = 1; AddObjectToRecord(); } public void SetSmallNode( int iKey ) { itype = 2; AddObjectToRecord(); vsMem = ( iKey ); } public void SettreeNode( int iKey ) { itype = 3; AddObjectToRecord(); TreeNode nTree = new TreeNode(); nTree.Populate(iKey%10, nTree); vsMem = ( nTree ); } public void SetThread() { itype = 4; AddObjectToRecord(); LeakWheel mv_obj = new LeakWheel(); mv_obj.ThreadNode(); } ~Node() { //that whould be interesting to see what happens if we don't stop the thread //this thread is created in this node, this node go away, this the object chain //is local variable in ThreadNode, it will go away too. What this thread is going to do? //if( ThrdNode != null ) //{ // ThrdNode.Abort(); // ThrdNode.Join(); //} DelObjectFromRecord( ); } public void AddObjectToRecord() { lock(this) { switch( itype ) { case 0: Node.iVarAryCreat++; break; case 1: Node.iBitAryCreat++; break; case 2: Node.iSmallCreat++; break; case 3: Node.iBiTreeCreat++; break; case 4: Node.iThrdCreat++; break; } } } public void DelObjectFromRecord( ) { lock(this) { switch( itype ) { case 0: Node.iVarAryFinal++; break; case 1: Node.iBitAryFinal++; break; case 2: Node.iSmallFinal++; break; case 3: Node.iBiTreeFinal++; break; case 4: Node.iThrdFinal++; break; } } } } internal class TreeNode { internal TreeNode left; internal TreeNode right; internal byte [] mem; public TreeNode() { } // Build tree top down, assigning to older objects. internal void Populate(int iDepth, TreeNode thisNode) { if (iDepth<=0) { return; } else { mem = new byte[iDepth]; mem[0] = 0; mem[iDepth-1] = (byte)iDepth; iDepth--; thisNode.left = new TreeNode(); thisNode.right = new TreeNode(); Populate (iDepth, thisNode.left); Populate (iDepth, thisNode.right); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; namespace System.ComponentModel.DataAnnotations { /// <summary> /// DisplayAttribute is a general-purpose attribute to specify user-visible globalizable strings for types and members. /// The string properties of this class can be used either as literals or as resource identifiers into a specified /// <see cref="ResourceType" /> /// </summary> [AttributeUsage( AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public sealed class DisplayAttribute : Attribute { #region Member Fields private readonly LocalizableString _description = new LocalizableString("Description"); private readonly LocalizableString _groupName = new LocalizableString("GroupName"); private readonly LocalizableString _name = new LocalizableString("Name"); private readonly LocalizableString _prompt = new LocalizableString("Prompt"); private readonly LocalizableString _shortName = new LocalizableString("ShortName"); private bool? _autoGenerateField; private bool? _autoGenerateFilter; private int? _order; private Type _resourceType; #endregion #region All Constructors #endregion #region Properties /// <summary> /// Gets or sets the ShortName attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetShortName" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// short name for display. /// <para> /// The <see cref="GetShortName" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// The short name is generally used as the grid column label for a UI element bound to the member /// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that. /// </value> public string ShortName { get => _shortName.Value; set => _shortName.Value = value; } /// <summary> /// Gets or sets the Name attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetName" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// name for display. /// <para> /// The <see cref="GetName" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// The name is generally used as the field label for a UI element bound to the member /// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that. /// </value> public string Name { get => _name.Value; set => _name.Value = value; } /// <summary> /// Gets or sets the Description attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetDescription" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// description for display. /// <para> /// The <see cref="GetDescription" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// Description is generally used as a tool tip or description a UI element bound to the member /// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that. /// </value> public string Description { get => _description.Value; set => _description.Value = value; } /// <summary> /// Gets or sets the Prompt attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetPrompt" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// prompt for display. /// <para> /// The <see cref="GetPrompt" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// A prompt is generally used as a prompt or watermark for a UI element bound to the member /// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that. /// </value> public string Prompt { get => _prompt.Value; set => _prompt.Value = value; } /// <summary> /// Gets or sets the GroupName attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetGroupName" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// group name for display. /// <para> /// The <see cref="GetGroupName" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// A group name is used for grouping fields into the UI. A <c>null</c> or empty string is legal, /// and consumers must allow for that. /// </value> public string GroupName { get => _groupName.Value; set => _groupName.Value = value; } /// <summary> /// Gets or sets the <see cref="System.Type" /> that contains the resources for <see cref="ShortName" />, /// <see cref="Name" />, <see cref="Description" />, <see cref="Prompt" />, and <see cref="GroupName" />. /// Using <see cref="ResourceType" /> along with these Key properties, allows the <see cref="GetShortName" />, /// <see cref="GetName" />, <see cref="GetDescription" />, <see cref="GetPrompt" />, and <see cref="GetGroupName" /> /// methods to return localized values. /// </summary> public Type ResourceType { get => _resourceType; set { if (_resourceType != value) { _resourceType = value; _shortName.ResourceType = value; _name.ResourceType = value; _description.ResourceType = value; _prompt.ResourceType = value; _groupName.ResourceType = value; } } } /// <summary> /// Gets or sets whether UI should be generated automatically to display this field. If this property is not /// set then the presentation layer will automatically determine whether UI should be generated. Setting this /// property allows an override of the default behavior of the presentation layer. /// <para> /// Consumers must use the <see cref="GetAutoGenerateField" /> method to retrieve the value, as this property /// getter will throw an exception if the value has not been set. /// </para> /// </summary> /// <exception cref="System.InvalidOperationException"> /// If the getter of this property is invoked when the value has not been explicitly set using the setter. /// </exception> public bool AutoGenerateField { get { if (!_autoGenerateField.HasValue) { throw new InvalidOperationException(SR.Format(SR.DisplayAttribute_PropertyNotSet, nameof(AutoGenerateField), nameof(GetAutoGenerateField))); } return _autoGenerateField.GetValueOrDefault(); } set => _autoGenerateField = value; } /// <summary> /// Gets or sets whether UI should be generated automatically to display filtering for this field. If this property is /// not set then the presentation layer will automatically determine whether filtering UI should be generated. Setting this /// property allows an override of the default behavior of the presentation layer. /// <para> /// Consumers must use the <see cref="GetAutoGenerateFilter" /> method to retrieve the value, as this property /// getter will throw /// an exception if the value has not been set. /// </para> /// </summary> /// <exception cref="System.InvalidOperationException"> /// If the getter of this property is invoked when the value has not been explicitly set using the setter. /// </exception> public bool AutoGenerateFilter { get { if (!_autoGenerateFilter.HasValue) { throw new InvalidOperationException(SR.Format(SR.DisplayAttribute_PropertyNotSet, nameof(AutoGenerateFilter), nameof(GetAutoGenerateFilter))); } return _autoGenerateFilter.GetValueOrDefault(); } set => _autoGenerateFilter = value; } /// <summary> /// Gets or sets the order in which this field should be displayed. If this property is not set then /// the presentation layer will automatically determine the order. Setting this property explicitly /// allows an override of the default behavior of the presentation layer. /// <para> /// Consumers must use the <see cref="GetOrder" /> method to retrieve the value, as this property getter will throw /// an exception if the value has not been set. /// </para> /// </summary> /// <exception cref="System.InvalidOperationException"> /// If the getter of this property is invoked when the value has not been explicitly set using the setter. /// </exception> public int Order { get { if (!_order.HasValue) { throw new InvalidOperationException(SR.Format(SR.DisplayAttribute_PropertyNotSet, nameof(Order), nameof(GetOrder))); } return _order.GetValueOrDefault(); } set => _order = value; } #endregion #region Methods /// <summary> /// Gets the UI display string for ShortName. /// <para> /// This can be either a literal, non-localized string provided to <see cref="ShortName" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="ShortName" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="ShortName" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="ShortName" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// <para> /// If <see cref="ShortName" /> is <c>null</c>, the value from <see cref="GetName" /> will be returned. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="ShortName" /> property, /// but a public static property with a name matching the <see cref="ShortName" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetShortName() => _shortName.GetLocalizableValue() ?? GetName(); /// <summary> /// Gets the UI display string for Name. /// <para> /// This can be either a literal, non-localized string provided to <see cref="Name" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Name" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="Name" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="Name" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// <para> /// Can return <c>null</c> and will not fall back onto other values, as it's more likely for the /// consumer to want to fall back onto the property name. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="Name" /> property, /// but a public static property with a name matching the <see cref="Name" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetName() => _name.GetLocalizableValue(); /// <summary> /// Gets the UI display string for Description. /// <para> /// This can be either a literal, non-localized string provided to <see cref="Description" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Description" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="Description" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="Description" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="Description" /> property, /// but a public static property with a name matching the <see cref="Description" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetDescription() => _description.GetLocalizableValue(); /// <summary> /// Gets the UI display string for Prompt. /// <para> /// This can be either a literal, non-localized string provided to <see cref="Prompt" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Prompt" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="Prompt" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="Prompt" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="Prompt" /> property, /// but a public static property with a name matching the <see cref="Prompt" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetPrompt() => _prompt.GetLocalizableValue(); /// <summary> /// Gets the UI display string for GroupName. /// <para> /// This can be either a literal, non-localized string provided to <see cref="GroupName" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="GroupName" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="GroupName" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="GroupName" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="GroupName" /> property, /// but a public static property with a name matching the <see cref="GroupName" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetGroupName() => _groupName.GetLocalizableValue(); /// <summary> /// Gets the value of <see cref="AutoGenerateField" /> if it has been set, or <c>null</c>. /// </summary> /// <returns> /// When <see cref="AutoGenerateField" /> has been set returns the value of that property. /// <para> /// When <see cref="AutoGenerateField" /> has not been set returns <c>null</c>. /// </para> /// </returns> public bool? GetAutoGenerateField() => _autoGenerateField; /// <summary> /// Gets the value of <see cref="AutoGenerateFilter" /> if it has been set, or <c>null</c>. /// </summary> /// <returns> /// When <see cref="AutoGenerateFilter" /> has been set returns the value of that property. /// <para> /// When <see cref="AutoGenerateFilter" /> has not been set returns <c>null</c>. /// </para> /// </returns> public bool? GetAutoGenerateFilter() => _autoGenerateFilter; /// <summary> /// Gets the value of <see cref="Order" /> if it has been set, or <c>null</c>. /// </summary> /// <returns> /// When <see cref="Order" /> has been set returns the value of that property. /// <para> /// When <see cref="Order" /> has not been set returns <c>null</c>. /// </para> /// </returns> /// <remarks> /// When an order is not specified, presentation layers should consider using the value /// of 10000. This value allows for explicitly-ordered fields to be displayed before /// and after the fields that don't specify an order. /// </remarks> public int? GetOrder() => _order; #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; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; // // Note: F# compiler depends on the exact tuple hashing algorithm. Do not ever change it. // namespace System { /// <summary> /// Helper so we can call some tuple methods recursively without knowing the underlying types. /// </summary> internal interface ITupleInternal : ITuple { string ToString(StringBuilder sb); int GetHashCode(IEqualityComparer comparer); } public static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3>(item1, item2, item3); } public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) { return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4); } public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5); } public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6); } public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7); } public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8)); } // From System.Web.Util.HashCodeCombiner internal static int CombineHashCodes(int h1, int h2) { return (((h1 << 5) + h1) ^ h2); } internal static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, ObjectEqualityComparer.Default); } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1> objTuple = other as Tuple<T1>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, LowLevelComparer.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1> objTuple = other as Tuple<T1>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } return comparer.Compare(m_Item1, objTuple.m_Item1); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(ObjectEqualityComparer.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(m_Item1); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 1; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return Item1; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T2 m_Item2; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, ObjectEqualityComparer.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2> objTuple = other as Tuple<T1, T2>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, LowLevelComparer.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2> objTuple = other as Tuple<T1, T2>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; return comparer.Compare(m_Item2, objTuple.m_Item2); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(ObjectEqualityComparer.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 2; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T2 m_Item2; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T3 m_Item3; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public Tuple(T1 item1, T2 item2, T3 item3) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, ObjectEqualityComparer.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, LowLevelComparer.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; return comparer.Compare(m_Item3, objTuple.m_Item3); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(ObjectEqualityComparer.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 3; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T2 m_Item2; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T3 m_Item3; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T4 m_Item4; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, ObjectEqualityComparer.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, LowLevelComparer.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; return comparer.Compare(m_Item4, objTuple.m_Item4); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(ObjectEqualityComparer.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 4; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T2 m_Item2; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T3 m_Item3; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T4 m_Item4; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T5 m_Item5; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public T5 Item5 { get { return m_Item5; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, ObjectEqualityComparer.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, LowLevelComparer.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; return comparer.Compare(m_Item5, objTuple.m_Item5); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(ObjectEqualityComparer.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 5; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T2 m_Item2; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T3 m_Item3; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T4 m_Item4; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T5 m_Item5; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T6 m_Item6; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public T5 Item5 { get { return m_Item5; } } public T6 Item6 { get { return m_Item6; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, ObjectEqualityComparer.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, LowLevelComparer.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; return comparer.Compare(m_Item6, objTuple.m_Item6); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(ObjectEqualityComparer.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 6; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; case 5: return Item6; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T2 m_Item2; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T3 m_Item3; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T4 m_Item4; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T5 m_Item5; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T6 m_Item6; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T7 m_Item7; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public T5 Item5 { get { return m_Item5; } } public T6 Item6 { get { return m_Item6; } } public T7 Item7 { get { return m_Item7; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, ObjectEqualityComparer.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, LowLevelComparer.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; c = comparer.Compare(m_Item6, objTuple.m_Item6); if (c != 0) return c; return comparer.Compare(m_Item7, objTuple.m_Item7); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(ObjectEqualityComparer.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7)); } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 7; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; case 5: return Item6; case 6: return Item7; default: throw new IndexOutOfRangeException(); } } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T2 m_Item2; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T3 m_Item3; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T4 m_Item4; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T5 m_Item5; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T6 m_Item6; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly T7 m_Item7; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. private readonly TRest m_Rest; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload. public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public T3 Item3 { get { return m_Item3; } } public T4 Item4 { get { return m_Item4; } } public T5 Item5 { get { return m_Item5; } } public T6 Item6 { get { return m_Item6; } } public T7 Item7 { get { return m_Item7; } } public TRest Rest { get { return m_Rest; } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { if (!(rest is ITupleInternal)) { throw new ArgumentException(SR.ArgumentException_TupleLastArgumentNotATuple); } m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; m_Rest = rest; } public override Boolean Equals(Object obj) { return ((IStructuralEquatable)this).Equals(obj, ObjectEqualityComparer.Default); ; } Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>; if (objTuple == null) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest); } Int32 IComparable.CompareTo(Object obj) { return ((IStructuralComparable)this).CompareTo(obj, LowLevelComparer.Default); } Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { if (other == null) return 1; Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>; if (objTuple == null) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; c = comparer.Compare(m_Item6, objTuple.m_Item6); if (c != 0) return c; c = comparer.Compare(m_Item7, objTuple.m_Item7); if (c != 0) return c; return comparer.Compare(m_Rest, objTuple.m_Rest); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(ObjectEqualityComparer.Default); } Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple ITupleInternal t = (ITupleInternal)m_Rest; if (t.Length >= 8) { return t.GetHashCode(comparer); } // In this case, the rest memeber has less than 8 elements so we need to combine some our elements with the elements in rest int k = 8 - t.Length; switch (k) { case 1: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 2: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 3: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 4: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 5: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 6: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); case 7: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer)); } Debug.Assert(false, "Missed all cases for computing Tuple hash code"); return -1; } Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(", "); return ((ITupleInternal)m_Rest).ToString(sb); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length { get { return 7 + ((ITupleInternal)Rest).Length; } } /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; case 5: return Item6; case 6: return Item7; } return ((ITupleInternal)Rest)[index - 7]; } } } }
/* * 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.RDS.Model { /// <summary> /// Container for the parameters to the DescribeDBEngineVersions operation. /// <para> Returns a list of the available DB engines. </para> /// </summary> /// <seealso cref="Amazon.RDS.AmazonRDS.DescribeDBEngineVersions"/> public class DescribeDBEngineVersionsRequest : AmazonWebServiceRequest { private string engine; private string engineVersion; private string dBParameterGroupFamily; private int? maxRecords; private string marker; private bool? defaultOnly; private bool? listSupportedCharacterSets; /// <summary> /// The database engine to return. /// /// </summary> public string Engine { get { return this.engine; } set { this.engine = value; } } /// <summary> /// Sets the Engine property /// </summary> /// <param name="engine">The value to set for the Engine 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 DescribeDBEngineVersionsRequest WithEngine(string engine) { this.engine = engine; return this; } // Check to see if Engine property is set internal bool IsSetEngine() { return this.engine != null; } /// <summary> /// The database engine version to return. Example: <c>5.1.49</c> /// /// </summary> public string EngineVersion { get { return this.engineVersion; } set { this.engineVersion = value; } } /// <summary> /// Sets the EngineVersion property /// </summary> /// <param name="engineVersion">The value to set for the EngineVersion 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 DescribeDBEngineVersionsRequest WithEngineVersion(string engineVersion) { this.engineVersion = engineVersion; return this; } // Check to see if EngineVersion property is set internal bool IsSetEngineVersion() { return this.engineVersion != null; } /// <summary> /// The name of a specific DB Parameter Group family to return details for. Constraints: <ul> <li>Must be 1 to 255 alphanumeric characters</li> /// <li>First character must be a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li> </ul> /// /// </summary> public string DBParameterGroupFamily { get { return this.dBParameterGroupFamily; } set { this.dBParameterGroupFamily = value; } } /// <summary> /// Sets the DBParameterGroupFamily property /// </summary> /// <param name="dBParameterGroupFamily">The value to set for the DBParameterGroupFamily 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 DescribeDBEngineVersionsRequest WithDBParameterGroupFamily(string dBParameterGroupFamily) { this.dBParameterGroupFamily = dBParameterGroupFamily; return this; } // Check to see if DBParameterGroupFamily property is set internal bool IsSetDBParameterGroupFamily() { return this.dBParameterGroupFamily != null; } /// <summary> /// The maximum number of records to include in the response. If more than the <c>MaxRecords</c> value is available, a pagination token called a /// marker is included in the response so that the following results can be retrieved. Default: 100 Constraints: minimum 20, maximum 100 /// /// </summary> public int MaxRecords { get { return this.maxRecords ?? default(int); } set { this.maxRecords = value; } } /// <summary> /// Sets the MaxRecords property /// </summary> /// <param name="maxRecords">The value to set for the MaxRecords 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 DescribeDBEngineVersionsRequest WithMaxRecords(int maxRecords) { this.maxRecords = maxRecords; return this; } // Check to see if MaxRecords property is set internal bool IsSetMaxRecords() { return this.maxRecords.HasValue; } /// <summary> /// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the /// marker, up to the value specified by <c>MaxRecords</c>. /// /// </summary> public string Marker { get { return this.marker; } set { this.marker = value; } } /// <summary> /// Sets the Marker property /// </summary> /// <param name="marker">The value to set for the Marker 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 DescribeDBEngineVersionsRequest WithMarker(string marker) { this.marker = marker; return this; } // Check to see if Marker property is set internal bool IsSetMarker() { return this.marker != null; } /// <summary> /// Indicates that only the default version of the specified engine or engine and major version combination is returned. /// /// </summary> public bool DefaultOnly { get { return this.defaultOnly ?? default(bool); } set { this.defaultOnly = value; } } /// <summary> /// Sets the DefaultOnly property /// </summary> /// <param name="defaultOnly">The value to set for the DefaultOnly 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 DescribeDBEngineVersionsRequest WithDefaultOnly(bool defaultOnly) { this.defaultOnly = defaultOnly; return this; } // Check to see if DefaultOnly property is set internal bool IsSetDefaultOnly() { return this.defaultOnly.HasValue; } /// <summary> /// If this parameter is specified, and if the requested engine supports the CharacterSetName parameter for CreateDBInstance, the response /// includes a list of supported character sets for each engine version. /// /// </summary> public bool ListSupportedCharacterSets { get { return this.listSupportedCharacterSets ?? default(bool); } set { this.listSupportedCharacterSets = value; } } /// <summary> /// Sets the ListSupportedCharacterSets property /// </summary> /// <param name="listSupportedCharacterSets">The value to set for the ListSupportedCharacterSets 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 DescribeDBEngineVersionsRequest WithListSupportedCharacterSets(bool listSupportedCharacterSets) { this.listSupportedCharacterSets = listSupportedCharacterSets; return this; } // Check to see if ListSupportedCharacterSets property is set internal bool IsSetListSupportedCharacterSets() { return this.listSupportedCharacterSets.HasValue; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ReverseQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Reverse imposes ordinal order preservation. There are normally two phases to this /// operator's execution. Each partition first builds a buffer containing all of its /// elements, and then proceeds to yielding the elements in reverse. There is a /// 'barrier' (but not a blocking barrier) in between these two steps, at which point the largest index becomes /// known. This is necessary so that when elements from the buffer are yielded, the /// CurrentIndex can be reported as the largest index minus the original index (thereby /// reversing the indices as well as the elements themselves). If the largest index is /// known a priori, because we have an array for example, we can avoid the barrier in /// between the steps. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class ReverseQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource> { //--------------------------------------------------------------------------------------- // Initializes a new reverse operator. // // Arguments: // child - the child whose data we will reverse // internal ReverseQueryOperator(IEnumerable<TSource> child) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); if (Child.OrdinalIndexState == OrdinalIndexState.Indexable) { SetOrdinalIndexState(OrdinalIndexState.Indexable); } else { SetOrdinalIndexState(OrdinalIndexState.Shuffled); } } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings) { Debug.Assert(Child.OrdinalIndexState != OrdinalIndexState.Indexable, "Don't take this code path if the child is indexable."); int partitionCount = inputStream.PartitionCount; PartitionedStream<TSource, TKey> outputStream = new PartitionedStream<TSource, TKey>( partitionCount, new ReverseComparer<TKey>(inputStream.KeyComparer), OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ReverseQueryOperatorEnumerator<TKey>(inputStream[i], settings.CancellationState.MergedCancellationToken); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { QueryResults<TSource> childQueryResults = Child.Open(settings, false); return ReverseQueryOperatorResults.NewResults(childQueryResults, this, settings, preferStriping); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { IEnumerable<TSource> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.Reverse(); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the reverse operation. // private class ReverseQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TSource, TKey> { private readonly QueryOperatorEnumerator<TSource, TKey> _source; // The data source to reverse. private readonly CancellationToken _cancellationToken; private List<Pair<TSource, TKey>>? _buffer; // Our buffer. [allocate in moveNext to avoid false-sharing] private Shared<int>? _bufferIndex; // Our current index within the buffer. [allocate in moveNext to avoid false-sharing] //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal ReverseQueryOperatorEnumerator(QueryOperatorEnumerator<TSource, TKey> source, CancellationToken cancellationToken) { Debug.Assert(source != null); _source = source; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TSource currentElement, ref TKey currentKey) { // If the buffer has not been created, we will generate it lazily on demand. if (_buffer == null) { _bufferIndex = new Shared<int>(0); // Buffer all of our data. _buffer = new List<Pair<TSource, TKey>>(); TSource current = default(TSource)!; TKey key = default(TKey)!; int i = 0; while (_source.MoveNext(ref current!, ref key)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); _buffer.Add(new Pair<TSource, TKey>(current, key)); _bufferIndex.Value++; } } Debug.Assert(_bufferIndex != null); // Continue yielding elements from our buffer. if (--_bufferIndex.Value >= 0) { currentElement = _buffer[_bufferIndex.Value].First; currentKey = _buffer[_bufferIndex.Value].Second; return true; } return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } //----------------------------------------------------------------------------------- // Query results for a Reverse operator. The results are indexable if the child // results were indexable. // private class ReverseQueryOperatorResults : UnaryQueryOperatorResults { private readonly int _count; // The number of elements in child results public static QueryResults<TSource> NewResults( QueryResults<TSource> childQueryResults, ReverseQueryOperator<TSource> op, QuerySettings settings, bool preferStriping) { if (childQueryResults.IsIndexible) { return new ReverseQueryOperatorResults( childQueryResults, op, settings, preferStriping); } else { return new UnaryQueryOperatorResults( childQueryResults, op, settings, preferStriping); } } private ReverseQueryOperatorResults( QueryResults<TSource> childQueryResults, ReverseQueryOperator<TSource> op, QuerySettings settings, bool preferStriping) : base(childQueryResults, op, settings, preferStriping) { Debug.Assert(_childQueryResults.IsIndexible); _count = _childQueryResults.ElementsCount; } internal override bool IsIndexible { get { return true; } } internal override int ElementsCount { get { Debug.Assert(_count >= 0); return _count; } } internal override TSource GetElement(int index) { Debug.Assert(_count >= 0); Debug.Assert(index >= 0); Debug.Assert(index < _count); return _childQueryResults.GetElement(_count - index - 1); } } } }
// 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.Reflection.Emit.MethodBuilder.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.Reflection.Emit { sealed public partial class MethodBuilder : System.Reflection.MethodInfo, System.Runtime.InteropServices._MethodBuilder { #region Methods and constructors public void AddDeclarativeSecurity(System.Security.Permissions.SecurityAction action, System.Security.PermissionSet pset) { } public void CreateMethodBody(byte[] il, int count) { } public GenericTypeParameterBuilder[] DefineGenericParameters(string[] names) { Contract.Ensures(Contract.Result<System.Reflection.Emit.GenericTypeParameterBuilder[]>() != null); return default(GenericTypeParameterBuilder[]); } public ParameterBuilder DefineParameter(int position, System.Reflection.ParameterAttributes attributes, string strParamName) { Contract.Ensures(Contract.Result<System.Reflection.Emit.ParameterBuilder>() != null); return default(ParameterBuilder); } public override bool Equals(Object obj) { return default(bool); } public override System.Reflection.MethodInfo GetBaseDefinition() { return default(System.Reflection.MethodInfo); } public override Object[] GetCustomAttributes(bool inherit) { return default(Object[]); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return default(Object[]); } public override Type[] GetGenericArguments() { return default(Type[]); } public override System.Reflection.MethodInfo GetGenericMethodDefinition() { return default(System.Reflection.MethodInfo); } public override int GetHashCode() { return default(int); } public ILGenerator GetILGenerator(int size) { Contract.Ensures(Contract.Result<System.Reflection.Emit.ILGenerator>() != null); return default(ILGenerator); } public ILGenerator GetILGenerator() { Contract.Ensures(Contract.Result<System.Reflection.Emit.ILGenerator>() != null); return default(ILGenerator); } public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { return default(System.Reflection.MethodImplAttributes); } public System.Reflection.Module GetModule() { return default(System.Reflection.Module); } public override System.Reflection.ParameterInfo[] GetParameters() { return default(System.Reflection.ParameterInfo[]); } public MethodToken GetToken() { return default(MethodToken); } public override Object Invoke(Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, Object[] parameters, System.Globalization.CultureInfo culture) { return default(Object); } public override bool IsDefined(Type attributeType, bool inherit) { return default(bool); } public override System.Reflection.MethodInfo MakeGenericMethod(Type[] typeArguments) { return default(System.Reflection.MethodInfo); } internal MethodBuilder() { } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { } public void SetMarshal(UnmanagedMarshal unmanagedMarshal) { } public void SetParameters(Type[] parameterTypes) { } public void SetReturnType(Type returnType) { } public void SetSignature(Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { } public void SetSymCustomAttribute(string name, byte[] data) { } void System.Runtime.InteropServices._MethodBuilder.GetIDsOfNames(ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { } void System.Runtime.InteropServices._MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { } void System.Runtime.InteropServices._MethodBuilder.GetTypeInfoCount(out uint pcTInfo) { pcTInfo = default(uint); } void System.Runtime.InteropServices._MethodBuilder.Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { } public override string ToString() { return default(string); } #endregion #region Properties and indexers public override System.Reflection.MethodAttributes Attributes { get { return default(System.Reflection.MethodAttributes); } } public override System.Reflection.CallingConventions CallingConvention { get { return default(System.Reflection.CallingConventions); } } public override bool ContainsGenericParameters { get { return default(bool); } } public override Type DeclaringType { get { return default(Type); } } public bool InitLocals { get { return default(bool); } set { } } public override bool IsGenericMethod { get { return default(bool); } } public override bool IsGenericMethodDefinition { get { return default(bool); } } public override bool IsSecurityCritical { get { return default(bool); } } public override bool IsSecuritySafeCritical { get { return default(bool); } } public override bool IsSecurityTransparent { get { return default(bool); } } public override RuntimeMethodHandle MethodHandle { get { return default(RuntimeMethodHandle); } } public override System.Reflection.Module Module { get { return default(System.Reflection.Module); } } public override string Name { get { return default(string); } } public override Type ReflectedType { get { return default(Type); } } public override System.Reflection.ParameterInfo ReturnParameter { get { return default(System.Reflection.ParameterInfo); } } public override Type ReturnType { get { return default(Type); } } public override System.Reflection.ICustomAttributeProvider ReturnTypeCustomAttributes { get { return default(System.Reflection.ICustomAttributeProvider); } } public string Signature { get { return default(string); } } #endregion } }
using System; using System.Collections.Generic; namespace FairyGUI { /// <summary> /// /// </summary> public class GTreeNode { /// <summary> /// /// </summary> public object data; /// <summary> /// /// </summary> public GTreeNode parent { get; private set; } /// <summary> /// /// </summary> public GTree tree { get; private set; } List<GTreeNode> _children; bool _expanded; int _level; internal GComponent _cell; internal string _resURL; /// <summary> /// /// </summary> /// <param name="hasChild"></param> public GTreeNode(bool hasChild) : this(hasChild, null) { } /// <summary> /// /// </summary> /// <param name="hasChild"></param> /// <param name="resURL"></param> public GTreeNode(bool hasChild, string resURL) { if (hasChild) _children = new List<GTreeNode>(); _resURL = resURL; } /// <summary> /// /// </summary> public GComponent cell { get { return _cell; } } /// <summary> /// /// </summary> public int level { get { return _level; } } /// <summary> /// /// </summary> public bool expanded { get { return _expanded; } set { if (_children == null) return; if (_expanded != value) { _expanded = value; if (tree != null) { if (_expanded) tree._AfterExpanded(this); else tree._AfterCollapsed(this); } } } } /// <summary> /// /// </summary> public void ExpandToRoot() { GTreeNode p = this; while (p != null) { p.expanded = true; p = p.parent; } } /// <summary> /// /// </summary> public bool isFolder { get { return _children != null; } } /// <summary> /// /// </summary> public string text { get { if (_cell != null) return _cell.text; else return null; } set { if (_cell != null) _cell.text = value; } } /// <summary> /// /// </summary> public string icon { get { if (_cell != null) return _cell.icon; else return null; } set { if (_cell != null) _cell.icon = value; } } /// <summary> /// /// </summary> /// <param name="child"></param> /// <returns></returns> public GTreeNode AddChild(GTreeNode child) { AddChildAt(child, _children.Count); return child; } /// <summary> /// /// </summary> /// <param name="child"></param> /// <param name="index"></param> /// <returns></returns> public GTreeNode AddChildAt(GTreeNode child, int index) { if (child == null) throw new Exception("child is null"); int numChildren = _children.Count; if (index >= 0 && index <= numChildren) { if (child.parent == this) { SetChildIndex(child, index); } else { if (child.parent != null) child.parent.RemoveChild(child); int cnt = _children.Count; if (index == cnt) _children.Add(child); else _children.Insert(index, child); child.parent = this; child._level = _level + 1; child._SetTree(this.tree); if (tree != null && this == tree.rootNode || _cell != null && _cell.parent != null && _expanded) tree._AfterInserted(child); } return child; } else { throw new Exception("Invalid child index"); } } /// <summary> /// /// </summary> /// <param name="child"></param> /// <returns></returns> public GTreeNode RemoveChild(GTreeNode child) { int childIndex = _children.IndexOf(child); if (childIndex != -1) { RemoveChildAt(childIndex); } return child; } /// <summary> /// /// </summary> /// <param name="index"></param> /// <returns></returns> public GTreeNode RemoveChildAt(int index) { if (index >= 0 && index < numChildren) { GTreeNode child = _children[index]; _children.RemoveAt(index); child.parent = null; if (tree != null) { child._SetTree(null); tree._AfterRemoved(child); } return child; } else { throw new Exception("Invalid child index"); } } /// <summary> /// /// </summary> /// <param name="beginIndex"></param> /// <param name="endIndex"></param> public void RemoveChildren(int beginIndex = 0, int endIndex = -1) { if (endIndex < 0 || endIndex >= numChildren) endIndex = numChildren - 1; for (int i = beginIndex; i <= endIndex; ++i) RemoveChildAt(beginIndex); } /// <summary> /// /// </summary> /// <param name="index"></param> /// <returns></returns> public GTreeNode GetChildAt(int index) { if (index >= 0 && index < numChildren) return _children[index]; else throw new Exception("Invalid child index"); } /// <summary> /// /// </summary> /// <param name="child"></param> /// <returns></returns> public int GetChildIndex(GTreeNode child) { return _children.IndexOf(child); } /// <summary> /// /// </summary> /// <returns></returns> public GTreeNode GetPrevSibling() { if (parent == null) return null; int i = parent._children.IndexOf(this); if (i <= 0) return null; return parent._children[i - 1]; } /// <summary> /// /// </summary> /// <returns></returns> public GTreeNode GetNextSibling() { if (parent == null) return null; int i = parent._children.IndexOf(this); if (i < 0 || i >= parent._children.Count - 1) return null; return parent._children[i + 1]; } /// <summary> /// /// </summary> /// <param name="child"></param> /// <param name="index"></param> public void SetChildIndex(GTreeNode child, int index) { int oldIndex = _children.IndexOf(child); if (oldIndex == -1) throw new Exception("Not a child of this container"); int cnt = _children.Count; if (index < 0) index = 0; else if (index > cnt) index = cnt; if (oldIndex == index) return; _children.RemoveAt(oldIndex); _children.Insert(index, child); if (tree != null && this == tree.rootNode || _cell != null && _cell.parent != null && _expanded) tree._AfterMoved(child); } /// <summary> /// /// </summary> /// <param name="child1"></param> /// <param name="child2"></param> public void SwapChildren(GTreeNode child1, GTreeNode child2) { int index1 = _children.IndexOf(child1); int index2 = _children.IndexOf(child2); if (index1 == -1 || index2 == -1) throw new Exception("Not a child of this container"); SwapChildrenAt(index1, index2); } /// <summary> /// /// </summary> /// <param name="index1"></param> /// <param name="index2"></param> public void SwapChildrenAt(int index1, int index2) { GTreeNode child1 = _children[index1]; GTreeNode child2 = _children[index2]; SetChildIndex(child1, index2); SetChildIndex(child2, index1); } /// <summary> /// /// </summary> public int numChildren { get { return (null == _children) ? 0 : _children.Count; } } internal void _SetTree(GTree value) { tree = value; if (tree != null && tree.treeNodeWillExpand != null && _expanded) tree.treeNodeWillExpand(this, true); if (_children != null) { int cnt = _children.Count; for (int i = 0; i < cnt; i++) { GTreeNode node = _children[i]; node._level = _level + 1; node._SetTree(value); } } } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// ScreenRecordingSegment /// </summary> [DataContract] public partial class ScreenRecordingSegment : IEquatable<ScreenRecordingSegment>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ScreenRecordingSegment" /> class. /// </summary> /// <param name="createDts">createDts.</param> /// <param name="description">description.</param> /// <param name="filter">filter.</param> /// <param name="histogramData">histogramData.</param> /// <param name="histogramInterval">histogramInterval.</param> /// <param name="histogramStartDts">histogramStartDts.</param> /// <param name="name">name.</param> /// <param name="screenRecordingSegmentOid">screenRecordingSegmentOid.</param> /// <param name="sessionCount">sessionCount.</param> /// <param name="sessionCountLastUpdateDts">sessionCountLastUpdateDts.</param> public ScreenRecordingSegment(string createDts = default(string), string description = default(string), ScreenRecordingFilter filter = default(ScreenRecordingFilter), List<int?> histogramData = default(List<int?>), string histogramInterval = default(string), string histogramStartDts = default(string), string name = default(string), int? screenRecordingSegmentOid = default(int?), int? sessionCount = default(int?), string sessionCountLastUpdateDts = default(string)) { this.CreateDts = createDts; this.Description = description; this.Filter = filter; this.HistogramData = histogramData; this.HistogramInterval = histogramInterval; this.HistogramStartDts = histogramStartDts; this.Name = name; this.ScreenRecordingSegmentOid = screenRecordingSegmentOid; this.SessionCount = sessionCount; this.SessionCountLastUpdateDts = sessionCountLastUpdateDts; } /// <summary> /// Gets or Sets CreateDts /// </summary> [DataMember(Name="create_dts", EmitDefaultValue=false)] public string CreateDts { get; set; } /// <summary> /// Gets or Sets Description /// </summary> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// Gets or Sets Filter /// </summary> [DataMember(Name="filter", EmitDefaultValue=false)] public ScreenRecordingFilter Filter { get; set; } /// <summary> /// Gets or Sets HistogramData /// </summary> [DataMember(Name="histogram_data", EmitDefaultValue=false)] public List<int?> HistogramData { get; set; } /// <summary> /// Gets or Sets HistogramInterval /// </summary> [DataMember(Name="histogram_interval", EmitDefaultValue=false)] public string HistogramInterval { get; set; } /// <summary> /// Gets or Sets HistogramStartDts /// </summary> [DataMember(Name="histogram_start_dts", EmitDefaultValue=false)] public string HistogramStartDts { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets ScreenRecordingSegmentOid /// </summary> [DataMember(Name="screen_recording_segment_oid", EmitDefaultValue=false)] public int? ScreenRecordingSegmentOid { get; set; } /// <summary> /// Gets or Sets SessionCount /// </summary> [DataMember(Name="session_count", EmitDefaultValue=false)] public int? SessionCount { get; set; } /// <summary> /// Gets or Sets SessionCountLastUpdateDts /// </summary> [DataMember(Name="session_count_last_update_dts", EmitDefaultValue=false)] public string SessionCountLastUpdateDts { 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 ScreenRecordingSegment {\n"); sb.Append(" CreateDts: ").Append(CreateDts).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Filter: ").Append(Filter).Append("\n"); sb.Append(" HistogramData: ").Append(HistogramData).Append("\n"); sb.Append(" HistogramInterval: ").Append(HistogramInterval).Append("\n"); sb.Append(" HistogramStartDts: ").Append(HistogramStartDts).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" ScreenRecordingSegmentOid: ").Append(ScreenRecordingSegmentOid).Append("\n"); sb.Append(" SessionCount: ").Append(SessionCount).Append("\n"); sb.Append(" SessionCountLastUpdateDts: ").Append(SessionCountLastUpdateDts).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 virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ScreenRecordingSegment); } /// <summary> /// Returns true if ScreenRecordingSegment instances are equal /// </summary> /// <param name="input">Instance of ScreenRecordingSegment to be compared</param> /// <returns>Boolean</returns> public bool Equals(ScreenRecordingSegment input) { if (input == null) return false; return ( this.CreateDts == input.CreateDts || (this.CreateDts != null && this.CreateDts.Equals(input.CreateDts)) ) && ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.Filter == input.Filter || (this.Filter != null && this.Filter.Equals(input.Filter)) ) && ( this.HistogramData == input.HistogramData || this.HistogramData != null && this.HistogramData.SequenceEqual(input.HistogramData) ) && ( this.HistogramInterval == input.HistogramInterval || (this.HistogramInterval != null && this.HistogramInterval.Equals(input.HistogramInterval)) ) && ( this.HistogramStartDts == input.HistogramStartDts || (this.HistogramStartDts != null && this.HistogramStartDts.Equals(input.HistogramStartDts)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.ScreenRecordingSegmentOid == input.ScreenRecordingSegmentOid || (this.ScreenRecordingSegmentOid != null && this.ScreenRecordingSegmentOid.Equals(input.ScreenRecordingSegmentOid)) ) && ( this.SessionCount == input.SessionCount || (this.SessionCount != null && this.SessionCount.Equals(input.SessionCount)) ) && ( this.SessionCountLastUpdateDts == input.SessionCountLastUpdateDts || (this.SessionCountLastUpdateDts != null && this.SessionCountLastUpdateDts.Equals(input.SessionCountLastUpdateDts)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.CreateDts != null) hashCode = hashCode * 59 + this.CreateDts.GetHashCode(); if (this.Description != null) hashCode = hashCode * 59 + this.Description.GetHashCode(); if (this.Filter != null) hashCode = hashCode * 59 + this.Filter.GetHashCode(); if (this.HistogramData != null) hashCode = hashCode * 59 + this.HistogramData.GetHashCode(); if (this.HistogramInterval != null) hashCode = hashCode * 59 + this.HistogramInterval.GetHashCode(); if (this.HistogramStartDts != null) hashCode = hashCode * 59 + this.HistogramStartDts.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.ScreenRecordingSegmentOid != null) hashCode = hashCode * 59 + this.ScreenRecordingSegmentOid.GetHashCode(); if (this.SessionCount != null) hashCode = hashCode * 59 + this.SessionCount.GetHashCode(); if (this.SessionCountLastUpdateDts != null) hashCode = hashCode * 59 + this.SessionCountLastUpdateDts.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using ServiceStack.CacheAccess; using ServiceStack.CacheAccess.Providers; using ServiceStack.Common; using ServiceStack.Common.Web; using ServiceStack.DependencyInjection; using ServiceStack.Html; using ServiceStack.IO; using ServiceStack.Messaging; using ServiceStack.MiniProfiler; using ServiceStack.ServiceHost; using ServiceStack.VirtualPath; using ServiceStack.ServiceModel.Serialization; using ServiceStack.WebHost.Endpoints.Extensions; using ServiceStack.WebHost.Endpoints.Formats; using ServiceStack.WebHost.Endpoints.Support; using ServiceStack.WebHost.Endpoints.Utils; namespace ServiceStack.WebHost.Endpoints { public class EndpointHost { public static IAppHost AppHost { get; internal set; } public static IContentTypeFilter ContentTypeFilter { get; set; } public static List<Action<IHttpRequest, IHttpResponse>> RawRequestFilters { get; private set; } public static List<Action<IHttpRequest, IHttpResponse, object>> RequestFilters { get; private set; } public static List<Action<IHttpRequest, IHttpResponse, object>> ResponseFilters { get; private set; } public static List<IViewEngine> ViewEngines { get; set; } //TODO: rename to UncaughtExceptionsHandler public static HandleUncaughtExceptionDelegate ExceptionHandler { get; set; } //TODO: rename to ServiceExceptionsHandler public static HandleServiceExceptionDelegate ServiceExceptionHandler { get; set; } public static List<HttpHandlerResolverDelegate> CatchAllHandlers { get; set; } private static bool pluginsLoaded = false; public static List<IPlugin> Plugins { get; set; } public static IVirtualPathProvider VirtualPathProvider { get; set; } public static DateTime StartedAt { get; set; } public static DateTime ReadyAt { get; set; } private static void Reset() { ContentTypeFilter = HttpResponseFilter.Instance; RawRequestFilters = new List<Action<IHttpRequest, IHttpResponse>>(); RequestFilters = new List<Action<IHttpRequest, IHttpResponse, object>>(); ResponseFilters = new List<Action<IHttpRequest, IHttpResponse, object>>(); ViewEngines = new List<IViewEngine>(); CatchAllHandlers = new List<HttpHandlerResolverDelegate>(); Plugins = new List<IPlugin> { new HtmlFormat(), new CsvFormat(), new MarkdownFormat(), new PredefinedRoutesFeature(), new MetadataFeature(), }; //Default Config for projects that want to use components but not WebFramework (e.g. MVC) Config = new EndpointHostConfig( "Empty Config", new ServiceManager(new DependencyService(null), new ServiceController(null))); } // Pre user config public static void ConfigureHost(IAppHost appHost, string serviceName, ServiceManager serviceManager) { Reset(); AppHost = appHost; EndpointHostConfig.Instance.ServiceName = serviceName; EndpointHostConfig.Instance.ServiceManager = serviceManager; var config = EndpointHostConfig.Instance; Config = config; // avoid cross-dependency on Config setter VirtualPathProvider = new FileSystemVirtualPathProvider(AppHost, Config.WebHostPhysicalPath); Config.DebugMode = appHost.GetType().Assembly.IsDebugBuild(); if (Config.DebugMode) { Plugins.Add(new RequestInfoFeature()); } } // Config has changed private static void ApplyConfigChanges() { config.ServiceEndpointsMetadataConfig = ServiceEndpointsMetadataConfig.Create(config.ServiceStackHandlerFactoryPath); JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers; JsonDataContractDeserializer.Instance.UseBcl = config.UseBclJsonSerializers; } //After configure called public static void AfterInit() { StartedAt = DateTime.UtcNow; if (config.EnableFeatures != Feature.All) { if ((Feature.Xml & config.EnableFeatures) != Feature.Xml) config.IgnoreFormatsInMetadata.Add("xml"); if ((Feature.Json & config.EnableFeatures) != Feature.Json) config.IgnoreFormatsInMetadata.Add("json"); if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv) config.IgnoreFormatsInMetadata.Add("jsv"); if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) config.IgnoreFormatsInMetadata.Add("csv"); if ((Feature.Html & config.EnableFeatures) != Feature.Html) config.IgnoreFormatsInMetadata.Add("html"); if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11) config.IgnoreFormatsInMetadata.Add("soap11"); if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12) config.IgnoreFormatsInMetadata.Add("soap12"); } if ((Feature.Html & config.EnableFeatures) != Feature.Html) Plugins.RemoveAll(x => x is HtmlFormat); if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) Plugins.RemoveAll(x => x is CsvFormat); if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown) Plugins.RemoveAll(x => x is MarkdownFormat); if ((Feature.PredefinedRoutes & config.EnableFeatures) != Feature.PredefinedRoutes) Plugins.RemoveAll(x => x is PredefinedRoutesFeature); if ((Feature.Metadata & config.EnableFeatures) != Feature.Metadata) Plugins.RemoveAll(x => x is MetadataFeature); if ((Feature.RequestInfo & config.EnableFeatures) != Feature.RequestInfo) Plugins.RemoveAll(x => x is RequestInfoFeature); if ((Feature.Razor & config.EnableFeatures) != Feature.Razor) Plugins.RemoveAll(x => x is IRazorPlugin); //external if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf) Plugins.RemoveAll(x => x is IProtoBufPlugin); //external if ((Feature.MsgPack & config.EnableFeatures) != Feature.MsgPack) Plugins.RemoveAll(x => x is IMsgPackPlugin); //external if (ExceptionHandler == null) { ExceptionHandler = (httpReq, httpRes, operationName, ex) => { var errorMessage = String.Format("Error occured while Processing Request: {0}", ex.Message); var statusCode = ex.ToStatusCode(); //httpRes.WriteToResponse always calls .Close in it's finally statement so //if there is a problem writing to response, by now it will be closed if (!httpRes.IsClosed) { httpRes.WriteErrorToResponse(httpReq, httpReq.ResponseContentType, operationName, errorMessage, ex, statusCode); } }; } if (config.ServiceStackHandlerFactoryPath != null) config.ServiceStackHandlerFactoryPath = config.ServiceStackHandlerFactoryPath.TrimStart('/'); var specifiedContentType = config.DefaultContentType; //Before plugins loaded ConfigurePlugins(); AppHost.LoadPlugin(Plugins.ToArray()); pluginsLoaded = true; AfterPluginsLoaded(specifiedContentType); /* DAC fix and restore var registeredCacheClient = AppHost.TryResolve<ICacheClient>(); using (registeredCacheClient) { if (registeredCacheClient == null) { DependencyService.Register<ICacheClient>(new MemoryCacheClient()); } } var registeredMqService = AppHost.TryResolve<IMessageService>(); var registeredMqFactory = AppHost.TryResolve<IMessageFactory>(); if (registeredMqService != null && registeredMqFactory == null) { DependencyService.Register(c => registeredMqService.MessageFactory); } */ ReadyAt = DateTime.UtcNow; } public static T TryResolve<T>() { return AppHost != null ? AppHost.TryResolve<T>() : default(T); } /// <summary> /// The AppHost.DependencyService. Note: it is not thread safe to register dependencies after AppStart. /// </summary> public static DependencyService DependencyService { get { var aspHost = AppHost as AppHostBase; if (aspHost != null) return aspHost.DependencyService; var listenerHost = AppHost as HttpListenerBase; return listenerHost != null ? listenerHost.DependencyService : null; //testing may use alt AppHost } } private static void ConfigurePlugins() { //Some plugins need to initialize before other plugins are registered. foreach (var plugin in Plugins) { var preInitPlugin = plugin as IPreInitPlugin; if (preInitPlugin != null) { preInitPlugin.Configure(AppHost); } } } private static void AfterPluginsLoaded(string specifiedContentType) { if (!String.IsNullOrEmpty(specifiedContentType)) config.DefaultContentType = specifiedContentType; else if (String.IsNullOrEmpty(config.DefaultContentType)) config.DefaultContentType = ContentType.Json; config.ServiceManager.AfterInit(); ServiceManager = config.ServiceManager; //reset operations } public static T GetPlugin<T>() where T : class, IPlugin { return Plugins.FirstOrDefault(x => x is T) as T; } public static void AddPlugin(params IPlugin[] plugins) { if (pluginsLoaded) { AppHost.LoadPlugin(plugins); } else { foreach (var plugin in plugins) { Plugins.Add(plugin); } } } public static ServiceManager ServiceManager { get { return config.ServiceManager; } set { config.ServiceManager = value; } } private static EndpointHostConfig config; public static EndpointHostConfig Config { get { return config; } set { if (value.ServiceName == null) throw new ArgumentNullException("ServiceName"); if (value.ServiceController == null) throw new ArgumentNullException("ServiceController"); config = value; ApplyConfigChanges(); } } public static void AssertTestConfig(params Assembly[] assemblies) { if (Config != null) return; var config = EndpointHostConfig.Instance; config.ServiceName = "Test Services"; config.ServiceManager = new ServiceManager(config.ServiceManager.DependencyService, assemblies.Length == 0 ? new[] { Assembly.GetCallingAssembly() } : assemblies); Config = config; } public static bool DebugMode { get { return Config != null && Config.DebugMode; } } public static bool ReportExceptionStackTraces { get { return Config != null && Config.ReportExceptionStackTraces; } } public static ServiceMetadata Metadata { get { return Config.Metadata; } } /// <summary> /// Applies the raw request filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyPreRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes) { foreach (var requestFilter in RawRequestFilters) { requestFilter(httpReq, httpRes); if (httpRes.IsClosed) break; } return httpRes.IsClosed; } /// <summary> /// Applies the request filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes, object requestDto) { httpReq.ThrowIfNull("httpReq"); httpRes.ThrowIfNull("httpRes"); using (Profiler.Current.Step("Executing Request Filters")) { //Exec all RequestFilter attributes with Priority < 0 var attributes = FilterAttributeCache.GetRequestFilterAttributes(requestDto.GetType()); var i = 0; for (; i < attributes.Length && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; ServiceManager.DependencyService.AutoWire(attribute); attribute.RequestFilter(httpReq, httpRes, requestDto); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec global filters foreach (var requestFilter in RequestFilters) { requestFilter(httpReq, httpRes, requestDto); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec remaining RequestFilter attributes with Priority >= 0 for (; i < attributes.Length && attributes[i].Priority >= 0; i++) { var attribute = attributes[i]; ServiceManager.DependencyService.AutoWire(attribute); attribute.RequestFilter(httpReq, httpRes, requestDto); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } return httpRes.IsClosed; } } /// <summary> /// Applies the response filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyResponseFilters(IHttpRequest httpReq, IHttpResponse httpRes, object response) { httpReq.ThrowIfNull("httpReq"); httpRes.ThrowIfNull("httpRes"); using (Profiler.Current.Step("Executing Response Filters")) { var responseDto = response.ToResponseDto(); var attributes = responseDto != null ? FilterAttributeCache.GetResponseFilterAttributes(responseDto.GetType()) : null; //Exec all ResponseFilter attributes with Priority < 0 var i = 0; if (attributes != null) { for (; i < attributes.Length && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; ServiceManager.DependencyService.AutoWire(attribute); attribute.ResponseFilter(httpReq, httpRes, response); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } } //Exec global filters foreach (var responseFilter in ResponseFilters) { responseFilter(httpReq, httpRes, response); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec remaining RequestFilter attributes with Priority >= 0 if (attributes != null) { for (; i < attributes.Length; i++) { var attribute = attributes[i]; ServiceManager.DependencyService.AutoWire(attribute); attribute.ResponseFilter(httpReq, httpRes, response); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } } return httpRes.IsClosed; } } internal static object ExecuteService(object request, EndpointAttributes endpointAttributes, IHttpRequest httpReq, IHttpResponse httpRes) { using (Profiler.Current.Step("Execute Service")) { return config.ServiceController.Execute(request, new HttpRequestContext(httpReq, httpRes, request, endpointAttributes)); } } public static IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext) { return AppHost != null ? AppHost.CreateServiceRunner<TRequest>(actionContext) : new ServiceRunner<TRequest>(null, actionContext); } /// <summary> /// Call to signal the completion of a ServiceStack-handled Request /// </summary> internal static void CompleteRequest() { try { if (AppHost != null) { AppHost.OnEndRequest(); } } catch (Exception ex) { } } public static void Dispose() { AppHost = null; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// TaskActionsResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Autopilot.V1.Assistant.Task { public class TaskActionsResource : Resource { private static Request BuildFetchRequest(FetchTaskActionsOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Actions", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Returns JSON actions for the Task. /// </summary> /// <param name="options"> Fetch TaskActions parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TaskActions </returns> public static TaskActionsResource Fetch(FetchTaskActionsOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Returns JSON actions for the Task. /// </summary> /// <param name="options"> Fetch TaskActions parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TaskActions </returns> public static async System.Threading.Tasks.Task<TaskActionsResource> FetchAsync(FetchTaskActionsOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Returns JSON actions for the Task. /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task for which the task actions /// to fetch were defined </param> /// <param name="pathTaskSid"> The SID of the Task for which the task actions to fetch were defined </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TaskActions </returns> public static TaskActionsResource Fetch(string pathAssistantSid, string pathTaskSid, ITwilioRestClient client = null) { var options = new FetchTaskActionsOptions(pathAssistantSid, pathTaskSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Returns JSON actions for the Task. /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task for which the task actions /// to fetch were defined </param> /// <param name="pathTaskSid"> The SID of the Task for which the task actions to fetch were defined </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TaskActions </returns> public static async System.Threading.Tasks.Task<TaskActionsResource> FetchAsync(string pathAssistantSid, string pathTaskSid, ITwilioRestClient client = null) { var options = new FetchTaskActionsOptions(pathAssistantSid, pathTaskSid); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateTaskActionsOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Actions", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Updates the actions of an Task identified by {TaskSid} or {TaskUniqueName}. /// </summary> /// <param name="options"> Update TaskActions parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TaskActions </returns> public static TaskActionsResource Update(UpdateTaskActionsOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Updates the actions of an Task identified by {TaskSid} or {TaskUniqueName}. /// </summary> /// <param name="options"> Update TaskActions parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TaskActions </returns> public static async System.Threading.Tasks.Task<TaskActionsResource> UpdateAsync(UpdateTaskActionsOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Updates the actions of an Task identified by {TaskSid} or {TaskUniqueName}. /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task for which the task actions /// to update were defined </param> /// <param name="pathTaskSid"> The SID of the Task for which the task actions to update were defined </param> /// <param name="actions"> The JSON string that specifies the actions that instruct the Assistant on how to perform the /// task </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TaskActions </returns> public static TaskActionsResource Update(string pathAssistantSid, string pathTaskSid, object actions = null, ITwilioRestClient client = null) { var options = new UpdateTaskActionsOptions(pathAssistantSid, pathTaskSid){Actions = actions}; return Update(options, client); } #if !NET35 /// <summary> /// Updates the actions of an Task identified by {TaskSid} or {TaskUniqueName}. /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task for which the task actions /// to update were defined </param> /// <param name="pathTaskSid"> The SID of the Task for which the task actions to update were defined </param> /// <param name="actions"> The JSON string that specifies the actions that instruct the Assistant on how to perform the /// task </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TaskActions </returns> public static async System.Threading.Tasks.Task<TaskActionsResource> UpdateAsync(string pathAssistantSid, string pathTaskSid, object actions = null, ITwilioRestClient client = null) { var options = new UpdateTaskActionsOptions(pathAssistantSid, pathTaskSid){Actions = actions}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a TaskActionsResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> TaskActionsResource object represented by the provided JSON </returns> public static TaskActionsResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<TaskActionsResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Assistant that is the parent of the Task associated with the resource /// </summary> [JsonProperty("assistant_sid")] public string AssistantSid { get; private set; } /// <summary> /// The SID of the Task associated with the resource /// </summary> [JsonProperty("task_sid")] public string TaskSid { get; private set; } /// <summary> /// The absolute URL of the TaskActions resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The JSON string that specifies the actions that instruct the Assistant on how to perform the task /// </summary> [JsonProperty("data")] public object Data { get; private set; } private TaskActionsResource() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Sse2.IsSupported) { using (TestTable<double> doubleTable = new TestTable<double>(new double[2] { 1, -5 }, new double[2])) { var vf = Sse2.LoadAlignedVector128((double*)(doubleTable.inArrayPtr)); Unsafe.Write(doubleTable.outArrayPtr, vf); if (!doubleTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y))) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<int> intTable = new TestTable<int>(new int[4] { 1, -5, 100, 0 }, new int[4])) { var vf = Sse2.LoadAlignedVector128((int*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on int:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<long> longTable = new TestTable<long>(new long[2] { 1, -5 }, new long[2])) { var vf = Sse2.LoadAlignedVector128((long*)(longTable.inArrayPtr)); Unsafe.Write(longTable.outArrayPtr, vf); if (!longTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on long:"); foreach (var item in longTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<uint> uintTable = new TestTable<uint>(new uint[4] { 1, 5, 100, 0 }, new uint[4])) { var vf = Sse2.LoadAlignedVector128((uint*)(uintTable.inArrayPtr)); Unsafe.Write(uintTable.outArrayPtr, vf); if (!uintTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on uint:"); foreach (var item in uintTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<ulong> ulongTable = new TestTable<ulong>(new ulong[2] { 1, 5 }, new ulong[2])) { var vf = Sse2.LoadAlignedVector128((ulong*)(ulongTable.inArrayPtr)); Unsafe.Write(ulongTable.outArrayPtr, vf); if (!ulongTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on ulong:"); foreach (var item in ulongTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<short> shortTable = new TestTable<short>(new short[8] { 1, -5, 100, 0, 1, -5, 100, 0 }, new short[8])) { var vf = Sse2.LoadAlignedVector128((short*)(shortTable.inArrayPtr)); Unsafe.Write(shortTable.outArrayPtr, vf); if (!shortTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on short:"); foreach (var item in shortTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<ushort> ushortTable = new TestTable<ushort>(new ushort[8] { 1, 5, 100, 0, 1, 5, 100, 0 }, new ushort[8])) { var vf = Sse2.LoadAlignedVector128((ushort*)(ushortTable.inArrayPtr)); Unsafe.Write(ushortTable.outArrayPtr, vf); if (!ushortTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on ushort:"); foreach (var item in ushortTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<sbyte> sbyteTable = new TestTable<sbyte>(new sbyte[16] { 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0 }, new sbyte[16])) { var vf = Sse2.LoadAlignedVector128((sbyte*)(sbyteTable.inArrayPtr)); Unsafe.Write(sbyteTable.outArrayPtr, vf); if (!sbyteTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on sbyte:"); foreach (var item in sbyteTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<byte> byteTable = new TestTable<byte>(new byte[16] { 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0 }, new byte[16])) { var vf = Sse2.LoadAlignedVector128((byte*)(byteTable.inArrayPtr)); Unsafe.Write(byteTable.outArrayPtr, vf); if (!byteTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadAlignedVector128 failed on byte:"); foreach (var item in byteTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { private byte[] inArray; public T[] outArray; private GCHandle inHandle; private GCHandle outHandle; private byte simdSize; public TestTable(T[] a, T[] b) { this.inArray = new byte[32]; this.outArray = b; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.simdSize = 16; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<T, byte>(ref a[0]), this.simdSize); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), simdSize); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); public bool CheckResult(Func<T, T, bool> check) { for (int i = 0; i < outArray.Length; i++) { if (!check(Unsafe.Add<T>(ref Unsafe.AsRef<T>(inArrayPtr), i), outArray[i])) { return false; } } return true; } public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, byte expectedAlignment) { // Compute how bad the misalignment is, which is at most (expectedAlignment - 1). // Then subtract that from the expectedAlignment and add it to the original address // to compute the aligned address. var misalignment = expectedAlignment - ((ulong)(buffer) % expectedAlignment); return (void*)(buffer + misalignment); } } } }
using System; using System.IO; using System.Threading.Tasks; using GodotTools.Ides.Rider; using GodotTools.Internals; using JetBrains.Annotations; using static GodotTools.Internals.Globals; using File = GodotTools.Utils.File; using OS = GodotTools.Utils.OS; namespace GodotTools.Build { public static class BuildManager { private static BuildInfo _buildInProgress; public const string PropNameMSBuildMono = "MSBuild (Mono)"; public const string PropNameMSBuildVs = "MSBuild (VS Build Tools)"; public const string PropNameMSBuildJetBrains = "MSBuild (JetBrains Rider)"; public const string PropNameDotnetCli = "dotnet CLI"; public const string MsBuildIssuesFileName = "msbuild_issues.csv"; public const string MsBuildLogFileName = "msbuild_log.txt"; public delegate void BuildLaunchFailedEventHandler(BuildInfo buildInfo, string reason); public static event BuildLaunchFailedEventHandler BuildLaunchFailed; public static event Action<BuildInfo> BuildStarted; public static event Action<BuildResult> BuildFinished; public static event Action<string> StdOutputReceived; public static event Action<string> StdErrorReceived; private static void RemoveOldIssuesFile(BuildInfo buildInfo) { var issuesFile = GetIssuesFilePath(buildInfo); if (!File.Exists(issuesFile)) return; File.Delete(issuesFile); } private static void ShowBuildErrorDialog(string message) { var plugin = GodotSharpEditor.Instance; plugin.ShowErrorDialog(message, "Build error"); plugin.MakeBottomPanelItemVisible(plugin.MSBuildPanel); } public static void RestartBuild(BuildOutputView buildOutputView) => throw new NotImplementedException(); public static void StopBuild(BuildOutputView buildOutputView) => throw new NotImplementedException(); private static string GetLogFilePath(BuildInfo buildInfo) { return Path.Combine(buildInfo.LogsDirPath, MsBuildLogFileName); } private static string GetIssuesFilePath(BuildInfo buildInfo) { return Path.Combine(buildInfo.LogsDirPath, MsBuildIssuesFileName); } private static void PrintVerbose(string text) { if (Godot.OS.IsStdoutVerbose()) Godot.GD.Print(text); } public static bool Build(BuildInfo buildInfo) { if (_buildInProgress != null) throw new InvalidOperationException("A build is already in progress"); _buildInProgress = buildInfo; try { BuildStarted?.Invoke(buildInfo); // Required in order to update the build tasks list Internal.GodotMainIteration(); try { RemoveOldIssuesFile(buildInfo); } catch (IOException e) { BuildLaunchFailed?.Invoke(buildInfo, $"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}"); Console.Error.WriteLine(e); } try { int exitCode = BuildSystem.Build(buildInfo, StdOutputReceived, StdErrorReceived); if (exitCode != 0) PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}"); BuildFinished?.Invoke(exitCode == 0 ? BuildResult.Success : BuildResult.Error); return exitCode == 0; } catch (Exception e) { BuildLaunchFailed?.Invoke(buildInfo, $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}"); Console.Error.WriteLine(e); return false; } } finally { _buildInProgress = null; } } public static async Task<bool> BuildAsync(BuildInfo buildInfo) { if (_buildInProgress != null) throw new InvalidOperationException("A build is already in progress"); _buildInProgress = buildInfo; try { BuildStarted?.Invoke(buildInfo); try { RemoveOldIssuesFile(buildInfo); } catch (IOException e) { BuildLaunchFailed?.Invoke(buildInfo, $"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}"); Console.Error.WriteLine(e); } try { int exitCode = await BuildSystem.BuildAsync(buildInfo, StdOutputReceived, StdErrorReceived); if (exitCode != 0) PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}"); BuildFinished?.Invoke(exitCode == 0 ? BuildResult.Success : BuildResult.Error); return exitCode == 0; } catch (Exception e) { BuildLaunchFailed?.Invoke(buildInfo, $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}"); Console.Error.WriteLine(e); return false; } } finally { _buildInProgress = null; } } public static bool BuildProjectBlocking(string config, [CanBeNull] string[] targets = null, [CanBeNull] string platform = null) { var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, targets ?? new[] {"Build"}, config, restore: true); // If a platform was not specified, try determining the current one. If that fails, let MSBuild auto-detect it. if (platform != null || OS.PlatformNameMap.TryGetValue(Godot.OS.GetName(), out platform)) buildInfo.CustomProperties.Add($"GodotTargetPlatform={platform}"); if (Internal.GodotIsRealTDouble()) buildInfo.CustomProperties.Add("GodotRealTIsDouble=true"); return BuildProjectBlocking(buildInfo); } private static bool BuildProjectBlocking(BuildInfo buildInfo) { if (!File.Exists(buildInfo.Solution)) return true; // No solution to build // Make sure the API assemblies are up to date before building the project. // We may not have had the chance to update the release API assemblies, and the debug ones // may have been deleted by the user at some point after they were loaded by the Godot editor. string apiAssembliesUpdateError = Internal.UpdateApiAssembliesFromPrebuilt(buildInfo.Configuration == "ExportRelease" ? "Release" : "Debug"); if (!string.IsNullOrEmpty(apiAssembliesUpdateError)) { ShowBuildErrorDialog("Failed to update the Godot API assemblies"); return false; } using (var pr = new EditorProgress("mono_project_debug_build", "Building project solution...", 1)) { pr.Step("Building project solution", 0); if (!Build(buildInfo)) { ShowBuildErrorDialog("Failed to build project solution"); return false; } } return true; } public static bool EditorBuildCallback() { if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) return true; // No solution to build try { // Make sure our packages are added to the fallback folder NuGetUtils.AddBundledPackagesToFallbackFolder(NuGetUtils.GodotFallbackFolderPath); } catch (Exception e) { Godot.GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message); } if (GodotSharpEditor.Instance.SkipBuildBeforePlaying) return true; // Requested play from an external editor/IDE which already built the project return BuildProjectBlocking("Debug"); } public static void Initialize() { // Build tool settings var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); BuildTool msbuildDefault; if (OS.IsWindows) { if (RiderPathManager.IsExternalEditorSetToRider(editorSettings)) msbuildDefault = BuildTool.JetBrainsMsBuild; else msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildVs; } else { msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildMono; } EditorDef("mono/builds/build_tool", msbuildDefault); string hintString; if (OS.IsWindows) { hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," + $"{PropNameMSBuildVs}:{(int)BuildTool.MsBuildVs}," + $"{PropNameMSBuildJetBrains}:{(int)BuildTool.JetBrainsMsBuild}," + $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}"; } else { hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," + $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}"; } editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary { ["type"] = Godot.Variant.Type.Int, ["name"] = "mono/builds/build_tool", ["hint"] = Godot.PropertyHint.Enum, ["hint_string"] = hintString }); } } }
// Copyright (c) 2015 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.Generic; using System.Linq; using System.Text; using System.Threading; using System.IO; using System.Configuration; namespace Enyim.Caching { public class DiagnosticsLogFactory : ILogFactory { private TextWriter writer; public DiagnosticsLogFactory() : this(ConfigurationManager.AppSettings["Enyim.Caching.Diagnostics.LogPath"]) { } public DiagnosticsLogFactory(string logPath) { if (String.IsNullOrEmpty(logPath)) throw new ArgumentNullException( "Log path must be defined. Add the following to configuration/appSettings: <add key=\"Enyim.Caching.Diagnostics.LogPath\" " + "value=\"path to the log file\" /> or specify a valid path in in the constructor."); this.writer = new StreamWriter(logPath, true); } ILog ILogFactory.GetLogger(string name) { return new TextWriterLog(name, this.writer); } ILog ILogFactory.GetLogger(Type type) { return new TextWriterLog(type.FullName, this.writer); } } public class ConsoleLogFactory : ILogFactory { ILog ILogFactory.GetLogger(string name) { return new TextWriterLog(name, Console.Out); } ILog ILogFactory.GetLogger(Type type) { return new TextWriterLog(type.FullName, Console.Out); } } #region [ ILog implementation ] internal class TextWriterLog : ILog { private const string PrefixDebug = "DEBUG"; private const string PrefixInfo = "INFO"; private const string PrefixWarn = "WARN"; private const string PrefixError = "ERROR"; private const string PrefixFatal = "FATAL"; private TextWriter writer; private string name; public TextWriterLog(string name, TextWriter writer) { this.name = name; this.writer = writer; } private void Dump(string prefix, string message, params object[] args) { var line = String.Format("{0:yyyy-MM-dd' 'HH:mm:ss} [{1}] {2} {3} - ", DateTime.Now, prefix, Thread.CurrentThread.ManagedThreadId, this.name) + String.Format(message, args); lock (this.writer) { this.writer.WriteLine(line); this.writer.Flush(); } } private void Dump(string prefix, object message) { var line = String.Format("{0:yyyy-MM-dd' 'HH:mm:ss} [{1}] {2} {3} - {4}", DateTime.Now, prefix, Thread.CurrentThread.ManagedThreadId, this.name, message); lock (this.writer) { this.writer.WriteLine(line); this.writer.Flush(); } } bool ILog.IsDebugEnabled { get { return true; } } bool ILog.IsInfoEnabled { get { return true; } } bool ILog.IsWarnEnabled { get { return true; } } bool ILog.IsErrorEnabled { get { return true; } } bool ILog.IsFatalEnabled { get { return true; } } void ILog.Debug(object message) { this.Dump(PrefixDebug, message); } void ILog.Debug(object message, Exception exception) { this.Dump(PrefixDebug, message + " - " + exception); } void ILog.DebugFormat(string format, object arg0) { this.Dump(PrefixDebug, format, arg0); } void ILog.DebugFormat(string format, object arg0, object arg1) { this.Dump(PrefixDebug, format, arg0, arg1); } void ILog.DebugFormat(string format, object arg0, object arg1, object arg2) { this.Dump(PrefixDebug, format, arg0, arg1, arg2); } void ILog.DebugFormat(string format, params object[] args) { this.Dump(PrefixDebug, format, args); } void ILog.DebugFormat(IFormatProvider provider, string format, params object[] args) { this.Dump(PrefixDebug, String.Format(provider, format, args)); } void ILog.Info(object message) { this.Dump(PrefixInfo, message); } void ILog.Info(object message, Exception exception) { this.Dump(PrefixInfo, message + " - " + exception); } void ILog.InfoFormat(string format, object arg0) { this.Dump(PrefixInfo, format, arg0); } void ILog.InfoFormat(string format, object arg0, object arg1) { this.Dump(PrefixInfo, format, arg0, arg1); } void ILog.InfoFormat(string format, object arg0, object arg1, object arg2) { this.Dump(PrefixInfo, format, arg0, arg1, arg2); } void ILog.InfoFormat(string format, params object[] args) { this.Dump(PrefixInfo, format, args); } void ILog.InfoFormat(IFormatProvider provider, string format, params object[] args) { this.Dump(PrefixInfo, String.Format(provider, format, args)); } void ILog.Warn(object message) { this.Dump(PrefixWarn, message); } void ILog.Warn(object message, Exception exception) { this.Dump(PrefixWarn, message + " - " + exception); } void ILog.WarnFormat(string format, object arg0) { this.Dump(PrefixWarn, format, arg0); } void ILog.WarnFormat(string format, object arg0, object arg1) { this.Dump(PrefixWarn, format, arg0, arg1); } void ILog.WarnFormat(string format, object arg0, object arg1, object arg2) { this.Dump(PrefixWarn, format, arg0, arg1, arg2); } void ILog.WarnFormat(string format, params object[] args) { this.Dump(PrefixWarn, format, args); } void ILog.WarnFormat(IFormatProvider provider, string format, params object[] args) { this.Dump(PrefixWarn, String.Format(provider, format, args)); } void ILog.Error(object message) { this.Dump(PrefixError, message); } void ILog.Error(object message, Exception exception) { this.Dump(PrefixError, message + " - " + exception); } void ILog.ErrorFormat(string format, object arg0) { this.Dump(PrefixError, format, arg0); } void ILog.ErrorFormat(string format, object arg0, object arg1) { this.Dump(PrefixError, format, arg0, arg1); } void ILog.ErrorFormat(string format, object arg0, object arg1, object arg2) { this.Dump(PrefixError, format, arg0, arg1, arg2); } void ILog.ErrorFormat(string format, params object[] args) { this.Dump(PrefixError, format, args); } void ILog.ErrorFormat(IFormatProvider provider, string format, params object[] args) { this.Dump(PrefixError, String.Format(provider, format, args)); } void ILog.Fatal(object message) { this.Dump(PrefixFatal, message); } void ILog.Fatal(object message, Exception exception) { this.Dump(PrefixFatal, message + " - " + exception); } void ILog.FatalFormat(string format, object arg0) { this.Dump(PrefixFatal, format, arg0); } void ILog.FatalFormat(string format, object arg0, object arg1) { this.Dump(PrefixFatal, format, arg0, arg1); } void ILog.FatalFormat(string format, object arg0, object arg1, object arg2) { this.Dump(PrefixFatal, format, arg0, arg1, arg2); } void ILog.FatalFormat(string format, params object[] args) { this.Dump(PrefixFatal, format, args); } void ILog.FatalFormat(IFormatProvider provider, string format, params object[] args) { this.Dump(PrefixFatal, String.Format(provider, format, args)); } } #endregion }
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Metadata; namespace <%= appNamespace %>.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
// 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; using System.IO; using System.Net; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; namespace System.Security.Cryptography.Xml { public class EncryptedXml { // // public constant Url identifiers used within the XML Encryption classes // public const string XmlEncNamespaceUrl = "http://www.w3.org/2001/04/xmlenc#"; public const string XmlEncElementUrl = "http://www.w3.org/2001/04/xmlenc#Element"; public const string XmlEncElementContentUrl = "http://www.w3.org/2001/04/xmlenc#Content"; public const string XmlEncEncryptedKeyUrl = "http://www.w3.org/2001/04/xmlenc#EncryptedKey"; // // Symmetric Block Encryption // public const string XmlEncDESUrl = "http://www.w3.org/2001/04/xmlenc#des-cbc"; public const string XmlEncTripleDESUrl = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"; public const string XmlEncAES128Url = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; public const string XmlEncAES256Url = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; public const string XmlEncAES192Url = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; // // Key Transport // public const string XmlEncRSA15Url = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; public const string XmlEncRSAOAEPUrl = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"; // // Symmetric Key Wrap // public const string XmlEncTripleDESKeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-tripledes"; public const string XmlEncAES128KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes128"; public const string XmlEncAES256KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes256"; public const string XmlEncAES192KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes192"; // // Message Digest // public const string XmlEncSHA256Url = "http://www.w3.org/2001/04/xmlenc#sha256"; public const string XmlEncSHA512Url = "http://www.w3.org/2001/04/xmlenc#sha512"; // // private members // private XmlDocument _document; private XmlResolver _xmlResolver; // hash table defining the key name mapping private const int _capacity = 4; // 4 is a reasonable capacity for // the key name mapping hash table private Hashtable _keyNameMapping; private PaddingMode _padding; private CipherMode _mode; private Encoding _encoding; private string _recipient; private int _xmlDsigSearchDepthCounter = 0; private int _xmlDsigSearchDepth; // // public constructors // public EncryptedXml() : this(new XmlDocument()) { } public EncryptedXml(XmlDocument document) { _document = document; _xmlResolver = null; // set the default padding to ISO-10126 _padding = PaddingMode.ISO10126; // set the default cipher mode to CBC _mode = CipherMode.CBC; // By default the encoding is going to be UTF8 _encoding = Encoding.UTF8; _keyNameMapping = new Hashtable(_capacity); _xmlDsigSearchDepth = Utils.XmlDsigSearchDepth; } /// <summary> /// This mentod validates the _xmlDsigSearchDepthCounter counter /// if the counter is over the limit defined by admin or developer. /// </summary> /// <returns>returns true if the limit has reached otherwise false</returns> private bool IsOverXmlDsigRecursionLimit() { if (_xmlDsigSearchDepthCounter > XmlDSigSearchDepth) { return true; } return false; } /// <summary> /// Gets / Sets the max limit for recursive search of encryption key in signed XML /// </summary> public int XmlDSigSearchDepth { get { return _xmlDsigSearchDepth; } set { _xmlDsigSearchDepth = value; } } // The resolver to use for external entities public XmlResolver Resolver { get { return _xmlResolver; } set { _xmlResolver = value; } } // The padding to be used. XML Encryption uses ISO 10126 // but it's nice to provide a way to extend this to include other forms of paddings public PaddingMode Padding { get { return _padding; } set { _padding = value; } } // The cipher mode to be used. XML Encryption uses CBC padding // but it's nice to provide a way to extend this to include other cipher modes public CipherMode Mode { get { return _mode; } set { _mode = value; } } // The encoding of the XML document public Encoding Encoding { get { return _encoding; } set { _encoding = value; } } // This is used to specify the EncryptedKey elements that should be considered // when an EncyptedData references an EncryptedKey using a CarriedKeyName and Recipient public string Recipient { get { // an unspecified value for an XmlAttribute is string.Empty if (_recipient == null) _recipient = string.Empty; return _recipient; } set { _recipient = value; } } // // private methods // private byte[] GetCipherValue(CipherData cipherData) { if (cipherData == null) throw new ArgumentNullException(nameof(cipherData)); WebResponse response = null; Stream inputStream = null; if (cipherData.CipherValue != null) { return cipherData.CipherValue; } else if (cipherData.CipherReference != null) { if (cipherData.CipherReference.CipherValue != null) return cipherData.CipherReference.CipherValue; Stream decInputStream = null; // See if the CipherReference is a local URI if (cipherData.CipherReference.Uri.Length == 0) { // self referenced Uri string baseUri = (_document == null ? null : _document.BaseURI); TransformChain tc = cipherData.CipherReference.TransformChain; decInputStream = tc.TransformToOctetStream(_document, _xmlResolver, baseUri); } else if (cipherData.CipherReference.Uri[0] == '#') { string idref = Utils.ExtractIdFromLocalUri(cipherData.CipherReference.Uri); // Serialize inputStream = new MemoryStream(_encoding.GetBytes(GetIdElement(_document, idref).OuterXml)); string baseUri = (_document == null ? null : _document.BaseURI); TransformChain tc = cipherData.CipherReference.TransformChain; decInputStream = tc.TransformToOctetStream(inputStream, _xmlResolver, baseUri); } else { throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, cipherData.CipherReference.Uri); } // read the output stream into a memory stream byte[] cipherValue = null; using (MemoryStream ms = new MemoryStream()) { Utils.Pump(decInputStream, ms); cipherValue = ms.ToArray(); // Close the stream and return if (response != null) response.Close(); if (inputStream != null) inputStream.Close(); decInputStream.Close(); } // cache the cipher value for Perf reasons in case we call this routine twice cipherData.CipherReference.CipherValue = cipherValue; return cipherValue; } // Throw a CryptographicException if we were unable to retrieve the cipher data. throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); } // // public virtual methods // // This describes how the application wants to associate id references to elements public virtual XmlElement GetIdElement(XmlDocument document, string idValue) { return SignedXml.DefaultGetIdElement(document, idValue); } // default behaviour is to look for the IV in the CipherValue public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmetricAlgorithmUri) { if (encryptedData == null) throw new ArgumentNullException(nameof(encryptedData)); int initBytesSize = 0; // If the Uri is not provided by the application, try to get it from the EncryptionMethod if (symmetricAlgorithmUri == null) { if (encryptedData.EncryptionMethod == null) throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm; } switch (symmetricAlgorithmUri) { case EncryptedXml.XmlEncDESUrl: case EncryptedXml.XmlEncTripleDESUrl: initBytesSize = 8; break; case EncryptedXml.XmlEncAES128Url: case EncryptedXml.XmlEncAES192Url: case EncryptedXml.XmlEncAES256Url: initBytesSize = 16; break; default: // The Uri is not supported. throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported); } byte[] IV = new byte[initBytesSize]; byte[] cipherValue = GetCipherValue(encryptedData.CipherData); Buffer.BlockCopy(cipherValue, 0, IV, 0, IV.Length); return IV; } // default behaviour is to look for keys defined by an EncryptedKey clause // either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri) { if (encryptedData == null) throw new ArgumentNullException(nameof(encryptedData)); if (encryptedData.KeyInfo == null) return null; IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator(); KeyInfoRetrievalMethod kiRetrievalMethod; KeyInfoName kiName; KeyInfoEncryptedKey kiEncKey; EncryptedKey ek = null; while (keyInfoEnum.MoveNext()) { kiName = keyInfoEnum.Current as KeyInfoName; if (kiName != null) { // Get the decryption key from the key mapping string keyName = kiName.Value; if ((SymmetricAlgorithm)_keyNameMapping[keyName] != null) return (SymmetricAlgorithm)_keyNameMapping[keyName]; // try to get it from a CarriedKeyName XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlNodeList encryptedKeyList = _document.SelectNodes("//enc:EncryptedKey", nsm); if (encryptedKeyList != null) { foreach (XmlNode encryptedKeyNode in encryptedKeyList) { XmlElement encryptedKeyElement = encryptedKeyNode as XmlElement; EncryptedKey ek1 = new EncryptedKey(); ek1.LoadXml(encryptedKeyElement); if (ek1.CarriedKeyName == keyName && ek1.Recipient == Recipient) { ek = ek1; break; } } } break; } kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; if (kiRetrievalMethod != null) { string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); ek = new EncryptedKey(); ek.LoadXml(GetIdElement(_document, idref)); break; } kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey; if (kiEncKey != null) { ek = kiEncKey.EncryptedKey; break; } } // if we have an EncryptedKey, decrypt to get the symmetric key if (ek != null) { // now process the EncryptedKey, loop recursively // If the Uri is not provided by the application, try to get it from the EncryptionMethod if (symmetricAlgorithmUri == null) { if (encryptedData.EncryptionMethod == null) throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm; } byte[] key = DecryptEncryptedKey(ek); if (key == null) throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey); SymmetricAlgorithm symAlg = (SymmetricAlgorithm)CryptoHelpers.CreateFromName(symmetricAlgorithmUri); symAlg.Key = key; return symAlg; } return null; } // Try to decrypt the EncryptedKey given the key mapping public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { if (encryptedKey == null) throw new ArgumentNullException(nameof(encryptedKey)); if (encryptedKey.KeyInfo == null) return null; IEnumerator keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator(); KeyInfoName kiName; KeyInfoX509Data kiX509Data; KeyInfoRetrievalMethod kiRetrievalMethod; KeyInfoEncryptedKey kiEncKey; EncryptedKey ek = null; bool fOAEP = false; while (keyInfoEnum.MoveNext()) { kiName = keyInfoEnum.Current as KeyInfoName; if (kiName != null) { // Get the decryption key from the key mapping string keyName = kiName.Value; object kek = _keyNameMapping[keyName]; if (kek != null) { // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table if (kek is SymmetricAlgorithm) return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek); // kek is an RSA key: get fOAEP from the algorithm, default to false fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)kek, fOAEP); } break; } kiX509Data = keyInfoEnum.Current as KeyInfoX509Data; if (kiX509Data != null) { X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption); foreach (X509Certificate2 certificate in collection) { using (RSA privateKey = certificate.GetRSAPrivateKey()) { if (privateKey != null) { fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP); } } } break; } kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; if (kiRetrievalMethod != null) { string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); ek = new EncryptedKey(); ek.LoadXml(GetIdElement(_document, idref)); try { //Following checks if XML dsig processing is in loop and within the limit defined by machine // admin or developer. Once the recursion depth crosses the defined limit it will throw exception. _xmlDsigSearchDepthCounter++; if (IsOverXmlDsigRecursionLimit()) { //Throw exception once recursion limit is hit. throw new CryptoSignedXmlRecursionException(); } else { return DecryptEncryptedKey(ek); } } finally { _xmlDsigSearchDepthCounter--; } } kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey; if (kiEncKey != null) { ek = kiEncKey.EncryptedKey; // recursively process EncryptedKey elements byte[] encryptionKey = DecryptEncryptedKey(ek); if (encryptionKey != null) { // this is a symmetric algorithm for sure SymmetricAlgorithm symAlg = (SymmetricAlgorithm)CryptoHelpers.CreateFromName(encryptedKey.EncryptionMethod.KeyAlgorithm); symAlg.Key = encryptionKey; return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symAlg); } } } return null; } // // public methods // // defines a key name mapping. Default behaviour is to require the key object // to be an RSA key or a SymmetricAlgorithm public void AddKeyNameMapping(string keyName, object keyObject) { if (keyName == null) throw new ArgumentNullException(nameof(keyName)); if (keyObject == null) throw new ArgumentNullException(nameof(keyObject)); if (!(keyObject is SymmetricAlgorithm) && !(keyObject is RSA)) throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); _keyNameMapping.Add(keyName, keyObject); } public void ClearKeyNameMappings() { _keyNameMapping.Clear(); } // Encrypts the given element with the certificate specified. The certificate is added as // an X509Data KeyInfo to an EncryptedKey (AES session key) generated randomly. public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certificate) { if (inputElement == null) throw new ArgumentNullException(nameof(inputElement)); if (certificate == null) throw new ArgumentNullException(nameof(certificate)); using (RSA rsaPublicKey = certificate.GetRSAPublicKey()) { if (rsaPublicKey == null) throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); // Create the EncryptedData object, using an AES-256 session key by default. EncryptedData ed = new EncryptedData(); ed.Type = EncryptedXml.XmlEncElementUrl; ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Include the certificate in the EncryptedKey KeyInfo. EncryptedKey ek = new EncryptedKey(); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); ek.KeyInfo.AddClause(new KeyInfoX509Data(certificate)); // Create a random AES session key and encrypt it with the public key associated with the certificate. RijndaelManaged rijn = new RijndaelManaged(); ek.CipherData.CipherValue = EncryptedXml.EncryptKey(rijn.Key, rsaPublicKey, false); // Encrypt the input element with the random session key that we've created above. KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek); ed.KeyInfo.AddClause(kek); ed.CipherData.CipherValue = EncryptData(inputElement, rijn, false); return ed; } } // Encrypts the given element with the key name specified. A corresponding key name mapping // has to be defined before calling this method. The key name is added as // a KeyNameInfo KeyInfo to an EncryptedKey (AES session key) generated randomly. public EncryptedData Encrypt(XmlElement inputElement, string keyName) { if (inputElement == null) throw new ArgumentNullException(nameof(inputElement)); if (keyName == null) throw new ArgumentNullException(nameof(keyName)); object encryptionKey = null; if (_keyNameMapping != null) encryptionKey = _keyNameMapping[keyName]; if (encryptionKey == null) throw new CryptographicException(SR.Cryptography_Xml_MissingEncryptionKey); // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table SymmetricAlgorithm symKey = encryptionKey as SymmetricAlgorithm; RSA rsa = encryptionKey as RSA; // Create the EncryptedData object, using an AES-256 session key by default. EncryptedData ed = new EncryptedData(); ed.Type = EncryptedXml.XmlEncElementUrl; ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Include the key name in the EncryptedKey KeyInfo. string encryptionMethod = null; if (symKey == null) { encryptionMethod = EncryptedXml.XmlEncRSA15Url; } else if (symKey is TripleDES) { // CMS Triple DES Key Wrap encryptionMethod = EncryptedXml.XmlEncTripleDESKeyWrapUrl; } else if (symKey is Rijndael || symKey is Aes) { // FIPS AES Key Wrap switch (symKey.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128KeyWrapUrl; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192KeyWrapUrl; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256KeyWrapUrl; break; } } else { // throw an exception if the transform is not in the previous categories throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); } EncryptedKey ek = new EncryptedKey(); ek.EncryptionMethod = new EncryptionMethod(encryptionMethod); ek.KeyInfo.AddClause(new KeyInfoName(keyName)); // Create a random AES session key and encrypt it with the public key associated with the certificate. RijndaelManaged rijn = new RijndaelManaged(); ek.CipherData.CipherValue = (symKey == null ? EncryptedXml.EncryptKey(rijn.Key, rsa, false) : EncryptedXml.EncryptKey(rijn.Key, symKey)); // Encrypt the input element with the random session key that we've created above. KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek); ed.KeyInfo.AddClause(kek); ed.CipherData.CipherValue = EncryptData(inputElement, rijn, false); return ed; } // decrypts the document using the defined key mapping in GetDecryptionKey // The behaviour of this method can be extended because GetDecryptionKey is virtual // the document is decrypted in place public void DecryptDocument() { // Look for all EncryptedData elements and decrypt them XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlNodeList encryptedDataList = _document.SelectNodes("//enc:EncryptedData", nsm); if (encryptedDataList != null) { foreach (XmlNode encryptedDataNode in encryptedDataList) { XmlElement encryptedDataElement = encryptedDataNode as XmlElement; EncryptedData ed = new EncryptedData(); ed.LoadXml(encryptedDataElement); SymmetricAlgorithm symAlg = GetDecryptionKey(ed, null); if (symAlg == null) throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey); byte[] decrypted = DecryptData(ed, symAlg); ReplaceData(encryptedDataElement, decrypted); } } } // encrypts the supplied arbitrary data public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorithm) { if (plaintext == null) throw new ArgumentNullException(nameof(plaintext)); if (symmetricAlgorithm == null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); // save the original symmetric algorithm CipherMode origMode = symmetricAlgorithm.Mode; PaddingMode origPadding = symmetricAlgorithm.Padding; byte[] cipher = null; try { symmetricAlgorithm.Mode = _mode; symmetricAlgorithm.Padding = _padding; ICryptoTransform enc = symmetricAlgorithm.CreateEncryptor(); cipher = enc.TransformFinalBlock(plaintext, 0, plaintext.Length); } finally { // now restore the original symmetric algorithm symmetricAlgorithm.Mode = origMode; symmetricAlgorithm.Padding = origPadding; } byte[] output = null; if (_mode == CipherMode.ECB) { output = cipher; } else { byte[] IV = symmetricAlgorithm.IV; output = new byte[cipher.Length + IV.Length]; Buffer.BlockCopy(IV, 0, output, 0, IV.Length); Buffer.BlockCopy(cipher, 0, output, IV.Length, cipher.Length); } return output; } // encrypts the supplied input element public byte[] EncryptData(XmlElement inputElement, SymmetricAlgorithm symmetricAlgorithm, bool content) { if (inputElement == null) throw new ArgumentNullException(nameof(inputElement)); if (symmetricAlgorithm == null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); byte[] plainText = (content ? _encoding.GetBytes(inputElement.InnerXml) : _encoding.GetBytes(inputElement.OuterXml)); return EncryptData(plainText, symmetricAlgorithm); } // decrypts the supplied EncryptedData public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmetricAlgorithm) { if (encryptedData == null) throw new ArgumentNullException(nameof(encryptedData)); if (symmetricAlgorithm == null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); // get the cipher value and decrypt byte[] cipherValue = GetCipherValue(encryptedData.CipherData); // save the original symmetric algorithm CipherMode origMode = symmetricAlgorithm.Mode; PaddingMode origPadding = symmetricAlgorithm.Padding; byte[] origIV = symmetricAlgorithm.IV; // read the IV from cipherValue byte[] decryptionIV = null; if (_mode != CipherMode.ECB) decryptionIV = GetDecryptionIV(encryptedData, null); byte[] output = null; try { int lengthIV = 0; if (decryptionIV != null) { symmetricAlgorithm.IV = decryptionIV; lengthIV = decryptionIV.Length; } symmetricAlgorithm.Mode = _mode; symmetricAlgorithm.Padding = _padding; ICryptoTransform dec = symmetricAlgorithm.CreateDecryptor(); output = dec.TransformFinalBlock(cipherValue, lengthIV, cipherValue.Length - lengthIV); } finally { // now restore the original symmetric algorithm symmetricAlgorithm.Mode = origMode; symmetricAlgorithm.Padding = origPadding; symmetricAlgorithm.IV = origIV; } return output; } // This method replaces an EncryptedData element with the decrypted sequence of bytes public void ReplaceData(XmlElement inputElement, byte[] decryptedData) { if (inputElement == null) throw new ArgumentNullException(nameof(inputElement)); if (decryptedData == null) throw new ArgumentNullException(nameof(decryptedData)); XmlNode parent = inputElement.ParentNode; if (parent.NodeType == XmlNodeType.Document) { // We're replacing the root element, but we can't just wholesale replace the owner // document's InnerXml, since we need to preserve any other top-level XML elements (such as // comments or the XML entity declaration. Instead, create a new document with the // decrypted XML, import it into the existing document, and replace just the root element. XmlDocument importDocument = new XmlDocument(); importDocument.PreserveWhitespace = true; string decryptedString = _encoding.GetString(decryptedData); using (StringReader sr = new StringReader(decryptedString)) { using (XmlReader xr = XmlReader.Create(sr, Utils.GetSecureXmlReaderSettings(_xmlResolver))) { importDocument.Load(xr); } } XmlNode importedNode = inputElement.OwnerDocument.ImportNode(importDocument.DocumentElement, true); parent.RemoveChild(inputElement); parent.AppendChild(importedNode); } else { XmlNode dummy = parent.OwnerDocument.CreateElement(parent.Prefix, parent.LocalName, parent.NamespaceURI); try { parent.AppendChild(dummy); // Replace the children of the dummy node with the sequence of bytes passed in. // The string will be parsed into DOM objects in the context of the parent of the EncryptedData element. dummy.InnerXml = _encoding.GetString(decryptedData); // Move the children of the dummy node up to the parent. XmlNode child = dummy.FirstChild; XmlNode sibling = inputElement.NextSibling; XmlNode nextChild = null; while (child != null) { nextChild = child.NextSibling; parent.InsertBefore(child, sibling); child = nextChild; } } finally { // Remove the dummy element. parent.RemoveChild(dummy); } // Remove the EncryptedData element parent.RemoveChild(inputElement); } } // // public static methods // // replaces the inputElement with the provided EncryptedData public static void ReplaceElement(XmlElement inputElement, EncryptedData encryptedData, bool content) { if (inputElement == null) throw new ArgumentNullException(nameof(inputElement)); if (encryptedData == null) throw new ArgumentNullException(nameof(encryptedData)); // First, get the XML representation of the EncryptedData object XmlElement elemED = encryptedData.GetXml(inputElement.OwnerDocument); switch (content) { case true: // remove all children of the input element Utils.RemoveAllChildren(inputElement); // then append the encrypted data as a child of the input element inputElement.AppendChild(elemED); break; case false: XmlNode parentNode = inputElement.ParentNode; // remove the input element from the containing document parentNode.ReplaceChild(elemED, inputElement); break; } } // wraps the supplied input key data using the provided symmetric algorithm public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm) { if (keyData == null) throw new ArgumentNullException(nameof(keyData)); if (symmetricAlgorithm == null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); if (symmetricAlgorithm is TripleDES) { // CMS Triple DES Key Wrap return SymmetricKeyWrap.TripleDESKeyWrapEncrypt(symmetricAlgorithm.Key, keyData); } else if (symmetricAlgorithm is Rijndael || symmetricAlgorithm is Aes) { // FIPS AES Key Wrap return SymmetricKeyWrap.AESKeyWrapEncrypt(symmetricAlgorithm.Key, keyData); } // throw an exception if the transform is not in the previous categories throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); } // encrypts the supplied input key data using an RSA key and specifies whether we want to use OAEP // padding or PKCS#1 v1.5 padding as described in the PKCS specification public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP) { if (keyData == null) throw new ArgumentNullException(nameof(keyData)); if (rsa == null) throw new ArgumentNullException(nameof(rsa)); if (useOAEP) { RSAOAEPKeyExchangeFormatter rsaFormatter = new RSAOAEPKeyExchangeFormatter(rsa); return rsaFormatter.CreateKeyExchange(keyData); } else { RSAPKCS1KeyExchangeFormatter rsaFormatter = new RSAPKCS1KeyExchangeFormatter(rsa); return rsaFormatter.CreateKeyExchange(keyData); } } // decrypts the supplied wrapped key using the provided symmetric algorithm public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm) { if (keyData == null) throw new ArgumentNullException(nameof(keyData)); if (symmetricAlgorithm == null) throw new ArgumentNullException(nameof(symmetricAlgorithm)); if (symmetricAlgorithm is TripleDES) { // CMS Triple DES Key Wrap return SymmetricKeyWrap.TripleDESKeyWrapDecrypt(symmetricAlgorithm.Key, keyData); } else if (symmetricAlgorithm is Rijndael || symmetricAlgorithm is Aes) { // FIPS AES Key Wrap return SymmetricKeyWrap.AESKeyWrapDecrypt(symmetricAlgorithm.Key, keyData); } // throw an exception if the transform is not in the previous categories throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); } // decrypts the supplied data using an RSA key and specifies whether we want to use OAEP // padding or PKCS#1 v1.5 padding as described in the PKCS specification public static byte[] DecryptKey(byte[] keyData, RSA rsa, bool useOAEP) { if (keyData == null) throw new ArgumentNullException(nameof(keyData)); if (rsa == null) throw new ArgumentNullException(nameof(rsa)); if (useOAEP) { RSAOAEPKeyExchangeDeformatter rsaDeformatter = new RSAOAEPKeyExchangeDeformatter(rsa); return rsaDeformatter.DecryptKeyExchange(keyData); } else { RSAPKCS1KeyExchangeDeformatter rsaDeformatter = new RSAPKCS1KeyExchangeDeformatter(rsa); return rsaDeformatter.DecryptKeyExchange(keyData); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Tracy.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); } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.TestAdapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Python; namespace TestAdapterTests { [TestClass] public class TestDiscovererTests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } private const string _runSettings = @"<?xml version=""1.0""?><RunSettings><DataCollectionRunSettings><DataCollectors /></DataCollectionRunSettings><RunConfiguration><ResultsDirectory>C:\Visual Studio 2015\Projects\PythonApplication107\TestResults</ResultsDirectory><TargetPlatform>X86</TargetPlatform><TargetFrameworkVersion>Framework45</TargetFrameworkVersion></RunConfiguration><Python><TestCases><Project path=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\PythonApplication107.pyproj"" home=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\"" nativeDebugging="""" djangoSettingsModule="""" workingDir=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\"" interpreter=""C:\Python35-32\python.exe"" pathEnv=""PYTHONPATH""><Environment /><SearchPaths><Search value=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\"" /></SearchPaths> <Test className=""Test_test1"" file=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\test1.py"" line=""17"" column=""9"" method=""test_A"" /> <Test className=""Test_test1"" file=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\test1.py"" line=""21"" column=""9"" method=""test_B"" /> <Test className=""Test_test2"" file=""C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\test1.py"" line=""48"" column=""9"" method=""test_C"" /></Project></TestCases></Python></RunSettings>"; [TestMethod, Priority(1)] [TestCategory("10s")] public void TestDiscover() { var ctx = new MockDiscoveryContext(new MockRunSettings(_runSettings)); var sink = new MockTestCaseDiscoverySink(); var logger = new MockMessageLogger(); const string projectPath = @"C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\PythonApplication107.pyproj"; const string testFilePath = @"C:\Visual Studio 2015\Projects\PythonApplication107\PythonApplication107\test1.py"; new TestDiscoverer().DiscoverTests( new[] { testFilePath }, ctx, logger, sink ); PrintTestCases(sink.Tests); var expectedTests = new[] { TestInfo.FromRelativePaths("Test_test1", "test_A", projectPath, testFilePath, 17, TestOutcome.Passed), TestInfo.FromRelativePaths("Test_test1", "test_B", projectPath, testFilePath, 21, TestOutcome.Passed), TestInfo.FromRelativePaths("Test_test2", "test_C", projectPath, testFilePath, 48, TestOutcome.Passed) }; Assert.AreEqual(expectedTests.Length, sink.Tests.Count); foreach (var expectedTest in expectedTests) { var expectedFullyQualifiedName = TestDiscoverer.MakeFullyQualifiedTestName(expectedTest.RelativeClassFilePath, expectedTest.ClassName, expectedTest.MethodName); var actualTestCase = sink.Tests.SingleOrDefault(tc => tc.FullyQualifiedName == expectedFullyQualifiedName); Assert.IsNotNull(actualTestCase, expectedFullyQualifiedName); Assert.AreEqual(expectedTest.MethodName, actualTestCase.DisplayName, expectedFullyQualifiedName); Assert.AreEqual(new Uri(TestExecutor.ExecutorUriString), actualTestCase.ExecutorUri); Assert.AreEqual(expectedTest.SourceCodeLineNumber, actualTestCase.LineNumber, expectedFullyQualifiedName); Assert.IsTrue(IsSameFile(expectedTest.SourceCodeFilePath, actualTestCase.CodeFilePath), expectedFullyQualifiedName); sink.Tests.Remove(actualTestCase); } Debug.WriteLine(""); Debug.WriteLine(""); Debug.WriteLine(""); Debug.WriteLine(""); PrintTestCases(sink.Tests); } [TestMethod, Priority(1)] public void DecoratedTests() { using (var analyzer = MakeTestAnalyzer()) { var entry = AddModule(analyzer, "Fob", @"import unittest def decorator(fn): def wrapped(*args, **kwargs): return fn(*args, **kwargs) return wrapped class MyTest(unittest.TestCase): @decorator def testAbc(self): pass "); entry.Analyze(CancellationToken.None, true); analyzer.AnalyzeQueuedEntries(CancellationToken.None); var test = TestAnalyzer.GetTestCases(entry).Single(); Assert.AreEqual("testAbc", test.MethodName); Assert.AreEqual(10, test.StartLine); } } [TestMethod, Priority(1)] public void TestCaseSubclasses() { using (var analyzer = MakeTestAnalyzer()) { var entry1 = AddModule(analyzer, "Pkg.SubPkg", @"import unittest class TestBase(unittest.TestCase): pass "); var entry2 = AddModule( analyzer, "Pkg", moduleFile: "Pkg\\__init__.py", code: @"from .SubPkg import TestBase" ); var entry3 = AddModule(analyzer, "__main__", @"from Pkg.SubPkg import TestBase as TB1 from Pkg import TestBase as TB2 from Pkg import * class MyTest1(TB1): def test1(self): pass class MyTest2(TB2): def test2(self): pass class MyTest3(TestBase): def test3(self): pass "); entry1.Analyze(CancellationToken.None, true); entry2.Analyze(CancellationToken.None, true); entry3.Analyze(CancellationToken.None, true); analyzer.AnalyzeQueuedEntries(CancellationToken.None); var test = TestAnalyzer.GetTestCases(entry3).ToList(); AssertUtil.ContainsExactly(test.Select(t => t.MethodName), "test1", "test2", "test3"); } } [TestMethod, Priority(1)] public void TestCaseRunTests() { using (var analyzer = MakeTestAnalyzer()) { var entry = AddModule(analyzer, "__main__", @"import unittest class TestBase(unittest.TestCase): def runTests(self): pass # should not discover this as it isn't runTest or test* def runTest(self): pass "); entry.Analyze(CancellationToken.None, true); analyzer.AnalyzeQueuedEntries(CancellationToken.None); var test = TestAnalyzer.GetTestCases(entry).ToList(); AssertUtil.ContainsExactly(test.Select(t => t.ClassName), "TestBase"); } } /// <summary> /// If we have test* and runTest we shouldn't discover runTest /// </summary> [TestMethod, Priority(1)] public void TestCaseRunTestsWithTest() { using (var analyzer = MakeTestAnalyzer()) { var entry = AddModule(analyzer, "__main__", @"import unittest class TestBase(unittest.TestCase): def test_1(self): pass def runTest(self): pass "); entry.Analyze(CancellationToken.None, true); analyzer.AnalyzeQueuedEntries(CancellationToken.None); var test = TestAnalyzer.GetTestCases(entry).ToList(); AssertUtil.ContainsExactly(test.Select(t => t.MethodName), "test_1"); } } private PythonAnalyzer MakeTestAnalyzer() { return PythonAnalyzer.CreateAsync(InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7))).Result; } private IPythonProjectEntry AddModule(PythonAnalyzer analyzer, string moduleName, string code, string moduleFile = null) { using (var source = new StringReader(code)) { var entry = analyzer.AddModule( moduleName, TestData.GetPath("Fob\\" + (moduleFile ?? moduleName.Replace('.', '\\') + ".py")) ); using (var parser = Parser.CreateParser(source, PythonLanguageVersion.V27, new ParserOptions() { BindReferences = true })) { entry.UpdateTree(parser.ParseFile(), null); } return entry; } } private static bool IsSameFile(string a, string b) { return String.Compare(new FileInfo(a).FullName, new FileInfo(b).FullName, StringComparison.CurrentCultureIgnoreCase) == 0; } private static void PrintTestCases(IEnumerable<TestCase> testCases) { foreach (var tst in testCases) { Console.WriteLine("Test: " + tst.FullyQualifiedName); Console.WriteLine("Source: " + tst.Source); Console.WriteLine("Display: " + tst.DisplayName); Console.WriteLine("Location: " + tst.CodeFilePath); Console.WriteLine("Location: " + tst.LineNumber.ToString()); Console.WriteLine(""); } } } }
using System; /// <summary> /// ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32) /// </summary> public class DateTimeCtor3 { #region Private Fields private int m_ErrorNo = 0; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: We can call ctor to constructor a new DateTime instance by using valid value"); try { retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 4, 7, 43); retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 0, 0); retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 56, 56); } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: We can call ctor to constructor a new DateTime instance by using MAX/MIN values"); try { retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 23, 59, 59); retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 0, 0); retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 59, 59); retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 23, 59, 59); retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 0, 0); retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 59, 59); retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 23, 59, 59); retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 0, 0); retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 59, 59); retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 23, 59, 59); retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 0, 0); retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 59, 59); retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 23, 59, 59); retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 0, 0); retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 59, 59); retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 23, 59, 59); retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 0, 0); retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 59, 59); retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 23, 59, 59); retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 0, 0); retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 59, 59); retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 23, 59, 59); retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 0, 0); retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 59, 59); } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: We can call ctor to constructor a new DateTime instance by using correct day/month pair"); try { retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43); retVal = retVal && VerifyDateTimeHelper(2006, 2, 28, 12, 0, 0); retVal = retVal && VerifyDateTimeHelper(2006, 4, 30, 16, 7, 43); } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when year is less than 1 or greater than 9999."); try { DateTime value = new DateTime(0, 1, 1, 1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is less than 1"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(10000, 1, 1, 1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is greater than 9999"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when month is less than 1 or greater than 12"); try { DateTime value = new DateTime(2006, 0, 1, 1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is less than 1"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 13, 1, 1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is greater than 12"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException should be thrown when day is less than 1 or greater than the number of days in month"); try { DateTime value = new DateTime(2006, 1, 0, 1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is less than 1"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 1, 32, 1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 2, 29, 1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 4, 31, 1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException should be thrown when hour is less than 0 or greater than 23"); try { DateTime value = new DateTime(2006, 1, 1, -1, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when hour is less than 0"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 1, 1, 24, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when hour is greater than 23"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException should be thrown when minute is less than 0 or greater than 59"); try { DateTime value = new DateTime(2006, 1, 1, 1, -1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown minute year is less than 0"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 1, 1, 1, 60, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when minute is greater than 59"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException should be thrown when second is less than 0 or greater than 59"); try { DateTime value = new DateTime(2006, 1, 1, 1, 1, -1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when second is less than 0"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 1, 1, 1, 1, 60); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when second is greater than 59"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DateTimeCtor3 test = new DateTimeCtor3(); TestLibrary.TestFramework.BeginTestCase("DateTimeCtor3"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool VerifyDateTimeHelper(int desiredYear, int desiredMonth, int desiredDay, int desiredHour, int desiredMinute, int desiredSecond) { bool retVal = true; DateTime value = new DateTime(desiredYear, desiredMonth, desiredDay, desiredHour, desiredMinute, desiredSecond); m_ErrorNo++; if ((desiredYear != value.Year) || (desiredMonth != value.Month) || (desiredDay != value.Day) || (desiredHour != value.Hour) || (desiredMinute != value.Minute) || (desiredSecond != value.Second)) { TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a wrong DateTime instance by using valid value"); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredYear = " + desiredYear.ToString() + ", desiredMonth = " + desiredMonth.ToString() + ", desiredDay = " + desiredDay.ToString() + ", desiredHour = " + desiredHour.ToString() + ", desiredMinute = " + desiredMinute.ToString() + ", desiredSecond = " + desiredSecond.ToString() + ", actualYear = " + value.Year.ToString() + ", actualMonth = " + value.Month.ToString() + ", actualDay = " + value.Day.ToString() + ", actualHour = " + value.Hour.ToString() + ", actualMinute = " + value.Minute.ToString() + ", actualSecond = " + value.Second.ToString()); retVal = false; } m_ErrorNo++; if (value.Kind != DateTimeKind.Unspecified) { TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a wrong DateTime instance by using valid value"); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredKind = DateTimeKind.Unspecified" + ", actualKind = " + value.Kind.ToString()); retVal = false; } return retVal; } #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.Immutable; using System.IO; using System.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.Internal.Tests { public class AbstractMemoryBlockTests { [Fact] public unsafe void ByteArray() { var array = ImmutableArray.Create(new byte[] { 1, 2, 3, 4 }); using (var provider = new ByteArrayMemoryProvider(array)) { using (var block = provider.GetMemoryBlock()) { Assert.Equal(4, block.Size); AssertEx.Equal(provider.Pointer, block.Pointer); AssertEx.Equal(new byte[] { }, block.GetContentUnchecked(0, 0)); AssertEx.Equal(new byte[] { 3, 4 }, block.GetContentUnchecked(2, 2)); AssertEx.Equal(new byte[] { 1, 2, 3 }, block.GetContentUnchecked(0, 3)); } using (var block = provider.GetMemoryBlock(1, 2)) { AssertEx.Equal(provider.Pointer + 1, block.Pointer); Assert.Equal(2, block.Size); AssertEx.Equal(new byte[] { 2, 3 }, block.GetContentUnchecked(0, 2)); AssertEx.Equal(new byte[] { 3 }, block.GetContentUnchecked(1, 1)); AssertEx.Equal(new byte[] { }, block.GetContentUnchecked(2, 0)); } } } [Fact] public unsafe void External() { var array = new byte[] { 1, 2, 3, 4 }; fixed (byte* arrayPtr = array) { using (var provider = new ExternalMemoryBlockProvider(arrayPtr, array.Length)) { using (var block = provider.GetMemoryBlock()) { Assert.Equal(4, block.Size); AssertEx.Equal(provider.Pointer, block.Pointer); AssertEx.Equal(new byte[] { }, block.GetContentUnchecked(0, 0)); AssertEx.Equal(new byte[] { 3, 4 }, block.GetContentUnchecked(2, 2)); AssertEx.Equal(new byte[] { 1, 2, 3 }, block.GetContentUnchecked(0, 3)); } using (var block = provider.GetMemoryBlock(1, 2)) { AssertEx.Equal(provider.Pointer + 1, block.Pointer); Assert.Equal(2, block.Size); AssertEx.Equal(new byte[] { 2, 3 }, block.GetContentUnchecked(0, 2)); AssertEx.Equal(new byte[] { 3 }, block.GetContentUnchecked(1, 1)); AssertEx.Equal(new byte[] { }, block.GetContentUnchecked(2, 0)); } } } } [Fact] public void Stream() { var array = new byte[] { 1, 2, 3, 4 }; using (var stream = new MemoryStream(array)) { Assert.False(FileStreamReadLightUp.IsFileStream(stream)); using (var provider = new StreamMemoryBlockProvider(stream, 0, array.Length, isFileStream: false, leaveOpen: true)) { using (var block = provider.GetMemoryBlock()) { Assert.IsType<NativeHeapMemoryBlock>(block); Assert.Equal(4, block.Size); AssertEx.Equal(new byte[] { }, block.GetContentUnchecked(0, 0)); AssertEx.Equal(new byte[] { 3, 4 }, block.GetContentUnchecked(2, 2)); AssertEx.Equal(new byte[] { 1, 2, 3 }, block.GetContentUnchecked(0, 3)); } Assert.Equal(4, stream.Position); using (var block = provider.GetMemoryBlock(1, 2)) { Assert.IsType<NativeHeapMemoryBlock>(block); Assert.Equal(2, block.Size); AssertEx.Equal(new byte[] { 2, 3 }, block.GetContentUnchecked(0, 2)); AssertEx.Equal(new byte[] { 3 }, block.GetContentUnchecked(1, 1)); AssertEx.Equal(new byte[] { }, block.GetContentUnchecked(2, 0)); } Assert.Equal(3, stream.Position); } using (var provider = new StreamMemoryBlockProvider(stream, 0, array.Length, isFileStream: false, leaveOpen: false)) { using (var block = provider.GetMemoryBlock()) { Assert.IsType<NativeHeapMemoryBlock>(block); Assert.Equal(4, block.Size); AssertEx.Equal(new byte[] { }, block.GetContentUnchecked(0, 0)); AssertEx.Equal(new byte[] { 3, 4 }, block.GetContentUnchecked(2, 2)); AssertEx.Equal(new byte[] { 1, 2, 3 }, block.GetContentUnchecked(0, 3)); } Assert.Equal(4, stream.Position); } Assert.Throws<ObjectDisposedException>(() => stream.Position); } } [Fact] public void FileStreamWin7() { try { FileStreamReadLightUp.readFileModernNotAvailable = true; FileStream(); } finally { FileStreamReadLightUp.readFileModernNotAvailable = false; } } [Fact] public void FileStreamUnix() { try { FileStreamReadLightUp.readFileModernNotAvailable = true; FileStreamReadLightUp.readFileCompatNotAvailable = true; FileStream(); } finally { FileStreamReadLightUp.readFileModernNotAvailable = false; FileStreamReadLightUp.readFileCompatNotAvailable = false; } } [Fact] public void FileStream() { string filePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { var array = new byte[StreamMemoryBlockProvider.MemoryMapThreshold + 1]; for (int i = 0; i < array.Length; i++) { array[i] = 0x12; } File.WriteAllBytes(filePath, array); foreach (bool useAsync in new[] { true, false }) { using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync)) { Assert.True(FileStreamReadLightUp.IsFileStream(stream)); using (var provider = new StreamMemoryBlockProvider(stream, imageStart: 0, imageSize: array.Length, isFileStream: true, leaveOpen: false)) { // large: using (var block = provider.GetMemoryBlock()) { Assert.IsType<MemoryMappedFileBlock>(block); Assert.Equal(array.Length, block.Size); Assert.Equal(array, block.GetContentUnchecked(0, block.Size)); } // we didn't use the stream for reading Assert.Equal(0, stream.Position); // small: using (var block = provider.GetMemoryBlock(1, 2)) { Assert.IsType<NativeHeapMemoryBlock>(block); Assert.Equal(2, block.Size); Assert.Equal(new byte[] { 0x12, 0x12 }, block.GetContentUnchecked(0, block.Size)); } Assert.Equal(3, stream.Position); } Assert.Throws<ObjectDisposedException>(() => stream.Position); } } } finally { File.Delete(filePath); } } } }
// 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 InsertVector128Byte1() { var test = new InsertVector128Test__InsertVector128Byte1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local 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__InsertVector128Byte1 { private struct TestStruct { public Vector256<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(InsertVector128Test__InsertVector128Byte1 testClass) { var result = Avx2.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector128<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static InsertVector128Test__InsertVector128Byte1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public InsertVector128Test__InsertVector128Byte1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.InsertVector128( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.InsertVector128( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), LoadVector128((Byte*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.InsertVector128( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), LoadVector128((Byte*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.InsertVector128( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var right = LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var right = LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertVector128Test__InsertVector128Byte1(); var result = Avx2.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.InsertVector128(test._fld1, test._fld2, 1); 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(Vector256<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i > 15 ? result[i] != right[i - 16] : result[i] != left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.InsertVector128)}<Byte>(Vector256<Byte>, Vector128<Byte>.1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Abstract base class for all Streams. Provides ** default implementations of asynchronous reads & writes, in ** terms of the synchronous reads & writes (and vice versa). ** ** ===========================================================*/ using System; using System.Buffers; using System.Threading; using System.Threading.Tasks; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; namespace System.IO { public abstract class Stream : MarshalByRefObject, IDisposable { public static readonly Stream Null = new NullStream(); //We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant // improvement in Copy performance. private const int _DefaultCopyBufferSize = 81920; // To implement Async IO operations on streams that don't support async IO [NonSerialized] private ReadWriteTask _activeReadWriteTask; [NonSerialized] private SemaphoreSlim _asyncActiveSemaphore; internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } public abstract bool CanRead { [Pure] get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { [Pure] get; } public virtual bool CanTimeout { [Pure] get { return false; } } public abstract bool CanWrite { [Pure] get; } public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } } public virtual int WriteTimeout { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } } public Task CopyToAsync(Stream destination) { int bufferSize = _DefaultCopyBufferSize; if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // If we go down this branch, it means there are // no bytes left in this stream. // Ideally we would just return Task.CompletedTask here, // but CopyToAsync(Stream, int, CancellationToken) was already // virtual at the time this optimization was introduced. So // if it does things like argument validation (checking if destination // is null and throwing an exception), then await fooStream.CopyToAsync(null) // would no longer throw if there were no bytes left. On the other hand, // we also can't roll our own argument validation and return Task.CompletedTask, // because it would be a breaking change if the stream's override didn't throw before, // or in a different order. So for simplicity, we just set the bufferSize to 1 // (not 0 since the default implementation throws for 0) and forward to the virtual method. bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } return CopyToAsync(destination, bufferSize); } public Task CopyToAsync(Stream destination, Int32 bufferSize) { return CopyToAsync(destination, bufferSize, CancellationToken.None); } public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); return CopyToAsyncInternal(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { Contract.Requires(destination != null); Contract.Requires(bufferSize > 0); Contract.Requires(CanRead); Contract.Requires(destination.CanWrite); byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine try { while (true) { int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); if (bytesRead == 0) break; if (bytesRead > bufferSize) bufferSize = bytesRead; await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } finally { Array.Clear(buffer, 0, bufferSize); // clear only the most we used ArrayPool<byte>.Shared.Return(buffer, clearArray: false); } } // Reads the bytes from the current stream and writes the bytes to // the destination stream until all bytes are read, starting at // the current position. public void CopyTo(Stream destination) { int bufferSize = _DefaultCopyBufferSize; if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // No bytes left in stream // Call the other overload with a bufferSize of 1, // in case it's made virtual in the future bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } CopyTo(destination, bufferSize); } public virtual void CopyTo(Stream destination, int bufferSize) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); int highwaterMark = 0; try { int read; while ((read = Read(buffer, 0, buffer.Length)) != 0) { if (read > highwaterMark) highwaterMark = read; destination.Write(buffer, 0, read); } } finally { Array.Clear(buffer, 0, highwaterMark); // clear only the most we used ArrayPool<byte>.Shared.Return(buffer, clearArray: false); } } // Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup starting in V2. public virtual void Close() { /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. Contract.Ensures(CanRead == false); Contract.Ensures(CanWrite == false); Contract.Ensures(CanSeek == false); */ Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. Contract.Ensures(CanRead == false); Contract.Ensures(CanWrite == false); Contract.Ensures(CanSeek == false); */ Close(); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public abstract void Flush(); public Task FlushAsync() { return FlushAsync(CancellationToken.None); } public virtual Task FlushAsync(CancellationToken cancellationToken) { return Task.Factory.StartNew(state => ((Stream)state).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")] protected virtual WaitHandle CreateWaitHandle() { Contract.Ensures(Contract.Result<WaitHandle>() != null); return new ManualResetEvent(false); } public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } internal IAsyncResult BeginReadInternal( byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously, bool apm) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); if (!CanRead) __Error.ReadNotSupported(); // To avoid a race with a stream's position pointer & generating race conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. var semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); } else { semaphore.Wait(); } // Create the task to asynchronously do a Read. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Read. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); try { // Do the Read and return the number of bytes read return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count); } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); else RunReadWriteTask(asyncResult); return asyncResult; // return it } public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.Ensures(Contract.Result<int>() >= 0); Contract.EndContractBlock(); var readTask = _activeReadWriteTask; if (readTask == null) { throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); } else if (readTask != asyncResult) { throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); } else if (!readTask._isRead) { throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); } try { return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception } finally { FinishTrackingAsyncOperation(); } } public Task<int> ReadAsync(Byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None); } public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. return cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : BeginEndReadAsync(buffer, offset, count); } public virtual ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken)) { if (destination.TryGetArray(out ArraySegment<byte> array)) { return new ValueTask<int>(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken)); } else { byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length); return FinishReadAsync(ReadAsync(buffer, 0, destination.Length, cancellationToken), buffer, destination); async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination) { try { int result = await readTask.ConfigureAwait(false); new Span<byte>(localBuffer, 0, result).CopyTo(localDestination.Span); return result; } finally { ArrayPool<byte>.Shared.Return(localBuffer); } } } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndRead(); private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) { if (!HasOverriddenBeginEndRead()) { // If the Stream does not override Begin/EndRead, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return (Task<Int32>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<Int32>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler } private struct ReadWriteParameters // struct for arguments to Read and Write calls { internal byte[] Buffer; internal int Offset; internal int Count; } public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } internal IAsyncResult BeginWriteInternal( byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously, bool apm) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); if (!CanWrite) __Error.WriteNotSupported(); // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. var semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block } else { semaphore.Wait(); // synchronously wait here } // Create the task to asynchronously do a Write. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Write. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); try { // Do the Write thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count); return 0; // not used, but signature requires a value be returned } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); else RunReadWriteTask(asyncResult); return asyncResult; // return it } private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) { Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with // preconditions in async methods that await. Debug.Assert(asyncWaiter != null); // Ditto // If the wait has already completed, run the task. if (asyncWaiter.IsCompleted) { Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); RunReadWriteTask(readWriteTask); } else // Otherwise, wait for our turn, and then run the task. { asyncWaiter.ContinueWith((t, state) => { Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); var rwt = (ReadWriteTask)state; rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask); }, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } private void RunReadWriteTask(ReadWriteTask readWriteTask) { Contract.Requires(readWriteTask != null); Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers"); // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding // two interlocked operations. However, if ReadWriteTask is ever changed to use // a cancellation token, this should be changed to use Start. _activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one readWriteTask.m_taskScheduler = TaskScheduler.Default; readWriteTask.ScheduleAndStart(needsProtection: false); } private void FinishTrackingAsyncOperation() { _activeReadWriteTask = null; Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); _asyncActiveSemaphore.Release(); } public virtual void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); var writeTask = _activeReadWriteTask; if (writeTask == null) { throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); } else if (writeTask != asyncResult) { throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); } else if (writeTask._isRead) { throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); } try { writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion); } finally { FinishTrackingAsyncOperation(); } } // Task used by BeginRead / BeginWrite to do Read / Write asynchronously. // A single instance of this task serves four purposes: // 1. The work item scheduled to run the Read / Write operation // 2. The state holding the arguments to be passed to Read / Write // 3. The IAsyncResult returned from BeginRead / BeginWrite // 4. The completion action that runs to invoke the user-provided callback. // This last item is a bit tricky. Before the AsyncCallback is invoked, the // IAsyncResult must have completed, so we can't just invoke the handler // from within the task, since it is the IAsyncResult, and thus it's not // yet completed. Instead, we use AddCompletionAction to install this // task as its own completion handler. That saves the need to allocate // a separate completion handler, it guarantees that the task will // have completed by the time the handler is invoked, and it allows // the handler to be invoked synchronously upon the completion of the // task. This all enables BeginRead / BeginWrite to be implemented // with a single allocation. private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction { internal readonly bool _isRead; internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync internal Stream _stream; internal byte[] _buffer; internal readonly int _offset; internal readonly int _count; private AsyncCallback _callback; private ExecutionContext _context; internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC { _stream = null; _buffer = null; } public ReadWriteTask( bool isRead, bool apm, Func<object, int> function, object state, Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) : base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach) { Contract.Requires(function != null); Contract.Requires(stream != null); Contract.Requires(buffer != null); Contract.EndContractBlock(); // Store the arguments _isRead = isRead; _apm = apm; _stream = stream; _buffer = buffer; _offset = offset; _count = count; // If a callback was provided, we need to: // - Store the user-provided handler // - Capture an ExecutionContext under which to invoke the handler // - Add this task as its own completion handler so that the Invoke method // will run the callback when this task completes. if (callback != null) { _callback = callback; _context = ExecutionContext.Capture(); base.AddCompletionAction(this); } } private static void InvokeAsyncCallback(object completedTask) { var rwc = (ReadWriteTask)completedTask; var callback = rwc._callback; rwc._callback = null; callback(rwc); } private static ContextCallback s_invokeAsyncCallback; void ITaskCompletionAction.Invoke(Task completingTask) { // Get the ExecutionContext. If there is none, just run the callback // directly, passing in the completed task as the IAsyncResult. // If there is one, process it with ExecutionContext.Run. var context = _context; if (context == null) { var callback = _callback; _callback = null; callback(completingTask); } else { _context = null; var invokeAsyncCallback = s_invokeAsyncCallback; if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition ExecutionContext.Run(context, invokeAsyncCallback, this); } } bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } } } public Task WriteAsync(Byte[] buffer, int offset, int count) { return WriteAsync(buffer, offset, count, CancellationToken.None); } public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : BeginEndWriteAsync(buffer, offset, count); } public virtual Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { if (source.DangerousTryGetArray(out ArraySegment<byte> array)) { return WriteAsync(array.Array, array.Offset, array.Count, cancellationToken); } else { byte[] buffer = ArrayPool<byte>.Shared.Rent(source.Length); source.Span.CopyTo(buffer); return FinishWriteAsync(WriteAsync(buffer, 0, source.Length, cancellationToken), buffer); async Task FinishWriteAsync(Task writeTask, byte[] localBuffer) { try { await writeTask.ConfigureAwait(false); } finally { ArrayPool<byte>.Shared.Return(localBuffer); } } } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndWrite(); private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) { if (!HasOverriddenBeginEndWrite()) { // If the Stream does not override Begin/EndWrite, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<VoidTaskResult>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => // cached by compiler { stream.EndWrite(asyncResult); return default(VoidTaskResult); }); } public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read([In, Out] byte[] buffer, int offset, int count); public virtual int Read(Span<byte> destination) { byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length); try { int numRead = Read(buffer, 0, destination.Length); if ((uint)numRead > destination.Length) { throw new IOException(SR.IO_StreamTooLong); } new Span<byte>(buffer, 0, numRead).CopyTo(destination); return numRead; } finally { ArrayPool<byte>.Shared.Return(buffer); } } // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. public virtual int ReadByte() { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < 256); byte[] oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); if (r == 0) return -1; return oneByteArray[0]; } public abstract void Write(byte[] buffer, int offset, int count); public virtual void Write(ReadOnlySpan<byte> source) { byte[] buffer = ArrayPool<byte>.Shared.Rent(source.Length); try { source.CopyTo(buffer); Write(buffer, 0, source.Length); } finally { ArrayPool<byte>.Shared.Return(buffer); } } // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte(byte value) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } public static Stream Synchronized(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); Contract.Ensures(Contract.Result<Stream>() != null); Contract.EndContractBlock(); if (stream is SyncStream) return stream; return new SyncStream(stream); } [Obsolete("Do not call or override this method.")] protected virtual void ObjectInvariant() { } internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); // To avoid a race with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { int numRead = Read(buffer, offset, count); asyncResult = new SynchronousAsyncResult(numRead, state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static int BlockingEndRead(IAsyncResult asyncResult) { Contract.Ensures(Contract.Result<int>() >= 0); return SynchronousAsyncResult.EndRead(asyncResult); } internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { Write(buffer, offset, count); asyncResult = new SynchronousAsyncResult(state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static void BlockingEndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult.EndWrite(asyncResult); } private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead { [Pure] get { return true; } } public override bool CanWrite { [Pure] get { return true; } } public override bool CanSeek { [Pure] get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } public override void CopyTo(Stream destination, int bufferSize) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // After we validate arguments this is a nop. } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // Validate arguments here for compat, since previously this method // was inherited from Stream (which did check its arguments). StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanRead) __Error.ReadNotSupported(); return BlockingBeginRead(buffer, offset, count, callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); return BlockingEndRead(asyncResult); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanWrite) __Error.WriteNotSupported(); return BlockingBeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); BlockingEndWrite(asyncResult); } public override int Read([In, Out] byte[] buffer, int offset, int count) { return 0; } public override int Read(Span<byte> destination) { return 0; } public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return AsyncTaskMethodBuilder<int>.s_defaultResultTask; } public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken)) { return new ValueTask<int>(0); } public override int ReadByte() { return -1; } public override void Write(byte[] buffer, int offset, int count) { } public override void Write(ReadOnlySpan<byte> source) { } public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long length) { } } /// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary> internal sealed class SynchronousAsyncResult : IAsyncResult { private readonly Object _stateObject; private readonly bool _isWrite; private ManualResetEvent _waitHandle; private ExceptionDispatchInfo _exceptionInfo; private bool _endXxxCalled; private Int32 _bytesRead; internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) { _bytesRead = bytesRead; _stateObject = asyncStateObject; //_isWrite = false; } internal SynchronousAsyncResult(Object asyncStateObject) { _stateObject = asyncStateObject; _isWrite = true; } internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) { _exceptionInfo = ExceptionDispatchInfo.Capture(ex); _stateObject = asyncStateObject; _isWrite = isWrite; } public bool IsCompleted { // We never hand out objects of this type to the user before the synchronous IO completed: get { return true; } } public WaitHandle AsyncWaitHandle { get { return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true)); } } public Object AsyncState { get { return _stateObject; } } public bool CompletedSynchronously { get { return true; } } internal void ThrowIfError() { if (_exceptionInfo != null) _exceptionInfo.Throw(); } internal static Int32 EndRead(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || ar._isWrite) __Error.WrongAsyncResult(); if (ar._endXxxCalled) __Error.EndReadCalledTwice(); ar._endXxxCalled = true; ar.ThrowIfError(); return ar._bytesRead; } internal static void EndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || !ar._isWrite) __Error.WrongAsyncResult(); if (ar._endXxxCalled) __Error.EndWriteCalledTwice(); ar._endXxxCalled = true; ar.ThrowIfError(); } } // class SynchronousAsyncResult // SyncStream is a wrapper around a stream that takes // a lock for every operation making it thread safe. internal sealed class SyncStream : Stream, IDisposable { private Stream _stream; internal SyncStream(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); Contract.EndContractBlock(); _stream = stream; } public override bool CanRead { [Pure] get { return _stream.CanRead; } } public override bool CanWrite { [Pure] get { return _stream.CanWrite; } } public override bool CanSeek { [Pure] get { return _stream.CanSeek; } } public override bool CanTimeout { [Pure] get { return _stream.CanTimeout; } } public override long Length { get { lock (_stream) { return _stream.Length; } } } public override long Position { get { lock (_stream) { return _stream.Position; } } set { lock (_stream) { _stream.Position = value; } } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // In the off chance that some wrapped stream has different // semantics for Close vs. Dispose, let's preserve that. public override void Close() { lock (_stream) { try { _stream.Close(); } finally { base.Dispose(true); } } } protected override void Dispose(bool disposing) { lock (_stream) { try { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_stream).Dispose(); } finally { base.Dispose(disposing); } } } public override void Flush() { lock (_stream) _stream.Flush(); } public override int Read([In, Out]byte[] bytes, int offset, int count) { lock (_stream) return _stream.Read(bytes, offset, count); } public override int Read(Span<byte> destination) { lock (_stream) return _stream.Read(destination); } public override int ReadByte() { lock (_stream) return _stream.ReadByte(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { bool overridesBeginRead = _stream.HasOverriddenBeginEndRead(); lock (_stream) { // If the Stream does have its own BeginRead implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginRead ? _stream.BeginRead(buffer, offset, count, callback, state) : _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.Ensures(Contract.Result<int>() >= 0); Contract.EndContractBlock(); lock (_stream) return _stream.EndRead(asyncResult); } public override long Seek(long offset, SeekOrigin origin) { lock (_stream) return _stream.Seek(offset, origin); } public override void SetLength(long length) { lock (_stream) _stream.SetLength(length); } public override void Write(byte[] bytes, int offset, int count) { lock (_stream) _stream.Write(bytes, offset, count); } public override void Write(ReadOnlySpan<byte> source) { lock (_stream) _stream.Write(source); } public override void WriteByte(byte b) { lock (_stream) _stream.WriteByte(b); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite(); lock (_stream) { // If the Stream does have its own BeginWrite implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginWrite ? _stream.BeginWrite(buffer, offset, count, callback, state) : _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); lock (_stream) _stream.EndWrite(asyncResult); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using eidss.gis.Serializers; using SharpMap.Layers; using SharpMap.Data.Providers; using ICSharpCode.SharpZipLib.Zip; using System.Xml; using SharpMap; using GdalRasterLayer = GIS_V4.Layers.GdalRasterLayer; namespace eidss.gis.Utils { //TODO[enikulin]: Need code review! Change zip lib! Vector and raster layer from SharpMap or GIS_V4? public static class MapPacker { static MapPacker() { if (ZipConstants.DefaultCodePage == 1) ZipConstants.DefaultCodePage = 437; //Bug in ZipLib } private const string FileTagName = "Filename"; private const string MapNameTagName = "MapName"; /// <summary> /// Packaging map /// </summary> /// <param name="map">Map for packaging</param> /// <param name="mapName">Name of the map</param> /// <param name="packetOutputPath">Output file path</param> public static void PackMap(Map map, EidssMapSerializer.MapSettimgsObject settings, string mapName, string packetOutputPath) { string mapFilePath = null; try { ZipFile zipFile = ZipFile.Create(packetOutputPath); //maping full name -> short name in arch var filenames = new Dictionary<string, string>(); //add layers data to arc; foreach (ILayer layer in map.Layers) { string fileName = null; //if shp file get its fileName var vectorLayer = layer as VectorLayer; if (vectorLayer != null) { var prov = vectorLayer.DataSource as ShapeFile; if (prov != null) fileName = prov.Filename; } //if raster get its filename var rastLayer = layer as GdalRasterLayer; if (rastLayer != null) fileName = rastLayer.Filename; //add to arc if (fileName != null) { //search FullPath (if already exist - continue) if (filenames.ContainsKey(fileName)) continue; //file already added to arch string shortName = Path.GetFileName(fileName); //search shortName in dictionary (if exist, rename it) if (filenames.ContainsValue(shortName)) shortName = Path.GetFileNameWithoutExtension(shortName) + Guid.NewGuid() + Path.GetExtension(shortName); //add to dictionary filenames.Add(fileName, shortName); zipFile.BeginUpdate(); CompressFileWithAdditional(fileName, Path.GetFileNameWithoutExtension(shortName), zipFile); zipFile.CommitUpdate(); } } //add map file to arc string mapFileName = mapName + ".map"; mapFilePath = Path.GetTempPath() + Guid.NewGuid() + ".map"; //+ mapName //save as temporary file EidssMapSerializer.Instance.SerializeAsFile(map, settings, mapFilePath); PrePackParseMapFile(mapFilePath, filenames, mapName); //pack map file zipFile.BeginUpdate(); zipFile.Add(mapFilePath, mapFileName); zipFile.CommitUpdate(); //close zip file zipFile.Close(); //delete temporary map file File.Delete(mapFilePath); } catch (Exception ex) { //if(File.Exists(packetOutputPath)) // File.Delete(packetOutputPath); //if (File.Exists(mapFilePath)) // File.Delete(mapFilePath); throw; } } public delegate bool GetNewMapName(ref string mapName); /// <summary> /// Unpackaging map /// </summary> /// <param name="packPath">Path to pack file</param> /// <param name="mapOutputFolder">Output folder for unpacking map</param> /// <param name="newMapNameDelegate">Delegeate for request new mapName</param> public static void UnpackMap(string packPath, string mapOutputFolder, GetNewMapName newMapNameDelegate) { string newMapDir = Path.Combine(mapOutputFolder, "Map_"+Guid.NewGuid()); string mapFilePath=null; string newMapFilePath = null; try { Directory.CreateDirectory(newMapDir); //extract map var fastZip = new FastZip(); fastZip.ExtractZip(packPath, newMapDir, null); //copy map file and set new file path string[] mapFiles = Directory.GetFiles(newMapDir, "*.map"); if (mapFiles.Length != 1) throw new ApplicationException(string.Format("MapPack has {0} map files!", mapFiles.Length)); mapFilePath = mapFiles[0]; newMapFilePath = Path.Combine(mapOutputFolder, Path.GetFileName(mapFilePath)); //system map directory already contains map with such name if (File.Exists(newMapFilePath)) { if (!newMapNameDelegate(ref newMapFilePath)) { Directory.Delete(newMapDir, true); return; } } File.Copy(mapFilePath, newMapFilePath, true); File.Delete(mapFilePath); PostUnpackParseMapFile(newMapFilePath, newMapDir); } catch (Exception) { if(Directory.Exists(newMapDir)) Directory.Delete(newMapDir, true); if(File.Exists(newMapFilePath)) File.Delete(newMapFilePath); if (File.Exists(mapFilePath)) File.Delete(mapFilePath); throw; } } //TODO[enikulin]: make private public static void CompressFileWithAdditional(string filePath, string entryName, ZipFile zipFile) { var file = new FileInfo(filePath); var files = file.Directory.GetFiles(Path.GetFileNameWithoutExtension(filePath) + ".*"); foreach (FileInfo fileInfo in files) { zipFile.Add(fileInfo.FullName, entryName + Path.GetExtension(fileInfo.FullName)); } } public static void PrePackParseMapFile(string mapFilePath, Dictionary<string , string> fileNamesDict, string mapName) { var xmlDoc=new XmlDocument(); xmlDoc.Load(mapFilePath); var filenameNodes = xmlDoc.GetElementsByTagName(FileTagName); //remake paths foreach (XmlNode fileNode in filenameNodes) { fileNode.InnerText = fileNamesDict.ContainsKey(fileNode.InnerText) ? fileNamesDict[fileNode.InnerText] : Path.GetFileName(fileNode.InnerText); } //rename map var mapnameNode = xmlDoc.GetElementsByTagName(MapNameTagName); if (mapnameNode.Count != 1) Debug.WriteLine("Map file is broken!"); else mapnameNode[0].InnerText = mapName; xmlDoc.Save(mapFilePath); } public static void PostUnpackParseMapFile(string mapFilePath, string dataPath) { var xmlDoc = new XmlDocument(); xmlDoc.Load(mapFilePath); var filenames = xmlDoc.GetElementsByTagName(FileTagName); foreach (XmlNode fileNode in filenames) { fileNode.InnerText = Path.Combine(dataPath, fileNode.InnerText); } xmlDoc.Save(mapFilePath); } } }
using System; using System.Text.RegularExpressions; using MagicChunks.Documents; using Xunit; namespace MagicChunks.Tests.Documents { public class XmlDocumentTests { [Fact] public void Transform() { // Arrange var document = new XmlDocument(@"<xml> <a> <x>1</x> </a> <b>2</b> <c>3</c> <e> <item key=""item1"">1</item> <item key=""item2"">2</item> <item key=""item3"">3</item> </e> <f> <item key=""item1""> <val>1</val> </item> <item key=""item2""> <val>2</val> </item> <item key=""item3""> <val>3</val> </item> </f> </xml>"); // Act document.ReplaceKey(new[] { "xml", "a", "y" }, "2"); document.ReplaceKey(new[] { "xml", "a", "@y" }, "3"); document.ReplaceKey(new[] { "xml", "a", "z", "t", "w" }, "3"); document.ReplaceKey(new[] { "xml", "b" }, "5"); document.ReplaceKey(new[] { "xml", "c", "a" }, "1"); document.ReplaceKey(new[] { "xml", "c", "b" }, "2"); document.ReplaceKey(new[] { "xml", "c", "b", "t" }, "3"); document.ReplaceKey(new[] { "xml", "e", "item[@key = 'item2']" }, "5"); document.ReplaceKey(new[] { "xml", "e", "item[@key=\"item3\"]" }, "6"); document.ReplaceKey(new[] { "xml", "f", "item[@key = 'item2']", "val" }, "7"); document.ReplaceKey(new[] { "xml", "f", "item[@key=\"item3\"]", "val" }, "8"); document.ReplaceKey(new[] { "xml", "d" }, "4"); var result = document.ToString(); // Assert Assert.Equal(@"<xml> <a y=""3""> <x>1</x> <y>2</y> <z> <t> <w>3</w> </t> </z> </a> <b>5</b> <c> <a>1</a> <b> <t>3</t> </b> </c> <e> <item key=""item1"">1</item> <item key=""item2"">5</item> <item key=""item3"">6</item> </e> <f> <item key=""item1""> <val>1</val> </item> <item key=""item2""> <val>7</val> </item> <item key=""item3""> <val>8</val> </item> </f> <d>4</d> </xml>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformByIndex() { // Arrange var document = new XmlDocument(@"<info> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </info>"); // Act document.ReplaceKey(new[] { "info", "param[1]", "option" }, "DD"); var result = document.ToString(); // Assert Assert.Equal(@"<info> <param> <option>AA</option> </param> <param> <option>DD</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </info>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformByIndex2() { // Arrange var document = new XmlDocument(@"<info> <val x=""1""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> <val x=""2""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> <val x=""1""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> </info>"); // Act document.ReplaceKey(new[] { "info", "val[@x=\"2\"]", "param[1]", "option" }, "DD"); var result = document.ToString(); // Assert Assert.Equal(@"<info> <val x=""1""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> <val x=""2""> <param> <option>AA</option> </param> <param> <option>DD</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> <val x=""1""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> </info>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformWithXmlHeader() { // Arrange var document = new XmlDocument(@"<?xml version=""1.0"" encoding=""utf-8""?> <foo> </foo>"); // Act // document.ReplaceKey(new[] { "foo/@value" }, "foo"); var result = document.ToString(); // Assert Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?> <foo></foo>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformWithNamesapce() { // Arrange var document = new XmlDocument(@"<html xmlns=""http://www.w3.org/1999/xhtml""> <head></head> <BODY> <p></p> <DIV id=""d1""></DIV> <div id=""d2""><P></P></div> </BODY> </html>"); // Act document.ReplaceKey(new[] {"html", "body", "p"}, "Text"); document.ReplaceKey(new[] {"html", "body", "div[@id='d1']"}, "Div"); document.ReplaceKey(new[] {"html", "body", "div[@id='d2']", "p"}, "Text2"); var result = document.ToString(); // Assert Assert.Equal(@"<html xmlns=""http://www.w3.org/1999/xhtml""> <head></head> <BODY> <p>Text</p> <DIV id=""d1"">Div</DIV> <div id=""d2""> <P>Text2</P> </div> </BODY> </html>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformWithNamesapce2() { // Arrange var document = new XmlDocument(@"<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" autoReload=""true""> <targets> <target name=""file"" xsi:type=""File"" layout=""${longdate} ${message} ${exception:format=tostring}"" filename=""${basedir}\logs\${date:format=yyyy-MM-dd}.txt"" archiveFileName=""${basedir}\logs\${date:format=yyyy-MM-dd}.{#}.txt"" archiveEvery=""Day"" archiveAboveSize=""512000"" archiveNumbering=""Rolling"" maxArchiveFiles=""15"" keepFileOpen=""false"" /> </targets> <rules> <logger name=""*"" minlevel=""Info"" writeTo=""file"" /> </rules> </nlog>"); // Act document.ReplaceKey(new[] { "nlog", "targets", "target[@name='file']", "@filename"}, "$(logspath)\\${date:format=yyyy-MM-dd}.txt"); document.ReplaceKey(new[] { "nlog", "targets", "target[@name='file']", "@archiveFileName"}, "$(logspath)\\${date:format=yyyy-MM-dd}.{#}.txt"); document.ReplaceKey(new[] { "nlog", "rules", "logger[@name='*']", "@minlevel"}, "$(loglevel)"); var result = document.ToString(); // Assert Assert.Equal(@"<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" autoReload=""true""> <targets> <target name=""file"" xsi:type=""File"" layout=""${longdate} ${message} ${exception:format=tostring}"" filename=""$(logspath)\${date:format=yyyy-MM-dd}.txt"" archiveFileName=""$(logspath)\${date:format=yyyy-MM-dd}.{#}.txt"" archiveEvery=""Day"" archiveAboveSize=""512000"" archiveNumbering=""Rolling"" maxArchiveFiles=""15"" keepFileOpen=""false"" /> </targets> <rules> <logger name=""*"" minlevel=""$(loglevel)"" writeTo=""file"" /> </rules> </nlog>".Replace("\r", String.Empty).Replace("\n", String.Empty), result.Replace("\r", String.Empty).Replace("\n", String.Empty), ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformWithNamesapce3() { // Arrange var document = new XmlDocument(@"<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> <targets> <target name=""file"" xsi:type=""File"" xsi:type2=""12345"" /> <xsi:element></xsi:element> </targets> </nlog>"); // Act document.ReplaceKey(new[] { "nlog", "targets", "target[@name='file']", "@xsi:type2" }, "val1"); document.ReplaceKey(new[] { "nlog", "targets", "target[@xsi:type='File']" }, "val2"); document.ReplaceKey(new[] { "nlog", "targets", "xsi:element" }, "val3"); document.ReplaceKey(new[] { "nlog", "targets", "xsi:element", "@prop" }, "val4"); var result = document.ToString(); // Assert Assert.Equal(@"<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> <targets> <target name=""file"" xsi:type=""File"" xsi:type2=""val1"">val2</target> <xsi:element prop=""val4"">val3</xsi:element> </targets> </nlog>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformWithNamesapce4() { // Arrange var document = new XmlDocument(@"<manifest xmlns:android=""http://schemas.android.com/apk/res/android"" package=""com.myapp.name.here"" android:installLocation=""auto"" android:versionCode=""10000"" android:versionName=""1""> <uses-sdk android:minSdkVersion=""18"" android:targetSdkVersion=""23"" /> <uses-permission android:name=""android.permission.CHANGE_WIFI_STATE"" /> <uses-permission android:name=""android.permission.ACCESS_WIFI_STATE"" /> <application android:label=""Scan Plan 2 Test"" android:icon="""" android:theme="""" /> </manifest>"); // Act document.ReplaceKey(new[] { "manifest", "@android:versionCode" }, "10001"); var result = document.ToString(); // Assert Assert.Equal(@"<manifest xmlns:android=""http://schemas.android.com/apk/res/android"" package=""com.myapp.name.here"" android:installLocation=""auto"" android:versionCode=""10001"" android:versionName=""1""> <uses-sdk android:minSdkVersion=""18"" android:targetSdkVersion=""23"" /> <uses-permission android:name=""android.permission.CHANGE_WIFI_STATE"" /> <uses-permission android:name=""android.permission.ACCESS_WIFI_STATE"" /> <application android:label=""Scan Plan 2 Test"" android:icon="""" android:theme="""" /> </manifest>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformWithNamesapce5() { // Arrange var document = new XmlDocument(@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <appSettings> <add key=""ida:issuer"" value=""10000"" /> </appSettings> </configuration> "); // Act document.ReplaceKey(new[] { "configuration", "appSettings", "add[@key='ida:issuer']", "@value" }, "10001"); var result = document.ToString(); // Assert Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <appSettings> <add key=""ida:issuer"" value=""10001"" /> </appSettings> </configuration>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void AddElementToArray() { // Arrange var document = new XmlDocument(@"<xml> <a> <x>1</x> </a> <b>2</b> <c>3</c> <d /> </xml>"); // Act document.AddElementToArray(new[] { "xml", "d" }, "<val>1</val>"); document.AddElementToArray(new[] { "xml", "d" }, "<val>2</val>"); document.AddElementToArray(new[] { "xml", "f" }, "<x>1</x>"); var result = document.ToString(); // Assert Assert.Equal(@"<xml> <a> <x>1</x> </a> <b>2</b> <c>3</c> <d> <val>1</val> <val>2</val> </d> <f> <x>1</x> </f> </xml>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void Remove() { // Arrange var document = new XmlDocument(@"<xml> <a> <x>1</x> </a> <b> <x>1</x> </b> <c key=""item1"" foo=""bar"">3</c> </xml>"); // Act document.RemoveKey(new[] { "xml", "a" }); document.RemoveKey(new[] { "xml", "b", "x" }); document.RemoveKey(new[] { "xml", "c", "@key" }); var result = document.ToString(); // Assert Assert.Equal(@"<xml> <b /> <c foo=""bar"">3</c> </xml>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void RemoveByIndex() { // Arrange var document = new XmlDocument(@"<info> <val x=""1""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> <val x=""2""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> <val x=""1""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> </info>"); // Act document.RemoveKey(new[] { "info", "val[@x=\"2\"]", "param[1]", "option" }); document.RemoveKey(new[] { "info", "val[@x=\"1\"]", "param[2]" }); var result = document.ToString(); // Assert Assert.Equal(@"<info> <val x=""1""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> </val> <val x=""2""> <param> <option>AA</option> </param> <param> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> <val x=""1""> <param> <option>AA</option> </param> <param> <option>BB</option> <argument>CC</argument> </param> <param> <option>DD</option> </param> </val> </info>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void ValidateEmptyPath() { // Arrange XmlDocument document = new XmlDocument("<xml/>"); // Act ArgumentException result = Assert.Throws<ArgumentException>(() => document.ReplaceKey(new[] { "a", "", "b" }, "")); // Assert Assert.True(result.Message?.StartsWith("There is empty items in the path.")); } [Fact] public void ValidateWhiteSpacePath() { // Arrange XmlDocument document = new XmlDocument("<xml/>"); // Act ArgumentException result = Assert.Throws<ArgumentException>(() => document.ReplaceKey(new[] { "a", " ", "b" }, "")); // Assert Assert.True(result.Message?.StartsWith("There is empty items in the path.")); } [Fact] public void ValidateAmpersandsEscaping() { // Arrange XmlDocument document = new XmlDocument(@"<configuration> <connectionStrings> <add name=""Connection"" connectionString="""" /> </connectionStrings> </configuration>"); // Act document.ReplaceKey(new [] { "configuration", "connectionStrings", "add[@name=\"Connection\"]", "@connectionString" }, @"metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=other-server\instance;initial catalog=database;integrated security=True;multipleactiveresultsets=True;&quot;"); var result = document.ToString(); // Assert Assert.Equal(@"<configuration> <connectionStrings> <add name=""Connection"" connectionString=""metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=other-server\instance;initial catalog=database;integrated security=True;multipleactiveresultsets=True;&quot;"" /> </connectionStrings> </configuration>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void ValidateAmpersandsEscaping2() { // Arrange XmlDocument document = new XmlDocument(@"<configuration> <connectionStrings> <add name=""Connection"" connectionString="""" /> </connectionStrings> </configuration>"); // Act document.ReplaceKey(new[] { "configuration", "connectionStrings", "add[@name=\"Connection\"]", "@connectionString" }, @"metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=""data source=other-server\instance;initial catalog=database;integrated security=True;multipleactiveresultsets=True;"""); var result = document.ToString(); // Assert1 Assert.Equal(@"<configuration> <connectionStrings> <add name=""Connection"" connectionString=""metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=other-server\instance;initial catalog=database;integrated security=True;multipleactiveresultsets=True;&quot;"" /> </connectionStrings> </configuration>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformWithColonInAttributeName() { // Arrange var document = new XmlDocument(@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <appSettings> <add key=""Auth:Environment"" value=""Testing"" /> <add key=""Auth:Credential"" value=""abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"" /> <add key=""Auth:Type"" value=""Basic"" /> <add key=""Auth:Provider:Name"" value=""Name"" /> </appSettings> </configuration>"); document.ReplaceKey(new[] { "configuration", "appSettings", "add[@key = 'Auth:Environment']", "@value" }, "Production"); document.ReplaceKey(new[] { "configuration", "appSettings", "add[@key=\"Auth:Credential\"]", "@value" }, "XqoL6MXqOPeGTxXrJsQA7gK5cXLvnlSYJUtAwFWbRo7GDkbsSu"); document.ReplaceKey(new[] { "configuration", "appSettings", "add[@key=\"Auth:Type\"]", "@value" }, "Bearer"); document.ReplaceKey(new[] { "configuration", "appSettings", "add[@key=\"Auth:Provider:Name\"]", "@value" }, "ABC"); var result = document.ToString(); // Assert Assert.Equal(@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <appSettings> <add key=""Auth:Environment"" value=""Production"" /> <add key=""Auth:Credential"" value=""XqoL6MXqOPeGTxXrJsQA7gK5cXLvnlSYJUtAwFWbRo7GDkbsSu"" /> <add key=""Auth:Type"" value=""Bearer"" /> <add key=""Auth:Provider:Name"" value=""ABC"" /> </appSettings> </configuration>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformProcessingInstructions() { // Arrange var document = new XmlDocument(@"<Wix xmlns=""http://schemas.microsoft.com/wix/2006/wi""> <?define ProductName=""My product for ArcGIS 10.2""?> <?define ProductVersion=""1.3.0.0"" ?> <?test value=""1"" ?> </Wix>"); document.ReplaceKey(new[] { "Wix", "?define[@ProductName = 'My product for ArcGIS 10.2']", "@ProductName" }, "My product for ArcGIS 10.3"); document.ReplaceKey(new[] { "Wix", "?define[@ProductName = 'My product for ArcGIS 10.3']", "@ProductURL" }, "http://"); document.ReplaceKey(new[] { "Wix", "?test", "@value" }, "2"); var result = document.ToString(); // Assert Assert.Equal(@"<Wix xmlns=""http://schemas.microsoft.com/wix/2006/wi""> <?define ProductName=""My product for ArcGIS 10.3"" ProductURL=""http://""?> <?define ProductVersion=""1.3.0.0"" ?> <?test value=""2"" ?> </Wix>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformProcessingInstructions2() { // Arrange var document = new XmlDocument(@"<Wix xmlns=""http://schemas.microsoft.com/wix/2006/wi""> <?define ProductName=""My product for ArcGIS 10.2"" x=""2""?> <?define ProductVersion=""1.3.0.0"" ?> </Wix>"); document.ReplaceKey(new[] { "Wix", "Nested", "Nested2", "?define", "@ProductName" }, "My product for ArcGIS 10.3"); document.RemoveKey(new[] { "Wix", "?define[@ProductName = 'My product for ArcGIS 10.2']", "@x" }); document.RemoveKey(new[] { "Wix", "?define[@ProductVersion = '1.3.0.0']" }); var result = document.ToString(); // Assert Assert.Equal(@"<Wix xmlns=""http://schemas.microsoft.com/wix/2006/wi""> <Nested> <Nested2> <?define ProductName=""My product for ArcGIS 10.3""?> </Nested2> </Nested> <?define ProductName=""My product for ArcGIS 10.2""?> </Wix>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } [Fact] public void TransformProcessingInstructions3() { // Arrange var document = new XmlDocument(@"<Wix xmlns=""http://schemas.microsoft.com/wix/2006/wi""> <?define ProductName=""My product for ArcGIS 10.2"" test=""1""?> <?define ProductVersion=""1.3.0.0"" ?> <?define ProductUrl=""1.3.0.0"" ?> <?define ProductLicence=""1.3.0.0"" ?> </Wix>"); document.ReplaceKey(new[] { "Wix", "?define[1]", "@test" }, "2"); document.RemoveKey(new[] { "Wix", "?define[0]", "@test" }); document.RemoveKey(new[] { "Wix", "?define[3]"}); var result = document.ToString(); // Assert Assert.Equal(@"<Wix xmlns=""http://schemas.microsoft.com/wix/2006/wi""> <?define ProductName=""My product for ArcGIS 10.2"" ?> <?define ProductVersion=""1.3.0.0"" test=""2""?> <?define ProductUrl=""1.3.0.0"" ?> </Wix>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } } }
using Breeze.Core; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Breeze.Persistence.EFCore { public class MetadataBuilder { public static BreezeMetadata BuildFrom(DbContext dbContext) { return new MetadataBuilder().GetMetadataFromContext(dbContext); } private BreezeMetadata GetMetadataFromContext(DbContext dbContext) { var metadata = new BreezeMetadata(); var dbSetMap = GetDbSetMap(dbContext); metadata.StructuralTypes = dbContext.Model.GetEntityTypes() .Where(et => !et.IsOwned()) .Select(et => CreateMetaType(et, dbSetMap)).ToList(); var complexTypes = dbContext.Model.GetEntityTypes() .Where(et => et.IsOwned()) .Select(et => CreateMetaType(et, dbSetMap)).ToList(); // Complex types show up once per parent reference and we need to reduce // this to just the unique types. var complexTypesMap = complexTypes.ToDictionary(mt => mt.ShortName); complexTypesMap.Values.ToList().ForEach(v => metadata.StructuralTypes.Insert(0, v)); // Get the enums out of the model types var enums = dbContext.Model.GetEntityTypes() .SelectMany(et => et.GetProperties().Where(p => p.PropertyInfo != null && IsEnum(p.PropertyInfo.PropertyType))).ToList(); if (enums.Any()) { metadata.EnumTypes = new List<MetaEnum>(); foreach (var myEnum in enums) { var realType = myEnum.ClrType; // Check if realType is nullable if (Nullable.GetUnderlyingType(realType) != null) { realType = Nullable.GetUnderlyingType(realType); } string[] enumNames = Enum.GetNames(realType); int[] enumOrds = Enum.GetValues(realType) as int[]; var et = new MetaEnum { ShortName = realType.Name, Namespace = realType.Namespace, Values = enumNames, Ordinals = enumOrds }; if (!metadata.EnumTypes.Exists(x => x.ShortName == realType.Name)) { metadata.EnumTypes.Add(et); } } } return metadata; } private static bool IsEnum(Type type) { return type.IsEnum || (Nullable.GetUnderlyingType(type) != null && Nullable.GetUnderlyingType(type).IsEnum); } private static Dictionary<Type, String> GetDbSetMap(DbContext context) { var dbSetProperties = new List<PropertyInfo>(); var properties = context.GetType().GetProperties(); var result = new Dictionary<Type, String>(); foreach (var property in properties) { var setType = property.PropertyType; var isDbSet = setType.IsGenericType && (typeof(DbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition())); if (isDbSet) { var entityType = setType.GetGenericArguments()[0]; var resourceName = property.Name; result.Add(entityType, resourceName); } } return result; } private MetaType CreateMetaType(Microsoft.EntityFrameworkCore.Metadata.IEntityType et, Dictionary<Type, String> dbSetMap) { var mt = new MetaType { ShortName = et.ClrType.Name, Namespace = et.ClrType.Namespace }; if (et.IsOwned()) { mt.IsComplexType = true; } if (dbSetMap.TryGetValue(et.ClrType, out string resourceName)) { mt.DefaultResourceName = resourceName; } var baseType = et.BaseType; if (baseType != null) { mt.BaseTypeName = baseType.ClrType.Name + ":#" + baseType.ClrType.Namespace; } if (et.IsAbstract()) { mt.IsAbstract = true; } // Create data properties declared on this type (not base types) mt.DataProperties = et.GetProperties() .Where(p => p.DeclaringEntityType == et) .Select(p => CreateDataProperty(p)).ToList(); // EF returns parent's key with the complex type - we need to remove this. if (mt.IsComplexType) { mt.DataProperties = mt.DataProperties.Where(dp => dp.IsPartOfKey == null).ToList(); } if (!mt.IsComplexType) { mt.AutoGeneratedKeyType = mt.DataProperties.Any(dp => dp.IsIdentityColumn) ? AutoGeneratedKeyType.Identity : AutoGeneratedKeyType.None; } // Handle complex properties // for now this only complex types ( 'owned types' in EF parlance are eager loaded) var ownedNavigations = et.GetNavigations() .Where(p => p.DeclaringEntityType == et) .Where(n => n.TargetEntityType.IsOwned()); ownedNavigations.ToList().ForEach(n => { var complexType = n.TargetEntityType.ClrType; var dp = new MetaDataProperty(); dp.NameOnServer = n.Name; dp.IsNullable = false; dp.IsPartOfKey = false; dp.ComplexTypeName = NormalizeTypeName(complexType); mt.DataProperties.Add(dp); }); mt.NavigationProperties = et.GetNavigations() .Where(p => p.DeclaringEntityType == et) .Where(n => !n.TargetEntityType.IsOwned()).Select(p => CreateNavProperty(p)).ToList(); return mt; } private MetaDataProperty CreateDataProperty(IProperty p) { var dp = new MetaDataProperty(); dp.NameOnServer = p.Name; dp.IsNullable = p.IsNullable; dp.IsPartOfKey = p.IsPrimaryKey() ? true : (bool?)null; dp.IsIdentityColumn = p.IsPrimaryKey() && p.ValueGenerated == ValueGenerated.OnAdd; dp.MaxLength = p.GetMaxLength(); dp.DataType = NormalizeDataTypeName(p.ClrType); if (IsEnum(p.ClrType)) { dp.EnumType = NormalizeTypeName(TypeFns.GetNonNullableType(p.ClrType)); } dp.ConcurrencyMode = p.IsConcurrencyToken ? "Fixed" : null; var dfa = p.GetAnnotations().Where(a => a.Name == "DefaultValue").FirstOrDefault(); if (dfa != null) { dp.DefaultValue = dfa.Value; } else if (!p.IsNullable) { // TODO: this should really be done on the client. if (p.ClrType == typeof(TimeSpan)) { dp.DefaultValue = "PT0S"; } // dp.DefaultValue = // get default value for p.ClrType datatype } dp.AddValidators(p.ClrType); return dp; } private MetaNavProperty CreateNavProperty(INavigation p) { var np = new MetaNavProperty(); np.NameOnServer = p.Name; np.EntityTypeName = NormalizeTypeName(p.TargetEntityType.ClrType); np.IsScalar = !p.IsCollection; // FK_<dependent type name>_<principal type name>_<foreign key property name> np.AssociationName = BuildAssocName(p); if (p.IsOnDependent) { np.AssociationName = BuildAssocName(p); np.ForeignKeyNamesOnServer = p.ForeignKey.Properties.Select(fkp => fkp.Name).ToList(); if (!p.ForeignKey.PrincipalKey.IsPrimaryKey()) { // if FK does not relate to PK of other entity, then identify the foreign property np.InvForeignKeyNamesOnServer = p.ForeignKey.PrincipalKey.Properties.Select(fkp => fkp.Name).ToList(); } } else { var invP = p.Inverse; string assocName; if (invP == null) { assocName = "Inv_" + BuildAssocName(p); } else { assocName = BuildAssocName(invP); } np.AssociationName = assocName; np.InvForeignKeyNamesOnServer = p.ForeignKey.Properties.Select(fkp => fkp.Name).ToList(); } return np; } private string BuildAssocName(INavigation prop) { var assocName = prop.DeclaringEntityType.Name + "_" + prop.TargetEntityType.Name + "_" + prop.Name; return assocName; } private string NormalizeTypeName(Type type) { return type.Name + ":#" + type.Namespace; } private string NormalizeDataTypeName(Type type) { type = TypeFns.GetNonNullableType(type); var result = type.ToString().Replace("System.", ""); if (result == "Byte[]") { return "Binary"; } else { return result; } } } }
using System; using System.Collections.Generic; using System.Net; using NUnit.Framework; using ServiceStack.Common.Extensions; using ServiceStack.Logging; using ServiceStack.Logging.Support.Logging; using ServiceStack.Service; using ServiceStack.ServiceClient.Web; using ServiceStack.ServiceModel.Serialization; using ServiceStack.WebHost.Endpoints.Tests.Support.Host; namespace ServiceStack.WebHost.Endpoints.Tests { /// <summary> /// These tests fail with Unauthorized exception when left last to run, /// so prefixing with '_' to hoist its priority till we find out wtf is up /// </summary> public abstract class SyncRestClientTests : IDisposable { protected const string ListeningOn = "http://localhost:85/"; ExampleAppHostHttpListener appHost; [TestFixtureSetUp] public void OnTestFixtureSetUp() { LogManager.LogFactory = new ConsoleLogFactory(); appHost = new ExampleAppHostHttpListener(); appHost.Init(); appHost.Start(ListeningOn); } [TestFixtureTearDown] public void OnTestFixtureTearDown() { Dispose(); } public void Dispose() { if (appHost == null) return; appHost.Dispose(); appHost = null; } protected abstract IRestClient CreateRestClient(); //protected virtual IRestClient CreateRestClient() //{ // return new XmlServiceClient(ListeningOn); //} static object[] GetFactorialRoutes = { "factorial/3", "fact/3" }; [TestCase("factorial/3")] [TestCase("fact/3")] public void Can_GET_GetFactorial_using_RestClient(string path) { var restClient = CreateRestClient(); var response = restClient.Get<GetFactorialResponse>(path); Assert.That(response, Is.Not.Null, "No response received"); Assert.That(response.Result, Is.EqualTo(GetFactorialService.GetFactorial(3))); } [TestCase("movies")] [TestCase("custom-movies")] public void Can_GET_Movies_using_RestClient(string path) { var restClient = CreateRestClient(); var response = restClient.Get<MoviesResponse>(path); Assert.That(response, Is.Not.Null, "No response received"); Assert.That(response.Movies.EquivalentTo(ResetMoviesService.Top5Movies)); } [TestCase("movies/1")] [TestCase("custom-movies/1")] public void Can_GET_single_Movie_using_RestClient(string path) { var restClient = CreateRestClient(); var response = restClient.Get<MovieResponse>(path); Assert.That(response, Is.Not.Null, "No response received"); Assert.That(response.Movie.Id, Is.EqualTo(1)); } [TestCase("movies")] [TestCase("custom-movies")] public void Can_POST_to_add_new_Movie_using_RestClient(string path) { var restClient = CreateRestClient(); var newMovie = new Movie { ImdbId = "tt0450259", Title = "Blood Diamond", Rating = 8.0m, Director = "Edward Zwick", ReleaseDate = new DateTime(2007, 1, 26), TagLine = "A fisherman, a smuggler, and a syndicate of businessmen match wits over the possession of a priceless diamond.", Genres = new List<string> { "Adventure", "Drama", "Thriller" }, }; var response = restClient.Post<MovieResponse>(path, newMovie); Assert.That(response, Is.Not.Null, "No response received"); var createdMovie = response.Movie; Assert.That(createdMovie.Id, Is.GreaterThan(0)); Assert.That(createdMovie.ImdbId, Is.EqualTo(newMovie.ImdbId)); } [Test] public void Can_Deserialize_Xml_MovieResponse() { try { var xml = "<MovieResponse xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.servicestack.net/types\"><Movie><Director>Edward Zwick</Director><Genres xmlns:d3p1=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"><d3p1:string>Adventure</d3p1:string><d3p1:string>Drama</d3p1:string><d3p1:string>Thriller</d3p1:string></Genres><Id>6</Id><ImdbId>tt0450259</ImdbId><Rating>8</Rating><ReleaseDate>2007-01-26T00:00:00+00:00</ReleaseDate><TagLine>A fisherman, a smuggler, and a syndicate of businessmen match wits over the possession of a priceless diamond.</TagLine><Title>Blood Diamond</Title></Movie></MovieResponse>"; var response = DataContractDeserializer.Instance.Parse<MovieResponse>(xml); var toXml = DataContractSerializer.Instance.Parse(response); Console.WriteLine("XML: " + toXml); } catch (Exception ex) { Console.WriteLine(ex); throw; } } [TestCase("movies", "movies/")] [TestCase("custom-movies", "custom-movies/")] public void Can_DELETE_Movie_using_RestClient(string postPath, string deletePath) { var restClient = CreateRestClient(); var newMovie = new Movie { ImdbId = "tt0450259", Title = "Blood Diamond", Rating = 8.0m, Director = "Edward Zwick", ReleaseDate = new DateTime(2007, 1, 26), TagLine = "A fisherman, a smuggler, and a syndicate of businessmen match wits over the possession of a priceless diamond.", Genres = new List<string> { "Adventure", "Drama", "Thriller" }, }; var response = restClient.Post<MovieResponse>(postPath, newMovie); var createdMovie = response.Movie; response = restClient.Delete<MovieResponse>(deletePath + createdMovie.Id); Assert.That(createdMovie, Is.Not.Null); Assert.That(response.Movie, Is.Null); } } [TestFixture] public class JsonSyncRestClientTests : SyncRestClientTests { protected override IRestClient CreateRestClient() { return new JsonServiceClient(ListeningOn); } [Test] public void Can_use_response_filters() { var isActioncalledGlobal = false; var isActioncalledLocal = false; ServiceClientBase.HttpWebResponseFilter = r => isActioncalledGlobal = true; var restClient = (JsonServiceClient)CreateRestClient(); restClient.LocalHttpWebResponseFilter = r => isActioncalledLocal = true; restClient.Get<MoviesResponse>("movies"); Assert.That(isActioncalledGlobal, Is.True); Assert.That(isActioncalledLocal, Is.True); } } [TestFixture] public class JsvSyncRestClientTests : SyncRestClientTests { protected override IRestClient CreateRestClient() { return new JsvServiceClient(ListeningOn); } } [TestFixture] public class XmlSyncRestClientTests : SyncRestClientTests { protected override IRestClient CreateRestClient() { return new XmlServiceClient(ListeningOn); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset { public class HGAssetBroker : ISharedRegionModule, IAssetService, IHyperAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private IImprovedAssetCache m_Cache = null; private IAssetService m_GridService; private IAssetService m_HGService; private Scene m_aScene; private string m_LocalAssetServiceURI; private bool m_Enabled = false; public Type ReplaceableInterface { get { return null; } } public string Name { get { return "HGAssetBroker"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetServices", ""); if (name == Name) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[HG ASSET CONNECTOR]: AssetService missing from OpenSim.ini"); return; } string localDll = assetConfig.GetString("LocalGridAssetService", String.Empty); string HGDll = assetConfig.GetString("HypergridAssetService", String.Empty); if (localDll == String.Empty) { m_log.Error("[HG ASSET CONNECTOR]: No LocalGridAssetService named in section AssetService"); return; } if (HGDll == String.Empty) { m_log.Error("[HG ASSET CONNECTOR]: No HypergridAssetService named in section AssetService"); return; } Object[] args = new Object[] { source }; m_GridService = ServerUtils.LoadPlugin<IAssetService>(localDll, args); m_HGService = ServerUtils.LoadPlugin<IAssetService>(HGDll, args); if (m_GridService == null) { m_log.Error("[HG ASSET CONNECTOR]: Can't load local asset service"); return; } if (m_HGService == null) { m_log.Error("[HG ASSET CONNECTOR]: Can't load hypergrid asset service"); return; } m_LocalAssetServiceURI = assetConfig.GetString("AssetServerURI", string.Empty); if (m_LocalAssetServiceURI == string.Empty) { IConfig netConfig = source.Configs["Network"]; m_LocalAssetServiceURI = netConfig.GetString("asset_server_url", string.Empty); } if (m_LocalAssetServiceURI != string.Empty) m_LocalAssetServiceURI = m_LocalAssetServiceURI.Trim('/'); m_Enabled = true; m_log.Info("[HG ASSET CONNECTOR]: HG asset broker enabled"); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_aScene = scene; scene.RegisterModuleInterface<IAssetService>(this); scene.RegisterModuleInterface<IHyperAssetService>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_Cache == null) { m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>(); if (!(m_Cache is ISharedRegionModule)) m_Cache = null; } m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled hypergrid asset broker for region {0}", scene.RegionInfo.RegionName); if (m_Cache != null) { m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName); } } private bool IsHG(string id) { Uri assetUri; if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) && assetUri.Scheme == Uri.UriSchemeHttp) return true; return false; } public AssetBase Get(string id) { //m_log.DebugFormat("[HG ASSET CONNECTOR]: Get {0}", id); AssetBase asset = null; if (m_Cache != null) { asset = m_Cache.Get(id); if (asset != null) return asset; } if (IsHG(id)) { asset = m_HGService.Get(id); if (asset != null) { // Now store it locally // For now, let me just do it for textures and scripts if (((AssetType)asset.Type == AssetType.Texture) || ((AssetType)asset.Type == AssetType.LSLBytecode) || ((AssetType)asset.Type == AssetType.LSLText)) { m_GridService.Store(asset); } } } else asset = m_GridService.Get(id); if (asset != null) { if (m_Cache != null) m_Cache.Cache(asset); } return asset; } public AssetBase GetCached(string id) { if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { AssetBase asset = null; if (m_Cache != null) { if (m_Cache != null) m_Cache.Get(id); if (asset != null) return asset.Metadata; } AssetMetadata metadata; if (IsHG(id)) metadata = m_HGService.GetMetadata(id); else metadata = m_GridService.GetMetadata(id); return metadata; } public byte[] GetData(string id) { AssetBase asset = null; if (m_Cache != null) { if (m_Cache != null) m_Cache.Get(id); if (asset != null) return asset.Data; } if (IsHG(id)) asset = m_HGService.Get(id); else asset = m_GridService.Get(id); if (asset != null) { if (m_Cache != null) m_Cache.Cache(asset); return asset.Data; } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) { Util.FireAndForget(delegate { handler(id, sender, asset); }); return true; } if (IsHG(id)) { return m_HGService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if (a != null && m_Cache != null) m_Cache.Cache(a); handler(assetID, s, a); }); } else { return m_GridService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if (a != null && m_Cache != null) m_Cache.Cache(a); handler(assetID, s, a); }); } } public string Store(AssetBase asset) { bool isHG = IsHG(asset.ID); if ((m_Cache != null) && !isHG) // Don't store it in the cache if the asset is to // be sent to the other grid, because this is already // a copy of the local asset. m_Cache.Cache(asset); if (asset.Temporary || asset.Local) return asset.ID; if (IsHG(asset.ID)) return m_HGService.Store(asset); else return m_GridService.Store(asset); } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) { asset.Data = data; m_Cache.Cache(asset); } if (IsHG(id)) return m_HGService.UpdateContent(id, data); else return m_GridService.UpdateContent(id, data); } public bool Delete(string id) { if (m_Cache != null) m_Cache.Expire(id); if (IsHG(id)) return m_HGService.Delete(id); else return m_GridService.Delete(id); } #region IHyperAssetService public string GetUserAssetServer(UUID userID) { CachedUserInfo uinfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(userID); if ((uinfo != null) && (uinfo.UserProfile != null)) { if ((uinfo.UserProfile.UserAssetURI == string.Empty) || (uinfo.UserProfile.UserAssetURI == "")) return m_LocalAssetServiceURI; return uinfo.UserProfile.UserAssetURI.Trim('/'); } else { // we don't know anyting about this user return string.Empty; } } public string GetSimAssetServer() { return m_LocalAssetServiceURI; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information using System; using System.Collections; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.Versioning; using System.Security; using System.Security.Principal; namespace System.Data.ProviderBase { internal abstract class DbConnectionPoolCounters { private static class CreationData { static internal readonly CounterCreationData HardConnectsPerSecond = new CounterCreationData( "HardConnectsPerSecond", "The number of actual connections per second that are being made to servers", PerformanceCounterType.RateOfCountsPerSecond32); static internal readonly CounterCreationData HardDisconnectsPerSecond = new CounterCreationData( "HardDisconnectsPerSecond", "The number of actual disconnects per second that are being made to servers", PerformanceCounterType.RateOfCountsPerSecond32); static internal readonly CounterCreationData SoftConnectsPerSecond = new CounterCreationData( "SoftConnectsPerSecond", "The number of connections we get from the pool per second", PerformanceCounterType.RateOfCountsPerSecond32); static internal readonly CounterCreationData SoftDisconnectsPerSecond = new CounterCreationData( "SoftDisconnectsPerSecond", "The number of connections we return to the pool per second", PerformanceCounterType.RateOfCountsPerSecond32); static internal readonly CounterCreationData NumberOfNonPooledConnections = new CounterCreationData( "NumberOfNonPooledConnections", "The number of connections that are not using connection pooling", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfPooledConnections = new CounterCreationData( "NumberOfPooledConnections", "The number of connections that are managed by the connection pooler", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfActiveConnectionPoolGroups = new CounterCreationData( "NumberOfActiveConnectionPoolGroups", "The number of unique connection strings", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfInactiveConnectionPoolGroups = new CounterCreationData( "NumberOfInactiveConnectionPoolGroups", "The number of unique connection strings waiting for pruning", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfActiveConnectionPools = new CounterCreationData( "NumberOfActiveConnectionPools", "The number of connection pools", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfInactiveConnectionPools = new CounterCreationData( "NumberOfInactiveConnectionPools", "The number of connection pools", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfActiveConnections = new CounterCreationData( "NumberOfActiveConnections", "The number of connections currently in-use", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfFreeConnections = new CounterCreationData( "NumberOfFreeConnections", "The number of connections currently available for use", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfStasisConnections = new CounterCreationData( "NumberOfStasisConnections", "The number of connections currently waiting to be made ready for use", PerformanceCounterType.NumberOfItems32); static internal readonly CounterCreationData NumberOfReclaimedConnections = new CounterCreationData( "NumberOfReclaimedConnections", "The number of connections we reclaim from GC'd external connections", PerformanceCounterType.NumberOfItems32); }; sealed internal class Counter { private PerformanceCounter _instance; internal Counter(string categoryName, string instanceName, string counterName, PerformanceCounterType counterType) { if (ADP.IsPlatformNT5) { try { if (!ADP.IsEmpty(categoryName) && !ADP.IsEmpty(instanceName)) { PerformanceCounter instance = new PerformanceCounter(); instance.CategoryName = categoryName; instance.CounterName = counterName; instance.InstanceName = instanceName; instance.InstanceLifetime = PerformanceCounterInstanceLifetime.Process; instance.ReadOnly = false; instance.RawValue = 0; // make sure we start out at zero _instance = instance; } } catch (InvalidOperationException e) { ADP.TraceExceptionWithoutRethrow(e); // TODO: generate Application EventLog entry about inability to find perf counter } } } internal void Decrement() { PerformanceCounter instance = _instance; if (null != instance) { instance.Decrement(); } } internal void Dispose() { // TODO: race condition, Dispose at the same time as Increment/Decrement PerformanceCounter instance = _instance; _instance = null; if (null != instance) { instance.RemoveInstance(); // should we be calling instance.Close? // if we do will it exacerbate the Dispose vs. Decrement race condition //instance.Close(); } } internal void Increment() { PerformanceCounter instance = _instance; if (null != instance) { instance.Increment(); } } }; const int CounterInstanceNameMaxLength = 127; internal readonly Counter HardConnectsPerSecond; internal readonly Counter HardDisconnectsPerSecond; internal readonly Counter SoftConnectsPerSecond; internal readonly Counter SoftDisconnectsPerSecond; internal readonly Counter NumberOfNonPooledConnections; internal readonly Counter NumberOfPooledConnections; internal readonly Counter NumberOfActiveConnectionPoolGroups; internal readonly Counter NumberOfInactiveConnectionPoolGroups; internal readonly Counter NumberOfActiveConnectionPools; internal readonly Counter NumberOfInactiveConnectionPools; internal readonly Counter NumberOfActiveConnections; internal readonly Counter NumberOfFreeConnections; internal readonly Counter NumberOfStasisConnections; internal readonly Counter NumberOfReclaimedConnections; protected DbConnectionPoolCounters() : this(null, null) { } protected DbConnectionPoolCounters(string categoryName, string categoryHelp) { AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadEventHandler); AppDomain.CurrentDomain.ProcessExit += new EventHandler(this.ExitEventHandler); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.ExceptionEventHandler); string instanceName = null; if (!ADP.IsEmpty(categoryName)) { if (ADP.IsPlatformNT5) { instanceName = GetInstanceName(); } } // level 0-3: hard connects/disconnects, plus basic pool/pool entry statistics string basicCategoryName = categoryName; HardConnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardConnectsPerSecond.CounterName, CreationData.HardConnectsPerSecond.CounterType); HardDisconnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardDisconnectsPerSecond.CounterName, CreationData.HardDisconnectsPerSecond.CounterType); NumberOfNonPooledConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfNonPooledConnections.CounterName, CreationData.NumberOfNonPooledConnections.CounterType); NumberOfPooledConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfPooledConnections.CounterName, CreationData.NumberOfPooledConnections.CounterType); NumberOfActiveConnectionPoolGroups = new Counter(basicCategoryName, instanceName, CreationData.NumberOfActiveConnectionPoolGroups.CounterName, CreationData.NumberOfActiveConnectionPoolGroups.CounterType); NumberOfInactiveConnectionPoolGroups = new Counter(basicCategoryName, instanceName, CreationData.NumberOfInactiveConnectionPoolGroups.CounterName, CreationData.NumberOfInactiveConnectionPoolGroups.CounterType); NumberOfActiveConnectionPools = new Counter(basicCategoryName, instanceName, CreationData.NumberOfActiveConnectionPools.CounterName, CreationData.NumberOfActiveConnectionPools.CounterType); NumberOfInactiveConnectionPools = new Counter(basicCategoryName, instanceName, CreationData.NumberOfInactiveConnectionPools.CounterName, CreationData.NumberOfInactiveConnectionPools.CounterType); NumberOfStasisConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfStasisConnections.CounterName, CreationData.NumberOfStasisConnections.CounterType); NumberOfReclaimedConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfReclaimedConnections.CounterName, CreationData.NumberOfReclaimedConnections.CounterType); // level 4: expensive stuff string verboseCategoryName = null; if (!ADP.IsEmpty(categoryName)) { // don't load TraceSwitch if no categoryName so that Odbc/OleDb have a chance of not loading TraceSwitch // which are also used by System.Diagnostics.PerformanceCounter.ctor & System.Transactions.get_Current TraceSwitch perfCtrSwitch = new TraceSwitch("ConnectionPoolPerformanceCounterDetail", "level of detail to track with connection pool performance counters"); if (TraceLevel.Verbose == perfCtrSwitch.Level) { verboseCategoryName = categoryName; } } SoftConnectsPerSecond = new Counter(verboseCategoryName, instanceName, CreationData.SoftConnectsPerSecond.CounterName, CreationData.SoftConnectsPerSecond.CounterType); SoftDisconnectsPerSecond = new Counter(verboseCategoryName, instanceName, CreationData.SoftDisconnectsPerSecond.CounterName, CreationData.SoftDisconnectsPerSecond.CounterType); NumberOfActiveConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfActiveConnections.CounterName, CreationData.NumberOfActiveConnections.CounterType); NumberOfFreeConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfFreeConnections.CounterName, CreationData.NumberOfFreeConnections.CounterType); } private string GetAssemblyName() { string result = null; // First try GetEntryAssembly name, then AppDomain.FriendlyName. Assembly assembly = Assembly.GetEntryAssembly(); if (null != assembly) { AssemblyName name = assembly.GetName(); if (name != null) { result = name.Name; } } return result; } // SxS: this method uses GetCurrentProcessId to construct the instance name. // TODO: remove the Resource* attributes if you do not use GetCurrentProcessId after the fix private string GetInstanceName() { string result = null; string instanceName = GetAssemblyName(); // instance perfcounter name if (ADP.IsEmpty(instanceName)) { AppDomain appDomain = AppDomain.CurrentDomain; if (null != appDomain) { instanceName = appDomain.FriendlyName; } } // TODO: If you do not use GetCurrentProcessId after fixing VSDD 534795, please remove Resource* attributes from this method int pid = SafeNativeMethods.GetCurrentProcessId(); // there are several characters which have special meaning // to PERFMON. They recommend that we translate them as shown below, to // prevent problems. result = String.Format((IFormatProvider)null, "{0}[{1}]", instanceName, pid); result = result.Replace('(', '[').Replace(')', ']').Replace('#', '_').Replace('/', '_').Replace('\\', '_'); // counter instance name cannot be greater than 127 if (result.Length > CounterInstanceNameMaxLength) { // Replacing the middle part with "[...]" // For example: if path is c:\long_path\very_(Ax200)_long__path\perftest.exe and process ID is 1234 than the resulted instance name will be: // c:\long_path\very_(AxM)[...](AxN)_long__path\perftest.exe[1234] // while M and N are adjusted to make each part before and after the [...] = 61 (making the total = 61 + 5 + 61 = 127) const string insertString = "[...]"; int firstPartLength = (CounterInstanceNameMaxLength - insertString.Length) / 2; int lastPartLength = CounterInstanceNameMaxLength - firstPartLength - insertString.Length; result = string.Format((IFormatProvider)null, "{0}{1}{2}", result.Substring(0, firstPartLength), insertString, result.Substring(result.Length - lastPartLength, lastPartLength)); Debug.Assert(result.Length == CounterInstanceNameMaxLength, string.Format((IFormatProvider)null, "wrong calculation of the instance name: expected {0}, actual: {1}", CounterInstanceNameMaxLength, result.Length)); } return result; } public void Dispose() { // ExceptionEventHandler with IsTerminiating may be called before // the Connection Close is called or the variables are initialized SafeDispose(HardConnectsPerSecond); SafeDispose(HardDisconnectsPerSecond); SafeDispose(SoftConnectsPerSecond); SafeDispose(SoftDisconnectsPerSecond); SafeDispose(NumberOfNonPooledConnections); SafeDispose(NumberOfPooledConnections); SafeDispose(NumberOfActiveConnectionPoolGroups); SafeDispose(NumberOfInactiveConnectionPoolGroups); SafeDispose(NumberOfActiveConnectionPools); SafeDispose(NumberOfActiveConnections); SafeDispose(NumberOfFreeConnections); SafeDispose(NumberOfStasisConnections); SafeDispose(NumberOfReclaimedConnections); } private void SafeDispose(Counter counter) { if (null != counter) { counter.Dispose(); } } void ExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) { if ((null != e) && e.IsTerminating) { Dispose(); } } void ExitEventHandler(object sender, EventArgs e) { Dispose(); } void UnloadEventHandler(object sender, EventArgs e) { Dispose(); } } sealed internal class DbConnectionPoolCountersNoCounters : DbConnectionPoolCounters { public static readonly DbConnectionPoolCountersNoCounters SingletonInstance = new DbConnectionPoolCountersNoCounters(); private DbConnectionPoolCountersNoCounters() : base() { } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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.Diagnostics; using System.IO; using System.Threading; using MindTouch.Dream; using MindTouch.IO; using MindTouch.Threading; namespace MindTouch.Tasking { using Yield = IEnumerator<IYield>; /// <summary> /// Thrown when completion of all of a list of alternate synchronization handles fails. /// </summary> /// <remarks>Used by <see cref="AResultEx.Alt"/> and <see cref="AResultEx.Alt{T}"/>.</remarks> /// <seealso cref="AResultEx.Alt"/> /// <seealso cref="AResultEx.Alt{T}"/> public class AsyncAllAlternatesFailed : Exception { } /// <summary> /// Static utility class containing extension and helper methods for handling asynchronous execution. /// </summary> public static class Async { //--- Types --- private delegate void AvailableThreadsDelegate(out int availableThreads, out int availablePorts); //--- Class Fields --- /// <summary> /// The globally accessible <see cref="IDispatchQueue"/> for dispatching work without queue affinity. /// </summary> public static readonly IDispatchQueue GlobalDispatchQueue; private static log4net.ILog _log = LogUtils.CreateLog(); private static readonly TimeSpan READ_TIMEOUT = TimeSpan.FromSeconds(30); private static bool _inplaceActivation = true; private static readonly int _minThreads; private static readonly int _maxThreads; private static readonly int _minPorts; private static readonly int _maxPorts; private static readonly AvailableThreadsDelegate _availableThreadsCallback; private static readonly int? _maxStackSize; [ThreadStatic] private static IDispatchQueue _currentDispatchQueue; //--- Constructors --- static Async() { if(!int.TryParse(System.Configuration.ConfigurationManager.AppSettings["threadpool-min"], out _minThreads)) { _minThreads = 4; } if(!int.TryParse(System.Configuration.ConfigurationManager.AppSettings["threadpool-max"], out _maxThreads)) { _maxThreads = 200; } int maxStackSize; if(int.TryParse(System.Configuration.ConfigurationManager.AppSettings["max-stacksize"], out maxStackSize)) { _maxStackSize = maxStackSize; } // check which global dispatch queue implementation to use int dummy; switch(System.Configuration.ConfigurationManager.AppSettings["threadpool"]) { default: case "elastic": ThreadPool.GetMinThreads(out dummy, out _minPorts); ThreadPool.GetMaxThreads(out dummy, out _maxPorts); _log.DebugFormat("Using ElasticThreadPool with {0}min / {1}max", _minThreads, _maxThreads); var elasticThreadPool = new ElasticThreadPool(_minThreads, _maxThreads); GlobalDispatchQueue = elasticThreadPool; _inplaceActivation = false; _availableThreadsCallback = delegate(out int threads, out int ports) { int dummy2; ThreadPool.GetAvailableThreads(out dummy2, out ports); threads = elasticThreadPool.MaxParallelThreads - elasticThreadPool.ThreadCount; }; break; case "legacy": ThreadPool.GetMinThreads(out dummy, out _minPorts); ThreadPool.GetMaxThreads(out dummy, out _maxPorts); ThreadPool.SetMinThreads(_minThreads, _minPorts); ThreadPool.SetMaxThreads(_maxThreads, _maxPorts); _log.Debug("Using LegacyThreadPool"); GlobalDispatchQueue = LegacyThreadPool.Instance; _availableThreadsCallback = ThreadPool.GetAvailableThreads; break; } } //--- Class Properties --- /// <summary> /// The <see cref="IDispatchQueue"/> used by the current execution environment. /// </summary> public static IDispatchQueue CurrentDispatchQueue { get { return _currentDispatchQueue ?? (_inplaceActivation ? ImmediateDispatchQueue.Instance : GlobalDispatchQueue); } set { _currentDispatchQueue = value; } } /// <summary> /// The maximum stack size that Threads created by Dream (<see cref="ElasticThreadPool"/>, <see cref="Fork(System.Action)"/>, <see cref="ForkThread(System.Action)"/>, etc.) /// should use. If null, uses process default stack size. /// </summary> public static int? MaxStackSize { get { return _maxStackSize; } } //--- Class Methods --- /// <summary> /// Get the maximum number of resources allowed for this process' execution environment. /// </summary> /// <param name="threads">Number of threads allowed.</param> /// <param name="ports">Number of completion ports allowed.</param> /// <param name="dispatchers">Number of dispatchers allowed.</param> public static void GetMaxThreads(out int threads, out int ports, out int dispatchers) { threads = _maxThreads; ports = _maxPorts; dispatchers = DispatchThreadScheduler.MaxThreadCount; } /// <summary> /// Get the minimum number of resources allocated forthis process' execution environment. /// </summary> /// <param name="threads">Minimum number of threads allocated.</param> /// <param name="ports">Minimum number of completion ports allocated.</param> /// <param name="dispatchers">Minimum number of dispatchers allocated.</param> public static void GetAvailableThreads(out int threads, out int ports, out int dispatchers) { _availableThreadsCallback(out threads, out ports); dispatchers = DispatchThreadScheduler.AvailableThreadCount; } /// <summary> /// Dispatch an action to be executed via the <see cref="GlobalDispatchQueue"/>. /// </summary> /// <param name="handler">Action to enqueue for execution.</param> public static void Fork(Action handler) { GlobalDispatchQueue.QueueWorkItemWithClonedEnv(handler, null); } /// <summary> /// Dispatch an action to be executed via the <see cref="GlobalDispatchQueue"/>. /// </summary> /// <param name="handler">Action to enqueue for execution.</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle for the action's execution.</returns> public static Result Fork(Action handler, Result result) { return GlobalDispatchQueue.QueueWorkItemWithClonedEnv(handler, result); } /// <summary> /// Dispatch an action to be executed via the <see cref="GlobalDispatchQueue"/>. /// </summary> /// <param name="handler">Action to enqueue for execution.</param> /// <param name="env">Environment in which to execute the action.</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle for the action's execution.</returns> public static Result Fork(Action handler, TaskEnv env, Result result) { return GlobalDispatchQueue.QueueWorkItemWithEnv(handler, env, result); } /// <summary> /// Dispatch an action to be executed via the <see cref="GlobalDispatchQueue"/>. /// </summary> /// <typeparam name="T">Type of result value produced by action.</typeparam> /// <param name="handler">Action to enqueue for execution.</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle for the action's execution.</returns> public static Result<T> Fork<T>(Func<T> handler, Result<T> result) { return GlobalDispatchQueue.QueueWorkItemWithClonedEnv(handler, result); } /// <summary> /// Dispatch an action to be executed with a new, dedicated backgrouns thread. /// </summary> /// <param name="handler">Action to enqueue for execution.</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle for the action's execution.</returns> public static Result ForkThread(Action handler, Result result) { ForkThread(TaskEnv.Clone().MakeAction(handler, result)); return result; } /// <summary> /// Dispatch an action to be executed with a new, dedicated backgrouns thread. /// </summary> /// <typeparam name="T">Type of result value produced by action.</typeparam> /// <param name="handler">Action to enqueue for execution.</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle for the action's execution.</returns> public static Result<T> ForkThread<T>(Func<T> handler, Result<T> result) { ForkThread(TaskEnv.Clone().MakeAction(handler, result)); return result; } /// <summary> /// Dispatch an action to be executed with a new, dedicated backgrouns thread. /// </summary> /// <param name="handler">Action to enqueue for execution.</param> private static void ForkThread(Action handler) { var t = MaxStackSize.HasValue ? new Thread(() => handler(), MaxStackSize.Value) { IsBackground = true } : new Thread(() => handler()) { IsBackground = true }; t.Start(); } /// <summary> /// De-schedule the current execution environment to sleep for some period. /// </summary> /// <param name="duration">Time to sleep.</param> /// <returns>Synchronization handle to continue execution after the sleep period.</returns> public static Result Sleep(TimeSpan duration) { Result result = new Result(TimeSpan.MaxValue); TaskTimerFactory.Current.New(duration, _ => result.Return(), null, TaskEnv.New()); return result; } /// <summary> /// Wrap a <see cref="WaitHandle"/> with <see cref="Result{WaitHandle}"/> to allow Result style synchronization with the handle. /// </summary> /// <param name="handle">The handle to wrap</param> /// <param name="result">The <see cref="Result{WaitHandle}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle for the action's execution.</returns> public static Result<WaitHandle> WaitHandle(this WaitHandle handle, Result<WaitHandle> result) { ThreadPool.RegisterWaitForSingleObject(handle, delegate(object _unused, bool timedOut) { if(timedOut) { result.Throw(new TimeoutException()); } else { result.Return(handle); } }, null, (int)result.Timeout.TotalMilliseconds, true); return result; } /// <summary> /// Execute a system process. /// </summary> /// <param name="application">Application to execute.</param> /// <param name="cmdline">Command line parameters for he application.</param> /// <param name="input">Input stream to pipe into the application.</param> /// <param name="result">The Result instance to be returned by this method.</param> /// <returns>Synchronization handle for the process execution, providing the application's exit code, output Stream and error Stream</returns> public static Result<Tuplet<int, Stream, Stream>> ExecuteProcess(string application, string cmdline, Stream input, Result<Tuplet<int, Stream, Stream>> result) { Stream output = new ChunkedMemoryStream(); Stream error = new ChunkedMemoryStream(); Result<int> innerResult = new Result<int>(result.Timeout); Coroutine.Invoke(ExecuteProcess_Helper, application, cmdline, input, output, error, innerResult).WhenDone(delegate(Result<int> _unused) { if(innerResult.HasException) { result.Throw(innerResult.Exception); } else { // reset stream positions output.Position = 0; error.Position = 0; // return outcome result.Return(new Tuplet<int, Stream, Stream>(innerResult.Value, output, error)); } }); return result; } /// <summary> /// Execute a system process. /// </summary> /// <param name="application">Application to execute.</param> /// <param name="cmdline">Command line parameters for he application.</param> /// <param name="input">Input stream to pipe into the application.</param> /// <param name="output"></param> /// <param name="error"></param> /// <param name="result">The <see cref="Result{Int32}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle for the process execution, providing the application's exit code</returns> public static Result<int> ExecuteProcess(string application, string cmdline, Stream input, Stream output, Stream error, Result<int> result) { return Coroutine.Invoke(ExecuteProcess_Helper, application, cmdline, input, output, error, result); } private static Yield ExecuteProcess_Helper(string application, string cmdline, Stream input, Stream output, Stream error, Result<int> result) { // start process var proc = new Process(); proc.StartInfo.FileName = application; proc.StartInfo.Arguments = cmdline; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardInput = (input != null); proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.Start(); // inject input if(input != null) { input.CopyTo(proc.StandardInput.BaseStream, long.MaxValue, new Result<long>(TimeSpan.MaxValue)).WhenDone(_ => { // trying closing the original input stream try { input.Close(); } catch { } // try closing the process input pipe try { proc.StandardInput.Close(); } catch { } }); } // extract output stream Result<long> outputDone = proc.StandardOutput.BaseStream.CopyTo(output, long.MaxValue, new Result<long>(TimeSpan.MaxValue)); // extract error stream Result<long> errorDone = proc.StandardError.BaseStream.CopyTo(error, long.MaxValue, new Result<long>(TimeSpan.MaxValue)); TaskTimer timer = TaskTimerFactory.Current.New(result.Timeout, delegate(TaskTimer t) { try { // NOTE (steveb): we had to add the try..catch handler because mono throws an exception when killing a terminated process (why? who knows!) proc.Kill(); } catch { } }, null, TaskEnv.New()); // wait for output and error streams to be done yield return new AResult[] { outputDone, errorDone }.Join(); int? exitCode = WaitForExit(proc, result.Timeout); timer.Cancel(); proc.Close(); if(exitCode.HasValue) { result.Return(exitCode.Value); } else { result.Throw(new InvalidOperationException("Unable to access process exit code")); } } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <param name="begin">Lambda wrapping a no-arg async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public static Result From(Func<AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, object state, Result result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { end(v); } catch(Exception e) { result.Throw(e); return; } result.Return(); }, result.Throw ); // begin asynchronous invocation try { begin(continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T1">Type of asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a single argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">Asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public static Result From<T1>(Func<T1, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, object state, Result result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { end(v); } catch(Exception e) { result.Throw(e); return; } result.Return(); }, result.Throw ); // begin asynchronous invocation try { begin(item1, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 2 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public static Result From<T1, T2>(Func<T1, T2, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, object state, Result result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { end(v); } catch(Exception e) { result.Throw(e); return; } result.Return(); }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <typeparam name="T3">Type of third asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 3 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="item3">Third asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public static Result From<T1, T2, T3>(Func<T1, T2, T3, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, T3 item3, object state, Result result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { end(v); } catch(Exception e) { result.Throw(e); return; } result.Return(); }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, item3, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <typeparam name="T3">Type of third asynchronous method argument.</typeparam> /// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 4 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="item3">Third asynchronous method argument.</param> /// <param name="item4">Fourth asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public static Result From<T1, T2, T3, T4>(Func<T1, T2, T3, T4, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, T3 item3, T4 item4, object state, Result result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { end(v); } catch(Exception e) { result.Throw(e); return; } result.Return(); }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, item3, item4, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <typeparam name="T3">Type of third asynchronous method argument.</typeparam> /// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam> /// <typeparam name="T5">Type of fifth asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 5 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="item3">Third asynchronous method argument.</param> /// <param name="item4">Fourth asynchronous method argument.</param> /// <param name="item5">Fifth asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public static Result From<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, object state, Result result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { end(v); } catch(Exception e) { result.Throw(e); return; } result.Return(); }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, item3, item4, item5, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <typeparam name="T3">Type of third asynchronous method argument.</typeparam> /// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam> /// <typeparam name="T5">Type of fifth asynchronous method argument.</typeparam> /// <typeparam name="T6">Type of sixth asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 6 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="item3">Third asynchronous method argument.</param> /// <param name="item4">Fourth asynchronous method argument.</param> /// <param name="item5">Fifth asynchronous method argument.</param> /// <param name="item6">Sixth asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public static Result From<T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, object state, Result result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { end(v); } catch(Exception e) { result.Throw(e); return; } result.Return(); }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, item3, item4, item5, item6, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T">Type of the asynchronous method return value.</typeparam> /// <param name="begin">Lambda wrapping a no argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle providing result value T.</returns> public static Result<T> From<T>(Func<AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, object state, Result<T> result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { result.Return(end(v)); } catch(Exception e) { result.Throw(e); } }, result.Throw ); // begin asynchronous invocation try { begin(continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T">Type of the asynchronous method return value.</typeparam> /// <typeparam name="T1">Type of asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a single argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">Asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle providing result value T.</returns> public static Result<T> From<T, T1>(Func<T1, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, object state, Result<T> result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { result.Return(end(v)); } catch(Exception e) { result.Throw(e); } }, result.Throw ); // begin asynchronous invocation try { begin(item1, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T">Type of the asynchronous method return value.</typeparam> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 2 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle providing result value T.</returns> public static Result<T> From<T, T1, T2>(Func<T1, T2, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, object state, Result<T> result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { result.Return(end(v)); } catch(Exception e) { result.Throw(e); } }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T">Type of the asynchronous method return value.</typeparam> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <typeparam name="T3">Type of third asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 3 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="item3">Third asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle providing result value T.</returns> public static Result<T> From<T, T1, T2, T3>(Func<T1, T2, T3, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, T3 item3, object state, Result<T> result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { result.Return(end(v)); } catch(Exception e) { result.Throw(e); } }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, item3, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T">Type of the asynchronous method return value.</typeparam> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <typeparam name="T3">Type of third asynchronous method argument.</typeparam> /// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 4 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="item3">Third asynchronous method argument.</param> /// <param name="item4">Fourth asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle providing result value T.</returns> public static Result<T> From<T, T1, T2, T3, T4>(Func<T1, T2, T3, T4, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, T3 item3, T4 item4, object state, Result<T> result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { result.Return(end(v)); } catch(Exception e) { result.Throw(e); } }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, item3, item4, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T">Type of the asynchronous method return value.</typeparam> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <typeparam name="T3">Type of third asynchronous method argument.</typeparam> /// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam> /// <typeparam name="T5">Type of fifth asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 5 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="item3">Third asynchronous method argument.</param> /// <param name="item4">Fourth asynchronous method argument.</param> /// <param name="item5">Fifth asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle providing result value T.</returns> public static Result<T> From<T, T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, object state, Result<T> result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { result.Return(end(v)); } catch(Exception e) { result.Throw(e); } }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, item3, item4, item5, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle. /// </summary> /// <typeparam name="T">Type of the asynchronous method return value.</typeparam> /// <typeparam name="T1">Type of first asynchronous method argument.</typeparam> /// <typeparam name="T2">Type of second asynchronous method argument.</typeparam> /// <typeparam name="T3">Type of third asynchronous method argument.</typeparam> /// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam> /// <typeparam name="T5">Type of fifth asynchronous method argument.</typeparam> /// <typeparam name="T6">Type of sixth asynchronous method argument.</typeparam> /// <param name="begin">Lambda wrapping a 6 argument async call.</param> /// <param name="end">Action to execute on async completion.</param> /// <param name="item1">First asynchronous method argument.</param> /// <param name="item2">Second asynchronous method argument.</param> /// <param name="item3">Third asynchronous method argument.</param> /// <param name="item4">Fourth asynchronous method argument.</param> /// <param name="item5">Fifth asynchronous method argument.</param> /// <param name="item6">Sixth asynchronous method argument.</param> /// <param name="state">State object</param> /// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle providing result value T.</returns> public static Result<T> From<T, T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, object state, Result<T> result) { // define continuation for asynchronous invocation var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone( v => { try { result.Return(end(v)); } catch(Exception e) { result.Throw(e); } }, result.Throw ); // begin asynchronous invocation try { begin(item1, item2, item3, item4, item5, item6, continuation.Return, state); } catch(Exception e) { result.Throw(e); } // return yield handle return result; } /// <summary> /// Waits for handle to be set. /// </summary> /// <param name="handle">Handle to wait on.</param> /// <param name="timeout">Timeout period. Use <cref see="TimeSpan"/>.MaxValue for no timeout.</param> /// <returns>Returns true if the handle was set before the timeout, false otherwise.</returns> public static bool WaitFor(WaitHandle handle, TimeSpan timeout) { DispatchThreadEvictWorkItems(); return handle.WaitOne((timeout == TimeSpan.MaxValue) ? Timeout.Infinite : (int)timeout.TotalMilliseconds); } /// <summary> /// Waits for event to be signaled. /// </summary> /// <param name="monitor">Event to wait on.</param> /// <param name="timeout">Timeout period. Use <cref see="TimeSpan"/>.MaxValue for no timeout.</param> /// <returns>Returns true if the event was signaled before the timeout, false otherwise.</returns> public static bool WaitFor(MonitorSemaphore monitor, TimeSpan timeout) { DispatchThreadEvictWorkItems(); return monitor.Wait(timeout); } private static int? WaitForExit(Process process, TimeSpan retryTime) { //NOTE (arnec): WaitForExit is unreliable on mono, so we have to loop on ExitCode to make sure // the process really has exited DateTime end = DateTime.UtcNow.Add(retryTime); process.WaitForExit(); do { try { return process.ExitCode; } catch(InvalidOperationException) { Thread.Sleep(TimeSpan.FromMilliseconds(50)); } } while(end > DateTime.UtcNow); return null; } private static void DispatchThreadEvictWorkItems() { var thread = DispatchThread.CurrentThread; if(thread != null) { thread.EvictWorkItems(); } } } }
//----------------------------------------------------------------------- // <copyright file="TQData.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TQVaultAE.Data { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using TQVaultAE.Logs; /// <summary> /// TQData is used to store information about reading and writing the data files in TQ. /// </summary> public static class TQData { private static readonly log4net.ILog Log = Logger.Get(typeof(TQData)); /// <summary> /// Name of the vault folder /// </summary> private static string vaultFolder; /// <summary> /// Path to the Immortal Throne game directory. /// </summary> private static string immortalThroneGamePath; /// <summary> /// Path to the Titan Quest Game directory. /// </summary> private static string titanQuestGamePath; /// <summary> /// Gets the Immortal Throne Character save folder /// </summary> public static string ImmortalThroneSaveFolder { get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games"), "Titan Quest - Immortal Throne"); } } /// <summary> /// Gets the Titan Quest Character save folder. /// </summary> public static string TQSaveFolder { get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games"), "Titan Quest"); } } /// <summary> /// Gets the name of the game settings file. /// </summary> public static string TQSettingsFile { get { return Path.Combine(Path.Combine(TQSaveFolder, "Settings"), "options.txt"); } } /// <summary> /// Gets or sets the Titan Quest game path. /// </summary> public static string TQPath { get { if (string.IsNullOrWhiteSpace(titanQuestGamePath)) titanQuestGamePath = GamePathResolver.ResolveTQ(); return titanQuestGamePath; } set { titanQuestGamePath = value; } } /// <summary> /// Gets a value indicating whether Ragnarok DLC has been installed. /// </summary> public static bool IsRagnarokInstalled { get { return Directory.Exists(ImmortalThronePath + "\\Resources\\XPack2"); } } /// <summary> /// Gets a value indicating whether Atlantis DLC has been installed. /// </summary> public static bool IsAtlantisInstalled { get { return Directory.Exists(ImmortalThronePath + "\\Resources\\XPack3"); } } /// <summary> /// Gets or sets the Immortal Throne game path. /// </summary> public static string ImmortalThronePath { get { if (string.IsNullOrWhiteSpace(immortalThroneGamePath)) immortalThroneGamePath = GamePathResolver.ResolveTQIT(); return immortalThroneGamePath; } set { immortalThroneGamePath = value; } } public static IGamePathResolver GamePathResolver { get; set; } /// <summary> /// Gets or sets the name of the custom map. /// Added to support custom quest characters /// </summary> public static string MapName { get; set; } /// <summary> /// Gets a value indicating whether a custom map has been specified. /// </summary> public static bool IsCustom { get { return !string.IsNullOrEmpty(MapName) && (MapName.Trim().ToUpperInvariant() != "MAIN"); } } /// <summary> /// Gets a value indicating whether the vault save folder has been changed. /// Usually done via settings and triggers a reload of the vaults. /// </summary> public static bool VaultFolderChanged { get; private set; } /// <summary> /// Gets or sets the vault save folder path. /// </summary> public static string TQVaultSaveFolder { get { if (string.IsNullOrEmpty(vaultFolder)) { string folderPath = Path.Combine(TQSaveFolder, "TQVaultData"); // Lets see if our path exists and create it if it does not if (!Directory.Exists(folderPath)) { try { Directory.CreateDirectory(folderPath); } catch (Exception e) { throw new InvalidOperationException(string.Concat("Error creating directory: ", folderPath), e); } } vaultFolder = folderPath; VaultFolderChanged = true; } return vaultFolder; } // Added by VillageIdiot // Used to set vault path by configuration UI. set { if (Directory.Exists(value)) { vaultFolder = value; } } } /// <summary> /// Gets the vault backup folder path. /// </summary> public static string TQVaultBackupFolder { get { string baseFolder = TQVaultSaveFolder; string folderPath = Path.Combine(baseFolder, "Backups"); // Create the path if it does not yet exist if (!Directory.Exists(folderPath)) { try { Directory.CreateDirectory(folderPath); } catch (Exception e) { throw new InvalidOperationException(string.Concat("Error creating directory: ", folderPath), e); } } return folderPath; } } /// <summary> /// Gets the filename for the game's transfer stash. /// Stash files for Mods all have their own subdirectory which is the same as the mod's custom map folder /// </summary> public static string TransferStashFile { get { if (IsCustom) { return Path.Combine(Path.Combine(Path.Combine(Path.Combine(ImmortalThroneSaveFolder, "SaveData"), "Sys"), MapName), "winsys.dxb"); } return Path.Combine(Path.Combine(Path.Combine(ImmortalThroneSaveFolder, "SaveData"), "Sys"), "winsys.dxb"); } } /// <summary> /// Gets the filename for the game's relic vault stash. /// Stash files for Mods all have their own subdirectory which is the same as the mod's custom map folder /// </summary> public static string RelicVaultStashFile { get { if (IsCustom) { return Path.Combine(Path.Combine(Path.Combine(Path.Combine(ImmortalThroneSaveFolder, "SaveData"), "Sys"), MapName), "miscsys.dxb"); } return Path.Combine(Path.Combine(Path.Combine(ImmortalThroneSaveFolder, "SaveData"), "Sys"), "miscsys.dxb"); } } /// <summary> /// Validates that the next string is a certain value and throws an exception if it is not. /// </summary> /// <param name="value">value to be validated</param> /// <param name="reader">BinaryReader instance</param> public static void ValidateNextString(string value, BinaryReader reader) { string label = ReadCString(reader); if (!label.ToUpperInvariant().Equals(value.ToUpperInvariant())) { var ex = new ArgumentException(string.Format( CultureInfo.InvariantCulture, "Error reading file at position {2}. Expecting '{0}'. Got '{1}'", value, label, reader.BaseStream.Position - label.Length - 4)); Log.ErrorException(ex); throw ex; } } public static bool MatchNextString(string value, BinaryReader reader) { long readerPosition = reader.BaseStream.Position; string label = ReadCString(reader); reader.BaseStream.Position = readerPosition; if (!label.ToUpperInvariant().Equals(value.ToUpperInvariant())) { return false; } return true; } /// <summary> /// Writes a string along with its length to the file. /// </summary> /// <param name="writer">BinaryWriter instance</param> /// <param name="value">string value to be written.</param> public static void WriteCString(BinaryWriter writer, string value) { // Convert the string to ascii // Vorbis' fix for extended characters in the database. Encoding ascii = Encoding.GetEncoding(1252); byte[] rawstring = ascii.GetBytes(value); // Write the 4-byte length of the string writer.Write(rawstring.Length); // now write the string writer.Write(rawstring); } /// <summary> /// Normalizes the record path to Upper Case Invariant Culture and replace backslashes with slashes. /// </summary> /// <param name="recordId">record path to be normalized</param> /// <returns>normalized record path</returns> public static string NormalizeRecordPath(string recordId) { // uppercase it string normalizedRecordId = recordId.ToUpperInvariant(); // replace any '/' with '\\' normalizedRecordId = normalizedRecordId.Replace('/', '\\'); return normalizedRecordId; } /// <summary> /// Reads a string from the binary stream. /// Expects an integer length value followed by the actual string of the stated length. /// </summary> /// <param name="reader">BinaryReader instance</param> /// <returns>string of data that was read</returns> public static string ReadCString(BinaryReader reader) { // first 4 bytes is the string length, followed by the string. int len = reader.ReadInt32(); // Convert the next len bytes into a string // Vorbis' fix for extended characters in the database. Encoding ascii = Encoding.GetEncoding(1252); byte[] rawData = reader.ReadBytes(len); char[] chars = new char[ascii.GetCharCount(rawData, 0, len)]; ascii.GetChars(rawData, 0, len, chars, 0); string ans = new string(chars); return ans; } /// <summary> /// Reads a string from the binary stream. /// Expects an integer length value followed by the actual string of the stated length. /// </summary> /// <param name="reader">BinaryReader instance</param> /// <returns>string of data that was read</returns> public static string ReadUTF16String(BinaryReader reader) { // first 4 bytes is the string length, followed by the string. int len = reader.ReadInt32(); len *= 2;// 2 byte chars var rawData = reader.ReadBytes(len); //convert bytes string return (UnicodeEncoding.Unicode.GetString(rawData)); } /// <summary> /// TQ has an annoying habit of throwing away your char in preference /// for the Backup folder if it exists if it thinks your char is not valid. /// We need to move that folder away so TQ won't find it. /// </summary> /// <param name="playerFile">Name of the player file to backup</param> public static void BackupStupidPlayerBackupFolder(string playerFile) { string playerFolder = Path.GetDirectoryName(playerFile); string backupFolder = Path.Combine(playerFolder, "Backup"); if (Directory.Exists(backupFolder)) { // we need to move it. string newFolder = Path.Combine(playerFolder, "Backup-moved by TQVault"); if (Directory.Exists(newFolder)) { try { // It already exists--we need to remove it Directory.Delete(newFolder, true); } catch (Exception) { int fn = 1; while (Directory.Exists(String.Format("{0}({1})", newFolder, fn))) { fn++; } newFolder = String.Format("{0}({1})", newFolder, fn); } } Directory.Move(backupFolder, newFolder); } } /// <summary> /// Gets the base character save folder. /// Changed to support custom quest characters /// </summary> /// <returns>path of the save folder</returns> public static string GetBaseCharacterFolder() { string mapSaveFolder = "Main"; if (IsCustom) { mapSaveFolder = "User"; } return Path.Combine(Path.Combine(ImmortalThroneSaveFolder, "SaveData"), mapSaveFolder); } /// <summary> /// Gets the full path to the player character file. /// </summary> /// <param name="characterName">name of the character</param> /// <returns>full path to the character file.</returns> public static string GetPlayerFile(string characterName) { return Path.Combine(Path.Combine(GetBaseCharacterFolder(), string.Concat("_", characterName)), "Player.chr"); } /// <summary> /// Gets the full path to the player's stash file. /// </summary> /// <param name="characterName">name of the character</param> /// <returns>full path to the player stash file</returns> public static string GetPlayerStashFile(string characterName) { return Path.Combine(Path.Combine(GetBaseCharacterFolder(), string.Concat("_", characterName)), "winsys.dxb"); } /// <summary> /// Gets a list of all of the character files in the save folder. /// Added support for loading custom quest characters /// </summary> /// <returns>List of character files in a string array</returns> public static string[] GetCharacterList() { try { // Get all folders that start with a '_'. string[] folders = Directory.GetDirectories(GetBaseCharacterFolder(), "_*"); if (folders == null || folders.Length == 0) { return null; } List<string> characterList = new List<string>(folders.Length); // Copy the names over without the '_' and strip out the path information. foreach (string folder in folders) { characterList.Add(Path.GetFileName(folder).Substring(1)); } // sort alphabetically characterList.Sort(); return characterList.ToArray(); } catch (DirectoryNotFoundException) { return null; } } /// <summary> /// Gets a list of all of the custom maps. /// </summary> /// <returns>List of custom maps in a string array</returns> public static string[] GetCustomMapList() { try { // Get all folders in the CustomMaps directory. string saveFolder; saveFolder = ImmortalThroneSaveFolder; string[] mapFolders = Directory.GetDirectories(Path.Combine(saveFolder, "CustomMaps"), "*"); if (mapFolders == null || mapFolders.Length < 1) { return null; } List<string> customMapList = new List<string>(mapFolders.Length); // Strip out the path information foreach (string mapFolder in mapFolders) { customMapList.Add(Path.GetFileName(mapFolder)); } // sort alphabetically customMapList.Sort(); return customMapList.ToArray(); } catch (DirectoryNotFoundException) { return null; } } /// <summary> /// Gets the file name and path for a vault. /// </summary> /// <param name="vaultName">The name of the vault file.</param> /// <returns>The full path along with extension of the vault file.</returns> public static string GetVaultFile(string vaultName) { return string.Concat(Path.Combine(TQVaultSaveFolder, vaultName), ".vault"); } /// <summary> /// Gets a list of all of the vault files. /// </summary> /// <returns>The list of all of the vault files in the save folder.</returns> public static string[] GetVaultList() { try { // Get all files that have a .vault extension. string[] files = Directory.GetFiles(TQVaultSaveFolder, "*.vault"); if (files == null || files.Length < 1) { return null; } List<string> vaultList = new List<string>(files.Length); // Strip out the path information and extension. foreach (string file in files) { vaultList.Add(Path.GetFileNameWithoutExtension(file)); } // sort alphabetically vaultList.Sort(); return vaultList.ToArray(); } catch (DirectoryNotFoundException) { return null; } } /// <summary> /// Converts a file path to a backup file. Adding the current date and time to the name. /// </summary> /// <param name="prefix">prefix of the backup file.</param> /// <param name="filePath">Full path of the file to backup.</param> /// <returns>Returns the name of the backup file to use for this file. The backup file will have the given prefix.</returns> public static string ConvertFilePathToBackupPath(string prefix, string filePath) { // Get the actual filename without any path information string filename = Path.GetFileName(filePath); // Strip the extension off of it. string extension = Path.GetExtension(filename); if (!string.IsNullOrEmpty(extension)) { filename = Path.GetFileNameWithoutExtension(filename); } // Now come up with a timestamp string string timestamp = DateTime.Now.ToString("-yyyyMMdd-HHmmss-fffffff-", CultureInfo.InvariantCulture); string pathHead = Path.Combine(TQVaultBackupFolder, prefix); pathHead = string.Concat(pathHead, "-", filename, timestamp); int uniqueID = 0; // Now loop and construct the filename and check to see if the name // is already in use. If it is, increment uniqueID and try again. while (true) { string fullFilePath = string.Concat(pathHead, uniqueID.ToString("000", CultureInfo.InvariantCulture), extension); if (!File.Exists(fullFilePath)) { return fullFilePath; } // try again ++uniqueID; } } /// <summary> /// Backs up the file to the backup folder. /// </summary> /// <param name="prefix">prefix of the backup file</param> /// <param name="file">file name to backup</param> /// <returns>Returns the name of the backup file, or NULL if file does not exist</returns> public static string BackupFile(string prefix, string file) { if (File.Exists(file)) { // only backup if it exists! string backupFile = ConvertFilePathToBackupPath(prefix, file); File.Copy(file, backupFile); // Added by VillageIdiot // Backup the file pairs for the player stash files. if (Path.GetFileName(file).ToUpperInvariant() == "WINSYS.DXB") { string dxgfile = Path.ChangeExtension(file, ".dxg"); if (File.Exists(dxgfile)) { // only backup if it exists! backupFile = ConvertFilePathToBackupPath(prefix, dxgfile); File.Copy(dxgfile, backupFile); } } return backupFile; } else { return null; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Console; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Mono.Addins; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { /// <summary> /// This module loads and saves OpenSimulator inventory archives /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryArchiverModule")] public class InventoryArchiverModule : ISharedRegionModule, IInventoryArchiverModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <value> /// Enable or disable checking whether the iar user is actually logged in /// </value> // public bool DisablePresenceChecks { get; set; } public event InventoryArchiveSaved OnInventoryArchiveSaved; /// <summary> /// The file to load and save inventory if no filename has been specified /// </summary> protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar"; /// <value> /// Pending save completions initiated from the console /// </value> protected List<Guid> m_pendingConsoleSaves = new List<Guid>(); /// <value> /// All scenes that this module knows about /// </value> private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); private Scene m_aScene; private IUserAccountService m_UserAccountService; protected IUserAccountService UserAccountService { get { if (m_UserAccountService == null) // What a strange thing to do... foreach (Scene s in m_scenes.Values) { m_UserAccountService = s.RequestModuleInterface<IUserAccountService>(); break; } return m_UserAccountService; } } public InventoryArchiverModule() {} // public InventoryArchiverModule(bool disablePresenceChecks) // { // DisablePresenceChecks = disablePresenceChecks; // } #region ISharedRegionModule public void Initialise(IConfigSource source) { } public void AddRegion(Scene scene) { if (m_scenes.Count == 0) { scene.RegisterModuleInterface<IInventoryArchiverModule>(this); OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted; scene.AddCommand( "Archiving", this, "load iar", "load iar [-m|--merge] <first> <last> <inventory path> <password> [<IAR path>]", "Load user inventory archive (IAR).", "-m|--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones" + "<first> is user's first name." + Environment.NewLine + "<last> is user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine + "<password> is the user's password." + Environment.NewLine + "<IAR path> is the filesystem path or URI from which to load the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleLoadInvConsoleCommand); scene.AddCommand( "Archiving", this, "save iar", "save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]", "Save user inventory archive (IAR).", "<first> is the user's first name.\n" + "<last> is the user's last name.\n" + "<inventory path> is the path inside the user's inventory for the folder/item to be saved.\n" + "<IAR path> is the filesystem path at which to save the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used.\n", DEFAULT_INV_BACKUP_FILENAME) + "-h|--home=<url> adds the url of the profile service to the saved user information.\n" + "-c|--creators preserves information about foreign creators.\n" + "-e|--exclude=<name/uuid> don't save the inventory item in archive" + Environment.NewLine + "-f|--excludefolder=<folder/uuid> don't save contents of the folder in archive" + Environment.NewLine + "-v|--verbose extra debug messages.\n" + "--noassets stops assets being saved to the IAR.", HandleSaveInvConsoleCommand); m_aScene = scene; } m_scenes[scene.RegionInfo.RegionID] = scene; } public void RemoveRegion(Scene scene) { } public void Close() {} public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "Inventory Archiver Module"; } } #endregion /// <summary> /// Trigger the inventory archive saved event. /// </summary> protected internal void TriggerInventoryArchiveSaved( Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException) { InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved; if (handlerInventoryArchiveSaved != null) handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException); } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream) { return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>()); } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { // if (CheckPresence(userInfo.PrincipalID)) // { try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(options, UserAccountService); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } return true; // } // else // { // m_log.ErrorFormat( // "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", // userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); // } } } return false; } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, string savePath, Dictionary<string, object> options) { // if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, savePath)) // return false; if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { // if (CheckPresence(userInfo.PrincipalID)) // { try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(options, UserAccountService); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } return true; // } // else // { // m_log.ErrorFormat( // "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", // userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); // } } } return false; } public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream) { return DearchiveInventory(firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>()); } public bool DearchiveInventory( string firstName, string lastName, string invPath, string pass, Stream loadStream, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { // if (CheckPresence(userInfo.PrincipalID)) // { InventoryArchiveReadRequest request; bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false); try { request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream, merge); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; // } // else // { // m_log.ErrorFormat( // "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", // userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); // } } else m_log.ErrorFormat("[INVENTORY ARCHIVER]: User {0} {1} not found", firstName, lastName); } return false; } public bool DearchiveInventory( string firstName, string lastName, string invPath, string pass, string loadPath, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { // if (CheckPresence(userInfo.PrincipalID)) // { InventoryArchiveReadRequest request; bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false); try { request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath, merge); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; // } // else // { // m_log.ErrorFormat( // "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", // userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); // } } } return false; } /// <summary> /// Load inventory from an inventory file archive /// </summary> /// <param name="cmdparams"></param> protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams) { try { Dictionary<string, object> options = new Dictionary<string, object>(); OptionSet optionSet = new OptionSet().Add("m|merge", delegate (string v) { options["merge"] = v != null; }); List<string> mainParams = optionSet.Parse(cmdparams); if (mainParams.Count < 6) { m_log.Error( "[INVENTORY ARCHIVER]: usage is load iar [-m|--merge] <first name> <last name> <inventory path> <user password> [<load file path>]"); return; } string firstName = mainParams[2]; string lastName = mainParams[3]; string invPath = mainParams[4]; string pass = mainParams[5]; string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME); m_log.InfoFormat( "[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}", loadPath, invPath, firstName, lastName); if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath, options)) m_log.InfoFormat( "[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}", loadPath, firstName, lastName); } catch (InventoryArchiverException e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message); } } /// <summary> /// Save inventory to a file archive /// </summary> /// <param name="cmdparams"></param> protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams) { Guid id = Guid.NewGuid(); Dictionary<string, object> options = new Dictionary<string, object>(); OptionSet ops = new OptionSet(); //ops.Add("v|version=", delegate(string v) { options["version"] = v; }); ops.Add("h|home=", delegate(string v) { options["home"] = v; }); ops.Add("v|verbose", delegate(string v) { options["verbose"] = v; }); ops.Add("c|creators", delegate(string v) { options["creators"] = v; }); ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; }); ops.Add("e|exclude=", delegate(string v) { if (!options.ContainsKey("exclude")) options["exclude"] = new List<String>(); ((List<String>)options["exclude"]).Add(v); }); ops.Add("f|excludefolder=", delegate(string v) { if (!options.ContainsKey("excludefolders")) options["excludefolders"] = new List<String>(); ((List<String>)options["excludefolders"]).Add(v); }); List<string> mainParams = ops.Parse(cmdparams); try { if (mainParams.Count < 6) { m_log.Error( "[INVENTORY ARCHIVER]: save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]"); return; } if (options.ContainsKey("home")) m_log.WarnFormat("[INVENTORY ARCHIVER]: Please be aware that inventory archives with creator information are not compatible with OpenSim 0.7.0.2 and earlier. Do not use the -home option if you want to produce a compatible IAR"); string firstName = mainParams[2]; string lastName = mainParams[3]; string invPath = mainParams[4]; string pass = mainParams[5]; string savePath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME); m_log.InfoFormat( "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}", savePath, invPath, firstName, lastName); lock (m_pendingConsoleSaves) m_pendingConsoleSaves.Add(id); ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options); } catch (InventoryArchiverException e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message); } } private void SaveInvConsoleCommandCompleted( Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException) { lock (m_pendingConsoleSaves) { if (m_pendingConsoleSaves.Contains(id)) m_pendingConsoleSaves.Remove(id); else return; } if (succeeded) { m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0} {1}", userInfo.FirstName, userInfo.LastName); } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}", userInfo.FirstName, userInfo.LastName, reportedException.Message); } } /// <summary> /// Get user information for the given name. /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="pass">User password</param> /// <returns></returns> protected UserAccount GetUserInfo(string firstName, string lastName, string pass) { UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName); if (null == account) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}", firstName, lastName); return null; } try { string encpass = Util.Md5Hash(pass); if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty) { return account; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.", firstName, lastName); return null; } } catch (Exception e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e.Message); return null; } } /// <summary> /// Notify the client of loaded nodes if they are logged in /// </summary> /// <param name="loadedNodes">Can be empty. In which case, nothing happens</param> private void UpdateClientWithLoadedNodes(UserAccount userInfo, HashSet<InventoryNodeBase> loadedNodes) { if (loadedNodes.Count == 0) return; foreach (Scene scene in m_scenes.Values) { ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID); if (user != null && !user.IsChildAgent) { foreach (InventoryNodeBase node in loadedNodes) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}", // user.Name, node.Name); user.ControllingClient.SendBulkUpdateInventory(node); } break; } } } // /// <summary> // /// Check if the given user is present in any of the scenes. // /// </summary> // /// <param name="userId">The user to check</param> // /// <returns>true if the user is in any of the scenes, false otherwise</returns> // protected bool CheckPresence(UUID userId) // { // if (DisablePresenceChecks) // return true; // // foreach (Scene scene in m_scenes.Values) // { // ScenePresence p; // if ((p = scene.GetScenePresence(userId)) != null) // { // p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false); // return true; // } // } // // return false; // } } }
// 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.IO; using System.Linq; using System.Text; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Feedback.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Packaging; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; using Roslyn.VisualStudio.ProjectSystem; using VSLangProj; using VSLangProj140; using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1); private const string AppCodeFolderName = "App_Code"; protected readonly IServiceProvider ServiceProvider; private readonly IVsUIShellOpenDocument _shellOpenDocument; private readonly IVsTextManager _textManager; // Not readonly because it needs to be set in the derived class' constructor. private VisualStudioProjectTracker _projectTracker; // document worker coordinator private ISolutionCrawlerRegistrationService _registrationService; private readonly ForegroundThreadAffinitizedObject _foregroundObject = new ForegroundThreadAffinitizedObject(); public VisualStudioWorkspaceImpl( SVsServiceProvider serviceProvider, WorkspaceBackgroundWork backgroundWork) : base( CreateHostServices(serviceProvider), backgroundWork) { this.ServiceProvider = serviceProvider; _textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager; _shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti; var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile; // We have Watson hits where this came back null, so guard against it if (profileService != null) { Sqm.LogSession(session, profileService.IsMicrosoftInternal); } } internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider) { var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); return MefV1HostServices.Create(composition.DefaultExportProvider); } protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService) { var projectTracker = new VisualStudioProjectTracker(serviceProvider); // Ensure the document tracking service is initialized on the UI thread var documentTrackingService = this.Services.GetService<IDocumentTrackingService>(); var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService); projectTracker.DocumentProvider = documentProvider; projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>(); projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>(); this.SetProjectTracker(projectTracker); var workspaceHost = new VisualStudioWorkspaceHost(this); projectTracker.RegisterWorkspaceHost(workspaceHost); projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost); saveEventsService.StartSendingSaveEvents(); // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); } /// <summary>NOTE: Call only from derived class constructor</summary> protected void SetProjectTracker(VisualStudioProjectTracker projectTracker) { _projectTracker = projectTracker; } internal VisualStudioProjectTracker ProjectTracker { get { return _projectTracker; } } internal void ClearReferenceCache() { _projectTracker.MetadataReferenceProvider.ClearCache(); } internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId) { var project = GetHostProject(documentId.ProjectId); if (project != null) { return project.GetDocumentOrAdditionalDocument(documentId); } return null; } internal IVisualStudioHostProject GetHostProject(ProjectId projectId) { return this.ProjectTracker.GetProject(projectId); } private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project) { project = GetHostProject(projectId); return project != null; } internal override bool TryApplyChanges( Microsoft.CodeAnalysis.Solution newSolution, IProgressTracker progressTracker) { // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution, progressTracker); } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { hierarchy = null; project = null; return this.TryGetHostProject(projectId, out hostProject) && this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project)) { throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId)); } } internal EnvDTE.Project TryGetDTEProject(ProjectId projectId) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; return TryGetProjectData(projectId, out hostProject, out hierarchy, out project) ? project : null; } internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; try { GetProjectData(projectId, out hostProject, out hierarchy, out project); } catch (ArgumentException) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string GetAnalyzerPath(AnalyzerReference analyzerReference) { return analyzerReference.FullPath; } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string GetMetadataPath(MetadataReference metadataReference) { var fileMetadata = metadataReference as PortableExecutableReference; if (fileMetadata != null) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); } } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; Reference reference = vsProject.References.Find(filePath); if (reference != null) { reference.Remove(); } } } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); var vsProject = (VSProject)project.Object; vsProject.References.AddProject(refProject); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); var vsProject = (VSProject)project.Object; foreach (Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: false); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: true); } private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else if (folders.Any()) { AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else { AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } } private bool IsWebsite(EnvDTE.Project project) { return project.Kind == VsWebSite.PrjKind.prjKindVenusProject; } private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { string folderPath; if (!project.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToFolder( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { var folder = project.FindOrCreateFolder(folders); string folderPath; if (!folder.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToProjectItems( IVisualStudioHostProject hostProject, ProjectItems projectItems, DocumentId documentId, string folderPath, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText, string filePath, bool isAdditionalDocument) { if (filePath == null) { var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8)) { initialText.Write(writer); } } using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId)) { return projectItems.AddFromFile(filePath); } } protected void RemoveDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var document = this.GetHostDocument(documentId); if (document != null) { var project = document.Project.Hierarchy as IVsProject3; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } int result; project.RemoveItem(0, itemId, out result); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } public override void OpenDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void CloseDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public override void CloseAdditionalDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory) { frame = null; factory = null; var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; object value = null; // We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window if (monitorSelectionService != null && ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value))) { frame = value as IVsWindowFrame; } else { return false; } factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory; return frame != null && factory != null; } public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.ThisWorkspaceOnlySupportsOpeningDocumentsOnTheUIThread); } var document = this.GetHostDocument(documentId); if (document != null && document.Project != null) { IVsWindowFrame frame; if (TryGetFrame(document, out frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } } private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame) { frame = null; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. uint itemid; IVsUIHierarchy uiHierarchy; OLEServiceProvider oleServiceProvider; return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject( document.FilePath, VSConstants.LOGVIEWID.TextView_guid, out oleServiceProvider, out uiHierarchy, out itemid, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. var vsProject = document.Project.Hierarchy as IVsProject; return vsProject != null && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var document = this.GetHostDocument(documentId); if (document != null) { IVsUIHierarchy uiHierarchy; IVsWindowFrame frame; int isOpen; if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind) { // No extension was provided. Pick a good one based on the type of host project. switch (hostProject.Language) { case LanguageNames.CSharp: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; return ".cs"; case LanguageNames.VisualBasic: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; return ".vb"; default: throw new InvalidOperationException(); } } public override IVsHierarchy GetHierarchy(ProjectId projectId) { var project = this.GetHostProject(projectId); if (project == null) { return null; } return project.Hierarchy; } internal override void SetDocumentContext(DocumentId documentId) { var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var hierarchy = hostDocument.Project.Hierarchy; var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { if (sharedHierarchy.SetProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK) { // The ASP.NET 5 intellisense project is now updated. return; } else { // Universal Project shared files // Change the SharedItemContextHierarchy of the project's parent hierarchy, then // hierarchy events will trigger the workspace to update. var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy); } } else { // Regular linked files // Transfer the item (open buffer) to the new hierarchy, and then hierarchy events // will trigger the workspace to update. var vsproj = hierarchy as IVsProject3; var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null); } } internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId) { // TODO: This is a very roundabout way to update the context // The sharedHierarchy passed in has a new context, but we don't know what it is. // The documentId passed in is associated with this sharedHierarchy, and this method // will be called once for each such documentId. During this process, one of these // documentIds will actually belong to the new SharedItemContextHierarchy. Once we // find that one, we can map back to the open buffer and set its active context to // the appropriate project. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); if (hostProject.Hierarchy == sharedHierarchy) { // How? return; } if (hostProject.Id != documentId.ProjectId) { // While this documentId is associated with one of the head projects for this // sharedHierarchy, it is not associated with the new context hierarchy. Another // documentId will be passed to this method and update the context. return; } // This documentId belongs to the new SharedItemContextHierarchy. Update the associated // buffer. OnDocumentContextUpdated(documentId); } /// <summary> /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that /// is in the current context. For regular files (non-shared and non-linked) and closed /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked /// files and open shared files, the active context is already tracked by the /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/> /// is preferred. /// </summary> internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId) { // If the document is open, then the Workspace knows the current context for both // linked and shared files if (IsDocumentOpen(documentId)) { return base.GetDocumentIdInCurrentContext(documentId); } var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // An itemid is required to determine whether the file belongs to a Shared Project return base.GetDocumentIdInCurrentContext(documentId); } // If this is a regular document or a closed linked (non-shared) document, then use the // default logic for determining current context. var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy == null) { return base.GetDocumentIdInCurrentContext(documentId); } // This is a closed shared document, so we must determine the correct context. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); var matchingProject = CurrentSolution.GetProject(hostProject.Id); if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy) { return base.GetDocumentIdInCurrentContext(documentId); } if (matchingProject.ContainsDocument(documentId)) { // The provided documentId is in the current context project return documentId; } // The current context document is from another project. var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds(); var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id); return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId); } internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } public override string GetFilePath(DocumentId documentId) { var document = this.GetHostDocument(documentId); if (document == null) { return null; } else { return document.FilePath; } } internal void StartSolutionCrawler() { if (_registrationService == null) { lock (this) { if (_registrationService == null) { _registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } } } } internal void StopSolutionCrawler() { if (_registrationService != null) { lock (this) { if (_registrationService != null) { _registrationService.Unregister(this, blockingShutdown: true); _registrationService = null; } } } } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator StopSolutionCrawler(); base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave)); var fileNames = documents.Select(GetFilePath).ToArray(); uint editVerdict; uint editResultFlags; // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn int result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out editVerdict, prgfMoreInfo: out editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) { this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); } internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader); } internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader); } public TInterface GetVsService<TService, TInterface>() where TService : class where TInterface : class { return this.ServiceProvider.GetService(typeof(TService)) as TInterface; } public object GetVsService(Type serviceType) { return ServiceProvider.GetService(serviceType); } public DTE GetVsDte() { return GetVsService<SDTE, DTE>(); } internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { _foregroundObject.AssertIsForeground(); IVsHierarchy referencingHierarchy; IVsHierarchy referencedHierarchy; if (!TryGetHierarchy(referencingProject, out referencingHierarchy) || !TryGetHierarchy(referencedProject, out referencedHierarchy)) { // Couldn't even get a hierarchy for this project. So we have to assume // that adding a reference is disallowed. return false; } // First we have to see if either project disallows the reference being added. const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference; uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3; if (referencingProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3; if (referencedProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } // Neither project denied the reference being added. At this point, if either project // allows the reference to be added, and the other doesn't block it, then we can add // the reference. if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW || canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW) { return true; } // In both directions things are still unknown. Fallback to the reference manager // to make the determination here. var referenceManager = GetVsService<SVsReferenceManager, IVsReferenceManager>(); if (referenceManager == null) { // Couldn't get the reference manager. Have to assume it's not allowed. return false; } // As long as the reference manager does not deny things, then we allow the // reference to be added. var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy); return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY; } /// <summary> /// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just /// forwards the calls down to the underlying Workspace. /// </summary> protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder { private readonly VisualStudioWorkspaceImpl _workspace; private readonly Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>(); public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace) { _workspace = workspace; } void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions) { _workspace.OnCompilationOptionsChanged(projectId, compilationOptions); _workspace.OnParseOptionsChanged(projectId, parseOptions); } void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo) { _workspace.OnDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext) { // TODO: Move this out to DocumentProvider. As is, this depends on being able to // access the host document which will already be deleted in some cases, causing // a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a // Mercury shared document is closed. // UnsubscribeFromSharedHierarchyEvents(documentId); using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed")) { _workspace.OnDocumentClosed(documentId, loader, updateActiveContext); } } void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext) { SubscribeToSharedHierarchyEvents(documentId); _workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext); } private void SubscribeToSharedHierarchyEvents(DocumentId documentId) { // Todo: maybe avoid double alerts. var hostDocument = _workspace.GetHostDocument(documentId); if (hostDocument == null) { return; } var hierarchy = hostDocument.Project.Hierarchy; var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId); var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie); if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId)) { _documentIdToHierarchyEventsCookieMap.Add(documentId, cookie); } } } private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId) { var hostDocument = _workspace.GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie)) { var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie); _documentIdToHierarchyEventsCookieMap.Remove(documentId); } } } private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.RegisterPrimarySolution(solutionId); } private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.UnregisterPrimarySolution(solutionId, synchronousShutdown); } void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId) { _workspace.OnDocumentRemoved(documentId); } void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceAdded(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceRemoved(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project")) { _workspace.OnProjectAdded(projectInfo); } } void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceAdded(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceRemoved(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project")) { _workspace.OnProjectRemoved(projectId); } } void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo) { RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id); _workspace.OnSolutionAdded(solutionInfo); } void IVisualStudioWorkspaceHost.OnSolutionRemoved() { var solutionId = _workspace.CurrentSolution.Id; _workspace.OnSolutionRemoved(); _workspace.ClearReferenceCache(); UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false); } void IVisualStudioWorkspaceHost.ClearSolution() { _workspace.ClearSolution(); _workspace.ClearReferenceCache(); } void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName) { _workspace.OnAssemblyNameChanged(id, assemblyName); } void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath) { _workspace.OnOutputFilePathChanged(id, outputFilePath); } void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath) { _workspace.OnProjectNameChanged(projectId, name, filePath); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo documentInfo) { _workspace.OnAdditionalDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId documentInfo) { _workspace.OnAdditionalDocumentRemoved(documentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext) { _workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader) { _workspace.OnAdditionalDocumentClosed(documentId, loader); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnAdditionalDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation) { _workspace.OnHasAllInformationChanged(projectId, hasAllInformation); } void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange() { UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true); } void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange() { var solutionId = _workspace.CurrentSolution.Id; _workspace.ProjectTracker.UpdateSolutionProperties(solutionId); RegisterPrimarySolutionForPersistentStorage(solutionId); } } } }
using System; using swc = System.Windows.Controls; using sw = System.Windows; using swm = System.Windows.Media; using Eto.Forms; using Eto.Drawing; namespace Eto.Wpf.Forms.Controls { public class ScrollableHandler : WpfPanel<swc.Border, Scrollable, Scrollable.ICallback>, Scrollable.IHandler { BorderType borderType; bool expandContentWidth = true; bool expandContentHeight = true; readonly EtoScrollViewer scroller; public sw.FrameworkElement ContentControl { get { return scroller; } } protected override bool UseContentSize { get { return false; } } public class EtoScrollViewer : swc.ScrollViewer { public swc.Primitives.IScrollInfo GetScrollInfo() { return ScrollInfo; } } public override Color BackgroundColor { get { return scroller.Background.ToEtoColor(); } set { scroller.Background = value.ToWpfBrush(scroller.Background); } } public ScrollableHandler() { Control = new swc.Border { SnapsToDevicePixels = true, Focusable = false, }; scroller = new EtoScrollViewer { VerticalScrollBarVisibility = swc.ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = swc.ScrollBarVisibility.Auto, CanContentScroll = true, SnapsToDevicePixels = true, Focusable = false }; scroller.SizeChanged += HandleSizeChanged; scroller.Loaded += HandleSizeChanged; Control.Child = scroller; this.Border = BorderType.Bezel; } void HandleSizeChanged(object sender, EventArgs e) { UpdateSizes(); } void UpdateSizes() { var info = scroller.GetScrollInfo(); if (info != null) { var content = (swc.Border)scroller.Content; var viewportSize = new sw.Size(info.ViewportWidth, info.ViewportHeight); var prefSize = Content.GetPreferredSize(WpfConversions.PositiveInfinitySize); // hack for when a scrollable is in a group box it expands vertically if (Widget.FindParent<GroupBox>() != null) viewportSize.Height = Math.Max(0, viewportSize.Height - 1); if (ExpandContentWidth) content.Width = Math.Max(0, Math.Max(prefSize.Width, viewportSize.Width)); else content.Width = prefSize.Width; if (ExpandContentHeight) content.Height = Math.Max(0, Math.Max(prefSize.Height, viewportSize.Height)); else content.Height = prefSize.Height; scroller.InvalidateMeasure(); } } public override void UpdatePreferredSize() { UpdateSizes(); base.UpdatePreferredSize(); } public void UpdateScrollSizes() { Control.InvalidateMeasure(); UpdateSizes(); } public Point ScrollPosition { get { EnsureLoaded(); return new Point((int)scroller.HorizontalOffset, (int)scroller.VerticalOffset); } set { scroller.ScrollToVerticalOffset(value.Y); scroller.ScrollToHorizontalOffset(value.X); } } public Size ScrollSize { get { EnsureLoaded(); return new Size((int)scroller.ExtentWidth, (int)scroller.ExtentHeight); } set { var content = (swc.Border)Control.Child; content.MinHeight = value.Height; content.MinWidth = value.Width; UpdateSizes(); } } public BorderType Border { get { return borderType; } set { borderType = value; switch (value) { case BorderType.Bezel: Control.BorderBrush = sw.SystemColors.ControlDarkDarkBrush; Control.BorderThickness = new sw.Thickness(1.0); break; case BorderType.Line: Control.BorderBrush = sw.SystemColors.ControlDarkDarkBrush; Control.BorderThickness = new sw.Thickness(1); break; case BorderType.None: Control.BorderBrush = null; break; default: throw new NotSupportedException(); } } } public override Size ClientSize { get { if (!Widget.Loaded) return Size; EnsureLoaded(); var info = scroller.GetScrollInfo(); return info != null ? new Size((int)info.ViewportWidth, (int)info.ViewportHeight) : Size.Empty; } set { Size = value; } } public Rectangle VisibleRect { get { return new Rectangle(ScrollPosition, ClientSize); } } public override void SetContainerContent(sw.FrameworkElement content) { content.HorizontalAlignment = sw.HorizontalAlignment.Left; content.VerticalAlignment = sw.VerticalAlignment.Top; content.SizeChanged += HandleSizeChanged; scroller.Content = content; } public override void AttachEvent(string id) { switch (id) { case Scrollable.ScrollEvent: scroller.ScrollChanged += (sender, e) => { Callback.OnScroll(Widget, new ScrollEventArgs(new Point((int)e.HorizontalOffset, (int)e.VerticalOffset))); }; break; default: base.AttachEvent(id); break; } } public bool ExpandContentWidth { get { return expandContentWidth; } set { if (expandContentWidth != value) { expandContentWidth = value; UpdateSizes(); } } } public bool ExpandContentHeight { get { return expandContentHeight; } set { if (expandContentHeight != value) { expandContentHeight = value; UpdateSizes(); } } } public override void Invalidate() { base.Invalidate(); foreach (var control in Widget.Children) { control.Invalidate(); } } public override void Invalidate(Rectangle rect) { base.Invalidate(rect); foreach (var control in Widget.Children) { control.Invalidate(rect); } } public float MaximumZoom { get { return 1f; } set { } } public float MinimumZoom { get { return 1f; } set { } } public float Zoom { get { return 1f; } set { } } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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.Diagnostics; using System.Windows.Forms; using SharpDX; using SharpDX.D3DCompiler; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.DXGI; using SharpDX.Windows; using Buffer = SharpDX.Direct3D11.Buffer; using Device = SharpDX.Direct3D11.Device; using MapFlags = SharpDX.Direct3D11.MapFlags; namespace MiniCube { /// <summary> /// SharpDX MiniCube Direct3D 11 Sample /// </summary> internal static class Program { // [STAThread] private static void Main() { var form = new RenderForm("SharpDX - MiniCube Direct3D11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Used for debugging dispose object references // Configuration.EnableObjectTracking = true; // Disable throws on shader compilation errors //Configuration.ThrowOnShaderCompileError = false; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4( 1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); Matrix proj = Matrix.Identity; // Use clock var clock = new Stopwatch(); clock.Start(); // Declare texture for rendering bool userResized = true; Texture2D backBuffer = null; RenderTargetView renderView = null; Texture2D depthBuffer = null; DepthStencilView depthView = null; // Setup handler on resize form form.UserResized += (sender, args) => userResized = true; // Setup full screen mode change F5 (Full) F4 (Window) form.KeyUp += (sender, args) => { if (args.KeyCode == Keys.F5) swapChain.SetFullscreenState(true, null); else if (args.KeyCode == Keys.F4) swapChain.SetFullscreenState(false, null); else if (args.KeyCode == Keys.Escape) form.Close(); }; // Main loop RenderLoop.Run(form, () => { // If Form resized if (userResized) { // Dispose all previous allocated resources Utilities.Dispose(ref backBuffer); Utilities.Dispose(ref renderView); Utilities.Dispose(ref depthBuffer); Utilities.Dispose(ref depthView); // Resize the backbuffer swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None); // Get the backbuffer from the swapchain backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); // Renderview on the backbuffer renderView = new RenderTargetView(device, backBuffer); // Create the depth buffer depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view depthView = new DepthStencilView(device, depthBuffer); // Setup targets and viewport for rendering context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(depthView, renderView); // Setup new projection matrix with correct aspect ratio proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); // We are done resizing userResized = false; } var time = clock.ElapsedMilliseconds / 1000.0f; var viewProj = Matrix.Multiply(view, proj); // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources signature.Dispose(); vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); contantBuffer.Dispose(); depthBuffer.Dispose(); depthView.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); } } }
namespace NorthLion.Zero.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class AbpZero_Initial : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), ImpersonatorUserId = c.Long(), ImpersonatorTenantId = c.Int(), CustomData = c.String(maxLength: 2000), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true) .Index(t => t.EditionId); CreateTable( "dbo.AbpEditions", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguages", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 10), DisplayName = c.String(nullable: false, maxLength: 64), Icon = c.String(maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguageTexts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), LanguageName = c.String(nullable: false, maxLength: 10), Source = c.String(nullable: false, maxLength: 128), Key = c.String(nullable: false, maxLength: 256), Value = c.String(nullable: false), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.AbpOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), ParentId = c.Long(), Code = c.String(nullable: false, maxLength: 95), DisplayName = c.String(nullable: false, maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId) .Index(t => t.ParentId); CreateTable( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), AuthenticationSource = c.String(maxLength: 64), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 328), PasswordResetCode = c.String(maxLength: 328), LockoutEndDateUtc = c.DateTime(), AccessFailedCount = c.Int(nullable: false), IsLockoutEnabled = c.Boolean(nullable: false), PhoneNumber = c.String(), IsPhoneNumberConfirmed = c.Boolean(nullable: false), SecurityStamp = c.String(), IsTwoFactorEnabled = c.Boolean(nullable: false), IsActive = c.Boolean(nullable: false), UserName = c.String(nullable: false, maxLength: 32), TenantId = c.Int(), EmailAddress = c.String(nullable: false, maxLength: 256), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserClaims", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), ClaimType = c.String(), ClaimValue = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.AbpTenantNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), EditionId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), TenancyName = c.String(nullable: false, maxLength: 64), ConnectionString = c.String(maxLength: 1024), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpEditions", t => t.EditionId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.EditionId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserAccounts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), UserLinkId = c.Long(), UserName = c.String(), EmailAddress = c.String(), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.TenantId }) .Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result }); CreateTable( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), TenantNotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); CreateTable( "dbo.AbpUserOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), OrganizationUnitId = c.Long(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateIndex("AbpAuditLogs", new[] { "TenantId", "ExecutionTime" }); CreateIndex("AbpAuditLogs", new[] { "UserId", "ExecutionTime" }); CreateIndex("AbpEditions", new[] { "Name" }); CreateIndex("AbpFeatures", new[] { "Discriminator", "TenantId", "Name" }); CreateIndex("AbpFeatures", new[] { "Discriminator", "EditionId", "Name" }); CreateIndex("AbpFeatures", new[] { "TenantId", "Name" }); CreateIndex("AbpLanguages", new[] { "TenantId", "Name" }); CreateIndex("AbpLanguageTexts", new[] { "TenantId", "LanguageName", "Source", "Key" }); CreateIndex("AbpOrganizationUnits", new[] { "TenantId", "ParentId" }); CreateIndex("AbpOrganizationUnits", new[] { "TenantId", "Code" }); DropIndex("AbpPermissions", new[] { "UserId" }); DropIndex("AbpPermissions", new[] { "RoleId" }); CreateIndex("AbpPermissions", new[] { "UserId", "Name" }); CreateIndex("AbpPermissions", new[] { "RoleId", "Name" }); CreateIndex("AbpRoles", new[] { "TenantId", "Name" }); CreateIndex("AbpRoles", new[] { "IsDeleted", "TenantId", "Name" }); DropIndex("AbpSettings", new[] { "UserId" }); CreateIndex("AbpSettings", new[] { "TenantId", "Name" }); CreateIndex("AbpSettings", new[] { "UserId", "Name" }); CreateIndex("AbpTenants", new[] { "TenancyName" }); CreateIndex("AbpTenants", new[] { "IsDeleted", "TenancyName" }); DropIndex("AbpUserLogins", new[] { "UserId" }); CreateIndex("AbpUserLogins", new[] { "UserId", "LoginProvider" }); CreateIndex("AbpUserOrganizationUnits", new[] { "TenantId", "UserId" }); CreateIndex("AbpUserOrganizationUnits", new[] { "TenantId", "OrganizationUnitId" }); CreateIndex("AbpUserOrganizationUnits", new[] { "UserId" }); CreateIndex("AbpUserOrganizationUnits", new[] { "OrganizationUnitId" }); DropIndex("AbpUserRoles", new[] { "UserId" }); CreateIndex("AbpUserRoles", new[] { "UserId", "RoleId" }); CreateIndex("AbpUserRoles", new[] { "RoleId" }); CreateIndex("AbpUsers", new[] { "TenantId", "UserName" }); CreateIndex("AbpUsers", new[] { "TenantId", "EmailAddress" }); CreateIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "UserName" }); CreateIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "EmailAddress" }); } public override void Down() { DropIndex("AbpAuditLogs", new[] { "TenantId", "ExecutionTime" }); DropIndex("AbpAuditLogs", new[] { "UserId", "ExecutionTime" }); DropIndex("AbpEditions", new[] { "Name" }); DropIndex("AbpFeatures", new[] { "Discriminator", "TenantId", "Name" }); DropIndex("AbpFeatures", new[] { "Discriminator", "EditionId", "Name" }); DropIndex("AbpFeatures", new[] { "TenantId", "Name" }); DropIndex("AbpLanguages", new[] { "TenantId", "Name" }); DropIndex("AbpLanguageTexts", new[] { "TenantId", "LanguageName", "Source", "Key" }); DropIndex("AbpOrganizationUnits", new[] { "TenantId", "ParentId" }); DropIndex("AbpOrganizationUnits", new[] { "TenantId", "Code" }); CreateIndex("AbpPermissions", new[] { "UserId" }); CreateIndex("AbpPermissions", new[] { "RoleId" }); DropIndex("AbpPermissions", new[] { "UserId", "Name" }); DropIndex("AbpPermissions", new[] { "RoleId", "Name" }); DropIndex("AbpRoles", new[] { "TenantId", "Name" }); DropIndex("AbpRoles", new[] { "IsDeleted", "TenantId", "Name" }); CreateIndex("AbpSettings", new[] { "UserId" }); DropIndex("AbpSettings", new[] { "TenantId", "Name" }); DropIndex("AbpSettings", new[] { "UserId", "Name" }); DropIndex("AbpTenants", new[] { "TenancyName" }); DropIndex("AbpTenants", new[] { "IsDeleted", "TenancyName" }); CreateIndex("AbpUserLogins", new[] { "UserId" }); DropIndex("AbpUserLogins", new[] { "UserId", "LoginProvider" }); DropIndex("AbpUserOrganizationUnits", new[] { "TenantId", "UserId" }); DropIndex("AbpUserOrganizationUnits", new[] { "TenantId", "OrganizationUnitId" }); DropIndex("AbpUserOrganizationUnits", new[] { "UserId" }); DropIndex("AbpUserOrganizationUnits", new[] { "OrganizationUnitId" }); CreateIndex("AbpUserRoles", new[] { "UserId" }); DropIndex("AbpUserRoles", new[] { "UserId", "RoleId" }); DropIndex("AbpUserRoles", new[] { "RoleId" }); DropIndex("AbpUsers", new[] { "TenantId", "UserName" }); DropIndex("AbpUsers", new[] { "TenantId", "EmailAddress" }); DropIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "UserName" }); DropIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "EmailAddress" }); DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions"); DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles"); DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserClaims", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits"); DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions"); DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" }); DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" }); DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); DropIndex("dbo.AbpTenants", new[] { "EditionId" }); DropIndex("dbo.AbpSettings", new[] { "UserId" }); DropIndex("dbo.AbpUserRoles", new[] { "UserId" }); DropIndex("dbo.AbpUserLogins", new[] { "UserId" }); DropIndex("dbo.AbpUserClaims", new[] { "UserId" }); DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" }); DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" }); DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" }); DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" }); DropIndex("dbo.AbpPermissions", new[] { "UserId" }); DropIndex("dbo.AbpPermissions", new[] { "RoleId" }); DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" }); DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpFeatures", new[] { "EditionId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.AbpUserOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserLoginAttempts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserAccounts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpTenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpTenantNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpSettings", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserLogins", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserClaims", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUsers", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpPermissions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotificationSubscriptions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpLanguageTexts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpLanguages", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpEditions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpFeatures", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpBackgroundJobs"); DropTable("dbo.AbpAuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
// // RichTextViewBackend.cs // // Author: // Marek Habersack <grendel@xamarin.com> // // Copyright (c) 2013 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Xml; using Xwt; using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nuint = System.UInt32; using nfloat = System.Single; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; #else using Foundation; using AppKit; using ObjCRuntime; using CoreGraphics; #endif namespace Xwt.Mac { public class RichTextViewBackend : ViewBackend <NSTextView, IRichTextViewEventSink>, IRichTextViewBackend { NSFont font; MacRichTextBuffer currentBuffer; public override object Font { get { return base.Font; } set { var fd = value as FontData; if (fd != null) font = fd.Font; else font = null; base.Font = value; } } public RichTextViewBackend () { } public override void Initialize () { base.Initialize (); var tv = new MacTextView (EventSink, ApplicationContext); ViewObject = tv; tv.VerticallyResizable = false; tv.HorizontallyResizable = false; } double CalcHeight (double width) { var f = Widget.Frame; Widget.VerticallyResizable = true; Widget.Frame = new CGRect (Widget.Frame.X, Widget.Frame.Y, (float)width, 0); Widget.SizeToFit (); var h = Widget.Frame.Height; Widget.VerticallyResizable = false; Widget.Frame = f; return h; } public override Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint) { var width = (double) Widget.TextStorage.Size.Width; if (widthConstraint.IsConstrained) width = widthConstraint.AvailableSize; if (minWidth != -1 && minWidth > width) width = minWidth; var height = CalcHeight (width); if (minHeight != -1 && minHeight > height) height = minHeight; return new Size (width, height); } public IRichTextBuffer CreateBuffer () { // Use cached font since Widget.Font size increases for each LoadText... It has to do // with the 'style' attribute for the 'body' element - not sure why that happens return new MacRichTextBuffer (font ?? Widget.Font); } public bool ReadOnly { get { return !Widget.Editable; } set { Widget.Editable = !value; } } public IRichTextBuffer CurrentBuffer { get { return currentBuffer; } } public void SetBuffer (IRichTextBuffer buffer) { var macBuffer = buffer as MacRichTextBuffer; if (macBuffer == null) throw new ArgumentException ("Passed buffer is of incorrect type", "buffer"); currentBuffer = macBuffer; var tview = ViewObject as MacTextView; if (tview == null) return; tview.TextStorage.SetString (macBuffer.ToAttributedString ()); } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (!(eventId is RichTextViewEvent)) return; var tview = ViewObject as MacTextView; if (tview == null) return; tview.EnableEvent ((RichTextViewEvent)eventId); } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (!(eventId is RichTextViewEvent)) return; var tview = ViewObject as MacTextView; if (tview == null) return; tview.DisableEvent ((RichTextViewEvent)eventId); } } class MacTextView : NSTextView, IViewObject { IRichTextViewEventSink eventSink; ApplicationContext context; public NSView View { get { return this; } } public ViewBackend Backend { get; set; } public MacTextView (IntPtr p) : base (p) { CommonInit (); } public MacTextView (IRichTextViewEventSink eventSink, ApplicationContext context) { CommonInit (); this.eventSink = eventSink; this.context = context; EnableEvent (RichTextViewEvent.NavigateToUrl); } public void EnableEvent (RichTextViewEvent ev) { if (ev != RichTextViewEvent.NavigateToUrl) return; LinkClicked = TextLinkClicked; } public void DisableEvent (RichTextViewEvent ev) { if (ev != RichTextViewEvent.NavigateToUrl) return; LinkClicked = null; } bool TextLinkClicked (NSTextView textView, NSObject link, nuint charIndex) { if (eventSink == null || context == null) return false; string linkUrl; if (link is NSString) linkUrl = (link as NSString); else if (link is NSUrl) linkUrl = (link as NSUrl).AbsoluteString; else linkUrl = null; Uri url = null; if (String.IsNullOrWhiteSpace (linkUrl) || !Uri.TryCreate (linkUrl, UriKind.RelativeOrAbsolute, out url)) url = null; context.InvokeUserCode (delegate { eventSink.OnNavigateToUrl (url); }); return true; } void CommonInit () { Editable = false; } } class MacRichTextBuffer : IRichTextBuffer { const int HeaderIncrement = 8; static readonly string[] lineSplitChars = new string[] { Environment.NewLine }; static readonly IntPtr selInitWithHTMLDocumentAttributes_Handle = Selector.GetHandle ("initWithHTML:documentAttributes:"); StringBuilder text; XmlWriter xmlWriter; Stack <int> paragraphIndent; public MacRichTextBuffer (NSFont font) { text = new StringBuilder (); xmlWriter = XmlWriter.Create (text, new XmlWriterSettings { OmitXmlDeclaration = true, Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t" }); float fontSize; string fontFamily; if (font != null) { fontSize = (float) font.PointSize; fontFamily = font.FontName; } else { fontSize = 16; fontFamily = "sans-serif"; } xmlWriter.WriteDocType ("html", "-//W3C//DTD XHTML 1.0", "Strict//EN", null); xmlWriter.WriteStartElement ("html"); xmlWriter.WriteStartElement ("meta"); xmlWriter.WriteAttributeString ("http-equiv", "Content-Type"); xmlWriter.WriteAttributeString ("content", "text/html; charset=utf-8"); xmlWriter.WriteEndElement (); xmlWriter.WriteStartElement ("body"); xmlWriter.WriteAttributeString ("style", String.Format ("font-family: {0}; font-size: {1}", fontFamily, fontSize)); } public NSAttributedString ToAttributedString () { xmlWriter.WriteEndElement (); // body xmlWriter.WriteEndElement (); // html xmlWriter.Flush (); if (text == null || text.Length == 0) return new NSAttributedString (String.Empty); NSDictionary docAttributes; try { return CreateStringFromHTML (text.ToString (), out docAttributes); } finally { text = null; xmlWriter.Dispose (); xmlWriter = null; docAttributes = null; } } NSAttributedString CreateStringFromHTML (string html, out NSDictionary docAttributes) { var data = NSData.FromString (html); IntPtr docAttributesPtr = Marshal.AllocHGlobal (4); Marshal.WriteInt32 (docAttributesPtr, 0); var attrString = new NSAttributedString (); attrString.Handle = Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (attrString.Handle, selInitWithHTMLDocumentAttributes_Handle, data.Handle, docAttributesPtr); IntPtr docAttributesValue = Marshal.ReadIntPtr (docAttributesPtr); docAttributes = docAttributesValue != IntPtr.Zero ? Runtime.GetNSObject (docAttributesValue) as NSDictionary : null; Marshal.FreeHGlobal (docAttributesPtr); return attrString; } public string PlainText { get { return text.ToString (); } } public void EmitText (string text, RichTextInlineStyle style) { if (String.IsNullOrEmpty (text)) return; bool haveStyle = true; switch (style) { case RichTextInlineStyle.Bold: xmlWriter.WriteStartElement ("strong"); break; case RichTextInlineStyle.Italic: xmlWriter.WriteStartElement ("em"); break; case RichTextInlineStyle.Monospace: xmlWriter.WriteStartElement ("tt"); break; default: haveStyle = false; break; } bool first = true; foreach (string line in text.Split (lineSplitChars, StringSplitOptions.None)) { if (!first) { xmlWriter.WriteStartElement ("br"); xmlWriter.WriteEndElement (); } else first = false; xmlWriter.WriteString (line); } if (haveStyle) xmlWriter.WriteEndElement (); } public void EmitStartHeader (int level) { if (level < 1) level = 1; if (level > 6) level = 6; xmlWriter.WriteStartElement ("h" + level); } public void EmitEndHeader () { xmlWriter.WriteEndElement (); } public void EmitStartParagraph (int indentLevel) { if (paragraphIndent == null) paragraphIndent = new Stack<int> (); paragraphIndent.Push (indentLevel); // FIXME: perhaps use CSS indent? for (int i = 0; i < indentLevel; i++) xmlWriter.WriteStartElement ("blockindent"); xmlWriter.WriteStartElement ("p"); } public void EmitEndParagraph () { xmlWriter.WriteEndElement (); // </p> int indentLevel; if (paragraphIndent != null && paragraphIndent.Count > 0) indentLevel = paragraphIndent.Pop (); else indentLevel = 0; for (int i = 0; i < indentLevel; i++) xmlWriter.WriteEndElement (); // </blockindent> } public void EmitOpenList () { xmlWriter.WriteStartElement ("ul"); } public void EmitOpenBullet () { xmlWriter.WriteStartElement ("li"); } public void EmitCloseBullet () { xmlWriter.WriteEndElement (); } public void EmitCloseList () { xmlWriter.WriteEndElement (); } public void EmitStartLink (string href, string title) { xmlWriter.WriteStartElement ("a"); xmlWriter.WriteAttributeString ("href", href); // FIXME: it appears NSTextView ignores 'title' when it's told to display // link tooltips - it will use the URL instead. See if there's a way to make // it show the actual title xmlWriter.WriteAttributeString ("title", title); } public void EmitEndLink () { xmlWriter.WriteEndElement (); } public void EmitCodeBlock (string code) { xmlWriter.WriteStartElement ("pre"); xmlWriter.WriteString (code); xmlWriter.WriteEndElement (); } public void EmitHorizontalRuler () { xmlWriter.WriteStartElement ("hr"); xmlWriter.WriteEndElement (); } } }
// Adler32.cs - Computes Adler32 data checksum of a data stream // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7 using System; namespace ICSharpCode.SharpZipLib.Checksums { /// <summary> /// Computes Adler32 checksum for a stream of data. An Adler32 /// checksum is not as reliable as a CRC32 checksum, but a lot faster to /// compute. /// /// The specification for Adler32 may be found in RFC 1950. /// ZLIB Compressed Data Format Specification version 3.3) /// /// /// From that document: /// /// "ADLER32 (Adler-32 checksum) /// This contains a checksum value of the uncompressed data /// (excluding any dictionary data) computed according to Adler-32 /// algorithm. This algorithm is a 32-bit extension and improvement /// of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073 /// standard. /// /// Adler-32 is composed of two sums accumulated per byte: s1 is /// the sum of all bytes, s2 is the sum of all s1 values. Both sums /// are done modulo 65521. s1 is initialized to 1, s2 to zero. The /// Adler-32 checksum is stored as s2*65536 + s1 in most- /// significant-byte first (network) order." /// /// "8.2. The Adler-32 algorithm /// /// The Adler-32 algorithm is much faster than the CRC32 algorithm yet /// still provides an extremely low probability of undetected errors. /// /// The modulo on unsigned long accumulators can be delayed for 5552 /// bytes, so the modulo operation time is negligible. If the bytes /// are a, b, c, the second sum is 3a + 2b + c + 3, and so is position /// and order sensitive, unlike the first sum, which is just a /// checksum. That 65521 is prime is important to avoid a possible /// large class of two-byte errors that leave the check unchanged. /// (The Fletcher checksum uses 255, which is not prime and which also /// makes the Fletcher check insensitive to single byte changes 0 - /// 255.) /// /// The sum s1 is initialized to 1 instead of zero to make the length /// of the sequence part of s2, so that the length does not have to be /// checked separately. (Any sequence of zeroes has a Fletcher /// checksum of zero.)" /// </summary> /// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream"/> /// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream"/> sealed class Adler32 : IChecksum { /// <summary> /// largest prime smaller than 65536 /// </summary> const uint BASE = 65521; /// <summary> /// Returns the Adler32 data checksum computed so far. /// </summary> public long Value { get { return checksum; } } /// <summary> /// Creates a new instance of the Adler32 class. /// The checksum starts off with a value of 1. /// </summary> public Adler32() { Reset(); } /// <summary> /// Resets the Adler32 checksum to the initial value. /// </summary> public void Reset() { checksum = 1; } /// <summary> /// Updates the checksum with a byte value. /// </summary> /// <param name="value"> /// The data value to add. The high byte of the int is ignored. /// </param> public void Update(int value) { // We could make a length 1 byte array and call update again, but I // would rather not have that overhead uint s1 = checksum & 0xFFFF; uint s2 = checksum >> 16; s1 = (s1 + ((uint)value & 0xFF)) % BASE; s2 = (s1 + s2) % BASE; checksum = (s2 << 16) + s1; } /// <summary> /// Updates the checksum with an array of bytes. /// </summary> /// <param name="buffer"> /// The source of the data to update with. /// </param> public void Update(byte[] buffer) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } Update(buffer, 0, buffer.Length); } /// <summary> /// Updates the checksum with the bytes taken from the array. /// </summary> /// <param name="buffer"> /// an array of bytes /// </param> /// <param name="offset"> /// the start of the data used for this update /// </param> /// <param name="count"> /// the number of bytes to use for this update /// </param> public void Update(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "cannot be negative"); #endif } if (offset >= buffer.Length) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "not a valid index into buffer"); #endif } if (offset + count > buffer.Length) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "exceeds buffer size"); #endif } //(By Per Bothner) uint s1 = checksum & 0xFFFF; uint s2 = checksum >> 16; while (count > 0) { // We can defer the modulo operation: // s1 maximally grows from 65521 to 65521 + 255 * 3800 // s2 maximally grows by 3800 * median(s1) = 2090079800 < 2^31 int n = 3800; if (n > count) { n = count; } count -= n; while (--n >= 0) { s1 = s1 + (uint)(buffer[offset++] & 0xff); s2 = s2 + s1; } s1 %= BASE; s2 %= BASE; } checksum = (s2 << 16) | s1; } #region Instance Fields uint checksum; #endregion } }
/* * Copyright 2010-2014 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. */ /* * Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model. */ 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.IdentityManagement.Model { /// <summary> /// Contains information about an IAM role, including all of the role's policies. /// /// /// <para> /// This data type is used as a response element in the <a>GetAccountAuthorizationDetails</a> /// action. /// </para> /// </summary> public partial class RoleDetail { private string _arn; private string _assumeRolePolicyDocument; private List<AttachedPolicyType> _attachedManagedPolicies = new List<AttachedPolicyType>(); private DateTime? _createDate; private List<InstanceProfile> _instanceProfileList = new List<InstanceProfile>(); private string _path; private string _roleId; private string _roleName; private List<PolicyDetail> _rolePolicyList = new List<PolicyDetail>(); /// <summary> /// Gets and sets the property Arn. /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property AssumeRolePolicyDocument. /// <para> /// The trust policy that grants permission to assume the role. /// </para> /// </summary> public string AssumeRolePolicyDocument { get { return this._assumeRolePolicyDocument; } set { this._assumeRolePolicyDocument = value; } } // Check to see if AssumeRolePolicyDocument property is set internal bool IsSetAssumeRolePolicyDocument() { return this._assumeRolePolicyDocument != null; } /// <summary> /// Gets and sets the property AttachedManagedPolicies. /// <para> /// A list of managed policies attached to the role. These policies are the role's access /// (permissions) policies. /// </para> /// </summary> public List<AttachedPolicyType> AttachedManagedPolicies { get { return this._attachedManagedPolicies; } set { this._attachedManagedPolicies = value; } } // Check to see if AttachedManagedPolicies property is set internal bool IsSetAttachedManagedPolicies() { return this._attachedManagedPolicies != null && this._attachedManagedPolicies.Count > 0; } /// <summary> /// Gets and sets the property CreateDate. /// <para> /// The date and time, in <a href="http://www.iso.org/iso/iso8601">ISO 8601 date-time /// format</a>, when the role was created. /// </para> /// </summary> public DateTime CreateDate { get { return this._createDate.GetValueOrDefault(); } set { this._createDate = value; } } // Check to see if CreateDate property is set internal bool IsSetCreateDate() { return this._createDate.HasValue; } /// <summary> /// Gets and sets the property InstanceProfileList. /// </summary> public List<InstanceProfile> InstanceProfileList { get { return this._instanceProfileList; } set { this._instanceProfileList = value; } } // Check to see if InstanceProfileList property is set internal bool IsSetInstanceProfileList() { return this._instanceProfileList != null && this._instanceProfileList.Count > 0; } /// <summary> /// Gets and sets the property Path. /// <para> /// The path to the role. For more information about paths, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">IAM /// Identifiers</a> in the <i>Using IAM</i> guide. /// </para> /// </summary> public string Path { get { return this._path; } set { this._path = value; } } // Check to see if Path property is set internal bool IsSetPath() { return this._path != null; } /// <summary> /// Gets and sets the property RoleId. /// <para> /// The stable and unique string identifying the role. For more information about IDs, /// see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">IAM /// Identifiers</a> in the <i>Using IAM</i> guide. /// </para> /// </summary> public string RoleId { get { return this._roleId; } set { this._roleId = value; } } // Check to see if RoleId property is set internal bool IsSetRoleId() { return this._roleId != null; } /// <summary> /// Gets and sets the property RoleName. /// <para> /// The friendly name that identifies the role. /// </para> /// </summary> public string RoleName { get { return this._roleName; } set { this._roleName = value; } } // Check to see if RoleName property is set internal bool IsSetRoleName() { return this._roleName != null; } /// <summary> /// Gets and sets the property RolePolicyList. /// <para> /// A list of inline policies embedded in the role. These policies are the role's access /// (permissions) policies. /// </para> /// </summary> public List<PolicyDetail> RolePolicyList { get { return this._rolePolicyList; } set { this._rolePolicyList = value; } } // Check to see if RolePolicyList property is set internal bool IsSetRolePolicyList() { return this._rolePolicyList != null && this._rolePolicyList.Count > 0; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gctv = Google.Cloud.Talent.V4; using sys = System; namespace Google.Cloud.Talent.V4 { /// <summary>Resource name for the <c>Tenant</c> resource.</summary> public sealed partial class TenantName : gax::IResourceName, sys::IEquatable<TenantName> { /// <summary>The possible contents of <see cref="TenantName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/tenants/{tenant}</c>.</summary> ProjectTenant = 1, } private static gax::PathTemplate s_projectTenant = new gax::PathTemplate("projects/{project}/tenants/{tenant}"); /// <summary>Creates a <see cref="TenantName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TenantName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static TenantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TenantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TenantName"/> with the pattern <c>projects/{project}/tenants/{tenant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TenantName"/> constructed from the provided ids.</returns> public static TenantName FromProjectTenant(string projectId, string tenantId) => new TenantName(ResourceNameType.ProjectTenant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), tenantId: gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TenantName"/> with pattern /// <c>projects/{project}/tenants/{tenant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TenantName"/> with pattern /// <c>projects/{project}/tenants/{tenant}</c>. /// </returns> public static string Format(string projectId, string tenantId) => FormatProjectTenant(projectId, tenantId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TenantName"/> with pattern /// <c>projects/{project}/tenants/{tenant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TenantName"/> with pattern /// <c>projects/{project}/tenants/{tenant}</c>. /// </returns> public static string FormatProjectTenant(string projectId, string tenantId) => s_projectTenant.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId))); /// <summary>Parses the given resource name string into a new <see cref="TenantName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/tenants/{tenant}</c></description></item> /// </list> /// </remarks> /// <param name="tenantName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TenantName"/> if successful.</returns> public static TenantName Parse(string tenantName) => Parse(tenantName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TenantName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/tenants/{tenant}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tenantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TenantName"/> if successful.</returns> public static TenantName Parse(string tenantName, bool allowUnparsed) => TryParse(tenantName, allowUnparsed, out TenantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TenantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/tenants/{tenant}</c></description></item> /// </list> /// </remarks> /// <param name="tenantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TenantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tenantName, out TenantName result) => TryParse(tenantName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TenantName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/tenants/{tenant}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tenantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TenantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tenantName, bool allowUnparsed, out TenantName result) { gax::GaxPreconditions.CheckNotNull(tenantName, nameof(tenantName)); gax::TemplatedResourceName resourceName; if (s_projectTenant.TryParseName(tenantName, out resourceName)) { result = FromProjectTenant(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(tenantName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TenantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string tenantId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; TenantId = tenantId; } /// <summary> /// Constructs a new instance of a <see cref="TenantName"/> class from the component parts of pattern /// <c>projects/{project}/tenants/{tenant}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param> public TenantName(string projectId, string tenantId) : this(ResourceNameType.ProjectTenant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), tenantId: gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Tenant</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TenantId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectTenant: return s_projectTenant.Expand(ProjectId, TenantId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TenantName); /// <inheritdoc/> public bool Equals(TenantName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TenantName a, TenantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TenantName a, TenantName b) => !(a == b); } public partial class Tenant { /// <summary> /// <see cref="gctv::TenantName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::TenantName TenantName { get => string.IsNullOrEmpty(Name) ? null : gctv::TenantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Text; using System.Text.Tests; using Xunit; using static System.Tests.Utf8TestUtilities; using ustring = System.Utf8String; namespace System.Tests { /* * Please keep these tests in sync with those in Utf8SpanTests.Searching.cs. */ public unsafe partial class Utf8StringTests { public static IEnumerable<object[]> TryFindData_Char_Ordinal() => Utf8SpanTests.TryFindData_Char_Ordinal(); [Theory] [MemberData(nameof(TryFindData_Char_Ordinal))] public static void TryFind_Char_Ordinal(ustring source, char searchTerm, Range? expectedForwardMatch, Range? expectedBackwardMatch) { if (source is null) { return; // don't null ref } // First, search forward bool wasFound = source.TryFind(searchTerm, out Range actualForwardMatch); Assert.Equal(expectedForwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedForwardMatch.Value, actualForwardMatch); } // Also check Contains / StartsWith / SplitOn Assert.Equal(wasFound, source.Contains(searchTerm)); Assert.Equal(wasFound && source[..actualForwardMatch.Start].Length == 0, source.StartsWith(searchTerm)); (var before, var after) = source.SplitOn(searchTerm); if (wasFound) { Assert.Equal(source[..actualForwardMatch.Start], before); Assert.Equal(source[actualForwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } // Now search backward wasFound = source.TryFindLast(searchTerm, out Range actualBackwardMatch); Assert.Equal(expectedBackwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedBackwardMatch.Value, actualBackwardMatch); } // Also check EndsWith / SplitOnLast Assert.Equal(wasFound && source[actualBackwardMatch.End..].Length == 0, source.EndsWith(searchTerm)); (before, after) = source.SplitOnLast(searchTerm); if (wasFound) { Assert.Equal(source[..actualBackwardMatch.Start], before); Assert.Equal(source[actualBackwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } } public static IEnumerable<object[]> TryFindData_Char_WithComparison() => Utf8SpanTests.TryFindData_Char_WithComparison(); [Theory] [PlatformSpecific(TestPlatforms.Windows)] [MemberData(nameof(TryFindData_Char_WithComparison))] public static void TryFind_Char_WithComparison(ustring source, char searchTerm, StringComparison comparison, CultureInfo currentCulture, Range? expectedForwardMatch, Range? expectedBackwardMatch) { if (source is null) { return; // don't null ref } RunOnDedicatedThread(() => { if (currentCulture != null) { CultureInfo.CurrentCulture = currentCulture; } // First, search forward bool wasFound = source.TryFind(searchTerm, comparison, out Range actualForwardMatch); Assert.Equal(expectedForwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedForwardMatch.Value, actualForwardMatch); } // Also check Contains / StartsWith / SplitOn Assert.Equal(wasFound, source.Contains(searchTerm, comparison)); Assert.Equal(wasFound && source[..actualForwardMatch.Start].Length == 0, source.StartsWith(searchTerm, comparison)); (var before, var after) = source.SplitOn(searchTerm, comparison); if (wasFound) { Assert.Equal(source[..actualForwardMatch.Start], before); Assert.Equal(source[actualForwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } // Now search backward wasFound = source.TryFindLast(searchTerm, comparison, out Range actualBackwardMatch); Assert.Equal(expectedBackwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedBackwardMatch.Value, actualBackwardMatch); } // Also check EndsWith / SplitOnLast Assert.Equal(wasFound && source[actualBackwardMatch.End..].Length == 0, source.EndsWith(searchTerm, comparison)); (before, after) = source.SplitOnLast(searchTerm, comparison); if (wasFound) { Assert.Equal(source[..actualBackwardMatch.Start], before); Assert.Equal(source[actualBackwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } }); } public static IEnumerable<object[]> TryFindData_Rune_Ordinal() => Utf8SpanTests.TryFindData_Rune_Ordinal(); [Theory] [MemberData(nameof(TryFindData_Rune_Ordinal))] public static void TryFind_Rune_Ordinal(ustring source, Rune searchTerm, Range? expectedForwardMatch, Range? expectedBackwardMatch) { if (source is null) { return; // don't null ref } // First, search forward bool wasFound = source.TryFind(searchTerm, out Range actualForwardMatch); Assert.Equal(expectedForwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedForwardMatch.Value, actualForwardMatch); } // Also check Contains / StartsWith / SplitOn Assert.Equal(wasFound, source.Contains(searchTerm)); Assert.Equal(wasFound && source[..actualForwardMatch.Start].Length == 0, source.StartsWith(searchTerm)); (var before, var after) = source.SplitOn(searchTerm); if (wasFound) { Assert.Equal(source[..actualForwardMatch.Start], before); Assert.Equal(source[actualForwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } // Now search backward wasFound = source.TryFindLast(searchTerm, out Range actualBackwardMatch); Assert.Equal(expectedBackwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedBackwardMatch.Value, actualBackwardMatch); } // Also check EndsWith / SplitOnLast Assert.Equal(wasFound && source[actualBackwardMatch.End..].Length == 0, source.EndsWith(searchTerm)); (before, after) = source.SplitOnLast(searchTerm); if (wasFound) { Assert.Equal(source[..actualBackwardMatch.Start], before); Assert.Equal(source[actualBackwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } } public static IEnumerable<object[]> TryFindData_Rune_WithComparison() => Utf8SpanTests.TryFindData_Rune_WithComparison(); [Theory] [PlatformSpecific(TestPlatforms.Windows)] [MemberData(nameof(TryFindData_Rune_WithComparison))] public static void TryFind_Rune_WithComparison(ustring source, Rune searchTerm, StringComparison comparison, CultureInfo currentCulture, Range? expectedForwardMatch, Range? expectedBackwardMatch) { if (source is null) { return; // don't null ref } RunOnDedicatedThread(() => { if (currentCulture != null) { CultureInfo.CurrentCulture = currentCulture; } // First, search forward bool wasFound = source.TryFind(searchTerm, comparison, out Range actualForwardMatch); Assert.Equal(expectedForwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedForwardMatch.Value, actualForwardMatch); } // Also check Contains / StartsWith / SplitOn Assert.Equal(wasFound, source.Contains(searchTerm, comparison)); Assert.Equal(wasFound && source[..actualForwardMatch.Start].Length == 0, source.StartsWith(searchTerm, comparison)); (var before, var after) = source.SplitOn(searchTerm, comparison); if (wasFound) { Assert.Equal(source[..actualForwardMatch.Start], before); Assert.Equal(source[actualForwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } // Now search backward wasFound = source.TryFindLast(searchTerm, comparison, out Range actualBackwardMatch); Assert.Equal(expectedBackwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedBackwardMatch.Value, actualBackwardMatch); } // Also check EndsWith / SplitOnLast Assert.Equal(wasFound && source[actualBackwardMatch.End..].Length == 0, source.EndsWith(searchTerm, comparison)); (before, after) = source.SplitOnLast(searchTerm, comparison); if (wasFound) { Assert.Equal(source[..actualBackwardMatch.Start], before); Assert.Equal(source[actualBackwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } }); } public static IEnumerable<object[]> TryFindData_Utf8String_Ordinal() => Utf8SpanTests.TryFindData_Utf8Span_Ordinal(); [Theory] [MemberData(nameof(TryFindData_Utf8String_Ordinal))] public static void TryFind_Utf8String_Ordinal(ustring source, ustring searchTerm, Range? expectedForwardMatch, Range? expectedBackwardMatch) { if (source is null) { return; // don't null ref } // First, search forward bool wasFound = source.TryFind(searchTerm, out Range actualForwardMatch); Assert.Equal(expectedForwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedForwardMatch.Value, actualForwardMatch); } // Also check Contains / StartsWith / SplitOn Assert.Equal(wasFound, source.Contains(searchTerm)); Assert.Equal(wasFound && source[..actualForwardMatch.Start].Length == 0, source.StartsWith(searchTerm)); (var before, var after) = source.SplitOn(searchTerm); if (wasFound) { Assert.Equal(source[..actualForwardMatch.Start], before); Assert.Equal(source[actualForwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } // Now search backward wasFound = source.TryFindLast(searchTerm, out Range actualBackwardMatch); Assert.Equal(expectedBackwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedBackwardMatch.Value, actualBackwardMatch); } // Also check EndsWith / SplitOnLast Assert.Equal(wasFound && source[actualBackwardMatch.End..].Length == 0, source.EndsWith(searchTerm)); (before, after) = source.SplitOnLast(searchTerm); if (wasFound) { Assert.Equal(source[..actualBackwardMatch.Start], before); Assert.Equal(source[actualBackwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } } public static IEnumerable<object[]> TryFindData_Utf8String_WithComparison() => Utf8SpanTests.TryFindData_Utf8Span_WithComparison(); [Theory] [PlatformSpecific(TestPlatforms.Windows)] [MemberData(nameof(TryFindData_Utf8String_WithComparison))] public static void TryFind_Utf8String_WithComparison(ustring source, ustring searchTerm, StringComparison comparison, CultureInfo currentCulture, Range? expectedForwardMatch, Range? expectedBackwardMatch) { if (source is null) { return; // don't null ref } RunOnDedicatedThread(() => { if (currentCulture != null) { CultureInfo.CurrentCulture = currentCulture; } // First, search forward bool wasFound = source.TryFind(searchTerm, comparison, out Range actualForwardMatch); Assert.Equal(expectedForwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedForwardMatch.Value, actualForwardMatch); } // Also check Contains / StartsWith / SplitOn Assert.Equal(wasFound, source.Contains(searchTerm, comparison)); Assert.Equal(wasFound && source[..actualForwardMatch.Start].Length == 0, source.StartsWith(searchTerm, comparison)); (var before, var after) = source.SplitOn(searchTerm, comparison); if (wasFound) { Assert.Equal(source[..actualForwardMatch.Start], before); Assert.Equal(source[actualForwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } // Now search backward wasFound = source.TryFindLast(searchTerm, comparison, out Range actualBackwardMatch); Assert.Equal(expectedBackwardMatch.HasValue, wasFound); if (wasFound) { AssertRangesEqual(source.Length, expectedBackwardMatch.Value, actualBackwardMatch); } // Also check EndsWith / SplitOnLast Assert.Equal(wasFound && source[actualBackwardMatch.End..].Length == 0, source.EndsWith(searchTerm, comparison)); (before, after) = source.SplitOnLast(searchTerm, comparison); if (wasFound) { Assert.Equal(source[..actualBackwardMatch.Start], before); Assert.Equal(source[actualBackwardMatch.End..], after); } else { Assert.Same(source, before); // check for reference equality Assert.Null(after); } }); } [Fact] public static void TryFind_WithNullUtf8String_Throws() { static void RunTest(Action action) { var exception = Assert.Throws<ArgumentNullException>(action); Assert.Equal("value", exception.ParamName); } ustring str = u8("Hello!"); const ustring value = null; const StringComparison comparison = StringComparison.OrdinalIgnoreCase; // Run this test for a bunch of methods, not simply TryFind RunTest(() => str.Contains(value)); RunTest(() => str.Contains(value, comparison)); RunTest(() => str.EndsWith(value)); RunTest(() => str.EndsWith(value, comparison)); RunTest(() => str.SplitOn(value)); RunTest(() => str.SplitOn(value, comparison)); RunTest(() => str.SplitOnLast(value)); RunTest(() => str.SplitOnLast(value, comparison)); RunTest(() => str.StartsWith(value)); RunTest(() => str.StartsWith(value, comparison)); RunTest(() => str.TryFind(value, out _)); RunTest(() => str.TryFind(value, comparison, out _)); RunTest(() => str.TryFindLast(value, out _)); RunTest(() => str.TryFindLast(value, comparison, out _)); } } }
// 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.IO; using System.Text; using Microsoft.Xml.Schema; using Microsoft.Xml.XPath; using System.Diagnostics; using System.Globalization; using System.Collections; // using System.Security.Policy; using System.Collections.Generic; using System.Runtime.Versioning; using System.Threading.Tasks; namespace Microsoft.Xml { using System; internal partial class XsdValidatingReader : XmlReader, IXmlSchemaInfo, IXmlLineInfo, IXmlNamespaceResolver { // Gets the text value of the current node. public override Task<string> GetValueAsync() { if ((int)_validationState < 0) { return Task.FromResult(_cachedNode.RawValue); } return _coreReader.GetValueAsync(); } public override Task<object> ReadContentAsObjectAsync() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException("ReadContentAsObject"); } return InternalReadContentAsObjectAsync(true); } public override async Task<string> ReadContentAsStringAsync() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException("ReadContentAsString"); } object typedValue = await InternalReadContentAsObjectAsync().ConfigureAwait(false); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToString(typedValue); } else { return typedValue as string; } } catch (InvalidCastException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } } public override async Task<object> ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException("ReadContentAs"); } string originalStringValue; var tuple_0 = await InternalReadContentAsObjectTupleAsync(false).ConfigureAwait(false); originalStringValue = tuple_0.Item1; object typedValue = tuple_0.Item2; XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; //TODO special case for xsd:duration and xsd:dateTime try { if (xmlType != null) { // special-case convertions to DateTimeOffset; typedValue is by default a DateTime // which cannot preserve time zone, so we need to convert from the original string if (returnType == typeof(DateTimeOffset) && xmlType.Datatype is Datatype_dateTimeBase) { typedValue = originalStringValue; } return xmlType.ValueConverter.ChangeType(typedValue, returnType); } else { return XmlUntypedConverter.Untyped.ChangeType(typedValue, returnType, namespaceResolver); } } catch (FormatException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } } public override async Task<object> ReadElementContentAsObjectAsync() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException("ReadElementContentAsObject"); } var tuple_1 = await InternalReadElementContentAsObjectAsync(true).ConfigureAwait(false); return tuple_1.Item2; } public override async Task<string> ReadElementContentAsStringAsync() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException("ReadElementContentAsString"); } XmlSchemaType xmlType; var tuple_9 = await InternalReadElementContentAsObjectAsync().ConfigureAwait(false); xmlType = tuple_9.Item1; object typedValue = tuple_9.Item2; try { if (xmlType != null) { return xmlType.ValueConverter.ToString(typedValue); } else { return typedValue as string; } } catch (InvalidCastException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } } public override async Task<object> ReadElementContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException("ReadElementContentAs"); } XmlSchemaType xmlType; string originalStringValue; var tuple_10 = await InternalReadElementContentAsObjectTupleAsync(false).ConfigureAwait(false); xmlType = tuple_10.Item1; originalStringValue = tuple_10.Item2; object typedValue = tuple_10.Item3; try { if (xmlType != null) { // special-case convertions to DateTimeOffset; typedValue is by default a DateTime // which cannot preserve time zone, so we need to convert from the original string if (returnType == typeof(DateTimeOffset) && xmlType.Datatype is Datatype_dateTimeBase) { typedValue = originalStringValue; } return xmlType.ValueConverter.ChangeType(typedValue, returnType, namespaceResolver); } else { return XmlUntypedConverter.Untyped.ChangeType(typedValue, returnType, namespaceResolver); } } catch (FormatException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(ResXml.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } } private Task<bool> ReadAsync_Read(Task<bool> task) { if (task.IsSuccess()) { if (task.Result) { return ProcessReaderEventAsync().ReturnTaskBoolWhenFinish(true); } else { _validator.EndValidation(); if (_coreReader.EOF) { _validationState = ValidatingReaderState.EOF; } return AsyncHelper.DoneTaskFalse; } } else { return _ReadAsync_Read(task); } } private async Task<bool> _ReadAsync_Read(Task<bool> task) { if (await task.ConfigureAwait(false)) { await ProcessReaderEventAsync().ConfigureAwait(false); return true; } else { _validator.EndValidation(); if (_coreReader.EOF) { _validationState = ValidatingReaderState.EOF; } return false; } } private Task<bool> ReadAsync_ReadAhead(Task task) { if (task.IsSuccess()) { _validationState = ValidatingReaderState.Read; return AsyncHelper.DoneTaskTrue; ; } else { return _ReadAsync_ReadAhead(task); } } private async Task<bool> _ReadAsync_ReadAhead(Task task) { await task.ConfigureAwait(false); _validationState = ValidatingReaderState.Read; return true; } // Reads the next node from the stream/TextReader. public override Task<bool> ReadAsync() { switch (_validationState) { case ValidatingReaderState.Read: Task<bool> readTask = _coreReader.ReadAsync(); return ReadAsync_Read(readTask); case ValidatingReaderState.ParseInlineSchema: return ProcessInlineSchemaAsync().ReturnTaskBoolWhenFinish(true); case ValidatingReaderState.OnAttribute: case ValidatingReaderState.OnDefaultAttribute: case ValidatingReaderState.ClearAttributes: case ValidatingReaderState.OnReadAttributeValue: ClearAttributesInfo(); if (_inlineSchemaParser != null) { _validationState = ValidatingReaderState.ParseInlineSchema; goto case ValidatingReaderState.ParseInlineSchema; } else { _validationState = ValidatingReaderState.Read; goto case ValidatingReaderState.Read; } case ValidatingReaderState.ReadAhead: //Will enter here on calling Skip() ClearAttributesInfo(); Task task = ProcessReaderEventAsync(); return ReadAsync_ReadAhead(task); case ValidatingReaderState.OnReadBinaryContent: _validationState = _savedState; return _readBinaryHelper.FinishAsync().CallBoolTaskFuncWhenFinish(ReadAsync); case ValidatingReaderState.Init: _validationState = ValidatingReaderState.Read; if (_coreReader.ReadState == ReadState.Interactive) { //If the underlying reader is already positioned on a ndoe, process it return ProcessReaderEventAsync().ReturnTaskBoolWhenFinish(true); } else { goto case ValidatingReaderState.Read; } case ValidatingReaderState.ReaderClosed: case ValidatingReaderState.EOF: return AsyncHelper.DoneTaskFalse; default: return AsyncHelper.DoneTaskFalse; } } // Skips to the end tag of the current element. public override async Task SkipAsync() { int startDepth = Depth; switch (NodeType) { case XmlNodeType.Element: if (_coreReader.IsEmptyElement) { break; } bool callSkipToEndElem = true; //If union and unionValue has been parsed till EndElement, then validator.ValidateEndElement has been called //Hence should not call SkipToEndElement as the current context has already been popped in the validator if ((_xmlSchemaInfo.IsUnionType || _xmlSchemaInfo.IsDefault) && _coreReader is XsdCachingReader) { callSkipToEndElem = false; } await _coreReader.SkipAsync().ConfigureAwait(false); _validationState = ValidatingReaderState.ReadAhead; if (callSkipToEndElem) { _validator.SkipToEndElement(_xmlSchemaInfo); } break; case XmlNodeType.Attribute: MoveToElement(); goto case XmlNodeType.Element; } //For all other NodeTypes Skip() same as Read() await ReadAsync().ConfigureAwait(false); return; } public override async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (_validationState != ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); _savedState = _validationState; } // restore original state in order to have a normal Read() behavior when called from readBinaryHelper _validationState = _savedState; // call to the helper int readCount = await _readBinaryHelper.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false); // set OnReadBinaryContent state again and return _savedState = _validationState; _validationState = ValidatingReaderState.OnReadBinaryContent; return readCount; } public override async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (_validationState != ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); _savedState = _validationState; } // restore original state in order to have a normal Read() behavior when called from readBinaryHelper _validationState = _savedState; // call to the helper int readCount = await _readBinaryHelper.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); // set OnReadBinaryContent state again and return _savedState = _validationState; _validationState = ValidatingReaderState.OnReadBinaryContent; return readCount; } public override async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (_validationState != ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); _savedState = _validationState; } // restore original state in order to have a normal Read() behavior when called from readBinaryHelper _validationState = _savedState; // call to the helper int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); // set OnReadBinaryContent state again and return _savedState = _validationState; _validationState = ValidatingReaderState.OnReadBinaryContent; return readCount; } public override async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (_validationState != ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); _savedState = _validationState; } // restore original state in order to have a normal Read() behavior when called from readBinaryHelper _validationState = _savedState; // call to the helper int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); // set OnReadBinaryContent state again and return _savedState = _validationState; _validationState = ValidatingReaderState.OnReadBinaryContent; return readCount; } private Task ProcessReaderEventAsync() { if (_replayCache) { //if in replay mode, do nothing since nodes have been validated already //If NodeType == XmlNodeType.EndElement && if manageNamespaces, may need to pop namespace scope, since scope is not popped in ReadAheadForMemberType return AsyncHelper.DoneTask; } switch (_coreReader.NodeType) { case XmlNodeType.Element: return ProcessElementEventAsync(); case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: _validator.ValidateWhitespace(GetStringValue); break; case XmlNodeType.Text: // text inside a node case XmlNodeType.CDATA: // <![CDATA[...]]> _validator.ValidateText(GetStringValue); break; case XmlNodeType.EndElement: return ProcessEndElementEventAsync(); case XmlNodeType.EntityReference: throw new InvalidOperationException(); case XmlNodeType.DocumentType: #if TEMP_HACK_FOR_SCHEMA_INFO validator.SetDtdSchemaInfo((SchemaInfo)coreReader.DtdInfo); #else _validator.SetDtdSchemaInfo(_coreReader.DtdInfo); #endif break; default: break; } return AsyncHelper.DoneTask; } // SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute. // Since the resource names (namespace location) are not provided directly by the user (they are read from the source // document) and the function does not expose any resources it is fine to disable the SxS warning. private async Task ProcessElementEventAsync() { if (_processInlineSchema && IsXSDRoot(_coreReader.LocalName, _coreReader.NamespaceURI) && _coreReader.Depth > 0) { _xmlSchemaInfo.Clear(); _attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount; if (!_coreReader.IsEmptyElement) { //If its not empty schema, then parse else ignore _inlineSchemaParser = new Parser(SchemaType.XSD, _coreReaderNameTable, _validator.SchemaSet.GetSchemaNames(_coreReaderNameTable), _validationEvent); await _inlineSchemaParser.StartParsingAsync(_coreReader, null).ConfigureAwait(false); _inlineSchemaParser.ParseReaderNode(); _validationState = ValidatingReaderState.ParseInlineSchema; } else { _validationState = ValidatingReaderState.ClearAttributes; } } else { //Validate element //Clear previous data _atomicValue = null; _originalAtomicValueString = null; _xmlSchemaInfo.Clear(); if (_manageNamespaces) { _nsManager.PushScope(); } //Find Xsi attributes that need to be processed before validating the element string xsiSchemaLocation = null; string xsiNoNamespaceSL = null; string xsiNil = null; string xsiType = null; if (_coreReader.MoveToFirstAttribute()) { do { string objectNs = _coreReader.NamespaceURI; string objectName = _coreReader.LocalName; if (Ref.Equal(objectNs, _nsXsi)) { if (Ref.Equal(objectName, _xsiSchemaLocation)) { xsiSchemaLocation = _coreReader.Value; } else if (Ref.Equal(objectName, _xsiNoNamespaceSchemaLocation)) { xsiNoNamespaceSL = _coreReader.Value; } else if (Ref.Equal(objectName, _xsiType)) { xsiType = _coreReader.Value; } else if (Ref.Equal(objectName, _xsiNil)) { xsiNil = _coreReader.Value; } } if (_manageNamespaces && Ref.Equal(_coreReader.NamespaceURI, _nsXmlNs)) { _nsManager.AddNamespace(_coreReader.Prefix.Length == 0 ? string.Empty : _coreReader.LocalName, _coreReader.Value); } } while (_coreReader.MoveToNextAttribute()); _coreReader.MoveToElement(); } _validator.ValidateElement(_coreReader.LocalName, _coreReader.NamespaceURI, _xmlSchemaInfo, xsiType, xsiNil, xsiSchemaLocation, xsiNoNamespaceSL); ValidateAttributes(); _validator.ValidateEndOfAttributes(_xmlSchemaInfo); if (_coreReader.IsEmptyElement) { await ProcessEndElementEventAsync().ConfigureAwait(false); } _validationState = ValidatingReaderState.ClearAttributes; } } private async Task ProcessEndElementEventAsync() { _atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo); _originalAtomicValueString = GetOriginalAtomicValueStringOfElement(); if (_xmlSchemaInfo.IsDefault) { //The atomicValue returned is a default value Debug.Assert(_atomicValue != null); int depth = _coreReader.Depth; _coreReader = GetCachingReader(); _cachingReader.RecordTextNode(_xmlSchemaInfo.XmlType.ValueConverter.ToString(_atomicValue), _originalAtomicValueString, depth + 1, 0, 0); _cachingReader.RecordEndElementNode(); await _cachingReader.SetToReplayModeAsync().ConfigureAwait(false); _replayCache = true; } else if (_manageNamespaces) { _nsManager.PopScope(); } } private async Task ProcessInlineSchemaAsync() { Debug.Assert(_inlineSchemaParser != null); if (await _coreReader.ReadAsync().ConfigureAwait(false)) { if (_coreReader.NodeType == XmlNodeType.Element) { _attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount; } else { //Clear attributes info if nodeType is not element ClearAttributesInfo(); } if (!_inlineSchemaParser.ParseReaderNode()) { _inlineSchemaParser.FinishParsing(); XmlSchema schema = _inlineSchemaParser.XmlSchema; _validator.AddSchema(schema); _inlineSchemaParser = null; _validationState = ValidatingReaderState.Read; } } } private Task<object> InternalReadContentAsObjectAsync() { return InternalReadContentAsObjectAsync(false); } private async Task<object> InternalReadContentAsObjectAsync(bool unwrapTypedValue) { var tuple_11 = await InternalReadContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false); return tuple_11.Item2; } private async Task<Tuple<string, object>> InternalReadContentAsObjectTupleAsync(bool unwrapTypedValue) { Tuple<string, object> tuple; string originalStringValue; XmlNodeType nodeType = this.NodeType; if (nodeType == XmlNodeType.Attribute) { originalStringValue = this.Value; if (_attributePSVI != null && _attributePSVI.typedAttributeValue != null) { if (_validationState == ValidatingReaderState.OnDefaultAttribute) { XmlSchemaAttribute schemaAttr = _attributePSVI.attributeSchemaInfo.SchemaAttribute; originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue; } tuple = new Tuple<string, object>(originalStringValue, ReturnBoxedValue(_attributePSVI.typedAttributeValue, AttributeSchemaInfo.XmlType, unwrapTypedValue)); return tuple; } else { //return string value tuple = new Tuple<string, object>(originalStringValue, this.Value); return tuple; } } else if (nodeType == XmlNodeType.EndElement) { if (_atomicValue != null) { originalStringValue = _originalAtomicValueString; tuple = new Tuple<string, object>(originalStringValue, _atomicValue); return tuple; } else { originalStringValue = string.Empty; tuple = new Tuple<string, object>(originalStringValue, string.Empty); return tuple; } } else { //Positioned on text, CDATA, PI, Comment etc if (_validator.CurrentContentType == XmlSchemaContentType.TextOnly) { //if current element is of simple type object value = ReturnBoxedValue(await ReadTillEndElementAsync().ConfigureAwait(false), _xmlSchemaInfo.XmlType, unwrapTypedValue); originalStringValue = _originalAtomicValueString; tuple = new Tuple<string, object>(originalStringValue, value); return tuple; } else { XsdCachingReader cachingReader = _coreReader as XsdCachingReader; if (cachingReader != null) { originalStringValue = cachingReader.ReadOriginalContentAsString(); } else { originalStringValue = await InternalReadContentAsStringAsync().ConfigureAwait(false); } tuple = new Tuple<string, object>(originalStringValue, originalStringValue); return tuple; } } } private Task<Tuple<XmlSchemaType, object>> InternalReadElementContentAsObjectAsync() { return InternalReadElementContentAsObjectAsync(false); } private async Task<Tuple<XmlSchemaType, object>> InternalReadElementContentAsObjectAsync(bool unwrapTypedValue) { var tuple_13 = await InternalReadElementContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false); return new Tuple<XmlSchemaType, object>(tuple_13.Item1, tuple_13.Item3); } private async Task<Tuple<XmlSchemaType, string, object>> InternalReadElementContentAsObjectTupleAsync(bool unwrapTypedValue) { Tuple<XmlSchemaType, string, object> tuple; XmlSchemaType xmlType; string originalString; Debug.Assert(this.NodeType == XmlNodeType.Element); object typedValue = null; xmlType = null; //If its an empty element, can have default/fixed value if (this.IsEmptyElement) { if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly) { typedValue = ReturnBoxedValue(_atomicValue, _xmlSchemaInfo.XmlType, unwrapTypedValue); } else { typedValue = _atomicValue; } originalString = _originalAtomicValueString; xmlType = ElementXmlType; //Set this for default values await this.ReadAsync().ConfigureAwait(false); tuple = new Tuple<XmlSchemaType, string, object>(xmlType, originalString, typedValue); return tuple; } // move to content and read typed value await this.ReadAsync().ConfigureAwait(false); if (this.NodeType == XmlNodeType.EndElement) { //If IsDefault is true, the next node will be EndElement if (_xmlSchemaInfo.IsDefault) { if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly) { typedValue = ReturnBoxedValue(_atomicValue, _xmlSchemaInfo.XmlType, unwrapTypedValue); } else { //anyType has default value typedValue = _atomicValue; } originalString = _originalAtomicValueString; } else { //Empty content typedValue = string.Empty; originalString = string.Empty; } } else if (this.NodeType == XmlNodeType.Element) { //the first child is again element node throw new XmlException(ResXml.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo); } else { var tuple_14 = await InternalReadContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false); originalString = tuple_14.Item1; typedValue = tuple_14.Item2; // ReadElementContentAsXXX cannot be called on mixed content, if positioned on node other than EndElement, Error if (this.NodeType != XmlNodeType.EndElement) { throw new XmlException(ResXml.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo); } } xmlType = ElementXmlType; //Set this as we are moving ahead to the next node // move to next node await this.ReadAsync().ConfigureAwait(false); tuple = new Tuple<XmlSchemaType, string, object>(xmlType, originalString, typedValue); return tuple; } private async Task<object> ReadTillEndElementAsync() { if (_atomicValue == null) { while (await _coreReader.ReadAsync().ConfigureAwait(false)) { if (_replayCache) { //If replaying nodes in the cache, they have already been validated continue; } switch (_coreReader.NodeType) { case XmlNodeType.Element: await ProcessReaderEventAsync().ConfigureAwait(false); goto breakWhile; case XmlNodeType.Text: case XmlNodeType.CDATA: _validator.ValidateText(GetStringValue); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: _validator.ValidateWhitespace(GetStringValue); break; case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.EndElement: _atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo); _originalAtomicValueString = GetOriginalAtomicValueStringOfElement(); if (_manageNamespaces) { _nsManager.PopScope(); } goto breakWhile; } continue; breakWhile: break; } } else { //atomicValue != null, meaning already read ahead - Switch reader if (_atomicValue == this) { //switch back invalid marker; dont need it since coreReader moved to endElement _atomicValue = null; } SwitchReader(); } return _atomicValue; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using 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.ArtifactRegistry.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedArtifactRegistryClientTest { [xunit::FactAttribute] public void GetRepositoryRequestObject() { moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict); GetRepositoryRequest request = new GetRepositoryRequest { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), }; Repository expectedResponse = new Repository { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), Format = Repository.Types.Format.Yum, Description = "description2cf9da67", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", }; mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null); Repository response = client.GetRepository(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRepositoryRequestObjectAsync() { moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict); GetRepositoryRequest request = new GetRepositoryRequest { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), }; Repository expectedResponse = new Repository { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), Format = Repository.Types.Format.Yum, Description = "description2cf9da67", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", }; mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null); Repository responseCallSettings = await client.GetRepositoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Repository responseCancellationToken = await client.GetRepositoryAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRepository() { moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict); GetRepositoryRequest request = new GetRepositoryRequest { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), }; Repository expectedResponse = new Repository { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), Format = Repository.Types.Format.Yum, Description = "description2cf9da67", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", }; mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null); Repository response = client.GetRepository(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRepositoryAsync() { moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict); GetRepositoryRequest request = new GetRepositoryRequest { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), }; Repository expectedResponse = new Repository { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), Format = Repository.Types.Format.Yum, Description = "description2cf9da67", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", }; mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null); Repository responseCallSettings = await client.GetRepositoryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Repository responseCancellationToken = await client.GetRepositoryAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRepositoryResourceNames() { moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict); GetRepositoryRequest request = new GetRepositoryRequest { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), }; Repository expectedResponse = new Repository { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), Format = Repository.Types.Format.Yum, Description = "description2cf9da67", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", }; mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null); Repository response = client.GetRepository(request.RepositoryName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRepositoryResourceNamesAsync() { moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict); GetRepositoryRequest request = new GetRepositoryRequest { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), }; Repository expectedResponse = new Repository { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), Format = Repository.Types.Format.Yum, Description = "description2cf9da67", Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", }; mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null); Repository responseCallSettings = await client.GetRepositoryAsync(request.RepositoryName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Repository responseCancellationToken = await client.GetRepositoryAsync(request.RepositoryName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.IO; using System.Windows.Forms; using System.Drawing; using System.Collections; using System.Xml; using Microsoft.DirectX; using D3D = Microsoft.DirectX.Direct3D; using Voyage.Terraingine.DataCore; namespace Voyage.Terraingine.ImportTerrainProject { /// <summary> /// Driver class for the ImportTerrainProject plug-in. /// </summary> public class Driver : PlugIn { #region Data Members private OpenFileDialog _dlgOpen; private XmlDocument _xmlDoc; private string _projectName; #endregion #region Properties /// <summary> /// Gets the name of the project imported. /// </summary> public string ProjectName { get { return _projectName; } } #endregion #region Basic Plug-In Methods /// <summary> /// Creates the Driver class. /// </summary> public Driver() { base.InitializeBase(); _name = "Import Terrain Project"; this.CenterToParent(); _xmlDoc = null; _projectName = null; _dlgOpen = new OpenFileDialog(); _dlgOpen.Filter = "XML Files (*.xml)|*.xml|All files (*.*)|*.*" ; _dlgOpen.InitialDirectory = Path.GetDirectoryName( Application.ExecutablePath ) + "\\Projects"; } /// <summary> /// Runs the plug-in. /// </summary> public override void Run() { DialogResult result = _dlgOpen.ShowDialog( _owner ); if ( result == DialogResult.OK && _dlgOpen.FileName != null ) { _xmlDoc = new XmlDocument(); LoadXML(); _success = true; } } /// <summary> /// Runs the plug-in as an automatic function. /// </summary> /// <param name="objects">Additional data sent to the plug-in.</param> public override void AutoRun( ArrayList objects ) { _dlgOpen.FileName = objects[0].ToString(); _xmlDoc = new XmlDocument(); LoadXML(); _success = true; } #endregion #region XML Handling /// <summary> /// Loads XML data from the chosen file in the OpenFileDialog. /// </summary> private void LoadXML() { if ( _dlgOpen.FileName != null ) { try { XmlNodeList xmlNodes; StreamReader reader = new StreamReader( _dlgOpen.FileName ); _xmlDoc.Load( reader.BaseStream ); xmlNodes = _xmlDoc.GetElementsByTagName( "TerrainPage" ); // Load the TerrainPage(s) _page = new TerrainPage(); LoadTerrainPage( xmlNodes.Item( 0 ) ); reader.Close(); } catch ( Exception e ) { string message = "The XML file is not properly formed!\n\n"; message += "Source: " + e.Source + "\n"; message += "Error: " + e.Message; MessageBox.Show( null, message, "Error Running Application", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } } /// <summary> /// Loads data about the TerrainPage from the XML document. /// </summary> /// <param name="xmlNode">The XML node to load data from.</param> private void LoadTerrainPage( XmlNode xmlNode ) { XmlNode xmlData = xmlNode.FirstChild; // Load the TerrainPage name _page.Name = LoadTextNode( xmlData ); // Load the TerrainPage position xmlData = xmlData.NextSibling; _page.Position = LoadVector3Node( xmlData ); // Load the TerrainPage rotation xmlData = xmlData.NextSibling; _page.Rotation = LoadQuaternionNode( xmlData ); // Load the TerrainPage scale xmlData = xmlData.NextSibling; _page.Scale = LoadVector3Node( xmlData ); // Load the maximum vertex height for the TerrainPage xmlData = xmlData.NextSibling; _page.MaximumVertexHeight = Convert.ToSingle( LoadTextNode( xmlData ) ); // Load the TerrainPatch data from the XML file xmlData = xmlData.NextSibling; LoadTerrainPatch( xmlData ); } /// <summary> /// Loads data about the TerrainPatch from the XML document. /// </summary> /// <param name="xmlNode">The XML node to load data from.</param> private void LoadTerrainPatch( XmlNode xmlNode ) { XmlNode xmlData = xmlNode.FirstChild; int rows, columns; float height, width; XmlNodeList xmlList; // Load the number of TerrainPatch rows rows = Convert.ToInt32( LoadTextNode( xmlData ) ); // Load the number of TerrainPatch columns xmlData = xmlData.NextSibling; columns = Convert.ToInt32( LoadTextNode( xmlData ) ); // Load the TerrainPatch height xmlData = xmlData.NextSibling; height = Convert.ToSingle( LoadTextNode( xmlData ) ); // Load the TerrainPatch width xmlData = xmlData.NextSibling; width = Convert.ToSingle( LoadTextNode( xmlData ) ); // Create the TerrainPatch _page.TerrainPatch.CreatePatch( rows, columns, height, width ); // Load the TerrainPatch textures xmlList = _xmlDoc.GetElementsByTagName( "Texture" ); _textures.Clear(); for ( int i = 0; i < xmlList.Count; i++ ) LoadTexture( xmlList.Item( i ) ); // Load the TerrainPatch vertices xmlList = _xmlDoc.GetElementsByTagName( "Vertex" ); for ( int i = 0; i < xmlList.Count; i++ ) LoadVertex( xmlList.Item( i ), i ); } /// <summary> /// Loads data about a texture from the XML document. /// </summary> /// <param name="xmlNode">The XML node to load data from.</param> private void LoadTexture( XmlNode xmlNode ) { DataCore.Texture tex = new Texture(); // Load the texture name xmlNode = xmlNode.FirstChild; tex.Name = xmlNode.InnerText; // Load the texture filename xmlNode = xmlNode.NextSibling; tex.FileName = xmlNode.InnerText; // Load the texture operation xmlNode = xmlNode.NextSibling; tex.OperationText = xmlNode.InnerText; // Load if the texture is a mask xmlNode = xmlNode.NextSibling; tex.Mask = Convert.ToBoolean( xmlNode.InnerText ); // Load the texture scale value xmlNode = xmlNode.NextSibling; tex.Scale = LoadVector2Node( xmlNode ); // Load the texture shift value xmlNode = xmlNode.NextSibling; tex.Shift = LoadVector2Node( xmlNode ); _textures.Add( tex ); _page.TerrainPatch.AddBlankTexture(); _modifiedTextures = true; } /// <summary> /// Loads data about a vertex from the XML document. /// </summary> /// <param name="xmlNode">The XML node to load data from.</param> /// <param name="index">The index of the vertex to load.</param> private void LoadVertex( XmlNode xmlNode, int index ) { D3D.CustomVertex.PositionNormal vert = _page.TerrainPatch.Vertices[index]; Vector2 texCoord; int texCount; // Load the vertex position xmlNode = xmlNode.FirstChild; vert.Position = LoadVector3Node( xmlNode ); // Load the vertex normal xmlNode = xmlNode.NextSibling; vert.Normal = LoadVector3Node( xmlNode ); if ( xmlNode.NextSibling != null ) { xmlNode = xmlNode.NextSibling.FirstChild; if ( xmlNode != null ) { texCount = 0; do { texCoord = LoadVector2Node( xmlNode ); ( (Vector2[]) _page.TerrainPatch.TextureCoordinates[texCount] )[index] = texCoord; xmlNode = xmlNode.NextSibling; texCount++; } while ( xmlNode != null ); } } _page.TerrainPatch.Vertices[index] = vert; } #endregion #region Element Retrieval /// <summary> /// Loads text data from an XmlNode. /// </summary> /// <param name="xmlElem">The XmlNode from which to load data.</param> /// <returns>The text data contained in the XmlNode.</returns> private string LoadTextNode( XmlNode xmlElem ) { // Load the XML data return xmlElem.InnerText; } /// <summary> /// Loads Vector2 data from an XmlNode. /// </summary> /// <param name="xmlElem">The XmlNode from which to load data.</param> /// <returns>The Vector2 data contained in the XmlNode.</returns> private Vector2 LoadVector2Node( XmlNode xmlElem ) { // Load the XML data Vector2 result = new Vector2(); // X-element result.X = Convert.ToSingle( xmlElem.FirstChild.InnerText ); // Y-element result.Y = Convert.ToSingle( xmlElem.FirstChild.NextSibling.InnerText ); return result; } /// <summary> /// Loads Vector3 data from an XmlNode. /// </summary> /// <param name="xmlElem">The XmlNode from which to load data.</param> /// <returns>The Vector3 data contained in the XmlNode.</returns> private Vector3 LoadVector3Node( XmlNode xmlElem ) { // Load the XML data Vector3 result = new Vector3(); // X-element result.X = Convert.ToSingle( xmlElem.FirstChild.InnerText ); // Y-element result.Y = Convert.ToSingle( xmlElem.FirstChild.NextSibling.InnerText ); // Z-element result.Z = Convert.ToSingle( xmlElem.FirstChild.NextSibling.NextSibling.InnerText ); return result; } /// <summary> /// Loads Quaternion data from an XmlNode. /// </summary> /// <param name="xmlElem">The XmlNode from which to load data.</param> /// <returns>The Quaternion data contained in the XmlNode.</returns> private Quaternion LoadQuaternionNode( XmlNode xmlElem ) { // Load the XML data Quaternion result = new Quaternion();; // X-element result.X = Convert.ToSingle( xmlElem.FirstChild.InnerText ); // Y-element result.Y = Convert.ToSingle( xmlElem.FirstChild.NextSibling.InnerText ); // Z-element result.Z = Convert.ToSingle( xmlElem.FirstChild.NextSibling.NextSibling.InnerText ); // W-element result.W = Convert.ToSingle( xmlElem.FirstChild.NextSibling.NextSibling.NextSibling.InnerText ); return result; } #endregion } }
// ----- // GNU General Public License // The Forex Professional Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. // The Forex Professional Analyzer 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 Lesser General Public License for more details. // ----- using System; using System.Collections.Generic; using System.Text; namespace fxpa { [CustomName("Trading Order")] public class Order { public enum ResultModeEnum { Currency, Raw, // Pips do not consider volume. Pips, } AnalyzerSession _session; protected IDataProvider DataProvider { get { lock (this) { if (_session != null) { return _session.DataProvider; } } return null; } } public IOrderExecutionProvider OrderExecutionProvider { get { lock (this) { if (_session != null) { return _session.OrderExecutionProvider; } } return null; } } public bool IsInitialized { get { return _session != null; } } OrderId _id; public OrderId Id { get { lock (this) { return _id; } } } volatile OrderTypeEnum _type; public OrderTypeEnum Type { get { return _type; } } double _currentVolume = 0; public double CurrentVolume { get { lock (this) { return _currentVolume; } } } double _initialVolume = 0; public double InitialVolume { get { lock (this) { return _initialVolume; } } } /// <summary> /// Result stored in absolute units, it does not consider lot size. /// So when exported or imported from class this is considered. /// </summary> double _currentResult = 0; double _totalResult = 0; public double InitialDirectionalVolume { get { if (IsBuy) { return InitialVolume; } else { return -InitialVolume; } } } public bool IsBuy { get { return _type == OrderTypeEnum.OP_BUY || _type == OrderTypeEnum.OP_BUYLIMIT || _type == OrderTypeEnum.OP_BUYSTOP; } } volatile bool _isOpen = false; public bool IsOpen { get { return _isOpen; } } double _openPrice = double.NaN; public double OpenPrice { get { lock(this) { return _openPrice; } } } double _closePrice = double.NaN; public double ClosePrice { get { lock (this) { return _closePrice; } } } double _orderMaximumResultAchieved = 0; public double OrderMaximumResultAchieved { get { lock (this) { return _orderMaximumResultAchieved; } } } double _defaultExecutionSlippage = 9999; public double DefaultExecutionSlippage { get { lock (this) { return _defaultExecutionSlippage; } } set { lock (this) { _defaultExecutionSlippage = value; } } } string _defaultComment = ""; public string DefaultComment { get { return _defaultComment; } set { _defaultComment = value; } } DateTime _sourceOpenTime = DateTime.MinValue; public DateTime SourceOpenTime { get { return _sourceOpenTime; } } DateTime _sourceCloseTime = DateTime.MinValue; public DateTime SourceCloseTime { get { return _sourceCloseTime; } } double _sourceStopLoss = double.NaN; public double SourceStopLoss { get { return _sourceStopLoss; } } double _sourceTakeProfit = double.NaN; public double SourceTakeProfit { get { return _sourceTakeProfit; } } DateTime _localOpenTime = DateTime.MinValue; public DateTime LocalOpenTime { get { return _localOpenTime; } } public delegate void OrderUpdatedDelegate(Order order); public event OrderUpdatedDelegate OrderUpdatedEvent; /// <summary> /// /// </summary> public Order() { _id = new OrderId(Guid.NewGuid()); } public bool Initialize(AnalyzerSession session) { if (this.IsInitialized) { return (_session == session); } lock (this) { _session = session; _session.DataProvider.ValuesUpdateEvent += new ValuesUpdatedDelegate(DataProviderSession_OnValuesUpdateEvent); } return true; } public void UnInitialize() { lock (this) { if (_session != null && _session.DataProvider != null) { _session.DataProvider.ValuesUpdateEvent -= new ValuesUpdatedDelegate(DataProviderSession_OnValuesUpdateEvent); } _session = null; } } protected virtual void DataProviderSession_OnValuesUpdateEvent(IDataProvider dataProvider, UpdateType updateType, int updateItemsCount, int stepsRemaining) { lock (this) { if (_session == null || _session.DataProvider == null || _session.OrderExecutionProvider == null || IsOpen == false) { return; } //UpdateResult(); } // lock } //void UpdateResult() //{ //} /// <summary> /// Will create the corresponding order, based to the passed in order information. /// Used to create corresponding orders to ones already existing in the platform. /// </summary> public virtual bool AdoptExistingOrderInformation(OrderInformation information) { _id.ExecutionPlatformId = information.OrderPlatformId; _type = information.OrderType; _currentResult = information.CurrentProfit / _session.SessionInfo.LotSize; if (information.IsOpen == false) { _totalResult = _currentResult; } _currentVolume = information.Volume; _initialVolume = 1; _isOpen = information.IsOpen; _openPrice = information.OpenPrice; _orderMaximumResultAchieved = _currentResult; _sourceOpenTime = information.SourceOpenTime; _sourceCloseTime = information.SourceCloseTime; _sourceStopLoss = information.OrderStopLoss; _sourceTakeProfit = information.OrderTakeProfit; _localOpenTime = DateTime.Now; return true; } /// <summary> /// Calculate order result. /// </summary> public double GetResult(ResultModeEnum mode) { lock (this) { if (this.IsOpen) { // Update result. //_currentResult = // GetRawResultAtPrice(_session.DataProvider.Ask, // _session.DataProvider.Bid, mode != ResultModeEnum.Pips); //_orderMaximumResultAchieved = Math.Max(_orderMaximumResultAchieved, _currentResult); } if (mode == ResultModeEnum.Pips) { return _currentResult * Math.Pow(10, _session.SessionInfo.PointDigits); } if (mode == ResultModeEnum.Raw) { return _currentResult; } else if (mode == ResultModeEnum.Currency) { //return _session.OrderExecutionProvider.Account.CompensateLotSize(_currentResult * _session.SessionInfo.LotSize); } //SystemMonitor.Throw("Unhandled mode."); return 0; } } #region User Operations /// <summary> /// Will use current platform prices for the operation. /// </summary> public virtual bool Open(OrderTypeEnum orderType, double volume) { double price = DataProvider.Ask; // Buy if (orderType == OrderTypeEnum.OP_SELL || orderType == OrderTypeEnum.OP_SELLLIMIT || orderType == OrderTypeEnum.OP_SELLSTOP) {// Sell. price = DataProvider.Bid; } return Open(orderType, volume, this.DefaultExecutionSlippage, price, DefaultComment); } /// <summary> /// /// </summary> public virtual bool Open(OrderTypeEnum orderType, double volume, double allowedSlippage, double desiredPrice, string comment) { string message; return Open(orderType, volume, allowedSlippage, desiredPrice, 0, 0, comment, out message); } /// <summary> /// This allows more specific control over the operation. /// </summary> public virtual bool Open(OrderTypeEnum orderType, double volume, double allowedSlippage, double desiredPrice, double sourceTakeProfit, double sourceStopLoss, string comment, out string operationResultMessage) { lock (this) { //SystemMonitor.CheckThrow(volume > 0, "Misuse of the Order class."); //SystemMonitor.CheckThrow(IsOpen == false, "Misuse of the Order class [Must not open trade, that has already been open]."); double openingPrice; DateTime sourceOpenTime; if (_session.OrderExecutionProvider.OpenOrder(this, orderType, volume, allowedSlippage, desiredPrice, sourceTakeProfit, sourceStopLoss, comment, out openingPrice, out sourceOpenTime, out operationResultMessage) == false) { //SystemMonitor.Report("Order was not executed [" + operationResultMessage + "]."); return false; } _type = orderType; _initialVolume = volume; _currentVolume = volume; _sourceStopLoss = sourceStopLoss; _sourceTakeProfit = sourceTakeProfit; _isOpen = true; _openPrice = openingPrice; _sourceOpenTime = sourceOpenTime; _localOpenTime = DateTime.Now; } if (OrderUpdatedEvent != null) { OrderUpdatedEvent(this); } return true; } /// <summary> /// Uses default slippage and current price to perform the operation. /// </summary> public bool DecreaseVolume(double volumeDecreasal, int slippage, out string operationResultMessage) { if (IsBuy) {// Buy. return DecreaseVolume(volumeDecreasal, slippage, DataProvider.Bid, out operationResultMessage); } else {// Sell. return DecreaseVolume(volumeDecreasal, slippage, DataProvider.Ask, out operationResultMessage); } } /// <summary> /// Uses default slippage and current price to perform the operation. /// </summary> public bool DecreaseVolume(double volumeDecreasal, out string operationResultMessage) { if (IsBuy) {// Buy. return DecreaseVolume(volumeDecreasal, this.DefaultExecutionSlippage, DataProvider.Bid, out operationResultMessage); } else {// Sell. return DecreaseVolume(volumeDecreasal, this.DefaultExecutionSlippage, DataProvider.Ask, out operationResultMessage); } } /// <summary> /// This allows a part of the order to be closed, or all. /// </summary> public bool DecreaseVolume(double volumeDecreasal, double allowedSlippage, double desiredPrice) { string message; return DecreaseVolume(volumeDecreasal, allowedSlippage, desiredPrice, out message); } /// <summary> /// This allows a part of the order to be closed, or all. /// </summary> public bool DecreaseVolume(double volumeDecreasal, double allowedSlippage, double desiredPrice, out string operationResultMessage) { //SystemMonitor.CheckThrow(volumeDecreasal >= 0 && volumeDecreasal <= CurrentVolume && IsOpen != false, "Misuse of the Order class [Can not close more volume than already open]."); double decreasalPrice; bool operationResult = false; if (volumeDecreasal == _currentVolume) { operationResult = _session.OrderExecutionProvider.CloseOrder(this, allowedSlippage, desiredPrice, out decreasalPrice, out _sourceCloseTime, out operationResultMessage); } else { operationResult = _session.OrderExecutionProvider.DecreaseOrderVolume(this, volumeDecreasal, allowedSlippage, desiredPrice, out decreasalPrice, out operationResultMessage); } if (operationResult == false) { //SystemMonitor.Report("Order decrease volume has failed."); return false; } // How much of the volume we shall close here and now. double priceDifference = decreasalPrice - this.OpenPrice; if (IsBuy == false) { priceDifference = -priceDifference; } lock (this) { // Finally apply the operation to the internal data, also round result to 6 fractional digits. _totalResult += Math.Round(volumeDecreasal * priceDifference, 6); _currentVolume -= volumeDecreasal; if (_currentVolume == 0) { _isOpen = false; _closePrice = decreasalPrice; _currentResult = _totalResult; } } if (OrderUpdatedEvent != null) { OrderUpdatedEvent(this); } return true; } /// <summary> /// Will close using the current price as reference and default slippage as maximum allowed slippage. /// </summary> public bool Close() { if (IsBuy) { return Close(this.DefaultExecutionSlippage, DataProvider.Bid); } else { return Close(this.DefaultExecutionSlippage, DataProvider.Ask); } } /// <summary> /// /// </summary> public bool Close(double allowedSlippage, double desiredPrice) { return DecreaseVolume(CurrentVolume, allowedSlippage, desiredPrice); } /// <summary> /// </summary> public bool Close(out string operationResultMessage) { return DecreaseVolume(CurrentVolume, out operationResultMessage); } /// <summary> /// Use to see how order is performing at current stage, considerVolume == false to see absolute values. /// This will consider accumulated results so far only if considerVolume is true. /// ConsiderVolume is to signify should the calculation observe order volume at all. /// autoLotSizeCompensation - since lot sizes seem to change, this compensates with a starting point of 100,000 /// (for ex. the GBPJPY with value 141.000 the lot is size reduced 100 times) /// </summary> //protected double GetRawResultAtPrice(double ask, double bid, bool considerVolume) //{ // if (IsOpen == false || _session == null || _session.OrderExecutionProvider == null // || _session.OrderExecutionProvider.Account == null || _session.OrderExecutionProvider.Account.OperationalState != OperationalStateEnum.Operational) // { // return 0; // } // double difference = 0; // if (IsBuy) // { // difference = bid - OpenPrice; // } // else // { // difference = OpenPrice - ask; // } // if (considerVolume) // { // return Math.Round(_totalResult + CurrentVolume * difference, 10); // } // else // { // return Math.Round(difference, 10); // } //} #endregion } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Adxstudio.Xrm.Resources; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Client.Messages; using Microsoft.Xrm.Portal; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Query; namespace Adxstudio.Xrm.Commerce { public class CommerceOrder { private OrganizationServiceContext _context; public Entity Entity { get; private set; } public Entity InvoiceEntity { get; private set; } public Guid Id { get; private set; } public CommerceOrder(Entity order, OrganizationServiceContext context) { if (order == null) { throw new ArgumentNullException("order"); } if (order.LogicalName != "salesorder") { throw new ArgumentException(string.Format("Value must have logical name {0}.", order.LogicalName), "order"); } Entity = order; Id = order.Id; _context = context; } public CommerceOrder(Dictionary<string, string> values, IPortalContext xrm, string paymentProvider, bool getCreateInvoiceSettingValue, Entity account = null, string tombstoneEntityLogicalName = null, string tombstoneEntityPrimaryKeyName = null) { if (paymentProvider == "PayPal") { System.Diagnostics.Debug.Write("we are creating the order and have determined we are using paypal..."); CreateOrderPayPal(values, xrm, getCreateInvoiceSettingValue); } else if (paymentProvider == "Authorize.Net" || paymentProvider == "Demo") { CreateOrderAuthorizeNet(values, xrm, getCreateInvoiceSettingValue, account, tombstoneEntityLogicalName, tombstoneEntityPrimaryKeyName); } } public T GetAttributeValue<T>(string attributeName) { return Entity.GetAttributeValue<T>(attributeName); } private void CreateOrderPayPal(Dictionary<string, string> values, IPortalContext xrm, bool getCreateInvoiceSettingValue) { System.Diagnostics.Debug.Write("A commerce order is being created..."); _context = xrm.ServiceContext; if (!values.ContainsKey("invoice")) { throw new Exception("no invoice found"); } var shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault( q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"])); var order = new Entity("salesorder"); var orderGuid = Guid.NewGuid(); order.Attributes["salesorderid"] = orderGuid; order.Id = orderGuid; order.Attributes["name"] = "order created by: " + shoppingCart.GetAttributeValue<string>("adx_name"); order.Attributes["adx_shoppingcartid"] = shoppingCart.ToEntityReference(); System.Diagnostics.Debug.Write(string.Format("shopping cart ID:{0}", shoppingCart.Id.ToString())); var supportRequest = _context.CreateQuery("adx_supportrequest") .FirstOrDefault(sr => sr.GetAttributeValue<EntityReference>("adx_shoppingcartid").Id == shoppingCart.Id); if (supportRequest != null) { System.Diagnostics.Debug.Write(string.Format("Support Request ID:{0}", supportRequest.Id.ToString())); var supportPlanReference = supportRequest.GetAttributeValue<EntityReference>("adx_supportplan"); System.Diagnostics.Debug.Write(string.Format("Support Reference:{0}", supportPlanReference)); var supportPlan = _context.CreateQuery("adx_supportplan").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_supportplanid") == supportPlanReference.Id); order.Attributes["adx_supportplanid"] = supportPlan.ToEntityReference(); } else { System.Diagnostics.Debug.Write("support request is null"); } //Ensure that there is a customer var customer = GetOrderCustomer(values, _context, shoppingCart); if (!_context.IsAttached(shoppingCart)) { _context.Attach(shoppingCart); } shoppingCart.Attributes["adx_contactid"] = customer.ToEntityReference(); var parentCustomer = customer.GetAttributeValue<EntityReference>("parentcustomerid"); var parentCustomerEntity = _context.CreateQuery("account").FirstOrDefault(pce => pce.GetAttributeValue<Guid>("accountid") == parentCustomer.Id); order.Attributes["customerid"] = (parentCustomerEntity != null) ? parentCustomerEntity.ToEntityReference() : customer.ToEntityReference(); var priceLevel = _context.CreateQuery("pricelevel").FirstOrDefault(pl => pl.GetAttributeValue<string>("name") == "Web"); if (priceLevel == null) { throw new Exception("price level null"); } //Set the price level var priceLevelReference = priceLevel.ToEntityReference(); order.Attributes["pricelevelid"] = priceLevelReference; //Set the address for the order SetOrderAddresses(values, order, customer); //order.Attributes["adx_confirmationnumber"] = shoppingCart.GetAttributeValue<string>("adx_confirmationnumber"); order.Attributes["adx_receiptnumber"] = values.ContainsKey("ipn_trac_id") ? values["ipn_track_id"] : null; _context.AddObject(order); _context.UpdateObject(shoppingCart); _context.SaveChanges(); //Set the products of the order SetOrderProducts(shoppingCart, _context, orderGuid, null); //Time to associate order with support plan //sw.WriteLine("ok, we are at the weird part!"); //Deactivate the shopping Cart shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault( q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"])); try { _context.SetState(1, 2, shoppingCart); _context.SaveChanges(); } catch { //Unlikely that there is an issue, most likely it has already been deactiveated. } //At this point we want to Create an Invoice, if that is indeed what we are doing. if (getCreateInvoiceSettingValue) { InvoiceEntity = CreateInvoiceFromOrder(_context, orderGuid); } Entity = _context.CreateQuery("salesorder").FirstOrDefault(o => o.GetAttributeValue<Guid>("salesorderid") == orderGuid); Id = Entity.Id; } private void CreateOrderAuthorizeNet(Dictionary<string, string> values, IPortalContext xrm, bool getCreateInvoiceSettingValue, Entity account = null, string tombstoneEntityLogicalName = null, string tombstoneEntityPrimaryKeyName = null) { _context = xrm.ServiceContext; if (!values.ContainsKey("order_id")) { throw new Exception("no order_id found"); } var orderId = values["order_id"]; string[] guids = orderId.Split('&'); var tombstoneEntityId = new Guid(guids[0]); Entity tombstoneEntity = null; Entity shoppingCart = null; Entity supportPlan = null; if (tombstoneEntityLogicalName != null) { tombstoneEntity = _context.CreateQuery(tombstoneEntityLogicalName) .FirstOrDefault(sr => sr.GetAttributeValue<Guid>(tombstoneEntityPrimaryKeyName) == tombstoneEntityId); shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_shoppingcartid") == tombstoneEntity.GetAttributeValue<EntityReference>("adx_shoppingcartid").Id); } else { shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_shoppingcartid") == tombstoneEntityId); } if (tombstoneEntityLogicalName == "adx_supportrequest") { supportPlan = _context.CreateQuery("adx_supportplan").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_supportplanid") == tombstoneEntity.GetAttributeValue<EntityReference>("adx_supportplan").Id); } var orderGuid = Guid.NewGuid(); var order = new Entity("salesorder") { Id = orderGuid }; order.Attributes["salesorderid"] = orderGuid; order.Id = orderGuid; order.Attributes["name"] = "order created by: " + shoppingCart.GetAttributeValue<string>("adx_name"); order.Attributes["adx_shoppingcartid"] = shoppingCart.ToEntityReference(); if (tombstoneEntityLogicalName == "adx_supportrequest") { order.Attributes["adx_supportplanid"] = supportPlan.ToEntityReference(); } //Ensure that there is a customer var customer = GetOrderCustomer(values, _context, shoppingCart); if (!_context.IsAttached(shoppingCart)) { _context.Attach(shoppingCart); } shoppingCart.Attributes["adx_contactid"] = customer.ToEntityReference(); if (account == null) { var parentCustomer = customer.GetAttributeValue<EntityReference>("parentcustomerid"); Entity parentCustomerEntity = null; if (parentCustomer != null) { parentCustomerEntity = _context.CreateQuery("account").FirstOrDefault(pce => pce.GetAttributeValue<Guid>("accountid") == parentCustomer.Id); } order.Attributes["customerid"] = (parentCustomerEntity != null) ? parentCustomerEntity.ToEntityReference() : customer.ToEntityReference(); } else { order.Attributes["customerid"] = account.ToEntityReference(); } var priceLevel = _context.CreateQuery("pricelevel").FirstOrDefault(pl => pl.GetAttributeValue<string>("name") == "Web"); if (priceLevel == null) { throw new Exception("price level null"); } //Set the price level var priceLevelReference = priceLevel.ToEntityReference(); order.Attributes["pricelevelid"] = priceLevelReference; //Set the address for the order SetOrderAddresses(values, order, customer); //order.Attributes["adx_confirmationnumber"] = shoppingCart.GetAttributeValue<string>("adx_confirmationnumber"); order.Attributes["adx_receiptnumber"] = values.ContainsKey("x_trans_id") ? values["x_trans_id"] : null; //Set the tax //order.Attributes["totaltax"] = values.ContainsKey("x_tax") ? new Money(decimal.Parse(values["x_tax"])) : null; var tax = values.ContainsKey("x_tax") ? new Money(decimal.Parse(values["x_tax"])) : null; _context.AddObject(order); _context.UpdateObject(shoppingCart); _context.SaveChanges(); //Set the products of the order SetOrderProducts(shoppingCart, _context, orderGuid, tax); tombstoneEntity = _context.CreateQuery(tombstoneEntityLogicalName) .FirstOrDefault(sr => sr.GetAttributeValue<Guid>(tombstoneEntityPrimaryKeyName) == tombstoneEntityId); shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_shoppingcartid") == tombstoneEntity.GetAttributeValue<EntityReference>("adx_shoppingcartid").Id); //Deactivate the shopping Cart try { _context.SetState(1, 2, shoppingCart); _context.SaveChanges(); } catch { //Unlikely that there is an issue, most likely it has already been deactiveated. } //At this point we want to Create an Invoice, if that is indeed what we are doing. if (getCreateInvoiceSettingValue) { InvoiceEntity = CreateInvoiceFromOrder(_context, orderGuid); } Entity = _context.CreateQuery("salesorder").FirstOrDefault(o => o.GetAttributeValue<Guid>("salesorderid") == orderGuid); Id = Entity.Id; //writer.Close(); } private static Entity CreateInvoiceFromOrder(OrganizationServiceContext context, Guid salesOrderId) { ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); var convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = salesOrderId, ColumnSet = invoiceColumns }; var convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)context.Execute(convertOrderRequest); var invoice = convertOrderResponse.Entity; var setStateRequest = new SetStateRequest() { EntityMoniker = invoice.ToEntityReference(), State = new OptionSetValue(2), Status = new OptionSetValue(100001) }; var setStateResponse = (SetStateResponse)context.Execute(setStateRequest); invoice = context.CreateQuery("invoice").Where(i => i.GetAttributeValue<Guid>("invoiceid") == convertOrderResponse.Entity.Id).FirstOrDefault(); return invoice; } private static void SetOrderProducts(Entity shoppingCart, OrganizationServiceContext context, Guid salesOrderGuid, Money tax) { bool first = true; var cartItems = context.CreateQuery("adx_shoppingcartitem") .Where( qp => qp.GetAttributeValue<EntityReference>("adx_shoppingcartid").Id == shoppingCart.GetAttributeValue<Guid>("adx_shoppingcartid")).ToList(); foreach (var item in cartItems) { var invoiceOrder = context.CreateQuery("salesorder").FirstOrDefault(o => o.GetAttributeValue<Guid>("salesorderid") == salesOrderGuid); var orderProduct = new Entity("salesorderdetail"); var detailGuid = Guid.NewGuid(); orderProduct.Attributes["salesorderdetailid"] = detailGuid; orderProduct.Id = detailGuid; var product = context.CreateQuery("product") .FirstOrDefault( p => p.GetAttributeValue<Guid>("productid") == item.GetAttributeValue<EntityReference>("adx_productid").Id); var unit = context.CreateQuery("uom") .FirstOrDefault( uom => uom.GetAttributeValue<Guid>("uomid") == item.GetAttributeValue<EntityReference>("adx_uomid").Id) ?? context.CreateQuery("uom").FirstOrDefault(uom => uom.GetAttributeValue<Guid>("uomid") == product.GetAttributeValue<EntityReference>("defaultuomid").Id); /*var unit = context.CreateQuery("uom") .FirstOrDefault( uom => uom.GetAttributeValue<Guid>("uomid") == item.GetAttributeValue<EntityReference>("adx_uomid").Id);*/ orderProduct.Attributes["productid"] = product.ToEntityReference(); orderProduct.Attributes["uomid"] = unit.ToEntityReference(); orderProduct.Attributes["ispriceoverridden"] = true; orderProduct.Attributes["priceperunit"] = item.GetAttributeValue<Money>("adx_quotedprice"); orderProduct.Attributes["quantity"] = item.GetAttributeValue<decimal>("adx_quantity"); orderProduct.Attributes["salesorderid"] = invoiceOrder.ToEntityReference(); //We only place our tax on the first item if (first) { first = false; orderProduct.Attributes["tax"] = tax; } context.AddObject(orderProduct); //context.UpdateObject(invoiceOrder); context.SaveChanges(); var detail = context.CreateQuery("salesorderdetail").FirstOrDefault(sod => sod.GetAttributeValue<Guid>("salesorderdetailid") == detailGuid); } } private static void SetOrderAddresses(Dictionary<string, string> values, Entity order, Entity customer) { order.Attributes["billto_line1"] = customer.GetAttributeValue<string>("address1_line1"); order.Attributes["billto_city"] = customer.GetAttributeValue<string>("address1_city"); order.Attributes["billto_country"] = customer.GetAttributeValue<string>("address1_country"); order.Attributes["billto_stateorprovince"] = customer.GetAttributeValue<string>("address1_stateorprovince"); order.Attributes["billto_postalcode"] = customer.GetAttributeValue<string>("address1_postalcode"); order.Attributes["shipto_line1"] = (values.ContainsKey("address_street") ? values["address_street"] : null) ?? (values.ContainsKey("x_address") ? values["x_address"] : null) ?? (values.ContainsKey("address1") ? values["address1"] : null) ?? customer.GetAttributeValue<string>("address1_line1"); order.Attributes["shipto_city"] = (values.ContainsKey("address_city") ? values["address_city"] : null) ?? (values.ContainsKey("x_city") ? values["x_city"] : null) ?? (values.ContainsKey("city") ? values["city"] : null) ?? customer.GetAttributeValue<string>("address1_city"); order.Attributes["shipto_country"] = (values.ContainsKey("address_country") ? values["address_country"] : null) ?? (values.ContainsKey("x_country") ? values["x_country"] : null) ?? (values.ContainsKey("country") ? values["country"] : null) ?? customer.GetAttributeValue<string>("address1_country"); order.Attributes["shipto_stateorprovince"] = (values.ContainsKey("address_state") ? values["address_state"] : null) ?? (values.ContainsKey("x_state") ? values["x_state"] : null) ?? (values.ContainsKey("state") ? values["state"] : null) ?? customer.GetAttributeValue<string>("address1_stateorprovince"); order.Attributes["shipto_postalcode"] = (values.ContainsKey("address_zip") ? values["address_zip"] : null) ?? (values.ContainsKey("x_zip") ? values["x_zip"] : null) ?? (values.ContainsKey("zip") ? values["zip"] : null) ?? customer.GetAttributeValue<string>("address1_postalcode"); } private static Entity GetOrderCustomer(Dictionary<string, string> values, OrganizationServiceContext context, Entity shoppingCart) { Guid customerID; Entity customer; if (shoppingCart.GetAttributeValue<EntityReference>("adx_contactid") != null) { customerID = shoppingCart.GetAttributeValue<EntityReference>("adx_contactid").Id; } else { customerID = Guid.NewGuid(); customer = new Entity("contact") { Id = customerID }; customer.Attributes["contactid"] = customerID; customer.Id = customerID; var firstName = (values.ContainsKey("first_name") ? values["first_name"] : null) ?? "Tim"; customer.Attributes["firstname"] = firstName; customer.Attributes["lastname"] = (values.ContainsKey("last_name") ? values["last_name"] : null) ?? "Sample"; customer.Attributes["telephone1"] = (values.ContainsKey("contact_phone") ? values["contact_phone"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "555-9765" : null); customer.Attributes["address1_line1"] = (values.ContainsKey("address_street") ? values["address_street"] : null) ?? (values.ContainsKey("address1") ? values["address1"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "123 easy street" : null); customer.Attributes["address1_city"] = (values.ContainsKey("address_city") ? values["address_city"] : null) ?? (values.ContainsKey("city") ? values["city"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "Anytown" : null); customer.Attributes["address1_country"] = (values.ContainsKey("address_country") ? values["address_country"] : null) ?? (values.ContainsKey("country") ? values["country"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "USA" : null); customer.Attributes["address1_stateorprovince"] = (values.ContainsKey("address_state") ? values["address_state"] : null) ?? (values.ContainsKey("state") ? values["state"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "NY" : null); customer.Attributes["address1_postalcode"] = (values.ContainsKey("address_zip") ? values["address_zip"] : null) ?? (values.ContainsKey("zip") ? values["zip"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "91210" : null); context.AddObject(customer); context.SaveChanges(); } customer = context.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == customerID); return customer; } } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System; using ExpressionBuilder.Enums; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ExpressionBuilder.Test { public class SimpleObject { public SimpleObject() { _name = GetType().Name; } private string _name; public bool PrivateInvoked { get; set; } public bool ProtectedInvoked { get; set; } public SimpleObject(string name) { _name = name; } public string GetName() { return _name; } public void SetName(string name) { _name = name; } private void PrivateMethod(string name) { PrivateInvoked = true; _name = name; } protected void ProtectedMethod(string name) { ProtectedInvoked = true; _name = name; } } [TestClass] public class OperationTest { [TestMethod] public void ItShouldPossibleToInvokeMethodsOnObjects() { const string expected = @"public System.String Call(ExpressionBuilder.Test.SimpleObject par) { System.String result; result = par.GetName(); return result; }"; var newExpression = Function.Create() .WithParameter<SimpleObject>("par") .WithBody( CodeLine.CreateVariable<string>("result"), CodeLine.Assign("result", Operation.InvokeReturn("par", "GetName")) ) .Returns("result"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<SimpleObject,string>>(); Assert.IsNotNull(lambda); var so = new SimpleObject(); var result = lambda(so); Assert.AreEqual("SimpleObject", result); } [TestMethod] public void ItShouldPossibleToInvokeMethodsWithParametersOnObjects() { const string expected = @"public System.String Call(ExpressionBuilder.Test.SimpleObject par, System.String name) { System.String result; par.SetName(name); result = par.GetName(); return result; }"; var newExpression = Function.Create() .WithParameter<SimpleObject>("par") .WithParameter<string>("name") .WithBody( CodeLine.CreateVariable<string>("result"), Operation.Invoke("par", "SetName",Operation.Variable("name")), CodeLine.Assign("result", Operation.InvokeReturn("par", "GetName")) ) .Returns("result"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<SimpleObject, string, string>>(); Assert.IsNotNull(lambda); var so = new SimpleObject(); var result = lambda(so,"paramName"); Assert.AreEqual("paramName", result); } [TestMethod] public void ItShouldPossibleToInvokeConstructorWithParameters() { const string expected = @"public System.String Call(System.String name) { System.String result; ExpressionBuilder.Test.SimpleObject par; par = new ExpressionBuilder.Test.SimpleObject(name); result = par.GetName(); return result; }"; var newExpression = Function.Create() .WithParameter<string>("name") .WithBody( CodeLine.CreateVariable<string>("result"), CodeLine.CreateVariable<SimpleObject>("par"), CodeLine.Assign("par", Operation.CreateInstance<SimpleObject>(Operation.Variable("name"))), CodeLine.Assign("result", Operation.InvokeReturn("par", "GetName")) ) .Returns("result"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<string, string>>(); Assert.IsNotNull(lambda); var result = lambda("paramName"); Assert.AreEqual("paramName", result); } [TestMethod] public void ItShouldPossibleToInvokeConstructor() { const string expected = @"public System.String Call(System.String name) { System.String result; ExpressionBuilder.Test.SimpleObject par; par = new ExpressionBuilder.Test.SimpleObject(); result = par.GetName(); return result; }"; var newExpression = Function.Create() .WithParameter<string>("name") .WithBody( CodeLine.CreateVariable<string>("result"), CodeLine.CreateVariable<SimpleObject>("par"), CodeLine.Assign("par",Operation.CreateInstance<SimpleObject>()), CodeLine.Assign("result", Operation.InvokeReturn("par", "GetName")) ) .Returns("result"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func< string, string>>(); Assert.IsNotNull(lambda); var result = lambda("paramName"); Assert.AreEqual("SimpleObject", result); } [TestMethod] public void CastShouldCast() { const string expected = @"public System.Int64 Call(System.Int32 first, System.Int64 second) { second = ((System.Int64)2); second += ((System.Int64)first); return second; }"; var newExpression = Function.Create() .WithParameter<int>("first") .WithParameter<long>("second") .WithBody( CodeLine.Assign("second", Operation.CastConst<long>(2)), CodeLine.Assign("second", Operation.Cast<long>("first"), AssignementOperator.SumAssign) ) .Returns("second"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<int, long, long>>(); Assert.IsNotNull(lambda); var result = lambda(3, 7); Assert.AreEqual(5, result); } [TestMethod] public void CastShouldCastSpecifiyingType() { const string expected = @"public System.Int64 Call(System.Int32 first, System.Int64 second) { second = ((System.Int64)2); second += ((System.Int64)first); return second; }"; var newExpression = Function.Create() .WithParameter<int>("first") .WithParameter<long>("second") .WithBody( CodeLine.Assign("second", Operation.CastConst(2, typeof(long))), CodeLine.Assign("second", Operation.Cast("first", typeof(long)), AssignementOperator.SumAssign) ) .Returns("second"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<int, long, long>>(); Assert.IsNotNull(lambda); var result = lambda(3, 7); Assert.AreEqual(5, result); } [TestMethod] public void ShouldBePossibleToCallLambdaFunction() { const string expected = @"public System.String Call(System.String first, System.String second) { System.String result; result = System.Func<System.Object, System.String, System.String>(first, second); return result; }"; var newExpression = Function.Create() .WithParameter<string>("first") .WithParameter<string>("second") .WithBody( CodeLine.CreateVariable<string>("result"), CodeLine.Assign("result", Operation.Func<object, string, string>( (a, b) => { b += "-extra"; return string.Format("{0}-{1}", a, b); }, Operation.Variable("first"), Operation.Variable("second")) ) ) .Returns("result"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<string, string, string>>(); Assert.IsNotNull(lambda); var result = lambda("a", "b"); Assert.AreEqual("a-b-extra", result); } [TestMethod] public void ItShouldPossibleToInvokeStaticMethodsOnObjects() { const string expected = @"public System.Boolean Call(System.Int32 year) { System.Boolean result; result = System.DateTime.IsLeapYear(year); return result; }"; var newExpression = Function.Create() .WithParameter<int>("year") .WithBody( CodeLine.CreateVariable<bool>("result"), CodeLine.Assign("result", Operation.InvokeReturn<DateTime>("IsLeapYear",Operation.Variable("year"))) ) .Returns("result"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<int, bool>>(); Assert.IsNotNull(lambda); var result = lambda(2011); Assert.IsFalse(result); result = lambda(2012); Assert.IsTrue(result); } [TestMethod] public void ItShouldPossibleToInvokePrivateMethodsOnObjects() { const string expected = @"public System.String Call(ExpressionBuilder.Test.SimpleObject par, System.String name) { System.String result; par.PrivateMethod(name); result = par.GetName(); return result; }"; var newExpression = Function.Create() .WithParameter<SimpleObject>("par") .WithParameter<string>("name") .WithBody( CodeLine.CreateVariable<string>("result"), Operation.Invoke("par", "PrivateMethod", Operation.Variable("name")), CodeLine.Assign("result", Operation.InvokeReturn("par", "GetName")) ) .Returns("result"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<SimpleObject, string, string>>(); Assert.IsNotNull(lambda); var so = new SimpleObject(); var result = lambda(so,"paramName"); Assert.AreEqual("paramName", result); Assert.IsTrue(so.PrivateInvoked); } [TestMethod] public void ItShouldPossibleToInvokeProtectedMethodsOnObjects() { const string expected = @"public System.String Call(ExpressionBuilder.Test.SimpleObject par, System.String name) { System.String result; par.ProtectedMethod(name); result = par.GetName(); return result; }"; var newExpression = Function.Create() .WithParameter<SimpleObject>("par") .WithParameter<string>("name") .WithBody( CodeLine.CreateVariable<string>("result"), Operation.Invoke("par", "ProtectedMethod", Operation.Variable("name")), CodeLine.Assign("result", Operation.InvokeReturn("par", "GetName")) ) .Returns("result"); AssertString.AreEqual(expected, newExpression.ToString()); var lambda = newExpression.ToLambda<Func<SimpleObject, string, string>>(); Assert.IsNotNull(lambda); var so = new SimpleObject(); var result = lambda(so, "paramName"); Assert.AreEqual("paramName", result); Assert.IsTrue(so.ProtectedInvoked); } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Web.UI.WebControls; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Web; using Subtext.Web.Properties; using Image = Subtext.Framework.Components.Image; namespace Subtext.Web.Admin.Pages { public partial class EditImage : AdminPage { protected const string VskeyImageid = "ImageId"; protected string GalleryTitle; protected Image _image; protected int _imageID; public EditImage() { TabSectionId = "Galleries"; } private int ImageId { get { if (ViewState[VskeyImageid] == null || NullValue.NullInt32 == (int)ViewState[VskeyImageid]) { if (null != Request.QueryString[Keys.QRYSTR_IMAGEID]) { ViewState[VskeyImageid] = Convert.ToInt32(Request.QueryString[Keys.QRYSTR_IMAGEID]); } } return (int)ViewState[VskeyImageid]; } } public Image Image { get { if (_image == null) { _image = Repository.GetImage(ImageId, false /* activeOnly */); } if (_image == null) { throw new InvalidOperationException(Resources.InvalidOperation_ImageUndefined); } return _image; } } public override void DataBind() { BindImage(); base.DataBind(); } private void BindImage() { ICollection<LinkCategory> selectionList = Repository.GetCategories(CategoryType.ImageCollection, ActiveFilter.None); if (selectionList.Count > 0) { ddlGalleries.DataSource = selectionList; ddlGalleries.DataValueField = "Id"; ddlGalleries.DataTextField = "Title"; lnkThumbnail.ImageUrl = EvalImageUrl(Image); lnkThumbnail.NavigateUrl = EvalImageNavigateUrl(Image); lnkThumbnail.Visible = true; ckbPublished.Checked = Image.IsActive; SetGalleryInfo(Image); ddlGalleries.DataBind(); ListItem listItem = ddlGalleries.Items.FindByValue(_image.CategoryID.ToString(CultureInfo.InvariantCulture)); if (listItem != null) { ddlGalleries.SelectedIndex = ddlGalleries.Items.IndexOf(listItem); } // HACK: we're disabling this until we do something with/around the provider // that will let us actually move the files too. ddlGalleries.Enabled = false; if (AdminMasterPage != null) { string title = string.Format(CultureInfo.InvariantCulture, Resources.EditGalleries_EditImage, Image.Title); AdminMasterPage.Title = title; } } } protected void SetGalleryInfo(Image image) { GalleryTitle = SubtextContext.Repository.GetLinkCategory(image.CategoryID, false).Title; } protected string EvalImageUrl(object imageObject) { if (imageObject is Image) { var image = (Image)imageObject; image.Blog = Blog; return Url.GalleryImageUrl(image); } return String.Empty; } protected string EvalImageNavigateUrl(object imageObject) { if (imageObject is Image) { var image = (Image)imageObject; return Url.GalleryImagePageUrl(image); } return String.Empty; } protected string GetImageGalleryUrl() { return string.Format(CultureInfo.InvariantCulture, "{0}?{1}={2}", Constants.URL_EDITGALLERIES, Keys.QRYSTR_CATEGORYID, Image.CategoryID); } private void UpdateImage() { if (Page.IsValid) { _image = Repository.GetImage(ImageId, false /* activeOnly */); _image.CategoryID = Convert.ToInt32(ddlGalleries.SelectedItem.Value); _image.Title = txbTitle.Text; _image.IsActive = ckbPublished.Checked; try { Repository.Update(_image); // would need to also move files for this to work here. should happen // in the provider though. Messages.ShowMessage(Resources.EditGalleries_ImageUpdated); BindImage(); } catch (Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, "TODO...", ex.Message)); } } } private void ReplaceImage() { if (Page.IsValid) { _image = Repository.GetImage(ImageId, false /* activeOnly */); _image.CategoryID = Convert.ToInt32(ddlGalleries.SelectedItem.Value); _image.Title = txbTitle.Text; _image.IsActive = ckbPublished.Checked; try { _image.FileName = Path.GetFileName(ImageFile.PostedFile.FileName); _image.Url = Url.ImageGalleryDirectoryUrl(Blog, _image.CategoryID); _image.LocalDirectoryPath = Url.GalleryDirectoryPath(Blog, _image.CategoryID); Repository.Update(_image, ImageFile.PostedFile.GetFileStream()); Messages.ShowMessage(Resources.EditGalleries_ImageUpdated); BindImage(); } catch (Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, "TODO...", ex.Message)); } } } override protected void OnInit(EventArgs e) { ViewState[VskeyImageid] = NullValue.NullInt32; } protected void lbkReplaceImage_Click(object sender, EventArgs e) { ReplaceImage(); } protected void lkbUpdateImage_Click(object sender, EventArgs e) { UpdateImage(); } } }
// 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.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { public class MultipartContentTest { [Fact] public void Ctor_NullOrEmptySubType_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("subtype", () => new MultipartContent(null)); AssertExtensions.Throws<ArgumentException>("subtype", () => new MultipartContent("")); AssertExtensions.Throws<ArgumentException>("subtype", () => new MultipartContent(" ")); } [Fact] public void Ctor_NullOrEmptyBoundary_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", null)); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", " ")); } [Fact] public void Ctor_TooLongBoundary_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => new MultipartContent("Some", "LongerThan70CharactersLongerThan70CharactersLongerThan70CharactersLongerThan70CharactersLongerThan70Characters")); } [Fact] public void Ctor_BadBoundary_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "EndsInSpace ")); // Invalid chars CTLs HT < > @ ; \ " [ ] { } ! # $ % & ^ ~ ` AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "a\t")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "<")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "@")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "[")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "{")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "!")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "#")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "$")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "%")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "&")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "^")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "~")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "`")); AssertExtensions.Throws<ArgumentException>("boundary", () => new MultipartContent("Some", "\"quoted\"")); } [Fact] public void Ctor_GoodBoundary_Success() { // RFC 2046 Section 5.1.1 // boundary := 0*69<bchars> bcharsnospace // bchars := bcharsnospace / " " // bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?" new MultipartContent("some", "09"); new MultipartContent("some", "az"); new MultipartContent("some", "AZ"); new MultipartContent("some", "'"); new MultipartContent("some", "("); new MultipartContent("some", "+"); new MultipartContent("some", "_"); new MultipartContent("some", ","); new MultipartContent("some", "-"); new MultipartContent("some", "."); new MultipartContent("some", "/"); new MultipartContent("some", ":"); new MultipartContent("some", "="); new MultipartContent("some", "?"); new MultipartContent("some", "Contains Space"); new MultipartContent("some", " StartsWithSpace"); new MultipartContent("some", Guid.NewGuid().ToString()); } [Fact] public void Ctor_Headers_AutomaticallyCreated() { var content = new MultipartContent("test_subtype", "test_boundary"); Assert.Equal("multipart/test_subtype", content.Headers.ContentType.MediaType); Assert.Equal(1, content.Headers.ContentType.Parameters.Count); } [Fact] public void Dispose_Empty_Sucess() { var content = new MultipartContent(); content.Dispose(); } [Fact] public void Dispose_InnerContent_InnerContentDisposed() { var content = new MultipartContent(); var innerContent = new MockContent(); content.Add(innerContent); content.Dispose(); Assert.Equal(1, innerContent.DisposeCount); content.Dispose(); // Inner content is discarded after first dispose. Assert.Equal(1, innerContent.DisposeCount); } [Fact] public void Dispose_NestedContent_NestedContentDisposed() { var outer = new MultipartContent(); var inner = new MultipartContent(); outer.Add(inner); var mock = new MockContent(); inner.Add(mock); outer.Dispose(); Assert.Equal(1, mock.DisposeCount); outer.Dispose(); // Inner content is discarded after first dispose. Assert.Equal(1, mock.DisposeCount); } [Theory] [InlineData(MultipartContentToStringMode.ReadAsStreamAsync)] [InlineData(MultipartContentToStringMode.CopyToAsync)] public async Task ReadAsStringAsync_NoSubContent_MatchesExpected(MultipartContentToStringMode mode) { var mc = new MultipartContent("someSubtype", "theBoundary"); Assert.Equal( "--theBoundary\r\n" + "\r\n" + "--theBoundary--\r\n", await MultipartContentToStringAsync(mc, mode)); } [Theory] [InlineData(MultipartContentToStringMode.ReadAsStreamAsync)] [InlineData(MultipartContentToStringMode.CopyToAsync)] public async Task ReadAsStringAsync_OneSubContentWithHeaders_MatchesExpected(MultipartContentToStringMode mode) { var subContent = new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent")); subContent.Headers.Add("someHeaderName", "andSomeHeaderValue"); subContent.Headers.Add("someOtherHeaderName", new[] { "withNotOne", "ButTwoValues" }); subContent.Headers.Add("oneMoreHeader", new[] { "withNotOne", "AndNotTwo", "butThreeValues" }); var mc = new MultipartContent("someSubtype", "theBoundary"); mc.Add(subContent); Assert.Equal( "--theBoundary\r\n" + "someHeaderName: andSomeHeaderValue\r\n" + "someOtherHeaderName: withNotOne, ButTwoValues\r\n" + "oneMoreHeader: withNotOne, AndNotTwo, butThreeValues\r\n" + "\r\n" + "This is a ByteArrayContent\r\n" + "--theBoundary--\r\n", await MultipartContentToStringAsync(mc, mode)); } [Theory] [InlineData(MultipartContentToStringMode.ReadAsStreamAsync)] [InlineData(MultipartContentToStringMode.CopyToAsync)] public async Task ReadAsStringAsync_TwoSubContents_MatchesExpected(MultipartContentToStringMode mode) { var mc = new MultipartContent("someSubtype", "theBoundary"); mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent"))); mc.Add(new StringContent("This is a StringContent")); Assert.Equal( "--theBoundary\r\n" + "\r\n" + "This is a ByteArrayContent\r\n" + "--theBoundary\r\n" + "Content-Type: text/plain; charset=utf-8\r\n" + "\r\n" + "This is a StringContent\r\n" + "--theBoundary--\r\n", await MultipartContentToStringAsync(mc, mode)); } [Fact] public async Task ReadAsStreamAsync_LargeContent_AllBytesRead() { var form = new MultipartFormDataContent(); const long PerContent = 1024 * 1024; const long ContentCount = 2048; var bytes = new byte[PerContent]; for (int i = 0; i < ContentCount; i++) { form.Add(new ByteArrayContent(bytes), "file", Guid.NewGuid().ToString()); } long totalAsyncRead = 0, totalSyncArrayRead = 0, totalSyncSpanRead = 0; int bytesRead; using (Stream s = await form.ReadAsStreamAsync()) { s.Position = 0; while ((bytesRead = await s.ReadAsync(bytes, 0, bytes.Length)) > 0) { totalAsyncRead += bytesRead; } s.Position = 0; while ((bytesRead = s.Read(bytes, 0, bytes.Length)) > 0) { totalSyncArrayRead += bytesRead; } s.Position = 0; while ((bytesRead = s.Read(new Span<byte>(bytes, 0, bytes.Length))) > 0) { totalSyncSpanRead += bytesRead; } } Assert.Equal(totalAsyncRead, totalSyncArrayRead); Assert.Equal(totalAsyncRead, totalSyncSpanRead); Assert.InRange(totalAsyncRead, PerContent * ContentCount, long.MaxValue); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public async Task ReadAsStreamAsync_CanSeekEvenIfAllStreamsNotSeekale(bool firstContentSeekable, bool secondContentSeekable) { var c = new MultipartContent(); c.Add(new StreamContent(firstContentSeekable ? new MemoryStream(new byte[42]) : new NonSeekableMemoryStream(new byte[42]))); c.Add(new StreamContent(secondContentSeekable ? new MemoryStream(new byte[42]) : new NonSeekableMemoryStream(new byte[1]))); using (Stream s = await c.ReadAsStreamAsync()) { Assert.True(s.CanSeek); Assert.InRange(s.Length, 43, int.MaxValue); s.Position = 1; Assert.Equal(1, s.Position); s.Seek(20, SeekOrigin.Current); Assert.Equal(21, s.Position); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task ReadAsStreamAsync_Seek_JumpsToSpecifiedPosition(bool nestedContent) { var mc = new MultipartContent(); if (nestedContent) { mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent"))); mc.Add(new StringContent("This is a StringContent")); mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("Another ByteArrayContent :-)"))); } var memStream = new MemoryStream(); await mc.CopyToAsync(memStream); byte[] buf1 = new byte[1], buf2 = new byte[1]; using (Stream s = await mc.ReadAsStreamAsync()) { var targets = new[] { new { Origin = SeekOrigin.Begin, Offset = memStream.Length / 2 }, new { Origin = SeekOrigin.Begin, Offset = memStream.Length - 1 }, new { Origin = SeekOrigin.Begin, Offset = memStream.Length }, new { Origin = SeekOrigin.Begin, Offset = memStream.Length + 1 }, new { Origin = SeekOrigin.Begin, Offset = 0L }, new { Origin = SeekOrigin.Begin, Offset = 1L }, new { Origin = SeekOrigin.Current, Offset = 1L }, new { Origin = SeekOrigin.Current, Offset = 2L }, new { Origin = SeekOrigin.Current, Offset = -2L }, new { Origin = SeekOrigin.Current, Offset = 0L }, new { Origin = SeekOrigin.Current, Offset = 1000L }, new { Origin = SeekOrigin.End, Offset = 0L }, new { Origin = SeekOrigin.End, Offset = memStream.Length }, new { Origin = SeekOrigin.End, Offset = memStream.Length / 2 }, }; foreach (var target in targets) { memStream.Seek(target.Offset, target.Origin); s.Seek(target.Offset, target.Origin); Assert.Equal(memStream.Position, s.Position); Assert.Equal(memStream.Read(buf1, 0, 1), s.Read(buf2, 0, 1)); Assert.Equal(buf1[0], buf2[0]); } } } [Fact] public async Task ReadAsStreamAsync_InvalidArgs_Throw() { var mc = new MultipartContent(); using (Stream s = await mc.ReadAsStreamAsync()) { Assert.True(s.CanRead); Assert.Equal(false, s.CanWrite); Assert.True(s.CanSeek); AssertExtensions.Throws<ArgumentNullException>("buffer", null, () => s.Read(null, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => s.Read(new byte[1], -1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => s.Read(new byte[1], 0, -1)); AssertExtensions.Throws<ArgumentException>("buffer", null, () => s.Read(new byte[1], 1, 1)); AssertExtensions.Throws<ArgumentNullException>("buffer", null, () => { s.ReadAsync(null, 0, 0); }); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => { s.ReadAsync(new byte[1], -1, 0); }); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => { s.ReadAsync(new byte[1], 0, -1); }); AssertExtensions.Throws<ArgumentException>("buffer", null, () => { s.ReadAsync(new byte[1], 1, 1); }); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => s.Position = -1); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => s.Seek(-1, SeekOrigin.Begin)); AssertExtensions.Throws<ArgumentOutOfRangeException>("origin", () => s.Seek(0, (SeekOrigin)42)); Assert.Throws<NotSupportedException>(() => s.Write(new byte[1], 0, 0)); Assert.Throws<NotSupportedException>(() => s.Write(new Span<byte>(new byte[1], 0, 0))); Assert.Throws<NotSupportedException>(() => { s.WriteAsync(new byte[1], 0, 0); }); Assert.Throws<NotSupportedException>(() => s.SetLength(1)); } } [Fact] public async Task ReadAsStreamAsync_OperationsThatDontChangePosition() { var mc = new MultipartContent(); using (Stream s = await mc.ReadAsStreamAsync()) { Assert.Equal(0, s.Read(new byte[1], 0, 0)); Assert.Equal(0, s.Read(new Span<byte>(new byte[1], 0, 0))); Assert.Equal(0, s.Position); Assert.Equal(0, await s.ReadAsync(new byte[1], 0, 0)); Assert.Equal(0, s.Position); s.Flush(); Assert.Equal(0, s.Position); await s.FlushAsync(); Assert.Equal(0, s.Position); } } [Fact] public async Task ReadAsStreamAsync_CreateContentReadStreamAsyncThrows_ExceptionStoredInTask() { var mc = new MultipartContent(); mc.Add(new MockContent()); Task t = mc.ReadAsStreamAsync(); await Assert.ThrowsAsync<NotImplementedException>(() => t); } [Fact] public async Task ReadAsStreamAsync_CanEncodeLatin1() { var mc = new MultipartContent("subtype", "fooBoundary"); var stringContent = new StringContent("bar1"); stringContent.Headers.Add("latin1", "\uD83D\uDE00"); mc.Add(stringContent); var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4")); byteArrayContent.Headers.Add("default", "\uD83D\uDE00"); mc.Add(byteArrayContent); var ms = new MemoryStream(); await (await mc.ReadAsStreamAsync()).CopyToAsync(ms); Encoding latin1 = Test.Common.HttpHeaderData.Latin1Encoding; byte[] expected = Concat( latin1.GetBytes("--fooBoundary\r\n"), latin1.GetBytes("Content-Type: text/plain; charset=utf-8\r\n"), latin1.GetBytes("latin1: "), latin1.GetBytes("\uD83D\uDE00"), latin1.GetBytes("\r\n\r\n"), latin1.GetBytes("bar1"), latin1.GetBytes("\r\n--fooBoundary\r\n"), latin1.GetBytes("default: "), latin1.GetBytes("\uD83D\uDE00"), latin1.GetBytes("\r\n\r\n"), latin1.GetBytes("bar4"), latin1.GetBytes("\r\n--fooBoundary--\r\n")); byte[] actual = ms.ToArray(); Assert.Equal(expected, actual); static byte[] Concat(params byte[][] arrays) => arrays.SelectMany(b => b).ToArray(); } #region Helpers private static async Task<string> MultipartContentToStringAsync(MultipartContent content, MultipartContentToStringMode mode) { Stream stream; switch (mode) { case MultipartContentToStringMode.ReadAsStreamAsync: stream = await content.ReadAsStreamAsync(); break; default: stream = new MemoryStream(); await content.CopyToAsync(stream); stream.Position = 0; break; } using (var reader = new StreamReader(stream)) { return await reader.ReadToEndAsync(); } } public enum MultipartContentToStringMode { ReadAsStreamAsync, CopyToAsync } private class MockContent : HttpContent { public int DisposeCount { get; private set; } public MockContent() { } protected override void Dispose(bool disposing) { DisposeCount++; base.Dispose(disposing); } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { throw new NotImplementedException(); } protected override bool TryComputeLength(out long length) { length = 0; return false; } protected override Task<Stream> CreateContentReadStreamAsync() { throw new NotImplementedException(); } } private sealed class NonSeekableMemoryStream : MemoryStream { public NonSeekableMemoryStream(byte[] data) : base(data) { } public override bool CanSeek => false; } #endregion Helpers } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.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.Runtime.InteropServices; using GLib; namespace Gdv { [StructLayout (LayoutKind.Sequential)] public struct Fraction { // Imports //////////////////////////////////////////////////// [DllImport ("gdv")] internal static extern IntPtr gdv_fraction_new (int num, int den); [DllImport ("gdv")] internal static extern IntPtr gdv_fraction_new_empty (); [DllImport ("gdv")] internal static extern IntPtr gdv_fraction_invert (ref Fraction f); [DllImport ("gdv")] internal static extern double gdv_fraction_to_double (ref Fraction f); [DllImport ("gdv")] internal static extern int gdv_fraction_compare (ref Fraction a, ref Fraction b); [DllImport ("gdv")] internal static extern bool gdv_fraction_simplify (ref Fraction f); [DllImport ("gdv")] internal static extern ulong gdv_fraction_fps_frame_duration (ref Fraction f); [DllImport ("gdv")] internal static extern ulong gdv_fraction_fps_time_at_frame (ref Fraction f, int no); [DllImport ("gdv")] internal static extern int gdv_fraction_fps_frame_at_time_rnd (ref Fraction f, ulong t); [DllImport ("gdv")] internal static extern int gdv_fraction_fps_frame_at_time (ref Fraction f, ulong t); [DllImport ("gdv")] internal static extern ulong gdv_fraction_fps_normalize_time_rnd (ref Fraction f, ulong t); [DllImport ("gdv")] internal static extern ulong gdv_fraction_fps_normalize_time (ref Fraction f, ulong t); [DllImport ("gdv")] internal static extern int gdv_fraction_fps_digitize (ref Fraction f); [DllImport ("gdv")] internal static extern IntPtr gdv_fraction_aspect_pixelize (ref Fraction f1, ref Fraction f2, ref FrameDimensions dimensions); [DllImport ("gdv")] internal static extern IntPtr gdv_fraction_get_type (); [DllImport ("gdv")] internal static extern void gdv_glue_gvalue_set_boxed (ref Value val, ref Fraction f); [DllImport ("gdv")] internal static extern IntPtr gdv_glue_gvalue_get_boxed (ref Value val); // Fields ///////////////////////////////////////////////////// int numerator; int denominator; bool simple; // Properties ///////////////////////////////////////////////// public int Numerator { get { return numerator; } set { numerator = value; simple = false; } } public int Denominator { get { return denominator; } set { denominator = value; simple = false; } } public bool Simple { get { return simple; } } public static Fraction Empty { get { return FromPtr (gdv_fraction_new_empty ()); } } public static GType GType { get { IntPtr ptr = gdv_fraction_get_type (); return new GType (ptr); } } // Methods //////////////////////////////////////////////////// public Fraction (int numerator, int denominator) { IntPtr ptr = gdv_fraction_new (numerator, denominator); // FIXME: Exception Fraction self = (Fraction) Marshal.PtrToStructure (ptr, typeof (Fraction)); this.numerator = self.Numerator; this.denominator = self.Denominator; this.simple = self.Simple; } public static Fraction FromPtr (IntPtr ptr) { // FIXME: Exception rather if (ptr == IntPtr.Zero) return new Fraction (); Fraction self = (Fraction) Marshal.PtrToStructure (ptr, typeof (Fraction)); return self; } public bool Simplify () { return gdv_fraction_simplify (ref this); } public Fraction Invert () { IntPtr ptr = gdv_fraction_invert (ref this); return FromPtr (ptr); } public Time FpsFrameDuration () { return gdv_fraction_fps_frame_duration (ref this); } public Time FpsTimeAtFrame (int frame) { return gdv_fraction_fps_time_at_frame (ref this, frame); } public int FpsFrameAtTimeRnd (Time t) { return gdv_fraction_fps_frame_at_time_rnd (ref this, t); } public int FpsFrameAtTime (Time t) { return gdv_fraction_fps_frame_at_time (ref this, t); } public Time FpsNormalizeTimeRnd (Time t) { return gdv_fraction_fps_normalize_time_rnd (ref this, t); } public Time FpsNormalizeTime (Time t) { return gdv_fraction_fps_normalize_time (ref this, t); } public int FpsDigitize () { return gdv_fraction_fps_digitize (ref this); } public override string ToString () { return (this == Empty) ? "(empty)" : String.Format ("{0}/{1}", numerator, denominator); } // Static methods ///////////////////////////////////////////// /* NUNIT */ public static FrameDimensions AspectPixelize (Fraction f1, Fraction f2, FrameDimensions dimensions) { IntPtr ptr = gdv_fraction_aspect_pixelize (ref f1, ref f2, ref dimensions); if (ptr == IntPtr.Zero) throw new Exception (); else return FrameDimensions.New (ptr); } // Operators ////////////////////////////////////////////////// public static explicit operator Value (Fraction f) { Value val = Value.Empty; val.Init (Fraction.GType); gdv_glue_gvalue_set_boxed (ref val, ref f); return val; } public static explicit operator Fraction (Value val) { IntPtr ptr = gdv_glue_gvalue_get_boxed (ref val); return FromPtr (ptr); } public static explicit operator double (Fraction f) { return gdv_fraction_to_double (ref f); } public override bool Equals (object o) { if (! (o is Fraction)) return false; Fraction other = (Fraction) o; return (gdv_fraction_compare (ref this, ref other) == 0) ? true : false; } public override int GetHashCode() { return numerator * denominator; } public static bool operator == (Fraction a, Fraction b) { return (gdv_fraction_compare (ref a, ref b) == 0) ? true : false; } public static bool operator != (Fraction a, Fraction b) { return (gdv_fraction_compare (ref a, ref b) != 0) ? true : false; } // FIXME: More operators! } }
using System; using System.Linq; using System.Collections.Generic; using System.Dynamic; namespace Python.Runtime { public class PyScopeException : Exception { public PyScopeException(string message) : base(message) { } } /// <summary> /// Classes/methods have this attribute must be used with GIL obtained. /// </summary> public class PyGILAttribute : Attribute { } [PyGIL] public class PyScope : DynamicObject, IPyDisposable { public readonly string Name; /// <summary> /// the python Module object the scope associated with. /// </summary> internal readonly IntPtr obj; /// <summary> /// the variable dict of the scope. /// </summary> internal readonly IntPtr variables; private bool _isDisposed; private bool _finalized = false; /// <summary> /// The Manager this scope associated with. /// It provides scopes this scope can import. /// </summary> internal readonly PyScopeManager Manager; /// <summary> /// event which will be triggered after the scope disposed. /// </summary> public event Action<PyScope> OnDispose; /// <summary> /// Constructor /// </summary> /// <remarks> /// Create a scope based on a Python Module. /// </remarks> internal PyScope(IntPtr ptr, PyScopeManager manager) { if (!Runtime.PyType_IsSubtype(Runtime.PyObject_TYPE(ptr), Runtime.PyModuleType)) { throw new PyScopeException("object is not a module"); } Manager = manager ?? PyScopeManager.Global; obj = ptr; //Refcount of the variables not increase variables = Runtime.PyModule_GetDict(obj); Runtime.CheckExceptionOccurred(); Runtime.PyDict_SetItemString( variables, "__builtins__", Runtime.PyEval_GetBuiltins() ); this.Name = this.Get<string>("__name__"); } /// <summary> /// return the variable dict of the scope. /// </summary> /// <returns></returns> public PyDict Variables() { Runtime.XIncref(variables); return new PyDict(variables); } /// <summary> /// Create a scope, and import all from this scope /// </summary> /// <returns></returns> public PyScope NewScope() { var scope = Manager.Create(); scope.ImportAll(this); return scope; } /// <summary> /// Import method /// </summary> /// <remarks> /// Import a scope or a module of given name, /// scope will be looked up first. /// </remarks> public dynamic Import(string name, string asname = null) { Check(); if (String.IsNullOrEmpty(asname)) { asname = name; } PyScope scope; Manager.TryGet(name, out scope); if (scope != null) { Import(scope, asname); return scope; } else { PyObject module = PythonEngine.ImportModule(name); Import(module, asname); return module; } } /// <summary> /// Import method /// </summary> /// <remarks> /// Import a scope as a variable of given name. /// </remarks> public void Import(PyScope scope, string asname) { this.Set(asname, scope.obj); } /// <summary> /// Import Method /// </summary> /// <remarks> /// The 'import .. as ..' statement in Python. /// Import a module as a variable into the scope. /// </remarks> public void Import(PyObject module, string asname = null) { if (String.IsNullOrEmpty(asname)) { asname = module.GetAttr("__name__").As<string>(); } Set(asname, module); } /// <summary> /// ImportAll Method /// </summary> /// <remarks> /// The 'import * from ..' statement in Python. /// Import all content of a scope/module of given name into the scope, scope will be looked up first. /// </remarks> public void ImportAll(string name) { PyScope scope; Manager.TryGet(name, out scope); if (scope != null) { ImportAll(scope); return; } else { PyObject module = PythonEngine.ImportModule(name); ImportAll(module); } } /// <summary> /// ImportAll Method /// </summary> /// <remarks> /// Import all variables of the scope into this scope. /// </remarks> public void ImportAll(PyScope scope) { int result = Runtime.PyDict_Update(variables, scope.variables); if (result < 0) { throw new PythonException(); } } /// <summary> /// ImportAll Method /// </summary> /// <remarks> /// Import all variables of the module into this scope. /// </remarks> public void ImportAll(PyObject module) { if (Runtime.PyObject_Type(module.obj) != Runtime.PyModuleType) { throw new PyScopeException("object is not a module"); } var module_dict = Runtime.PyModule_GetDict(module.obj); int result = Runtime.PyDict_Update(variables, module_dict); if (result < 0) { throw new PythonException(); } } /// <summary> /// ImportAll Method /// </summary> /// <remarks> /// Import all variables in the dictionary into this scope. /// </remarks> public void ImportAll(PyDict dict) { int result = Runtime.PyDict_Update(variables, dict.obj); if (result < 0) { throw new PythonException(); } } /// <summary> /// Execute method /// </summary> /// <remarks> /// Execute a Python ast and return the result as a PyObject. /// The ast can be either an expression or stmts. /// </remarks> public PyObject Execute(PyObject script, PyDict locals = null) { Check(); IntPtr _locals = locals == null ? variables : locals.obj; IntPtr ptr = Runtime.PyEval_EvalCode(script.Handle, variables, _locals); Runtime.CheckExceptionOccurred(); if (ptr == Runtime.PyNone) { Runtime.XDecref(ptr); return null; } return new PyObject(ptr); } /// <summary> /// Execute method /// </summary> /// <remarks> /// Execute a Python ast and return the result as a PyObject, /// and convert the result to a Managed Object of given type. /// The ast can be either an expression or stmts. /// </remarks> public T Execute<T>(PyObject script, PyDict locals = null) { Check(); PyObject pyObj = Execute(script, locals); if (pyObj == null) { return default(T); } var obj = pyObj.As<T>(); return obj; } /// <summary> /// Eval method /// </summary> /// <remarks> /// Evaluate a Python expression and return the result as a PyObject /// or null if an exception is raised. /// </remarks> public PyObject Eval(string code, PyDict locals = null) { Check(); IntPtr _locals = locals == null ? variables : locals.obj; var flag = (IntPtr)Runtime.Py_eval_input; IntPtr ptr = Runtime.PyRun_String( code, flag, variables, _locals ); Runtime.CheckExceptionOccurred(); return new PyObject(ptr); } /// <summary> /// Evaluate a Python expression /// </summary> /// <remarks> /// Evaluate a Python expression /// and convert the result to a Managed Object of given type. /// </remarks> public T Eval<T>(string code, PyDict locals = null) { Check(); PyObject pyObj = Eval(code, locals); var obj = pyObj.As<T>(); return obj; } /// <summary> /// Exec Method /// </summary> /// <remarks> /// Exec a Python script and save its local variables in the current local variable dict. /// </remarks> public void Exec(string code, PyDict locals = null) { Check(); IntPtr _locals = locals == null ? variables : locals.obj; Exec(code, variables, _locals); } private void Exec(string code, IntPtr _globals, IntPtr _locals) { var flag = (IntPtr)Runtime.Py_file_input; IntPtr ptr = Runtime.PyRun_String( code, flag, _globals, _locals ); Runtime.CheckExceptionOccurred(); if (ptr != Runtime.PyNone) { throw new PythonException(); } Runtime.XDecref(ptr); } /// <summary> /// Set Variable Method /// </summary> /// <remarks> /// Add a new variable to the variables dict if it not exist /// or update its value if the variable exists. /// </remarks> public void Set(string name, object value) { IntPtr _value = Converter.ToPython(value, value?.GetType()); Set(name, _value); Runtime.XDecref(_value); } private void Set(string name, IntPtr value) { Check(); using (var pyKey = new PyString(name)) { int r = Runtime.PyObject_SetItem(variables, pyKey.obj, value); if (r < 0) { throw new PythonException(); } } } /// <summary> /// Remove Method /// </summary> /// <remarks> /// Remove a variable from the variables dict. /// </remarks> public void Remove(string name) { Check(); using (var pyKey = new PyString(name)) { int r = Runtime.PyObject_DelItem(variables, pyKey.obj); if (r < 0) { throw new PythonException(); } } } /// <summary> /// Contains Method /// </summary> /// <remarks> /// Returns true if the variable exists in the scope. /// </remarks> public bool Contains(string name) { Check(); using (var pyKey = new PyString(name)) { return Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0; } } /// <summary> /// Get Method /// </summary> /// <remarks> /// Returns the value of the variable of given name. /// If the variable does not exist, throw an Exception. /// </remarks> public PyObject Get(string name) { PyObject scope; var state = TryGet(name, out scope); if (!state) { throw new PyScopeException($"The scope of name '{Name}' has no attribute '{name}'"); } return scope; } /// <summary> /// TryGet Method /// </summary> /// <remarks> /// Returns the value of the variable, local variable first. /// If the variable does not exist, return null. /// </remarks> public bool TryGet(string name, out PyObject value) { Check(); using (var pyKey = new PyString(name)) { if (Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0) { IntPtr op = Runtime.PyObject_GetItem(variables, pyKey.obj); if (op == IntPtr.Zero) { throw new PythonException(); } if (op == Runtime.PyNone) { Runtime.XDecref(op); value = null; return true; } value = new PyObject(op); return true; } else { value = null; return false; } } } /// <summary> /// Get Method /// </summary> /// <remarks> /// Obtain the value of the variable of given name, /// and convert the result to a Managed Object of given type. /// If the variable does not exist, throw an Exception. /// </remarks> public T Get<T>(string name) { Check(); PyObject pyObj = Get(name); if (pyObj == null) { return default(T); } return pyObj.As<T>(); } /// <summary> /// TryGet Method /// </summary> /// <remarks> /// Obtain the value of the variable of given name, /// and convert the result to a Managed Object of given type. /// If the variable does not exist, return false. /// </remarks> public bool TryGet<T>(string name, out T value) { Check(); PyObject pyObj; var result = TryGet(name, out pyObj); if (!result) { value = default(T); return false; } if (pyObj == null) { if (typeof(T).IsValueType) { throw new PyScopeException($"The value of the attribute '{name}' is None which cannot be convert to '{typeof(T).ToString()}'"); } else { value = default(T); return true; } } value = pyObj.As<T>(); return true; } public override bool TryGetMember(GetMemberBinder binder, out object result) { result = this.Get(binder.Name); return true; } public override bool TrySetMember(SetMemberBinder binder, object value) { this.Set(binder.Name, value); return true; } private void Check() { if (_isDisposed) { throw new PyScopeException($"The scope of name '{Name}' object has been disposed"); } } public void Dispose() { if (_isDisposed) { return; } _isDisposed = true; Runtime.XDecref(obj); this.OnDispose?.Invoke(this); } public IntPtr[] GetTrackedHandles() { return new IntPtr[] { obj }; } ~PyScope() { if (_finalized || _isDisposed) { return; } _finalized = true; Finalizer.Instance.AddFinalizedObject(this); } } public class PyScopeManager { public static PyScopeManager Global; private Dictionary<string, PyScope> NamedScopes = new Dictionary<string, PyScope>(); internal static void Reset() { Global = new PyScopeManager(); } internal PyScope NewScope(string name) { if (name == null) { name = ""; } var module = Runtime.PyModule_New(name); if (module == IntPtr.Zero) { throw new PythonException(); } return new PyScope(module, this); } /// <summary> /// Create Method /// </summary> /// <remarks> /// Create an anonymous scope. /// </remarks> [PyGIL] public PyScope Create() { var scope = this.NewScope(null); return scope; } /// <summary> /// Create Method /// </summary> /// <remarks> /// Create an named scope of given name. /// </remarks> [PyGIL] public PyScope Create(string name) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (name != null && Contains(name)) { throw new PyScopeException($"A scope of name '{name}' does already exist"); } var scope = this.NewScope(name); scope.OnDispose += Remove; NamedScopes[name] = scope; return scope; } /// <summary> /// Contains Method /// </summary> /// <remarks> /// return true if the scope exists in this manager. /// </remarks> public bool Contains(string name) { return NamedScopes.ContainsKey(name); } /// <summary> /// Get Method /// </summary> /// <remarks> /// Find the scope in this manager. /// If the scope not exist, an Exception will be thrown. /// </remarks> public PyScope Get(string name) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (NamedScopes.ContainsKey(name)) { return NamedScopes[name]; } throw new PyScopeException($"There is no scope named '{name}' registered in this manager"); } /// <summary> /// Get Method /// </summary> /// <remarks> /// Try to find the scope in this manager. /// </remarks> public bool TryGet(string name, out PyScope scope) { return NamedScopes.TryGetValue(name, out scope); } /// <summary> /// Remove Method /// </summary> /// <remarks> /// remove the scope from this manager. /// </remarks> public void Remove(PyScope scope) { NamedScopes.Remove(scope.Name); } [PyGIL] public void Clear() { var scopes = NamedScopes.Values.ToList(); foreach (var scope in scopes) { scope.Dispose(); } } } }
// Copyright 2018 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 Google.Api; using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Logging.V2; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Logging.V2.Snippets { /// <summary>Generated snippets</summary> public class GeneratedLoggingServiceV2ClientSnippets { /// <summary>Snippet for DeleteLogAsync</summary> public async Task DeleteLogAsync() { // Snippet: DeleteLogAsync(LogNameOneof,CallSettings) // Additional: DeleteLogAsync(LogNameOneof,CancellationToken) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); // Make the request await loggingServiceV2Client.DeleteLogAsync(logName); // End snippet } /// <summary>Snippet for DeleteLog</summary> public void DeleteLog() { // Snippet: DeleteLog(LogNameOneof,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); // Make the request loggingServiceV2Client.DeleteLog(logName); // End snippet } /// <summary>Snippet for DeleteLogAsync</summary> public async Task DeleteLogAsync_RequestObject() { // Snippet: DeleteLogAsync(DeleteLogRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) DeleteLogRequest request = new DeleteLogRequest { LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")), }; // Make the request await loggingServiceV2Client.DeleteLogAsync(request); // End snippet } /// <summary>Snippet for DeleteLog</summary> public void DeleteLog_RequestObject() { // Snippet: DeleteLog(DeleteLogRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) DeleteLogRequest request = new DeleteLogRequest { LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")), }; // Make the request loggingServiceV2Client.DeleteLog(request); // End snippet } /// <summary>Snippet for WriteLogEntriesAsync</summary> public async Task WriteLogEntriesAsync() { // Snippet: WriteLogEntriesAsync(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CallSettings) // Additional: WriteLogEntriesAsync(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CancellationToken) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); MonitoredResource resource = new MonitoredResource(); IDictionary<string, string> labels = new Dictionary<string, string>(); IEnumerable<LogEntry> entries = new List<LogEntry>(); // Make the request WriteLogEntriesResponse response = await loggingServiceV2Client.WriteLogEntriesAsync(logName, resource, labels, entries); // End snippet } /// <summary>Snippet for WriteLogEntries</summary> public void WriteLogEntries() { // Snippet: WriteLogEntries(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); MonitoredResource resource = new MonitoredResource(); IDictionary<string, string> labels = new Dictionary<string, string>(); IEnumerable<LogEntry> entries = new List<LogEntry>(); // Make the request WriteLogEntriesResponse response = loggingServiceV2Client.WriteLogEntries(logName, resource, labels, entries); // End snippet } /// <summary>Snippet for WriteLogEntriesAsync</summary> public async Task WriteLogEntriesAsync_RequestObject() { // Snippet: WriteLogEntriesAsync(WriteLogEntriesRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) WriteLogEntriesRequest request = new WriteLogEntriesRequest { Entries = { }, }; // Make the request WriteLogEntriesResponse response = await loggingServiceV2Client.WriteLogEntriesAsync(request); // End snippet } /// <summary>Snippet for WriteLogEntries</summary> public void WriteLogEntries_RequestObject() { // Snippet: WriteLogEntries(WriteLogEntriesRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) WriteLogEntriesRequest request = new WriteLogEntriesRequest { Entries = { }, }; // Make the request WriteLogEntriesResponse response = loggingServiceV2Client.WriteLogEntries(request); // End snippet } /// <summary>Snippet for ListLogEntriesAsync</summary> public async Task ListLogEntriesAsync() { // Snippet: ListLogEntriesAsync(IEnumerable<string>,string,string,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) IEnumerable<string> resourceNames = new List<string>(); string filter = ""; string orderBy = ""; // Make the request PagedAsyncEnumerable<ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntriesAsync(resourceNames, filter, orderBy); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogEntry 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((ListLogEntriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { 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<LogEntry> 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 (LogEntry item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogEntries</summary> public void ListLogEntries() { // Snippet: ListLogEntries(IEnumerable<string>,string,string,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) IEnumerable<string> resourceNames = new List<string>(); string filter = ""; string orderBy = ""; // Make the request PagedEnumerable<ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntries(resourceNames, filter, orderBy); // Iterate over all response items, lazily performing RPCs as required foreach (LogEntry 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 (ListLogEntriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { 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<LogEntry> 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 (LogEntry item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogEntriesAsync</summary> public async Task ListLogEntriesAsync_RequestObject() { // Snippet: ListLogEntriesAsync(ListLogEntriesRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) ListLogEntriesRequest request = new ListLogEntriesRequest { ResourceNames = { }, }; // Make the request PagedAsyncEnumerable<ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntriesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogEntry 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((ListLogEntriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { 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<LogEntry> 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 (LogEntry item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogEntries</summary> public void ListLogEntries_RequestObject() { // Snippet: ListLogEntries(ListLogEntriesRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) ListLogEntriesRequest request = new ListLogEntriesRequest { ResourceNames = { }, }; // Make the request PagedEnumerable<ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntries(request); // Iterate over all response items, lazily performing RPCs as required foreach (LogEntry 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 (ListLogEntriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { 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<LogEntry> 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 (LogEntry item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMonitoredResourceDescriptorsAsync</summary> public async Task ListMonitoredResourceDescriptorsAsync_RequestObject() { // Snippet: ListMonitoredResourceDescriptorsAsync(ListMonitoredResourceDescriptorsRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest(); // Make the request PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response = loggingServiceV2Client.ListMonitoredResourceDescriptorsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((MonitoredResourceDescriptor 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((ListMonitoredResourceDescriptorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResourceDescriptor item in page) { 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<MonitoredResourceDescriptor> 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 (MonitoredResourceDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMonitoredResourceDescriptors</summary> public void ListMonitoredResourceDescriptors_RequestObject() { // Snippet: ListMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest(); // Make the request PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response = loggingServiceV2Client.ListMonitoredResourceDescriptors(request); // Iterate over all response items, lazily performing RPCs as required foreach (MonitoredResourceDescriptor 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 (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResourceDescriptor item in page) { 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<MonitoredResourceDescriptor> 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 (MonitoredResourceDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogsAsync</summary> public async Task ListLogsAsync() { // Snippet: ListLogsAsync(ParentNameOneof,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); // Make the request PagedAsyncEnumerable<ListLogsResponse, string> response = loggingServiceV2Client.ListLogsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((string 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((ListLogsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (string item in page) { 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<string> 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 (string item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogs</summary> public void ListLogs() { // Snippet: ListLogs(ParentNameOneof,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); // Make the request PagedEnumerable<ListLogsResponse, string> response = loggingServiceV2Client.ListLogs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (string 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 (ListLogsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (string item in page) { 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<string> 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 (string item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogsAsync</summary> public async Task ListLogsAsync_RequestObject() { // Snippet: ListLogsAsync(ListLogsRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) ListLogsRequest request = new ListLogsRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), }; // Make the request PagedAsyncEnumerable<ListLogsResponse, string> response = loggingServiceV2Client.ListLogsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((string 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((ListLogsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (string item in page) { 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<string> 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 (string item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogs</summary> public void ListLogs_RequestObject() { // Snippet: ListLogs(ListLogsRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) ListLogsRequest request = new ListLogsRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), }; // Make the request PagedEnumerable<ListLogsResponse, string> response = loggingServiceV2Client.ListLogs(request); // Iterate over all response items, lazily performing RPCs as required foreach (string 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 (ListLogsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (string item in page) { 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<string> 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 (string item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal class AttributeNamedParameterCompletionProvider : CommonCompletionProvider { private const string EqualsString = "="; private const string SpaceEqualsString = " ="; private const string ColonString = ":"; internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); } public override async Task ProvideCompletionsAsync(CompletionContext context) { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (!token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken)) { return; } var attributeArgumentList = token.Parent as AttributeArgumentListSyntax; var attributeSyntax = token.Parent.Parent as AttributeSyntax; if (attributeSyntax == null || attributeArgumentList == null) { return; } if (IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token)) { context.IsExclusive = true; } // We actually want to collect two sets of named parameters to present the user. The // normal named parameters that come from the attribute constructors. These will be // presented like "foo:". And also the named parameters that come from the writable // fields/properties in the attribute. These will be presented like "bar =". var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position); var workspace = document.Project.Solution.Workspace; var semanticModel = await document.GetSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false); var nameColonItems = await GetNameColonItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false); var nameEqualsItems = await GetNameEqualsItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false); context.AddItems(nameEqualsItems); // If we're after a name= parameter, then we only want to show name= parameters. // Otherwise, show name: parameters too. if (!IsAfterNameEqualsArgument(token)) { context.AddItems(nameColonItems); } } private bool IsAfterNameColonArgument(SyntaxToken token) { var argumentList = token.Parent as AttributeArgumentListSyntax; if (token.Kind() == SyntaxKind.CommaToken && argumentList != null) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameColon != null) { return true; } } } } return false; } private bool IsAfterNameEqualsArgument(SyntaxToken token) { var argumentList = token.Parent as AttributeArgumentListSyntax; if (token.Kind() == SyntaxKind.CommaToken && argumentList != null) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameEquals != null) { return true; } } } } return false; } private async Task<ImmutableArray<CompletionItem>> GetNameEqualsItemsAsync( CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters) { var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, context.Position, attributeSyntax, context.CancellationToken); var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name)); var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false); var q = from p in attributeNamedParameters where !existingNamedParameters.Contains(p.Name) select SymbolCompletionItem.Create( displayText: p.Name.ToIdentifierToken().ToString() + SpaceEqualsString, insertionText: null, symbol: p, contextPosition: token.SpanStart, sortText: p.Name, rules: CompletionItemRules.Default); return q.ToImmutableArray(); } private async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync( CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters) { var parameterLists = GetParameterLists(semanticModel, context.Position, attributeSyntax, context.CancellationToken); parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters)); var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false); return from pl in parameterLists from p in pl where !existingNamedParameters.Contains(p.Name) select SymbolCompletionItem.Create( displayText: p.Name.ToIdentifierToken().ToString() + ColonString, insertionText: null, symbol: p, contextPosition: token.SpanStart, sortText: p.Name, rules: CompletionItemRules.Default); } public override Task<CompletionDescription> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { return SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); } private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters) { return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty(); } private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position) { var existingArguments1 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameColon != null) .Select(a => a.NameColon.Name.Identifier.ValueText); var existingArguments2 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameEquals != null) .Select(a => a.NameEquals.Name.Identifier.ValueText); return existingArguments1.Concat(existingArguments2).ToSet(); } private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; if (within != null && attributeType != null) { return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within)) .Select(c => c.Parameters); } return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>(); } private IEnumerable<ISymbol> GetAttributeNamedParameters( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within); } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { return Task.FromResult(GetTextChange(selectedItem, ch)); } private TextChange? GetTextChange(CompletionItem selectedItem, char? ch) { var displayText = selectedItem.DisplayText; if (ch != null) { // If user types a space, do not complete the " =" (space and equals) at the end of a named parameter. The // typed space character will be passed through to the editor, and they can then type the '='. if (ch == ' ' && displayText.EndsWith(SpaceEqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - SpaceEqualsString.Length)); } // If the user types '=', do not complete the '=' at the end of the named parameter because the typed '=' // will be passed through to the editor. if (ch == '=' && displayText.EndsWith(EqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - EqualsString.Length)); } // If the user types ':', do not complete the ':' at the end of the named parameter because the typed ':' // will be passed through to the editor. if (ch == ':' && displayText.EndsWith(ColonString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - ColonString.Length)); } } return new TextChange(selectedItem.Span, displayText); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ResourceServer__Web_API_v1_.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }
using LambdicSql.ConverterServices; using LambdicSql.ConverterServices.SymbolConverters; using LambdicSql.Oracle.ConverterAttributes; using LambdicSql.Specialized.SymbolConverters; namespace LambdicSql.Oracle { /// <summary> /// SQL Symbol. /// It can only be used within methods of the LambdicSql.Db class. /// Use[using static LambdicSql.Oracle.Symbol;], you can use to write natural SQL. /// </summary> public static partial class Symbol { /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="T">Type of selected.</typeparam> /// <param name="selected">Specify a new expression to represent the selection.</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<T> Select<T>(T selected) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="TSrc"></typeparam> /// <typeparam name="T">Type of selected.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="selected">Specify a new expression to represent the selection.</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<T> Select<TSrc, T>(this Clause<TSrc> before, T selected) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <param name="asterisk">*</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<Non> Select(AsteriskElement asterisk) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="TSrc">If there is a Select clause before, it is the type selected there. Normally, the Select clause does not exist before the Select clause, and object is specified.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="asterisk">*</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<Non> Select<TSrc>(this Clause<TSrc> before, AsteriskElement asterisk) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="T">Type of selected.</typeparam> /// <param name="asterisk">*</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<T> Select<T>(AsteriskElement<T> asterisk) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="TSrc">If there is a Select clause before, it is the type selected there. Normally, the Select clause does not exist before the Select clause, and object is specified.</typeparam> /// <typeparam name="T">Type of selected.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="asterisk">*</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<T> Select<TSrc, T>(this Clause<TSrc> before, AsteriskElement<T> asterisk) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="T">Type of selected.</typeparam> /// <param name="predicate">ALL or DISTINCT.</param> /// <param name="selected">Specify a new expression to represent the selection.</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<T> Select<T>(AggregatePredicateElement predicate, T selected) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="TSrc">If there is a Select clause before, it is the type selected there. Normally, the Select clause does not exist before the Select clause, and object is specified.</typeparam> /// <typeparam name="T">Type of selected.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="predicate">ALL or DISTINCT.</param> /// <param name="selected">Specify a new expression to represent the selection.</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<T> Select<TSrc, T>(this Clause<TSrc> before, AggregatePredicateElement predicate, T selected) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <param name="predicate">ALL or DISTINCT.</param> /// <param name="asterisk">*</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<Non> Select(AggregatePredicateElement predicate, AsteriskElement asterisk) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="TSrc">If there is a Select clause before, it is the type selected there. Normally, the Select clause does not exist before the Select clause, and object is specified.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="predicate">ALL or DISTINCT.</param> /// <param name="asterisk">*</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<Non> Select<TSrc>(this Clause<TSrc> before, AggregatePredicateElement predicate, AsteriskElement asterisk) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="T">Type of selected.</typeparam> /// <param name="predicate">ALL or DISTINCT.</param> /// <param name="asterisk">*</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<T> Select<T>(AggregatePredicateElement predicate, AsteriskElement<T> asterisk) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// SELECT clause. /// </summary> /// <typeparam name="TSrc">If there is a Select clause before, it is the type selected there. Normally, the Select clause does not exist before the Select clause, and object is specified.</typeparam> /// <typeparam name="T">Type of selected.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="predicate">ALL or DISTINCT.</param> /// <param name="asterisk">*</param> /// <returns>Clause.</returns> [SelectConverter] public static Clause<T> Select<TSrc, T>(this Clause<TSrc> before, AggregatePredicateElement predicate, AsteriskElement<T> asterisk) { throw new InvalitContextException(nameof(Select)); } /// <summary> /// CASE clause. /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Case() { throw new InvalitContextException(nameof(Case)); } /// <summary> /// CASE clause. /// </summary> /// <param name="target">It's target of CASE branch.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Case(object target) { throw new InvalitContextException(nameof(Case)); } /// <summary> /// CASE clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<T> Case<T>() { throw new InvalitContextException(nameof(Case)); } /// <summary> /// CASE clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <param name="target">It's target of CASE branch.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<T> Case<T>(object target) { throw new InvalitContextException(nameof(Case)); } /// <summary> /// WHEN clause. /// </summary> /// <param name="before">It is an before expression in the CASE clause.</param> /// <param name="expression">It is a conditional expression of the WHEN clause.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Indent = 1)] public static Clause<Non> When(this Clause<Non> before, object expression) { throw new InvalitContextException(nameof(When)); } /// <summary> /// WHEN clause. /// </summary> /// <param name="expression">It is a conditional expression of the WHEN clause.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Indent = 1)] public static Clause<Non> When(object expression) { throw new InvalitContextException(nameof(When)); } /// <summary> /// WHEN clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <param name="before">It is an before expression in the CASE clause.</param> /// <param name="expression">It is a conditional expression of the WHEN clause.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Indent = 1)] public static Clause<T> When<T>(this Clause<T> before, object expression) { throw new InvalitContextException(nameof(When)); } /// <summary> /// THEN clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <param name="before">It is an before expression in the CASE clause.</param> /// <param name="result">It is an item to return to when the THEN clause is valid.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Indent = 1)] public static Clause<T> Then<T>(this Clause<Non> before, T result) { throw new InvalitContextException(nameof(Then)); } /// <summary> /// THEN clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <param name="result">It is an item to return to when the THEN clause is valid.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Indent = 1)] public static Clause<T> Then<T>(T result) { throw new InvalitContextException(nameof(Then)); } /// <summary> /// THEN clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <param name="before">It is an before expression in the CASE clause.</param> /// <param name="result">It is an item to return to when the THEN clause is valid.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Indent = 1)] public static Clause<T> Then<T>(this Clause<T> before, T result) { throw new InvalitContextException(nameof(Then)); } /// <summary> /// ELSE clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <param name="before">It is an before expression in the CASE clause.</param> /// <param name="result">It is an item to return to when the ELSE clause is valid.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Indent = 1)] public static Clause<T> Else<T>(this Clause<T> before, T result) { throw new InvalitContextException(nameof(Then)); } /// <summary> /// ELSE clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <param name="result">It is an item to return to when the ELSE clause is valid.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Indent = 1)] public static Clause<T> Else<T>(T result) { throw new InvalitContextException(nameof(Then)); } /// <summary> /// END clause. /// </summary> /// <typeparam name="T">Type represented by CASE expression.</typeparam> /// <param name="before">It is an before expression in the CASE clause.</param> /// <returns>It is the result of CASE expression.</returns> [ClauseStyleConverter] public static T End<T>(this Clause<T> before) { throw new InvalitContextException(nameof(End)); } /// <summary> /// END clause. /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> End() { throw new InvalitContextException(nameof(End)); } /// <summary> /// FROM clause. /// </summary> /// <param name="expressions">Table or subquery.</param> /// <returns>Clause.</returns> [FromConverter] public static Clause<Non> From(params object[] expressions) { throw new InvalitContextException(nameof(From)); } /// <summary> /// FROM clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="tables">Table or subquery.</param> /// <returns>Clause.</returns> [FromConverter] public static Clause<T> From<T>(this Clause<T> before, params object[] tables) { throw new InvalitContextException(nameof(From)); } /// <summary> /// JOIN clause. /// </summary> /// <param name="table">Table or subquery.</param> /// <param name="condition">It is a condition of JOIN.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "JOIN")] public static Clause<Non> Join(object table, bool condition) { throw new InvalitContextException(nameof(Join)); } /// <summary> /// JOIN clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="table">Table or subquery.</param> /// <param name="condition">It is a condition of JOIN.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "JOIN")] public static Clause<T> Join<T>(this Clause<T> before, object table, bool condition) { throw new InvalitContextException(nameof(Join)); } /// <summary> /// JOIN clause. /// </summary> /// <param name="table">Table or subquery.</param> /// <param name="condition">It is a condition of LEFT JOIN.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "LEFT JOIN")] public static Clause<Non> LeftJoin(object table, bool condition) { throw new InvalitContextException(nameof(LeftJoin)); } /// <summary> /// LEFT JOIN clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="table">Table or subquery.</param> /// <param name="condition">It is a condition of LEFT JOIN.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "LEFT JOIN")] public static Clause<T> LeftJoin<T>(this Clause<T> before, object table, bool condition) { throw new InvalitContextException(nameof(LeftJoin)); } /// <summary> /// RIGHT JOIN clause. /// </summary> /// <param name="table">Table or subquery.</param> /// <param name="condition">It is a condition of RIGHT JOIN.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "RIGHT JOIN")] public static Clause<Non> RightJoin(object table, bool condition) { throw new InvalitContextException(nameof(RightJoin)); } /// <summary> /// RIGHT JOIN clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="table">Table or subquery.</param>> /// <param name="condition">It is a condition of RIGHT JOIN.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "RIGHT JOIN")] public static Clause<T> RightJoin<T>(this Clause<T> before, object table, bool condition) { throw new InvalitContextException(nameof(RightJoin)); } /// <summary> /// FULL JOIN clause. /// </summary> /// <param name="table">Table or subquery.</param> /// <param name="condition">It is a condition of RIGHT JOIN.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "FULL JOIN")] public static Clause<Non> FullJoin(object table, bool condition) { throw new InvalitContextException(nameof(FullJoin)); } /// <summary> /// FULL JOIN clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="table">Table or subquery.</param>> /// <param name="condition">It is a condition of RIGHT JOIN.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "FULL JOIN")] public static Clause<T> FullJoin<T>(this Clause<T> before, object table, bool condition) { throw new InvalitContextException(nameof(FullJoin)); } /// <summary> /// CROSS JOIN clause. /// </summary> /// <param name="expression">Table or subquery.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "CROSS JOIN")] public static Clause<Non> CrossJoin(object expression) { throw new InvalitContextException(nameof(CrossJoin)); } /// <summary> /// CROSS JOIN clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="table">Table or subquery.</param> /// <returns>Clause.</returns> [JoinConverter(Name = "CROSS JOIN")] public static Clause<T> CrossJoin<T>(this Clause<T> before, object table) { throw new InvalitContextException(nameof(CrossJoin)); } /// <summary> /// WHERE clause. /// </summary> /// <param name="condition">It is a conditional expression of WHERE.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "WHERE [0]", VanishIfEmptyParams = true)] public static Clause<Non> Where(bool condition) { throw new InvalitContextException(nameof(Where)); } /// <summary> /// WHERE clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="condition">It is a conditional expression of WHERE.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "WHERE [1]", VanishIfEmptyParams = true)] public static Clause<T> Where<T>(this Clause<T> before, bool condition) { throw new InvalitContextException(nameof(Where)); } /// <summary> /// GROUP BY clause. /// </summary> /// <param name="columns">Specify the target column of GROUP BY.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Name = "GROUP BY")] public static Clause<Non> GroupBy(params object[] columns) { throw new InvalitContextException(nameof(GroupBy)); } /// <summary> /// GROUP BY clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="columns">Specify the target column of GROUP BY.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Name = "GROUP BY")] public static Clause<T> GroupBy<T>(this Clause<T> before, params object[] columns) { throw new InvalitContextException(nameof(GroupBy)); } /// <summary> /// GROUP BY ROLLUP clause. /// </summary> /// <param name="columns">Specify the target column of GROUP BY.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "GROUP BY ROLLUP")] public static Clause<Non> GroupByRollup(params object[] columns) { throw new InvalitContextException(nameof(GroupByRollup)); } /// <summary> /// GROUP BY ROLLUP clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="columns">Specify the target column of GROUP BY.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "GROUP BY ROLLUP")] public static Clause<T> GroupByRollup<T>(this Clause<T> before, params object[] columns) { throw new InvalitContextException(nameof(GroupByRollup)); } /// <summary> /// GROUP BY CUBE clause. /// </summary> /// <param name="columns">Specify the target column of GROUP BY.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "GROUP BY CUBE")] public static Clause<Non> GroupByCube(params object[] columns) { throw new InvalitContextException(nameof(GroupByCube)); } /// <summary> /// GROUP BY CUBE clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="columns">Specify the target column of GROUP BY.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "GROUP BY CUBE")] public static Clause<T> GroupByCube<T>(this Clause<T> before, params object[] columns) { throw new InvalitContextException(nameof(GroupByCube)); } /// <summary> /// GROUP BY GROUPING SETS clause. /// </summary> /// <param name="columns">Specify the target column of GROUP BY.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "GROUP BY GROUPING SETS")] public static Clause<Non> GroupByGroupingSets(params object[] columns) { throw new InvalitContextException(nameof(GroupByGroupingSets)); } /// <summary> /// GROUP BY GROUPING SETS clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="columns">Specify the target column of GROUP BY.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "GROUP BY GROUPING SETS")] public static Clause<T> GroupByGroupingSets<T>(this Clause<T> before, params object[] columns) { throw new InvalitContextException(nameof(GroupByGroupingSets)); } /// <summary> /// HAVING clause. /// </summary> /// <param name="condition">It is a conditional expression of HAVING.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "HAVING [0]", VanishIfEmptyParams = true)] public static Clause<Non> Having(bool condition) { throw new InvalitContextException(nameof(Having)); } /// <summary> /// HAVING clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="condition">It is a conditional expression of HAVING.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "HAVING [1]", VanishIfEmptyParams = true)] public static Clause<T> Having<T>(this Clause<T> before, bool condition) { throw new InvalitContextException(nameof(Having)); } /// <summary> /// ORDER BY clause. /// </summary> /// <param name="elements">Specify column and sort order. Asc(column) or Desc(column).</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "ORDER BY |[<, >0]", FormatDirection = FormatDirection.Vertical, VanishIfEmptyParams = true)] public static Clause<OverElement> OrderBy(params OrderByElement[] elements) { throw new InvalitContextException(nameof(OrderBy)); } /// <summary> /// ORDER BY clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="elements">Specify column and sort order. Asc(column) or Desc(column).</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "ORDER BY |[<, >1]", FormatDirection = FormatDirection.Vertical, VanishIfEmptyParams = true)] public static Clause<T> OrderBy<T>(this Clause<T> before, params OrderByElement[] elements) { throw new InvalitContextException(nameof(OrderBy)); } /// <summary> /// UNION clause. /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Union() { throw new InvalitContextException(nameof(Union)); } /// <summary> /// UNION clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<T> Union<T>(this Clause<T> before) { throw new InvalitContextException(nameof(Union)); } /// <summary> /// UNION clause. /// </summary> /// <param name="all">If isAll is true, add an ALL predicate.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Union(AggregatePredicateAllElement all) { throw new InvalitContextException(nameof(Union)); } /// <summary> /// UNION clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="all">If isAll is true, add an ALL predicate.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<T> Union<T>(this Clause<T> before, AggregatePredicateAllElement all) { throw new InvalitContextException(nameof(Union)); } /// <summary> /// INTERSECT clause. /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Intersect() { throw new InvalitContextException(nameof(Intersect)); } /// <summary> /// INTERSECT clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<T> Intersect<T>(this Clause<T> before) { throw new InvalitContextException(nameof(Intersect)); } /// <summary> /// INTERSECT clause. /// </summary> /// <param name="all">If isAll is true, add an ALL predicate.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Intersect(AggregatePredicateAllElement all) { throw new InvalitContextException(nameof(Intersect)); } /// <summary> /// INTERSECT clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="all">If isAll is true, add an ALL predicate.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<T> Intersect<T>(this Clause<T> before, AggregatePredicateAllElement all) { throw new InvalitContextException(nameof(Intersect)); } /// <summary> /// MINUS clause. /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Minus() { throw new InvalitContextException(nameof(Minus)); } /// <summary> /// MINUS clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<T> Minus<T>(this Clause<T> before) { throw new InvalitContextException(nameof(Minus)); } /// <summary> /// UPDATE clause. /// </summary> /// <param name="table">Table for UPDATE.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Update(object table) { throw new InvalitContextException(nameof(Update)); } /// <summary> /// SET clause. /// </summary> /// <param name="assigns">Assignment in the SET clause.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "SET |[<,>0]", FormatDirection = FormatDirection.Vertical)] public static Clause<Non> Set(params Assign[] assigns) { throw new InvalitContextException(nameof(Set)); } /// <summary> /// SET clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="assigns">Assignment in the SET clause.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "SET |[<,>1]", FormatDirection = FormatDirection.Vertical)] public static Clause<T> Set<T>(this Clause<T> before, params Assign[] assigns) { throw new InvalitContextException(nameof(Set)); } /// <summary> /// DELETE clause. /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> Delete() { throw new InvalitContextException(nameof(Delete)); } /// <summary> /// INSERT INTO clause. /// </summary> /// <param name="table">Table for INSERT.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Name = "INSERT INTO")] public static Clause<Non> InsertInto(object table) { throw new InvalitContextException(nameof(InsertInto)); } /// <summary> /// INSERT INTO clause. /// </summary> /// <param name="table">Table for INSERT.</param> /// <param name="columns">It is a column that performs INSERT.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "INSERT INTO [0](|[#<, >1])")] public static Clause<Non> InsertInto(object table, params object[] columns) { throw new InvalitContextException(nameof(InsertInto)); } /// <summary> /// INSERT INTO clause. /// </summary> /// <param name="values">It is the value to be Inserted.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Indent = 1)] public static Clause<Non> Values(params object[] values) { throw new InvalitContextException(nameof(Values)); } /// <summary> /// INSERT INTO clause. /// </summary> /// <typeparam name="T">The type represented by before clause.</typeparam> /// <param name="before">It is the previous clause.</param> /// <param name="values">It is the value to be Inserted.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Indent = 1)] public static Clause<T> Values<T>(this Clause<T> before, params object[] values) { throw new InvalitContextException(nameof(Values)); } /// <summary> /// LIKE keyword. /// </summary> /// <param name="target">Target text.</param> /// <param name="pattern">Text that represents pattern matching.</param> /// <returns>If target matches the specified pattern, LIKE returns TRUE.</returns> [MethodFormatConverter(Format = "[0] LIKE |[1]")] public static bool Like(object target, object pattern) { throw new InvalitContextException(nameof(Like)); } /// <summary> /// BETWEEN keyword. /// </summary> /// <param name="target">Target of range check.</param> /// <param name="min">Minimum value.</param> /// <param name="max">Maxmum value.</param> /// <returns>Returns TRUE if target is included in the range of min and max.</returns> [MethodFormatConverter(Format = "[0] BETWEEN |[1] AND [2]")] public static bool Between(object target, object min, object max) { throw new InvalitContextException(nameof(Between)); } /// <summary> /// IN keyword. /// </summary> /// <param name="target">Target of IN check.</param> /// <param name="canditates">Canditates.</param> /// <returns>Returns TRUE if target is included in the canditates represented by expression.</returns> [MethodFormatConverter(Format = "[0] IN(|[<, >1])")] public static bool In<T>(T target, params T[] canditates) { throw new InvalitContextException(nameof(In)); } /// <summary> /// ALL Keyword /// </summary> /// <typeparam name="T">Retunn type.</typeparam> /// <param name="sub">Sub query.</param> /// <returns>Sub query's selected value.</returns> [FuncStyleConverter] public static T All<T>(Clause<T> sub) { throw new InvalitContextException(nameof(All)); } /// <summary> /// ALL Keyword /// </summary> /// <typeparam name="T">Retunn type.</typeparam> /// <param name="sub">Sub query.</param> /// <returns>Sub query's selected value.</returns> [FuncStyleConverter] public static T All<T>(Sql<T> sub) { throw new InvalitContextException(nameof(All)); } /// <summary> /// EXISTS keyword. /// </summary> /// <param name="expression">Sub query.</param> /// <returns>Returns TRUE if there is at least one record returned by expression, FALSE otherwise.</returns> [ClauseStyleConverter] public static bool Exists(object expression) { throw new InvalitContextException(nameof(Exists)); } /// <summary> /// IS NULL clause. /// </summary> /// <param name="target"></param> /// <returns>IS NULL</returns> [MethodFormatConverter(Format = "[0] IS NULL|")] public static bool IsNull(object target) { throw new InvalitContextException(nameof(IsNull)); } /// <summary> /// IS NOT NULL clause. /// </summary> /// <param name="target">target.</param> /// <returns>IS NOT NULL</returns> [MethodFormatConverter(Format = "[0] IS NOT NULL|")] public static bool IsNotNull(object target) { throw new InvalitContextException(nameof(IsNotNull)); } /// <summary> /// WITH clause. /// </summary> /// <param name="subQuerys">sub querys.</param> /// <returns></returns> [WithConverter] public static Clause<Non> With(params Sql[] subQuerys) { throw new InvalitContextException(nameof(With)); } /// <summary> /// WITH clause. /// </summary> /// <typeparam name="T">Type representing argument of recursive part.</typeparam> /// <param name="args">Argument of recursive part.</param> /// <param name="subQuery">sub query.</param> /// <returns>Clause.</returns> [WithConverter] public static Clause<T> With<T>(SqlRecursiveArguments<T> args, Sql subQuery) { throw new InvalitContextException(nameof(With)); } /// <summary> /// It becomes code which expanded T's property as argument. For example, data(a, b,c). /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns>IArgumentsExpandedObject.</returns> [ExpandArgumentsConverter] public static IArgumentsExpandedObject ExpandArguments<T>(this Sql<T> data) => throw new InvalitContextException(nameof(ExpandArguments)); /// <summary> /// AS /// </summary> /// <typeparam name="T">before type.</typeparam> /// <param name="before">AS clause before.</param> /// <param name="expression">As clause after expression.</param> /// <returns>T</returns> [ClauseStyleConverter] public static T As<T>(this T before, object expression) => throw new InvalitContextException(nameof(As)); /// <summary> /// WITH clause. /// </summary> /// <param name="expression">Argument of recursive part.</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<Non> With(IArgumentsExpandedObject expression) => throw new InvalitContextException(nameof(With)); /// <summary> /// CREATE TABLE clause. /// </summary> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "CREATE TABLE [0](|[#$<,>1])", FormatDirection = FormatDirection.Vertical)] public static Clause<Non> CreateTable(object table, params TableDefinitionElement[] designer) { throw new InvalitContextException(nameof(CreateTable)); } /// <summary> /// CONSTRAINT clause. /// </summary> /// <param name="name">Constraint name.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "CONSTRAINT [!0]")] public static Clause<ConstraintElement> Constraint(string name) { throw new InvalitContextException(nameof(Constraint)); } /// <summary> /// PRIMARY KEY clause. /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter(Name = "PRIMARY KEY")] public static Clause<ConstraintElement> PrimaryKey() { throw new InvalitContextException(nameof(PrimaryKey)); } /// <summary> /// PRIMARY KEY clause. /// </summary> /// <param name="columns">Columns.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "PRIMARY KEY")] public static Clause<ConstraintElement> PrimaryKey(params object[] columns) { throw new InvalitContextException(nameof(PrimaryKey)); } /// <summary> /// PRIMARY KEY clause. /// </summary> /// <param name="before">It is the previous clause.</param> /// <param name="columns">Columns.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "PRIMARY KEY", Indent = 1)] public static Clause<ConstraintElement> PrimaryKey(this Clause<ConstraintElement> before, params object[] columns) { throw new InvalitContextException(nameof(PrimaryKey)); } /// <summary> /// CHECK clause. /// </summary> /// <param name="condition">Condition.</param> /// <returns>Clause.</returns> [FuncStyleConverter] public static Clause<ConstraintElement> Check(bool condition) { throw new InvalitContextException(nameof(Check)); } /// <summary> /// CHECK clause. /// </summary> /// <param name="before">It is the previous clause.</param> /// <param name="condition">Condition.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Indent = 1)] public static Clause<ConstraintElement> Check(this Clause<ConstraintElement> before, bool condition) { throw new InvalitContextException(nameof(Check)); } /// <summary> /// UNIQUE clause. /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<ConstraintElement> Unique() { throw new InvalitContextException(nameof(Unique)); } /// <summary> /// UNIQUE clause. /// </summary> /// <param name="columns">Columns.</param> /// <returns>Clause.</returns> [FuncStyleConverter] public static Clause<ConstraintElement> Unique(params object[] columns) { throw new InvalitContextException(nameof(Unique)); } /// <summary> /// UNIQUE clause. /// </summary> /// <param name="before">It is the previous clause.</param> /// <param name="columns">Columns.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Indent = 1)] public static Clause<ConstraintElement> Unique(this Clause<ConstraintElement> before, params object[] columns) { throw new InvalitContextException(nameof(Unique)); } /// <summary> /// FOREIGN KEY clause. /// </summary> /// <param name="columns">Columns.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "FOREIGN KEY")] public static Clause<ConstraintElement> ForeignKey(params object[] columns) { throw new InvalitContextException(nameof(ForeignKey)); } /// <summary> /// FOREIGN KEY clause. /// </summary> /// <param name="before">It is the previous clause.</param> /// <param name="columns">Columns.</param> /// <returns>Clause.</returns> [FuncStyleConverter(Name = "FOREIGN KEY", Indent = 1)] public static Clause<ConstraintElement> ForeignKey(this Clause<ConstraintElement> before, params object[] columns) { throw new InvalitContextException(nameof(ForeignKey)); } /// <summary> /// NOT NULL /// </summary> /// <returns>Clause.</returns> [ClauseStyleConverter(Name = "NOT NULL")] public static Clause<ConstraintElement> NotNull() { throw new InvalitContextException(nameof(NotNull)); } /// <summary> /// DEFAULT /// </summary> /// <param name="value">value</param> /// <returns>Clause.</returns> [ClauseStyleConverter] public static Clause<ConstraintElement> Default(object value) { throw new InvalitContextException(nameof(Default)); } /// <summary> /// REFERENCES clause. /// </summary> /// <param name="before">It is the previous clause.</param> /// <param name="table">Table.</param> /// <param name="columns">Columns.</param> /// <returns>Clause.</returns> [MethodFormatConverter(Format = "REFERENCES [1](|[<, >2])", Indent = 1)] public static Clause<ConstraintElement> References(this Clause<ConstraintElement> before, object table, params object[] columns) { throw new InvalitContextException(nameof(References)); } /// <summary> /// DROP TABLE clause. /// </summary> /// <param name="tables">Tables.</param> /// <returns>Clause.</returns> [ClauseStyleConverter(Name = "DROP TABLE")] public static Clause<Non> DropTable(params object[] tables) { throw new InvalitContextException(nameof(DropTable)); } } }
using System; using System.Collections; using Raksha.Asn1; using Raksha.Asn1.X509; using Raksha.Utilities; using Raksha.Utilities.Collections; namespace Raksha.Pkix { public class PkixNameConstraintValidator { private ISet excludedSubtreesDN = new HashSet(); private ISet excludedSubtreesDNS = new HashSet(); private ISet excludedSubtreesEmail = new HashSet(); private ISet excludedSubtreesURI = new HashSet(); private ISet excludedSubtreesIP = new HashSet(); private ISet permittedSubtreesDN; private ISet permittedSubtreesDNS; private ISet permittedSubtreesEmail; private ISet permittedSubtreesURI; private ISet permittedSubtreesIP; public PkixNameConstraintValidator() { } private static bool WithinDNSubtree( Asn1Sequence dns, Asn1Sequence subtree) { if (subtree.Count < 1) { return false; } if (subtree.Count > dns.Count) { return false; } for (int j = subtree.Count - 1; j >= 0; j--) { if (!(subtree[j].Equals(dns[j]))) { return false; } } return true; } public void CheckPermittedDN(Asn1Sequence dns) //throws PkixNameConstraintValidatorException { CheckPermittedDN(permittedSubtreesDN, dns); } public void CheckExcludedDN(Asn1Sequence dns) //throws PkixNameConstraintValidatorException { CheckExcludedDN(excludedSubtreesDN, dns); } private void CheckPermittedDN(ISet permitted, Asn1Sequence dns) //throws PkixNameConstraintValidatorException { if (permitted == null) { return; } if ((permitted.Count == 0) && dns.Count == 0) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)it.Current; if (WithinDNSubtree(dns, subtree)) { return; } } throw new PkixNameConstraintValidatorException( "Subject distinguished name is not from a permitted subtree"); } private void CheckExcludedDN(ISet excluded, Asn1Sequence dns) //throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)it.Current; if (WithinDNSubtree(dns, subtree)) { throw new PkixNameConstraintValidatorException( "Subject distinguished name is from an excluded subtree"); } } } private ISet IntersectDN(ISet permitted, ISet dns) { ISet intersect = new HashSet(); for (IEnumerator it = dns.GetEnumerator(); it.MoveNext(); ) { Asn1Sequence dn = Asn1Sequence.GetInstance(((GeneralSubtree)it .Current).Base.Name.ToAsn1Object()); if (permitted == null) { if (dn != null) { intersect.Add(dn); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)_iter.Current; if (WithinDNSubtree(dn, subtree)) { intersect.Add(dn); } else if (WithinDNSubtree(subtree, dn)) { intersect.Add(subtree); } } } } return intersect; } private ISet UnionDN(ISet excluded, Asn1Sequence dn) { if (excluded.IsEmpty) { if (dn == null) { return excluded; } excluded.Add(dn); return excluded; } else { ISet intersect = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)it.Current; if (WithinDNSubtree(dn, subtree)) { intersect.Add(subtree); } else if (WithinDNSubtree(subtree, dn)) { intersect.Add(dn); } else { intersect.Add(subtree); intersect.Add(dn); } } return intersect; } } private ISet IntersectEmail(ISet permitted, ISet emails) { ISet intersect = new HashSet(); for (IEnumerator it = emails.GetEnumerator(); it.MoveNext(); ) { String email = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (email != null) { intersect.Add(email); } } else { IEnumerator it2 = permitted.GetEnumerator(); while (it2.MoveNext()) { String _permitted = (String)it2.Current; intersectEmail(email, _permitted, intersect); } } } return intersect; } private ISet UnionEmail(ISet excluded, String email) { if (excluded.IsEmpty) { if (email == null) { return excluded; } excluded.Add(email); return excluded; } else { ISet union = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { String _excluded = (String)it.Current; unionEmail(_excluded, email, union); } return union; } } /** * Returns the intersection of the permitted IP ranges in * <code>permitted</code> with <code>ip</code>. * * @param permitted A <code>Set</code> of permitted IP addresses with * their subnet mask as byte arrays. * @param ips The IP address with its subnet mask. * @return The <code>Set</code> of permitted IP ranges intersected with * <code>ip</code>. */ private ISet IntersectIP(ISet permitted, ISet ips) { ISet intersect = new HashSet(); for (IEnumerator it = ips.GetEnumerator(); it.MoveNext(); ) { byte[] ip = Asn1OctetString.GetInstance( ((GeneralSubtree)it.Current).Base.Name).GetOctets(); if (permitted == null) { if (ip != null) { intersect.Add(ip); } } else { IEnumerator it2 = permitted.GetEnumerator(); while (it2.MoveNext()) { byte[] _permitted = (byte[])it2.Current; intersect.AddAll(IntersectIPRange(_permitted, ip)); } } } return intersect; } /** * Returns the union of the excluded IP ranges in <code>excluded</code> * with <code>ip</code>. * * @param excluded A <code>Set</code> of excluded IP addresses with their * subnet mask as byte arrays. * @param ip The IP address with its subnet mask. * @return The <code>Set</code> of excluded IP ranges unified with * <code>ip</code> as byte arrays. */ private ISet UnionIP(ISet excluded, byte[] ip) { if (excluded.IsEmpty) { if (ip == null) { return excluded; } excluded.Add(ip); return excluded; } else { ISet union = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { byte[] _excluded = (byte[])it.Current; union.AddAll(UnionIPRange(_excluded, ip)); } return union; } } /** * Calculates the union if two IP ranges. * * @param ipWithSubmask1 The first IP address with its subnet mask. * @param ipWithSubmask2 The second IP address with its subnet mask. * @return A <code>Set</code> with the union of both addresses. */ private ISet UnionIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) { ISet set = new HashSet(); // difficult, adding always all IPs is not wrong if (Arrays.AreEqual(ipWithSubmask1, ipWithSubmask2)) { set.Add(ipWithSubmask1); } else { set.Add(ipWithSubmask1); set.Add(ipWithSubmask2); } return set; } /** * Calculates the interesction if two IP ranges. * * @param ipWithSubmask1 The first IP address with its subnet mask. * @param ipWithSubmask2 The second IP address with its subnet mask. * @return A <code>Set</code> with the single IP address with its subnet * mask as a byte array or an empty <code>Set</code>. */ private ISet IntersectIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) { if (ipWithSubmask1.Length != ipWithSubmask2.Length) { //Collections.EMPTY_SET; return new HashSet(); } byte[][] temp = ExtractIPsAndSubnetMasks(ipWithSubmask1, ipWithSubmask2); byte[] ip1 = temp[0]; byte[] subnetmask1 = temp[1]; byte[] ip2 = temp[2]; byte[] subnetmask2 = temp[3]; byte[][] minMax = MinMaxIPs(ip1, subnetmask1, ip2, subnetmask2); byte[] min; byte[] max; max = Min(minMax[1], minMax[3]); min = Max(minMax[0], minMax[2]); // minimum IP address must be bigger than max if (CompareTo(min, max) == 1) { //return Collections.EMPTY_SET; return new HashSet(); } // OR keeps all significant bits byte[] ip = Or(minMax[0], minMax[2]); byte[] subnetmask = Or(subnetmask1, subnetmask2); //return new HashSet( ICollectionsingleton(IpWithSubnetMask(ip, subnetmask)); ISet hs = new HashSet(); hs.Add(IpWithSubnetMask(ip, subnetmask)); return hs; } /** * Concatenates the IP address with its subnet mask. * * @param ip The IP address. * @param subnetMask Its subnet mask. * @return The concatenated IP address with its subnet mask. */ private byte[] IpWithSubnetMask(byte[] ip, byte[] subnetMask) { int ipLength = ip.Length; byte[] temp = new byte[ipLength * 2]; Array.Copy(ip, 0, temp, 0, ipLength); Array.Copy(subnetMask, 0, temp, ipLength, ipLength); return temp; } /** * Splits the IP addresses and their subnet mask. * * @param ipWithSubmask1 The first IP address with the subnet mask. * @param ipWithSubmask2 The second IP address with the subnet mask. * @return An array with two elements. Each element contains the IP address * and the subnet mask in this order. */ private byte[][] ExtractIPsAndSubnetMasks( byte[] ipWithSubmask1, byte[] ipWithSubmask2) { int ipLength = ipWithSubmask1.Length / 2; byte[] ip1 = new byte[ipLength]; byte[] subnetmask1 = new byte[ipLength]; Array.Copy(ipWithSubmask1, 0, ip1, 0, ipLength); Array.Copy(ipWithSubmask1, ipLength, subnetmask1, 0, ipLength); byte[] ip2 = new byte[ipLength]; byte[] subnetmask2 = new byte[ipLength]; Array.Copy(ipWithSubmask2, 0, ip2, 0, ipLength); Array.Copy(ipWithSubmask2, ipLength, subnetmask2, 0, ipLength); return new byte[][] {ip1, subnetmask1, ip2, subnetmask2}; } /** * Based on the two IP addresses and their subnet masks the IP range is * computed for each IP address - subnet mask pair and returned as the * minimum IP address and the maximum address of the range. * * @param ip1 The first IP address. * @param subnetmask1 The subnet mask of the first IP address. * @param ip2 The second IP address. * @param subnetmask2 The subnet mask of the second IP address. * @return A array with two elements. The first/second element contains the * min and max IP address of the first/second IP address and its * subnet mask. */ private byte[][] MinMaxIPs( byte[] ip1, byte[] subnetmask1, byte[] ip2, byte[] subnetmask2) { int ipLength = ip1.Length; byte[] min1 = new byte[ipLength]; byte[] max1 = new byte[ipLength]; byte[] min2 = new byte[ipLength]; byte[] max2 = new byte[ipLength]; for (int i = 0; i < ipLength; i++) { min1[i] = (byte)(ip1[i] & subnetmask1[i]); max1[i] = (byte)(ip1[i] & subnetmask1[i] | ~subnetmask1[i]); min2[i] = (byte)(ip2[i] & subnetmask2[i]); max2[i] = (byte)(ip2[i] & subnetmask2[i] | ~subnetmask2[i]); } return new byte[][] { min1, max1, min2, max2 }; } private void CheckPermittedEmail(ISet permitted, String email) //throws PkixNameConstraintValidatorException { if (permitted == null) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { String str = ((String)it.Current); if (EmailIsConstrained(email, str)) { return; } } if (email.Length == 0 && permitted.Count == 0) { return; } throw new PkixNameConstraintValidatorException( "Subject email address is not from a permitted subtree."); } private void CheckExcludedEmail(ISet excluded, String email) //throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { String str = (String)it.Current; if (EmailIsConstrained(email, str)) { throw new PkixNameConstraintValidatorException( "Email address is from an excluded subtree."); } } } /** * Checks if the IP <code>ip</code> is included in the permitted ISet * <code>permitted</code>. * * @param permitted A <code>Set</code> of permitted IP addresses with * their subnet mask as byte arrays. * @param ip The IP address. * @throws PkixNameConstraintValidatorException * if the IP is not permitted. */ private void CheckPermittedIP(ISet permitted, byte[] ip) //throws PkixNameConstraintValidatorException { if (permitted == null) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { byte[] ipWithSubnet = (byte[])it.Current; if (IsIPConstrained(ip, ipWithSubnet)) { return; } } if (ip.Length == 0 && permitted.Count == 0) { return; } throw new PkixNameConstraintValidatorException( "IP is not from a permitted subtree."); } /** * Checks if the IP <code>ip</code> is included in the excluded ISet * <code>excluded</code>. * * @param excluded A <code>Set</code> of excluded IP addresses with their * subnet mask as byte arrays. * @param ip The IP address. * @throws PkixNameConstraintValidatorException * if the IP is excluded. */ private void checkExcludedIP(ISet excluded, byte[] ip) //throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { byte[] ipWithSubnet = (byte[])it.Current; if (IsIPConstrained(ip, ipWithSubnet)) { throw new PkixNameConstraintValidatorException( "IP is from an excluded subtree."); } } } /** * Checks if the IP address <code>ip</code> is constrained by * <code>constraint</code>. * * @param ip The IP address. * @param constraint The constraint. This is an IP address concatenated with * its subnetmask. * @return <code>true</code> if constrained, <code>false</code> * otherwise. */ private bool IsIPConstrained(byte[] ip, byte[] constraint) { int ipLength = ip.Length; if (ipLength != (constraint.Length / 2)) { return false; } byte[] subnetMask = new byte[ipLength]; Array.Copy(constraint, ipLength, subnetMask, 0, ipLength); byte[] permittedSubnetAddress = new byte[ipLength]; byte[] ipSubnetAddress = new byte[ipLength]; // the resulting IP address by applying the subnet mask for (int i = 0; i < ipLength; i++) { permittedSubnetAddress[i] = (byte)(constraint[i] & subnetMask[i]); ipSubnetAddress[i] = (byte)(ip[i] & subnetMask[i]); } return Arrays.AreEqual(permittedSubnetAddress, ipSubnetAddress); } private bool EmailIsConstrained(String email, String constraint) { String sub = email.Substring(email.IndexOf('@') + 1); // a particular mailbox if (constraint.IndexOf('@') != -1) { if (email.ToUpper().Equals(constraint.ToUpper())) { return true; } } // on particular host else if (!(constraint[0].Equals('.'))) { if (sub.ToUpper().Equals(constraint.ToUpper())) { return true; } } // address in sub domain else if (WithinDomain(sub, constraint)) { return true; } return false; } private bool WithinDomain(String testDomain, String domain) { String tempDomain = domain; if (tempDomain.StartsWith(".")) { tempDomain = tempDomain.Substring(1); } String[] domainParts = tempDomain.Split('.'); // Strings.split(tempDomain, '.'); String[] testDomainParts = testDomain.Split('.'); // Strings.split(testDomain, '.'); // must have at least one subdomain if (testDomainParts.Length <= domainParts.Length) { return false; } int d = testDomainParts.Length - domainParts.Length; for (int i = -1; i < domainParts.Length; i++) { if (i == -1) { if (testDomainParts[i + d].Equals("")) { return false; } } else if (!(Platform.CompareIgnoreCase(testDomainParts[i + d], domainParts[i]) == 0)) { return false; } } return true; } private void CheckPermittedDNS(ISet permitted, String dns) //throws PkixNameConstraintValidatorException { if (permitted == null) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { String str = ((String)it.Current); // is sub domain if (WithinDomain(dns, str) || dns.ToUpper().Equals(str.ToUpper())) { return; } } if (dns.Length == 0 && permitted.Count == 0) { return; } throw new PkixNameConstraintValidatorException( "DNS is not from a permitted subtree."); } private void checkExcludedDNS(ISet excluded, String dns) // throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { String str = ((String)it.Current); // is sub domain or the same if (WithinDomain(dns, str) || (Platform.CompareIgnoreCase(dns, str) == 0)) { throw new PkixNameConstraintValidatorException( "DNS is from an excluded subtree."); } } } /** * The common part of <code>email1</code> and <code>email2</code> is * added to the union <code>union</code>. If <code>email1</code> and * <code>email2</code> have nothing in common they are added both. * * @param email1 Email address constraint 1. * @param email2 Email address constraint 2. * @param union The union. */ private void unionEmail(String email1, String email2, ISet union) { // email1 is a particular address if (email1.IndexOf('@') != -1) { String _sub = email1.Substring(email1.IndexOf('@') + 1); // both are a particular mailbox if (email2.IndexOf('@') != -1) { if (Platform.CompareIgnoreCase(email1, email2) == 0) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(_sub, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a particular host else { if (Platform.CompareIgnoreCase(_sub, email2) == 0) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } } // email1 specifies a domain else if (email1.StartsWith(".")) { if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email1.IndexOf('@') + 1); if (WithinDomain(_sub, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(email1, email2) || Platform.CompareIgnoreCase(email1, email2) == 0) { union.Add(email2); } else if (WithinDomain(email2, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } else { if (WithinDomain(email2, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } } // email specifies a host else { if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email1.IndexOf('@') + 1); if (Platform.CompareIgnoreCase(_sub, email1) == 0) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(email1, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a particular host else { if (Platform.CompareIgnoreCase(email1, email2) == 0) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } } } private void unionURI(String email1, String email2, ISet union) { // email1 is a particular address if (email1.IndexOf('@') != -1) { String _sub = email1.Substring(email1.IndexOf('@') + 1); // both are a particular mailbox if (email2.IndexOf('@') != -1) { if (Platform.CompareIgnoreCase(email1, email2) == 0) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(_sub, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a particular host else { if (Platform.CompareIgnoreCase(_sub, email2) == 0) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } } // email1 specifies a domain else if (email1.StartsWith(".")) { if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email1.IndexOf('@') + 1); if (WithinDomain(_sub, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(email1, email2) || Platform.CompareIgnoreCase(email1, email2) == 0) { union.Add(email2); } else if (WithinDomain(email2, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } else { if (WithinDomain(email2, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } } // email specifies a host else { if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email1.IndexOf('@') + 1); if (Platform.CompareIgnoreCase(_sub, email1) == 0) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(email1, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a particular host else { if (Platform.CompareIgnoreCase(email1, email2) == 0) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } } } private ISet intersectDNS(ISet permitted, ISet dnss) { ISet intersect = new HashSet(); for (IEnumerator it = dnss.GetEnumerator(); it.MoveNext(); ) { String dns = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (dns != null) { intersect.Add(dns); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { String _permitted = (String)_iter.Current; if (WithinDomain(_permitted, dns)) { intersect.Add(_permitted); } else if (WithinDomain(dns, _permitted)) { intersect.Add(dns); } } } } return intersect; } protected ISet unionDNS(ISet excluded, String dns) { if (excluded.IsEmpty) { if (dns == null) { return excluded; } excluded.Add(dns); return excluded; } else { ISet union = new HashSet(); IEnumerator _iter = excluded.GetEnumerator(); while (_iter.MoveNext()) { String _permitted = (String)_iter.Current; if (WithinDomain(_permitted, dns)) { union.Add(dns); } else if (WithinDomain(dns, _permitted)) { union.Add(_permitted); } else { union.Add(_permitted); union.Add(dns); } } return union; } } /** * The most restricting part from <code>email1</code> and * <code>email2</code> is added to the intersection <code>intersect</code>. * * @param email1 Email address constraint 1. * @param email2 Email address constraint 2. * @param intersect The intersection. */ private void intersectEmail(String email1, String email2, ISet intersect) { // email1 is a particular address if (email1.IndexOf('@') != -1) { String _sub = email1.Substring(email1.IndexOf('@') + 1); // both are a particular mailbox if (email2.IndexOf('@') != -1) { if (Platform.CompareIgnoreCase(email1, email2) == 0) { intersect.Add(email1); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(_sub, email2)) { intersect.Add(email1); } } // email2 specifies a particular host else { if (Platform.CompareIgnoreCase(_sub, email2) == 0) { intersect.Add(email1); } } } // email specifies a domain else if (email1.StartsWith(".")) { if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email1.IndexOf('@') + 1); if (WithinDomain(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(email1, email2) || (Platform.CompareIgnoreCase(email1, email2) == 0)) { intersect.Add(email1); } else if (WithinDomain(email2, email1)) { intersect.Add(email2); } } else { if (WithinDomain(email2, email1)) { intersect.Add(email2); } } } // email1 specifies a host else { if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email2.IndexOf('@') + 1); if (Platform.CompareIgnoreCase(_sub, email1) == 0) { intersect.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(email1, email2)) { intersect.Add(email1); } } // email2 specifies a particular host else { if (Platform.CompareIgnoreCase(email1, email2) == 0) { intersect.Add(email1); } } } } private void checkExcludedURI(ISet excluded, String uri) // throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { String str = ((String)it.Current); if (IsUriConstrained(uri, str)) { throw new PkixNameConstraintValidatorException( "URI is from an excluded subtree."); } } } private ISet intersectURI(ISet permitted, ISet uris) { ISet intersect = new HashSet(); for (IEnumerator it = uris.GetEnumerator(); it.MoveNext(); ) { String uri = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (uri != null) { intersect.Add(uri); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { String _permitted = (String)_iter.Current; intersectURI(_permitted, uri, intersect); } } } return intersect; } private ISet unionURI(ISet excluded, String uri) { if (excluded.IsEmpty) { if (uri == null) { return excluded; } excluded.Add(uri); return excluded; } else { ISet union = new HashSet(); IEnumerator _iter = excluded.GetEnumerator(); while (_iter.MoveNext()) { String _excluded = (String)_iter.Current; unionURI(_excluded, uri, union); } return union; } } private void intersectURI(String email1, String email2, ISet intersect) { // email1 is a particular address if (email1.IndexOf('@') != -1) { String _sub = email1.Substring(email1.IndexOf('@') + 1); // both are a particular mailbox if (email2.IndexOf('@') != -1) { if (Platform.CompareIgnoreCase(email1, email2) == 0) { intersect.Add(email1); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(_sub, email2)) { intersect.Add(email1); } } // email2 specifies a particular host else { if (Platform.CompareIgnoreCase(_sub, email2) == 0) { intersect.Add(email1); } } } // email specifies a domain else if (email1.StartsWith(".")) { if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email1.IndexOf('@') + 1); if (WithinDomain(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(email1, email2) || (Platform.CompareIgnoreCase(email1, email2) == 0)) { intersect.Add(email1); } else if (WithinDomain(email2, email1)) { intersect.Add(email2); } } else { if (WithinDomain(email2, email1)) { intersect.Add(email2); } } } // email1 specifies a host else { if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email2.IndexOf('@') + 1); if (Platform.CompareIgnoreCase(_sub, email1) == 0) { intersect.Add(email2); } } // email2 specifies a domain else if (email2.StartsWith(".")) { if (WithinDomain(email1, email2)) { intersect.Add(email1); } } // email2 specifies a particular host else { if (Platform.CompareIgnoreCase(email1, email2) == 0) { intersect.Add(email1); } } } } private void CheckPermittedURI(ISet permitted, String uri) // throws PkixNameConstraintValidatorException { if (permitted == null) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { String str = ((String)it.Current); if (IsUriConstrained(uri, str)) { return; } } if (uri.Length == 0 && permitted.Count == 0) { return; } throw new PkixNameConstraintValidatorException( "URI is not from a permitted subtree."); } private bool IsUriConstrained(String uri, String constraint) { String host = ExtractHostFromURL(uri); // a host if (!constraint.StartsWith(".")) { if (Platform.CompareIgnoreCase(host, constraint) == 0) { return true; } } // in sub domain or domain else if (WithinDomain(host, constraint)) { return true; } return false; } private static String ExtractHostFromURL(String url) { // see RFC 1738 // remove ':' after protocol, e.g. http: String sub = url.Substring(url.IndexOf(':') + 1); // extract host from Common Internet Scheme Syntax, e.g. http:// if (sub.IndexOf("//") != -1) { sub = sub.Substring(sub.IndexOf("//") + 2); } // first remove port, e.g. http://test.com:21 if (sub.LastIndexOf(':') != -1) { sub = sub.Substring(0, sub.LastIndexOf(':')); } // remove user and password, e.g. http://john:password@test.com sub = sub.Substring(sub.IndexOf(':') + 1); sub = sub.Substring(sub.IndexOf('@') + 1); // remove local parts, e.g. http://test.com/bla if (sub.IndexOf('/') != -1) { sub = sub.Substring(0, sub.IndexOf('/')); } return sub; } /** * Checks if the given GeneralName is in the permitted ISet. * * @param name The GeneralName * @throws PkixNameConstraintValidatorException * If the <code>name</code> */ public void checkPermitted(GeneralName name) // throws PkixNameConstraintValidatorException { switch (name.TagNo) { case 1: CheckPermittedEmail(permittedSubtreesEmail, ExtractNameAsString(name)); break; case 2: CheckPermittedDNS(permittedSubtreesDNS, DerIA5String.GetInstance( name.Name).GetString()); break; case 4: CheckPermittedDN(Asn1Sequence.GetInstance(name.Name.ToAsn1Object())); break; case 6: CheckPermittedURI(permittedSubtreesURI, DerIA5String.GetInstance( name.Name).GetString()); break; case 7: byte[] ip = Asn1OctetString.GetInstance(name.Name).GetOctets(); CheckPermittedIP(permittedSubtreesIP, ip); break; } } /** * Check if the given GeneralName is contained in the excluded ISet. * * @param name The GeneralName. * @throws PkixNameConstraintValidatorException * If the <code>name</code> is * excluded. */ public void checkExcluded(GeneralName name) // throws PkixNameConstraintValidatorException { switch (name.TagNo) { case 1: CheckExcludedEmail(excludedSubtreesEmail, ExtractNameAsString(name)); break; case 2: checkExcludedDNS(excludedSubtreesDNS, DerIA5String.GetInstance( name.Name).GetString()); break; case 4: CheckExcludedDN(Asn1Sequence.GetInstance(name.Name.ToAsn1Object())); break; case 6: checkExcludedURI(excludedSubtreesURI, DerIA5String.GetInstance( name.Name).GetString()); break; case 7: byte[] ip = Asn1OctetString.GetInstance(name.Name).GetOctets(); checkExcludedIP(excludedSubtreesIP, ip); break; } } /** * Updates the permitted ISet of these name constraints with the intersection * with the given subtree. * * @param permitted The permitted subtrees */ public void IntersectPermittedSubtree(Asn1Sequence permitted) { IDictionary subtreesMap = Platform.CreateHashtable(); // group in ISets in a map ordered by tag no. for (IEnumerator e = permitted.GetEnumerator(); e.MoveNext(); ) { GeneralSubtree subtree = GeneralSubtree.GetInstance(e.Current); int tagNo = subtree.Base.TagNo; if (subtreesMap[tagNo] == null) { subtreesMap[tagNo] = new HashSet(); } ((ISet)subtreesMap[tagNo]).Add(subtree); } for (IEnumerator it = subtreesMap.GetEnumerator(); it.MoveNext(); ) { DictionaryEntry entry = (DictionaryEntry)it.Current; // go through all subtree groups switch ((int)entry.Key ) { case 1: permittedSubtreesEmail = IntersectEmail(permittedSubtreesEmail, (ISet)entry.Value); break; case 2: permittedSubtreesDNS = intersectDNS(permittedSubtreesDNS, (ISet)entry.Value); break; case 4: permittedSubtreesDN = IntersectDN(permittedSubtreesDN, (ISet)entry.Value); break; case 6: permittedSubtreesURI = intersectURI(permittedSubtreesURI, (ISet)entry.Value); break; case 7: permittedSubtreesIP = IntersectIP(permittedSubtreesIP, (ISet)entry.Value); break; } } } private String ExtractNameAsString(GeneralName name) { return DerIA5String.GetInstance(name.Name).GetString(); } public void IntersectEmptyPermittedSubtree(int nameType) { switch (nameType) { case 1: permittedSubtreesEmail = new HashSet(); break; case 2: permittedSubtreesDNS = new HashSet(); break; case 4: permittedSubtreesDN = new HashSet(); break; case 6: permittedSubtreesURI = new HashSet(); break; case 7: permittedSubtreesIP = new HashSet(); break; } } /** * Adds a subtree to the excluded ISet of these name constraints. * * @param subtree A subtree with an excluded GeneralName. */ public void AddExcludedSubtree(GeneralSubtree subtree) { GeneralName subTreeBase = subtree.Base; switch (subTreeBase.TagNo) { case 1: excludedSubtreesEmail = UnionEmail(excludedSubtreesEmail, ExtractNameAsString(subTreeBase)); break; case 2: excludedSubtreesDNS = unionDNS(excludedSubtreesDNS, ExtractNameAsString(subTreeBase)); break; case 4: excludedSubtreesDN = UnionDN(excludedSubtreesDN, (Asn1Sequence)subTreeBase.Name.ToAsn1Object()); break; case 6: excludedSubtreesURI = unionURI(excludedSubtreesURI, ExtractNameAsString(subTreeBase)); break; case 7: excludedSubtreesIP = UnionIP(excludedSubtreesIP, Asn1OctetString .GetInstance(subTreeBase.Name).GetOctets()); break; } } /** * Returns the maximum IP address. * * @param ip1 The first IP address. * @param ip2 The second IP address. * @return The maximum IP address. */ private static byte[] Max(byte[] ip1, byte[] ip2) { for (int i = 0; i < ip1.Length; i++) { if ((ip1[i] & 0xFFFF) > (ip2[i] & 0xFFFF)) { return ip1; } } return ip2; } /** * Returns the minimum IP address. * * @param ip1 The first IP address. * @param ip2 The second IP address. * @return The minimum IP address. */ private static byte[] Min(byte[] ip1, byte[] ip2) { for (int i = 0; i < ip1.Length; i++) { if ((ip1[i] & 0xFFFF) < (ip2[i] & 0xFFFF)) { return ip1; } } return ip2; } /** * Compares IP address <code>ip1</code> with <code>ip2</code>. If ip1 * is equal to ip2 0 is returned. If ip1 is bigger 1 is returned, -1 * otherwise. * * @param ip1 The first IP address. * @param ip2 The second IP address. * @return 0 if ip1 is equal to ip2, 1 if ip1 is bigger, -1 otherwise. */ private static int CompareTo(byte[] ip1, byte[] ip2) { if (Arrays.AreEqual(ip1, ip2)) { return 0; } if (Arrays.AreEqual(Max(ip1, ip2), ip1)) { return 1; } return -1; } /** * Returns the logical OR of the IP addresses <code>ip1</code> and * <code>ip2</code>. * * @param ip1 The first IP address. * @param ip2 The second IP address. * @return The OR of <code>ip1</code> and <code>ip2</code>. */ private static byte[] Or(byte[] ip1, byte[] ip2) { byte[] temp = new byte[ip1.Length]; for (int i = 0; i < ip1.Length; i++) { temp[i] = (byte)(ip1[i] | ip2[i]); } return temp; } [Obsolete("Use GetHashCode instead")] public int HashCode() { return GetHashCode(); } public override int GetHashCode() { return HashCollection(excludedSubtreesDN) + HashCollection(excludedSubtreesDNS) + HashCollection(excludedSubtreesEmail) + HashCollection(excludedSubtreesIP) + HashCollection(excludedSubtreesURI) + HashCollection(permittedSubtreesDN) + HashCollection(permittedSubtreesDNS) + HashCollection(permittedSubtreesEmail) + HashCollection(permittedSubtreesIP) + HashCollection(permittedSubtreesURI); } private int HashCollection(ICollection coll) { if (coll == null) { return 0; } int hash = 0; IEnumerator it1 = coll.GetEnumerator(); while (it1.MoveNext()) { Object o = it1.Current; if (o is byte[]) { hash += Arrays.GetHashCode((byte[])o); } else { hash += o.GetHashCode(); } } return hash; } public override bool Equals(Object o) { if (!(o is PkixNameConstraintValidator)) return false; PkixNameConstraintValidator constraintValidator = (PkixNameConstraintValidator)o; return CollectionsAreEqual(constraintValidator.excludedSubtreesDN, excludedSubtreesDN) && CollectionsAreEqual(constraintValidator.excludedSubtreesDNS, excludedSubtreesDNS) && CollectionsAreEqual(constraintValidator.excludedSubtreesEmail, excludedSubtreesEmail) && CollectionsAreEqual(constraintValidator.excludedSubtreesIP, excludedSubtreesIP) && CollectionsAreEqual(constraintValidator.excludedSubtreesURI, excludedSubtreesURI) && CollectionsAreEqual(constraintValidator.permittedSubtreesDN, permittedSubtreesDN) && CollectionsAreEqual(constraintValidator.permittedSubtreesDNS, permittedSubtreesDNS) && CollectionsAreEqual(constraintValidator.permittedSubtreesEmail, permittedSubtreesEmail) && CollectionsAreEqual(constraintValidator.permittedSubtreesIP, permittedSubtreesIP) && CollectionsAreEqual(constraintValidator.permittedSubtreesURI, permittedSubtreesURI); } private bool CollectionsAreEqual(ICollection coll1, ICollection coll2) { if (coll1 == coll2) { return true; } if (coll1 == null || coll2 == null) { return false; } if (coll1.Count != coll2.Count) { return false; } IEnumerator it1 = coll1.GetEnumerator(); while (it1.MoveNext()) { Object a = it1.Current; IEnumerator it2 = coll2.GetEnumerator(); bool found = false; while (it2.MoveNext()) { Object b = it2.Current; if (SpecialEquals(a, b)) { found = true; break; } } if (!found) { return false; } } return true; } private bool SpecialEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if ((o1 is byte[]) && (o2 is byte[])) { return Arrays.AreEqual((byte[])o1, (byte[])o2); } else { return o1.Equals(o2); } } /** * Stringifies an IPv4 or v6 address with subnet mask. * * @param ip The IP with subnet mask. * @return The stringified IP address. */ private String StringifyIP(byte[] ip) { String temp = ""; for (int i = 0; i < ip.Length / 2; i++) { //temp += Integer.toString(ip[i] & 0x00FF) + "."; temp += (ip[i] & 0x00FF) + "."; } temp = temp.Substring(0, temp.Length - 1); temp += "/"; for (int i = ip.Length / 2; i < ip.Length; i++) { //temp += Integer.toString(ip[i] & 0x00FF) + "."; temp += (ip[i] & 0x00FF) + "."; } temp = temp.Substring(0, temp.Length - 1); return temp; } private String StringifyIPCollection(ISet ips) { String temp = ""; temp += "["; for (IEnumerator it = ips.GetEnumerator(); it.MoveNext(); ) { temp += StringifyIP((byte[])it.Current) + ","; } if (temp.Length > 1) { temp = temp.Substring(0, temp.Length - 1); } temp += "]"; return temp; } public override String ToString() { String temp = ""; temp += "permitted:\n"; if (permittedSubtreesDN != null) { temp += "DN:\n"; temp += permittedSubtreesDN.ToString() + "\n"; } if (permittedSubtreesDNS != null) { temp += "DNS:\n"; temp += permittedSubtreesDNS.ToString() + "\n"; } if (permittedSubtreesEmail != null) { temp += "Email:\n"; temp += permittedSubtreesEmail.ToString() + "\n"; } if (permittedSubtreesURI != null) { temp += "URI:\n"; temp += permittedSubtreesURI.ToString() + "\n"; } if (permittedSubtreesIP != null) { temp += "IP:\n"; temp += StringifyIPCollection(permittedSubtreesIP) + "\n"; } temp += "excluded:\n"; if (!(excludedSubtreesDN.IsEmpty)) { temp += "DN:\n"; temp += excludedSubtreesDN.ToString() + "\n"; } if (!excludedSubtreesDNS.IsEmpty) { temp += "DNS:\n"; temp += excludedSubtreesDNS.ToString() + "\n"; } if (!excludedSubtreesEmail.IsEmpty) { temp += "Email:\n"; temp += excludedSubtreesEmail.ToString() + "\n"; } if (!excludedSubtreesURI.IsEmpty) { temp += "URI:\n"; temp += excludedSubtreesURI.ToString() + "\n"; } if (!excludedSubtreesIP.IsEmpty) { temp += "IP:\n"; temp += StringifyIPCollection(excludedSubtreesIP) + "\n"; } return temp; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using NativeLong=System.IntPtr; using NativeULong=System.UIntPtr; internal static partial class Interop { internal static partial class libcrypto { [DllImport(Libraries.LibCrypto)] internal static extern void X509_free(IntPtr a); [DllImport(Libraries.LibCrypto)] internal static unsafe extern SafeX509Handle d2i_X509(IntPtr zero, byte** ppin, int len); [DllImport(Libraries.LibCrypto)] internal static extern unsafe int i2d_X509(SafeX509Handle x, byte** @out); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509Handle X509_dup(IntPtr handle); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509Handle X509_dup(SafeX509Handle handle); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509Handle PEM_read_bio_X509_AUX(SafeBioHandle bio, IntPtr zero, IntPtr zero1, IntPtr zero2); [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_get_serialNumber(SafeX509Handle x); [DllImport(Libraries.LibCrypto)] internal static unsafe extern SafeX509NameHandle d2i_X509_NAME(IntPtr zero, byte** ppin, int len); [DllImport(Libraries.LibCrypto)] internal static extern int X509_NAME_print_ex(SafeBioHandle @out, SafeX509NameHandle nm, int indent, NativeULong flags); [DllImport(Libraries.LibCrypto)] internal static extern void X509_NAME_free(IntPtr a); [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_get_issuer_name(SafeX509Handle a); [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_get_subject_name(SafeX509Handle a); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_check_purpose(SafeX509Handle x, int id, int ca); [DllImport(Libraries.LibCrypto)] internal static extern int X509_check_issued(SafeX509Handle issuer, SafeX509Handle subject); [DllImport(Libraries.LibCrypto)] internal static extern NativeULong X509_issuer_name_hash(SafeX509Handle x); [DllImport(Libraries.LibCrypto)] internal static extern int X509_get_ext_count(SafeX509Handle x); // Returns a pointer already being tracked by the SafeX509Handle, shouldn't be SafeHandle tracked/freed. // Bounds checking is in place for "loc", IntPtr.Zero is returned on violations. [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_get_ext(SafeX509Handle x, int loc); // Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed. [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_EXTENSION_get_object(IntPtr ex); // Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed. [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_EXTENSION_get_data(IntPtr ex); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_EXTENSION_get_critical(IntPtr ex); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509StoreHandle X509_STORE_new(); [DllImport(Libraries.LibCrypto)] internal static extern void X509_STORE_free(IntPtr v); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_STORE_add_cert(SafeX509StoreHandle ctx, SafeX509Handle x); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_STORE_add_crl(SafeX509StoreHandle ctx, SafeX509CrlHandle x); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_STORE_set_flags(SafeX509StoreHandle ctx, X509VerifyFlags flags); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509StoreCtxHandle X509_STORE_CTX_new(); [DllImport(Libraries.LibCrypto)] internal static extern void X509_STORE_CTX_free(IntPtr v); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_STORE_CTX_init(SafeX509StoreCtxHandle ctx, SafeX509StoreHandle store, SafeX509Handle x509, IntPtr zero); [DllImport(Libraries.LibCrypto)] internal static extern int X509_verify_cert(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509StackHandle X509_STORE_CTX_get1_chain(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.LibCrypto)] internal static extern X509VerifyStatusCode X509_STORE_CTX_get_error(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.LibCrypto)] internal static extern int X509_STORE_CTX_get_error_depth(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.LibCrypto)] internal static extern string X509_verify_cert_error_string(X509VerifyStatusCode n); [DllImport(Libraries.LibCrypto)] internal static extern void X509_CRL_free(IntPtr a); [DllImport(Libraries.LibCrypto)] internal static unsafe extern SafeX509CrlHandle d2i_X509_CRL(IntPtr zero, byte** ppin, int len); [DllImport(Libraries.LibCrypto)] internal static extern int PEM_write_bio_X509_CRL(SafeBioHandle bio, SafeX509CrlHandle crl); [DllImport(Libraries.LibCrypto)] private static extern SafeX509CrlHandle PEM_read_bio_X509_CRL(SafeBioHandle bio, IntPtr zero, IntPtr zero1, IntPtr zero2); internal static SafeX509CrlHandle PEM_read_bio_X509_CRL(SafeBioHandle bio) { return PEM_read_bio_X509_CRL(bio, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } // This is "unsigned long" in native, which means ulong on x64, uint on x86 // But we only support x64 for now. [Flags] internal enum X509VerifyFlags : ulong { None = 0, X509_V_FLAG_CB_ISSUER_CHECK = 0x0001, X509_V_FLAG_USE_CHECK_TIME = 0x0002, X509_V_FLAG_CRL_CHECK = 0x0004, X509_V_FLAG_CRL_CHECK_ALL = 0x0008, X509_V_FLAG_IGNORE_CRITICAL = 0x0010, X509_V_FLAG_X509_STRICT = 0x0020, X509_V_FLAG_ALLOW_PROXY_CERTS = 0x0040, X509_V_FLAG_POLICY_CHECK = 0x0080, X509_V_FLAG_EXPLICIT_POLICY = 0x0100, X509_V_FLAG_INHIBIT_ANY = 0x0200, X509_V_FLAG_INHIBIT_MAP = 0x0400, X509_V_FLAG_NOTIFY_POLICY = 0x0800, X509_V_FLAG_CHECK_SS_SIGNATURE = 0x4000, } internal enum X509VerifyStatusCode { X509_V_OK = 0, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2, X509_V_ERR_UNABLE_TO_GET_CRL = 3, X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE = 4, X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6, X509_V_ERR_CERT_SIGNATURE_FAILURE = 7, X509_V_ERR_CRL_SIGNATURE_FAILURE = 8, X509_V_ERR_CERT_NOT_YET_VALID = 9, X509_V_ERR_CERT_HAS_EXPIRED = 10, X509_V_ERR_CRL_NOT_YET_VALID = 11, X509_V_ERR_CRL_HAS_EXPIRED = 12, X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14, X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16, X509_V_ERR_OUT_OF_MEM = 17, X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18, X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20, X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21, X509_V_ERR_CERT_CHAIN_TOO_LONG = 22, X509_V_ERR_CERT_REVOKED = 23, X509_V_ERR_INVALID_CA = 24, X509_V_ERR_PATH_LENGTH_EXCEEDED = 25, X509_V_ERR_INVALID_PURPOSE = 26, X509_V_ERR_CERT_UNTRUSTED = 27, X509_V_ERR_CERT_REJECTED = 28, X509_V_ERR_AKID_SKID_MISMATCH = 30, X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH = 31, X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33, X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34, X509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 35, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 36, X509_V_ERR_INVALID_NON_CA = 37, X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED = 38, X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 39, X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED = 40, X509_V_ERR_INVALID_EXTENSION = 41, X509_V_ERR_INVALID_POLICY_EXTENSION = 42, X509_V_ERR_NO_EXPLICIT_POLICY = 43, X509_V_ERR_UNNESTED_RESOURCE = 44, X509_V_ERR_APPLICATION_VERIFICATION = 50, } } }
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using UnityEngine.Events; namespace UMA.Editors { public static class GUIHelper { private static Texture _helpIcon; private static GUIStyle _iconLabel; private static Texture _inspectIcon; private static GUIContent _inspectContent; private static GUIStyle _inspectStyle; private static float inspectBtnWidth = 25f; private static Texture helpIcon { get { if (_helpIcon != null) return _helpIcon; //Sometimes editor styles is not set up when we ask for this if (EditorStyles.label == null) return new Texture2D(16,16); _helpIcon = EditorGUIUtility.FindTexture("_Help"); return _helpIcon; } } private static GUIStyle iconLabel { get { if (_iconLabel != null) return _iconLabel; if (EditorStyles.label == null) return new GUIStyle(); _iconLabel = new GUIStyle(EditorStyles.label); _iconLabel.fixedHeight = 18f; _iconLabel.contentOffset = new Vector2(-4.0f, 0f); return _iconLabel; } } private static Texture inspectIcon { get { if (_inspectIcon != null) return _inspectIcon; //Check EditorStyles has been set up if (EditorStyles.label == null) return new Texture2D(16, 16); _inspectIcon = EditorGUIUtility.FindTexture("ViewToolOrbit"); return _inspectIcon; } } private static GUIContent inspectContent { get { if (_inspectContent != null && _inspectIcon != null) return _inspectContent; _inspectContent = new GUIContent("", "Inspect"); _inspectContent.image = inspectIcon; return _inspectContent; } } private static GUIStyle inspectStyle { get { if (_inspectStyle != null) return _inspectStyle; //Check EditorStyles is set up if (EditorStyles.miniButton == null) return new GUIStyle(); _inspectStyle = new GUIStyle(EditorStyles.miniButton); _inspectStyle.contentOffset = new Vector2(0f, 0f); _inspectStyle.padding = new RectOffset(0, 0, 0, 0); _inspectStyle.margin = new RectOffset(0, 0, 0, 0); return _inspectStyle; } } public static void BeginVerticalPadded() { if (EditorGUIUtility.isProSkin) { GUIHelper.BeginVerticalPadded(10, new Color(1.3f, 1.4f, 1.5f)); } else { GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f)); } } public static void EndVerticalPadded() { GUIHelper.EndVerticalPadded(10); } public static void BeginVerticalPadded(float padding, Color backgroundColor, GUIStyle theStyle = null) { if (theStyle == null) theStyle = EditorStyles.textField; GUI.color = backgroundColor; GUILayout.BeginHorizontal(theStyle); GUI.color = Color.white; GUILayout.Space(padding); GUILayout.BeginVertical(); GUILayout.Space(padding); } public static void EndVerticalPadded(float padding) { GUILayout.Space(padding); GUILayout.EndVertical(); GUILayout.Space(padding); GUILayout.EndHorizontal(); } public static void BeginVerticalIndented(float indentation, Color backgroundColor) { GUI.color = backgroundColor; GUILayout.BeginHorizontal(); GUILayout.Space(indentation); GUI.color = Color.white; GUILayout.BeginVertical(); } public static void EndVerticalIndented() { GUILayout.EndVertical(); GUILayout.EndHorizontal(); } public static void BeginHorizontalPadded(float padding, Color backgroundColor) { GUI.color = backgroundColor; GUILayout.BeginVertical(EditorStyles.textField); GUI.color = Color.white; GUILayout.Space(padding); GUILayout.BeginHorizontal(); GUILayout.Space(padding); } public static void EndHorizontalPadded(float padding) { GUILayout.Space(padding); GUILayout.EndHorizontal(); GUILayout.Space(padding); GUILayout.EndVertical(); } public static void Separator() { GUILayout.BeginHorizontal(EditorStyles.textField); GUILayout.EndHorizontal(); } public static void BeginCollapsableGroupPartStart(ref bool show, string text, string boneName, ref bool selected) { GUILayout.BeginHorizontal(EditorStyles.toolbarButton); GUI.SetNextControlName(boneName); show = EditorGUILayout.Foldout(show, text); var control = GUI.GetNameOfFocusedControl(); selected = control == boneName; //GUI.color = selected ? Color.yellow : Color.white; //if (GUILayout.Button(text, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) //{ // selected = true; //} //GUI.color = Color.white; } public static void BeginCollapsableGroupPartMiddle(ref bool show, string text, ref bool selected) { GUILayout.Label("", EditorStyles.toolbarButton); } public static bool BeginCollapsableGroupPartEnd(ref bool show, string text, ref bool selected) { GUILayout.EndHorizontal(); if (show) { GUILayout.BeginVertical(); } return show; } public static bool BeginCollapsableGroup(ref bool show, string text) { GUILayout.BeginHorizontal(); show = GUILayout.Toggle(show, show ? "\u002d" : "\u002b", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)); GUILayout.Label(text, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)); GUILayout.Label("", EditorStyles.toolbarButton); GUILayout.EndHorizontal(); if (show) { GUILayout.BeginVertical(); } return show; } public static void EndCollapsableGroup(ref bool show) { if (show) { EndCollapsableGroup(); } } public static void EndCollapsableGroup() { GUILayout.EndVertical(); } public static void BeginObject(string label, int minWidth) { GUILayout.BeginHorizontal(); GUILayout.Label(label, EditorStyles.boldLabel, GUILayout.ExpandWidth(false), GUILayout.MinWidth(minWidth)); } public static void EndObject() { GUILayout.EndHorizontal(); } public static void FoldoutBar(ref bool foldout, string content, out bool delete) { GUILayout.BeginHorizontal(EditorStyles.toolbarButton); GUILayout.Space(10); foldout = EditorGUILayout.Foldout(foldout, content,true); delete = GUILayout.Button("\u0078", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } public static bool FoldoutBar(bool foldout, string content) { GUILayout.BeginHorizontal(EditorStyles.toolbarButton); GUILayout.Space(10); bool nfoldout = EditorGUILayout.Foldout(foldout, content,true); GUILayout.EndHorizontal(); return nfoldout; } public static void FoldoutBarButton(ref bool foldout, string content, string button, out bool pressed, out bool delete) { GUILayout.BeginHorizontal(EditorStyles.toolbarButton); GUILayout.Space(10); foldout = EditorGUILayout.Foldout(foldout, content,true); pressed = GUILayout.Button(button, EditorStyles.miniButton, GUILayout.ExpandWidth(false)); delete = GUILayout.Button("\u0078", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } public static void FoldoutBarButton(ref bool foldout, string content, string button, out bool pressed, out int move, out bool delete) { GUILayout.BeginHorizontal(EditorStyles.toolbarButton); GUILayout.Space(10); foldout = EditorGUILayout.Foldout(foldout, content, true); move = 0; if (GUILayout.Button("\u25B2", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) move--; if (GUILayout.Button("\u25BC", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) move++; pressed = GUILayout.Button(button, EditorStyles.miniButton, GUILayout.ExpandWidth(false)); delete = GUILayout.Button("\u0078", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } public static void FoldoutBar(ref bool foldout, string content, out int move, out bool delete) { GUILayout.BeginHorizontal(EditorStyles.toolbarButton); GUILayout.Space(10); foldout = EditorGUILayout.Foldout(foldout, content,true); move = 0; if (GUILayout.Button("\u25B2", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) move--; if (GUILayout.Button("\u25BC", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) move++; delete = GUILayout.Button("\u0078", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } public static void ToolbarStyleFoldout(Rect rect, string label, ref bool isExpanded, GUIStyle toolbarStyleOverride = null, GUIStyle labelStyleOverride = null) { bool dummyHelpExpanded = false; ToolbarStyleFoldout(rect, new GUIContent(label), new string[0], ref isExpanded, ref dummyHelpExpanded, toolbarStyleOverride, labelStyleOverride); } public static void ToolbarStyleFoldout(Rect rect, GUIContent label, ref bool isExpanded, GUIStyle toolbarStyleOverride = null, GUIStyle labelStyleOverride = null) { bool dummyHelpExpanded = false; ToolbarStyleFoldout(rect, label, new string[0], ref isExpanded, ref dummyHelpExpanded, toolbarStyleOverride, labelStyleOverride); } public static void ToolbarStyleFoldout(Rect rect, string label, string[] help, ref bool isExpanded, ref bool helpExpanded, GUIStyle toolbarStyleOverride = null, GUIStyle labelStyleOverride = null) { ToolbarStyleFoldout(rect, new GUIContent(label), help, ref isExpanded, ref helpExpanded, toolbarStyleOverride, labelStyleOverride); } /// <summary> /// Draws a ToolBar style foldout with a centered foldout label. Optionally draws a help icon that will show the selected array of 'help' paragraphs /// </summary> /// <param name="rect"></param> /// <param name="label"></param> /// <param name="help">An array of help paragpahs. If supplied the help Icon will be shown</param> /// <param name="isExpanded"></param> /// <param name="helpExpanded"></param> /// <param name="toolbarStyleOverride">Overrides EdiorStyles.toolbar as the background</param> /// <param name="labelStyleOverride">Overrides EditorStyles.folodout as the label style</param> public static void ToolbarStyleFoldout(Rect rect, GUIContent label, string[] help, ref bool isExpanded, ref bool helpExpanded, GUIStyle toolbarStyleOverride = null, GUIStyle labelStyleOverride = null) { GUIStyle toolbarStyle = toolbarStyleOverride; GUIStyle labelStyle = labelStyleOverride; if (toolbarStyle == null) toolbarStyle = EditorStyles.toolbar; if (labelStyle == null) labelStyle = EditorStyles.foldout; var helpIconRect = new Rect(rect.xMax - 20f, rect.yMin, 20f, rect.height); var helpGUI= new GUIContent("", "Show Help"); helpGUI.image = helpIcon; Event current = Event.current; if (current.type == EventType.Repaint) { toolbarStyle.Draw(rect, GUIContent.none, false, false, false, false); } var labelWidth = labelStyle.CalcSize(label); labelWidth.x += 15f;//add the foldout arrow var toolbarFoldoutRect = new Rect((rect.xMax / 2f) - (labelWidth.x / 2f) + 30f, rect.yMin, ((rect.width / 2) + (labelWidth.x / 2f)) - 20f - 30f, rect.height); isExpanded = EditorGUI.Foldout(toolbarFoldoutRect, isExpanded, label, true, labelStyle); if (help.Length > 0) { helpExpanded = GUI.Toggle(helpIconRect, helpExpanded, helpGUI, iconLabel); if (helpExpanded) { ToolbarStyleHelp(help); } } } public static void ToolbarStyleHeader(Rect rect, GUIContent label, string[] help, ref bool helpExpanded, GUIStyle toolbarStyleOverride = null, GUIStyle labelStyleOverride = null) { var toolbarStyle = toolbarStyleOverride != null ? toolbarStyleOverride : EditorStyles.toolbar; var labelStyle = labelStyleOverride != null ? labelStyleOverride : EditorStyles.label; var helpIconRect = new Rect(rect.xMax - 20f, rect.yMin, 20f, rect.height); var helpGUI = new GUIContent("", "Show Help"); helpGUI.image = helpIcon; Event current = Event.current; if (current.type == EventType.Repaint) { toolbarStyle.Draw(rect, GUIContent.none, false, false, false, false); } var labelWidth = labelStyle.CalcSize(label); var toolbarFoldoutRect = new Rect((rect.xMax / 2f) - (labelWidth.x / 2f) + 30f, rect.yMin, ((rect.width / 2) + (labelWidth.x / 2f)) - 20f - 30f, rect.height); EditorGUI.LabelField(toolbarFoldoutRect, label, labelStyle); if (help.Length > 0) { helpExpanded = GUI.Toggle(helpIconRect, helpExpanded, helpGUI, iconLabel); if (helpExpanded) { ToolbarStyleHelp(help); } } } private static void ToolbarStyleHelp(string[] help) { BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f)); for (int i = 0; i < help.Length; i++) { EditorGUILayout.HelpBox(help[i], MessageType.None); } EndVerticalPadded(3); } /// <summary> /// Draws an object field with an 'inspect' button next to it which opens up the editor for the assigned object in a popup window /// </summary> public static void InspectableObjectField(Rect position, SerializedProperty property, GUIContent label, UnityAction<EditorWindow> onCreateWindowCallback = null) { label = EditorGUI.BeginProperty(position, label, property); var objectFieldRect = position; var inspectBtnRect = Rect.zero; if (property.objectReferenceValue) { objectFieldRect = new Rect(position.xMin, position.yMin, position.width - inspectBtnWidth - 4f, position.height); inspectBtnRect = new Rect(objectFieldRect.xMax + 4f, objectFieldRect.yMin, inspectBtnWidth, objectFieldRect.height); } EditorGUI.ObjectField(objectFieldRect, property, label); if (property.objectReferenceValue) { if (GUI.Button(inspectBtnRect, inspectContent, inspectStyle)) { var inspectorWindow = InspectorUtlity.InspectTarget(property.objectReferenceValue); if (onCreateWindowCallback != null) onCreateWindowCallback(inspectorWindow); } } EditorGUI.EndProperty(); } } } #endif
using System; using UnityEngine; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; namespace StrumpyShaderEditor { /*Subgraph parent * Stores all the nodes and the offsets ect */ [DataContract(Namespace = "http://strumpy.net/ShaderEditor/")] public abstract class SubGraph { private Dictionary<string, Node> _nodes = new Dictionary<string, Node>(); //Backing store, will be put into the dictionary on initialize for fast searching! [DataMember] private List<Node> nodes { get{ return _nodes.Values.ToList(); } set{ _nodes = _nodes ?? new Dictionary<string, Node>(); foreach( var node in value ) { _nodes.Add( node.UniqueNodeIdentifier, node ); } } } // Texel - Expose mechanism for getting node positions public Rect[] nodePositions { get { var rects = new List<Rect>(); foreach (Node node in nodes) rects.Add(node.NodePositionInGraph); return rects.ToArray(); } } [DataMember] public EditorFloat2 DrawOffset{ get; set;} private float _drawScale; public float DrawScale{ get{ return _drawScale; } set{ _drawScale = value; if( _drawScale > 2f ) { _drawScale = 2f; } else if( _drawScale < 0.0001 ) { _drawScale = 0.0001f; } } } private List<Node> _selected = new List<Node>(); [DataMember] private List<string> _reloadSelectedList = new List<string>(); //Cache these for performance private IEnumerable<Node> _depthSortedNodes = new List<Node> (); public bool Dirty { get; private set; } private CircularReferenceException _lastException; private ShaderGraph _owner; public IEnumerable<Node> Nodes { get { return _nodes.Values; } } public void Initialize ( ShaderGraph owner, Rect screenDimensions, bool updateDrawPos ) { _owner = owner; //Update the offset of all the nodes for drawing / panning var masterPos = new Vector2(RootNode.Position.X, RootNode.Position.Y); if( updateDrawPos ) { var desiredPosition = Vector2.zero; desiredPosition.x = 10; desiredPosition.y = screenDimensions.height / 4; DrawOffset = desiredPosition - masterPos; } DrawScale = 1f; Dirty = true; foreach (var node in Nodes) { node.Owner = this; node.Initialize (); } _selected = new List<Node>(); if( _reloadSelectedList == null ) { _reloadSelectedList = new List<string>(); } foreach( var node in Nodes ) { if( _reloadSelectedList.Contains( node.UniqueNodeIdentifier ) ) { _selected.Add( node ); } } } public abstract string GraphTypeName { get; } public abstract SubGraphType GraphType { get; } public IEnumerable<ShaderProperty> FindValidProperties( InputType type ) { return _owner.FindValidProperties( type ); } public int AddProperty( ShaderProperty p ) { return _owner.AddProperty( p ); } /*Search for all nodes that export to the struct output of the vertex shader hlss */ protected Dictionary<string, List<IStructInput>> GetValidStructNodes () { var allStructs = GetValidNodes<IStructInput> (); //Build up a dictionary of struct inputname => node var structMap = new Dictionary<string, List<IStructInput> > (); foreach (var input in allStructs) { var fieldName = input.GetStructFieldName (); if (structMap.ContainsKey (fieldName)) { //This will only happen if by bad programming / node creation if (structMap[fieldName].Any( x => x.GetStructFieldType() != input.GetStructFieldType () ) ) { throw new Exception ("Multiple struct nodes exist with the same name, but different types"); } structMap[fieldName].Add( input ); } else { structMap.Add (fieldName, new List<IStructInput>{ input } ); } } return structMap; } public IEnumerable<Node> SelectedNodes { get { return _selected; } } private void updateSerializedSelectedNodes() { _reloadSelectedList.Clear(); foreach( var node in SelectedNodes ) { _reloadSelectedList.Add( node.UniqueNodeIdentifier ); } } public bool NeedsTimeNode { get { return GetConnectedNodesDepthFirst().Any( x => x.NeedsTime() == true ); } } public bool NeedsSinTimeNode { get { return GetConnectedNodesDepthFirst().Any( x => x.NeedsSinTime() == true ); } } public bool NeedsCosTimeNode { get { return GetConnectedNodesDepthFirst().Any( x => x.NeedsCosTime() == true ); } } //Draw this graph with the offset given public void Draw ( NodeEditor editor, bool showComments, Rect drawWindow ) { foreach (var node in Nodes) { var topLeft = new Vector2( node.NodePositionInGraph.xMin, node.NodePositionInGraph.yMin ); var topRight = new Vector2( node.NodePositionInGraph.xMax, node.NodePositionInGraph.yMin ); var bottomLeft = new Vector2( node.NodePositionInGraph.xMin, node.NodePositionInGraph.yMax ); var bottomRight = new Vector2( node.NodePositionInGraph.xMax, node.NodePositionInGraph.yMax ); if( drawWindow.Contains( topLeft ) || drawWindow.Contains( topRight ) || drawWindow.Contains( bottomLeft ) || drawWindow.Contains( bottomRight ) ) { node.Draw ( editor, showComments, (_selected.Contains( node ) ), DrawOffset ); } } } public void SetPreview( bool isPreviewShader ) { //Set up proxy input shaders for export or preview var proxyInputs = GetValidNodes<IProxyOnSave> (); foreach (var proxyNode in proxyInputs) { proxyNode.Exporting = !isPreviewShader; } } public Node FirstSelected { get{ return _selected.LastOrDefault(); } } public void Deselect() { _selected.Clear(); updateSerializedSelectedNodes(); } public void Deselect( Node n ) { _selected.Remove( n ); updateSerializedSelectedNodes(); } public Node NodeAt (Vector2 location ) { var vec3Location = new Vector3 (location.x, location.y); //Find the last in the queue that is valid var clicked = (from node in Nodes where node.NodePositionInGraph.Contains (vec3Location) select node).LastOrDefault (); if( clicked != null ) { if( !clicked.ButtonAt( location ) ) { return clicked; } } return null; } public bool ButtonAt (Vector2 location ) { return Nodes.Any( x => x.ButtonAt( location ) ); } public bool IsSelected( Node n ) { return _selected.Contains( n ); } public bool Select (Vector2 location, bool addSelect ) { var vec3Location = new Vector3 (location.x, location.y); var selectionChanged = false; //Find the last in the queue that is valid var clicked = (from node in Nodes where node.NodePositionInGraph.Contains (vec3Location) select node).LastOrDefault (); if( clicked != null ) { if( !clicked.ButtonAt( location ) ) { if( addSelect ) { //Force the selected to be the last in the list if( _selected.Contains( clicked ) ) { _selected.Remove( clicked ); } _selected.Add( clicked ); } else { _selected.Clear(); _selected.Add( clicked ); } selectionChanged = true; } } else if( !addSelect ) { _selected.Clear(); } //Move it to the very end as it was just selected //if (_selected.LastOrDefault() != null ) { // nodes.Remove (_selected.LastOrDefault()); // nodes.Add (_selected.LastOrDefault()); //} updateSerializedSelectedNodes(); return selectionChanged; } public void Select ( Node n, bool addSelect ) { if( addSelect ) { //Force the selected to be the last in the list if( _selected.Contains( n ) ) { _selected.Remove( n ); } _selected.Add( n ); } else { _selected.Clear(); _selected.Add( n ); } updateSerializedSelectedNodes(); } public bool Select ( Rect area, bool addSelect ) { //Find the nodes to select //Find the last in the queue that is valid var toSelect = (from node in Nodes where area.OverLaps( node.NodePositionInGraph ) select node); if( !addSelect ) { _selected.Clear(); } foreach( var n in toSelect ) { //Force the selected to be the last in the list if( _selected.Contains( n ) ) { _selected.Remove( n ); } _selected.Add( n ); } updateSerializedSelectedNodes(); return toSelect.Count() > 0; } public void SelectAll( ) { _selected.Clear(); foreach( var node in Nodes ) { _selected.Add( node ); } updateSerializedSelectedNodes(); } public void MarkSelectedHot () { if (_selected == null || _selected.Count == 0 ) return; if (GUIUtility.hotControl == 0) { GUIUtility.hotControl = _selected.GetHashCode (); } } public void UnmarkSelectedHot () { if (_selected == null || _selected.Count == 0 ) return; if (GUIUtility.hotControl == _selected.GetHashCode ()) { GUIUtility.hotControl = 0; } } public bool DragSelectedNodes (Vector2 delta) { if (_selected == null) return false; if (GUIUtility.hotControl == _selected.GetHashCode ()) { _selected.ForEach( x => x.DeltaMove (delta) ); return true; } return false; } public Rect DrawSize { get { var dimension = new Rect (0, 0, 0, 0); foreach (var node in Nodes) { if (node.NodePositionInGraph.x < dimension.x) { dimension.x = node.NodePositionInGraph.x; } if (node.NodePositionInGraph.y < dimension.y) { dimension.y = node.NodePositionInGraph.y; } if (node.NodePositionInGraph.x + node.NodePositionInGraph.width > dimension.xMax) { dimension.xMax = node.NodePositionInGraph.x + node.NodePositionInGraph.width; } if (node.NodePositionInGraph.y + node.NodePositionInGraph.height > dimension.yMax) { dimension.yMax = node.NodePositionInGraph.y + node.NodePositionInGraph.height; } } return dimension; } } public abstract RootNode RootNode { get; } public void MarkDirty() { Dirty = true; cachedConnectedNodes = null; } private void MarkClean() { Dirty = false; } public IEnumerable<Node> GetConnectedNodesDepthFirst (Node parent, Stack<string> visitedNodes) { if (Dirty || _depthSortedNodes == null ) { try { _depthSortedNodes = GetConnectedNodesDepthFirstInner (parent, visitedNodes); } catch (CircularReferenceException) { throw; } } return _depthSortedNodes; } private IEnumerable<Node> GetConnectedNodesDepthFirstInner (Node parent, Stack<string> visitedNodes) { if (visitedNodes.Contains (parent.UniqueNodeIdentifier)) { visitedNodes.Push (parent.UniqueNodeIdentifier); _lastException = new CircularReferenceException { CircularTrace = visitedNodes, CausalNodeId = parent.UniqueNodeIdentifier }; _depthSortedNodes = null; throw _lastException; } visitedNodes.Push (parent.UniqueNodeIdentifier); var toReturn = new List<Node> (); foreach (var input in parent.GetInputChannels ()) { if (input.IncomingConnection != null) { toReturn.AddRange (GetConnectedNodesDepthFirstInner (GetNode (input.IncomingConnection.NodeIdentifier), visitedNodes)); } } visitedNodes.Pop (); toReturn.Add (parent); return toReturn; } public void UpdateErrorState () { var graphContainsCircularReferences = ContainsCircularReferences (); foreach (var node in Nodes) { node.ClearErrors(); var errors = IsNodeValid (node); if (errors.Count () > 0) { node.CurrentState = NodeState.Error; node.AddErrors( errors ); } else if (graphContainsCircularReferences) { node.CurrentState = NodeState.CircularReferenceInGraph; } else if (!IsNodeConnected (node.UniqueNodeIdentifier)) { node.CurrentState = NodeState.NotConnected; } else { node.CurrentState = NodeState.Valid; } } MarkClean(); } private static void BreakInputChannels (Node node) { foreach (var channel in node.GetInputChannels ()) { channel.IncomingConnection = null; } } private void BreakOutputChannels (Node node) { foreach (var localNode in Nodes) { foreach (var channel in localNode.GetInputChannels ()) { if (channel.IncomingConnection != null && channel.IncomingConnection.NodeIdentifier == node.UniqueNodeIdentifier) { channel.IncomingConnection = null; } } } } public void DeleteSelected() { foreach( var node in _selected ) { if (node == RootNode) { continue; } BreakInputChannels (node); BreakOutputChannels (node); _nodes.Remove(node.UniqueNodeIdentifier); } _selected.Clear(); } public IEnumerable<T> GetValidNodes<T> () where T : class { try { var candidateNodes = GetConnectedNodesDepthFirst (); var foundNodes = new List<T> (); foreach (var node in candidateNodes.Distinct ()) { if (node is T) { foundNodes.Add (node as T); } } return foundNodes; } catch (CircularReferenceException) { return new List<T> (); } } public bool ContainsCircularReferences () { try { GetConnectedNodesDepthFirst (); return false; } catch (CircularReferenceException) { return true; } } public bool IsSubGraphValid () { try { return GetConnectedNodesDepthFirst ().All (node => IsNodeValid (node).Count () <= 0); } catch (CircularReferenceException) { return false; } } public bool IsNodeConnected (string uniqueNodeId) { try { return (from node in GetConnectedNodesDepthFirst () where node.UniqueNodeIdentifier == uniqueNodeId select node).Count () > 0; } catch (CircularReferenceException) { return false; } } IEnumerable<Node> cachedConnectedNodes = null; public IEnumerable<Node> GetConnectedNodesDepthFirst () { if( cachedConnectedNodes == null ) { var parseStack = new Stack<string> (); cachedConnectedNodes = GetConnectedNodesDepthFirst (RootNode, parseStack); } return cachedConnectedNodes; } public Node GetNode (string uniqueNodeId) { //return nodes.FirstOrDefault( x => x.UniqueNodeIdentifier == uniqueNodeId ); return _nodes[uniqueNodeId]; } private IEnumerable<string> IsNodeValid (Node validatingNode) { var errors = new List<string> (); //Check for infinite loops in graph if (_depthSortedNodes == null) { if (_lastException.CausalNodeId == validatingNode.UniqueNodeIdentifier) { var reason = "Circular Reference Detected: "; foreach (var node in _lastException.CircularTrace) { reason += node; reason += " -> "; } reason += "Error"; errors.Add (reason); } return errors; } //If this is an input node if (validatingNode is IFieldInput) { var validatingInputNode = (IFieldInput)validatingNode; var allInputs = from node in Nodes where node is IFieldInput && (node.UniqueNodeIdentifier != validatingNode.UniqueNodeIdentifier) select node; errors.AddRange(from input in allInputs where input != validatingInputNode let fieldInputNode = (IFieldInput) input where fieldInputNode.GetFieldName() == validatingInputNode.GetFieldName() && fieldInputNode.GetFieldType() != validatingInputNode.GetFieldType() select "Shares input name with " + input.UniqueNodeIdentifier + " but not input type"); } errors.AddRange (validatingNode.IsValid ( GraphType )); return errors; } public InputChannel GetInputChannel (InputChannelReference chanRef) { var node = GetNode (chanRef.NodeIdentifier); return node.GetInputChannel (chanRef.ChannelId); } public OutputChannel GetOutputChannel (OutputChannelReference chanRef) { var node = GetNode (chanRef.NodeIdentifier); return node.GetOutputChannel (chanRef.ChannelId); } public void AddNode (Node n) { var sameTypeNodes = from node in Nodes where node.GetType () == n.GetType () orderby node.NodeID select node.NodeID; int nextId = 0; while (sameTypeNodes.Contains (nextId)) { ++nextId; } n.Owner = this; n.AddedToGraph(nextId); _nodes.Add( n.UniqueNodeIdentifier, n ); } public bool RequiresGrabPass { get{ return GetConnectedNodesDepthFirst ().Any (x => x.RequiresGrabPass); } } public bool RequiresSceneDepth { get{ return GetConnectedNodesDepthFirst ().Any (x => x.RequiresSceneDepth); } } } }
// 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.Runtime.InteropServices; using System.Threading.Tasks; using EnvDTE; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { public class FileCodeVariableTests : AbstractFileCodeElementTests { public FileCodeVariableTests() : base(@"using System; public class A { // This is a comment. public int intA; /// <summary> /// This is a summary. /// </summary> protected int intB; [Serializable] private int intC = 4; int intD; public static const int FORTYTWO = 42; } unsafe public struct DevDivBugs70194 { fixed char buffer[100]; }") { } private async Task<CodeVariable> GetCodeVariableAsync(params object[] path) { return (CodeVariable)await GetCodeElementAsync(path); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Access_Public() { CodeVariable testObject = await GetCodeVariableAsync("A", "intA"); Assert.Equal(vsCMAccess.vsCMAccessPublic, testObject.Access); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Access_Protected() { CodeVariable testObject = await GetCodeVariableAsync("A", "intB"); Assert.Equal(vsCMAccess.vsCMAccessProtected, testObject.Access); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Access_Private() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Equal(vsCMAccess.vsCMAccessPrivate, testObject.Access); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Attributes_Count() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Equal(1, testObject.Attributes.Count); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Children_Count() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Equal(1, testObject.Children.Count); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Comment() { CodeVariable testObject = await GetCodeVariableAsync("A", "intA"); Assert.Equal("This is a comment.\r\n", testObject.Comment); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task DocComment() { CodeVariable testObject = await GetCodeVariableAsync("A", "intB"); string expected = "<doc>\r\n<summary>\r\nThis is a summary.\r\n</summary>\r\n</doc>"; Assert.Equal(expected, testObject.DocComment); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task InitExpressions_NoExpression() { CodeVariable testObject = await GetCodeVariableAsync("A", "intB"); Assert.Equal(null, testObject.InitExpression); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task InitExpression() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Equal("4", testObject.InitExpression); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task InitExpression_FixedBuffer() { CodeVariable testObject = await GetCodeVariableAsync("DevDivBugs70194", "buffer"); Assert.Equal(null, testObject.InitExpression); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task IsConstant_True() { CodeVariable testObject = await GetCodeVariableAsync("A", "FORTYTWO"); Assert.True(testObject.IsConstant); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task IsConstant_False() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.False(testObject.IsConstant); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task IsShared_True() { CodeVariable testObject = await GetCodeVariableAsync("A", "FORTYTWO"); Assert.True(testObject.IsShared); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task IsShared_False() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.False(testObject.IsShared); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Kind() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Equal(vsCMElement.vsCMElementVariable, testObject.Kind); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Parent() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); CodeClass testObjectParent = testObject.Parent as CodeClass; Assert.Equal("A", testObjectParent.Name); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task Type() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Equal("System.Int32", testObject.Type.AsFullName); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_Attributes() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_AttributesWithDelimiter() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter); Assert.Equal(13, startPoint.Line); Assert.Equal(5, startPoint.LineCharOffset); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_Body() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<COMException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBody)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_BodyWithDelimiter() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_Header() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeader)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_HeaderWithAttributes() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_Name() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_Navigate() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(14, startPoint.Line); Assert.Equal(17, startPoint.LineCharOffset); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_Whole() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetStartPoint_WholeWithAttributes() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(13, startPoint.Line); Assert.Equal(5, startPoint.LineCharOffset); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_Attributes() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_AttributesWithDelimiter() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter); Assert.Equal(13, endPoint.Line); Assert.Equal(19, endPoint.LineCharOffset); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_Body() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<COMException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBody)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_BodyWithDelimiter() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_Header() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_HeaderWithAttributes() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_Name() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartName)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_Navigate() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(14, endPoint.Line); Assert.Equal(21, endPoint.LineCharOffset); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_Whole() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole)); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task GetEndPoint_WholeWithAttributes() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(14, endPoint.Line); Assert.Equal(26, endPoint.LineCharOffset); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task StartPoint() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); TextPoint startPoint = testObject.StartPoint; Assert.Equal(13, startPoint.Line); Assert.Equal(5, startPoint.LineCharOffset); } [ConditionalWpfFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public async Task EndPoint() { CodeVariable testObject = await GetCodeVariableAsync("A", "intC"); TextPoint endPoint = testObject.EndPoint; Assert.Equal(14, endPoint.Line); Assert.Equal(26, endPoint.LineCharOffset); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the abogve copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; //using System.Text; using Nwc.XmlRpc; using log4net; // using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; //using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.OptionalModules.Avatar.FlexiGroups { public class XmlRpcGroupDataProvider : IGroupDataProvider { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_serviceURL = string.Empty; private bool m_disableKeepAlive = false; private string m_groupReadKey = string.Empty; private string m_groupWriteKey = string.Empty; public XmlRpcGroupDataProvider(string serviceURL, bool disableKeepAlive, string groupReadKey, string groupWriteKey) { m_serviceURL = serviceURL.Trim(); m_disableKeepAlive = disableKeepAlive; if ((serviceURL == null) || (serviceURL == string.Empty)) { throw new Exception("Please specify a valid ServiceURL for XmlRpcGroupDataProvider in OpenSim.ini, [Groups], XmlRpcServiceURL"); } m_groupReadKey = groupReadKey; m_groupWriteKey = groupWriteKey; } /// <summary> /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. /// </summary> public UUID CreateGroup(GroupRequestID requestID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID) { UUID GroupID = UUID.Random(); UUID OwnerRoleID = UUID.Random(); Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); param["Name"] = name; param["Charter"] = charter; param["ShowInList"] = showInList == true ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = 0; param["OpenEnrollment"] = openEnrollment == true ? 1 : 0; param["AllowPublish"] = allowPublish == true ? 1 : 0; param["MaturePublish"] = maturePublish == true ? 1 : 0; param["FounderID"] = founderID.ToString(); param["EveryonePowers"] = ((ulong)Constants.DefaultEveryonePowers).ToString(); param["OwnerRoleID"] = OwnerRoleID.ToString(); // Would this be cleaner as (GroupPowers)ulong.MaxValue; GroupPowers OwnerPowers = (GroupPowers)ulong.MaxValue; param["OwnersPowers"] = ((ulong)OwnerPowers).ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.createGroup", param); if (respData.Contains("error")) { // UUID is not nullable return UUID.Zero; } return UUID.Parse((string)respData["GroupID"]); } public void UpdateGroup(GroupRequestID requestID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["Charter"] = charter; param["ShowInList"] = showInList == true ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = membershipFee; param["OpenEnrollment"] = openEnrollment == true ? 1 : 0; param["AllowPublish"] = allowPublish == true ? 1 : 0; param["MaturePublish"] = maturePublish == true ? 1 : 0; XmlRpcCall(requestID, "groups.updateGroup", param); } public void AddGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, bool skipPermissionChecks) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); param["Name"] = name; param["Description"] = description; param["Title"] = title; param["Powers"] = powers.ToString(); XmlRpcCall(requestID, "groups.addRoleToGroup", param); } public void RemoveGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); XmlRpcCall(requestID, "groups.removeRoleFromGroup", param); } public void UpdateGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); if (name != null) { param["Name"] = name; } if (description != null) { param["Description"] = description; } if (title != null) { param["Title"] = title; } param["Powers"] = powers.ToString(); XmlRpcCall(requestID, "groups.updateGroupRole", param); } public GroupRecord GetGroupRecord(GroupRequestID requestID, UUID GroupID, string GroupName) { Hashtable param = new Hashtable(); if (GroupID != UUID.Zero) { param["GroupID"] = GroupID.ToString(); } if ((GroupName != null) && (GroupName != string.Empty)) { param["Name"] = GroupName.ToString(); } Hashtable respData = XmlRpcCall(requestID, "groups.getGroup", param); if (respData.Contains("error")) { return null; } return GroupProfileHashtableToGroupRecord(respData); } public GroupProfileData GetMemberGroupProfile(GroupRequestID requestID, UUID GroupID, UUID AgentID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroup", param); if (respData.Contains("error")) { // GroupProfileData is not nullable return new GroupProfileData(); } GroupMembershipData MemberInfo = GetAgentGroupMembership(requestID, AgentID, GroupID); GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData); MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; return MemberGroupProfile; } private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile) { GroupProfileData group = new GroupProfileData(); group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); group.Name = (string)groupProfile["Name"]; if (groupProfile.ContainsKey("Charter")) { group.Charter = (string)groupProfile["Charter"]; } group.ShowInList = ((string)groupProfile["ShowInList"]) == "1"; group.InsigniaID = UUID.Parse((string)groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]); group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string)groupProfile["FounderID"]); group.OwnerRole = UUID.Parse((string)groupProfile["OwnerRoleID"]); group.GroupMembershipCount = int.Parse((string)groupProfile["GroupMembershipCount"]); group.GroupRolesCount = int.Parse((string)groupProfile["GroupRolesCount"]); return group; } private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile) { GroupRecord group = new GroupRecord(); group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); group.GroupName = groupProfile["Name"].ToString(); if (groupProfile.ContainsKey("Charter")) { group.Charter = (string)groupProfile["Charter"]; } group.ShowInList = ((string)groupProfile["ShowInList"]) == "1"; group.GroupPicture = UUID.Parse((string)groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]); group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string)groupProfile["FounderID"]); group.OwnerRoleID = UUID.Parse((string)groupProfile["OwnerRoleID"]); return group; } public void SetAgentActiveGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestID, "groups.setAgentActiveGroup", param); } public void SetAgentActiveGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["SelectedRoleID"] = RoleID.ToString(); XmlRpcCall(requestID, "groups.setAgentGroupInfo", param); } public void SetAgentGroupInfo(GroupRequestID requestID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["AcceptNotices"] = AcceptNotices ? "1" : "0"; param["ListInProfile"] = ListInProfile ? "1" : "0"; XmlRpcCall(requestID, "groups.setAgentGroupInfo", param); } public int AddAgentToGroupInvite(GroupRequestID requestID, UUID inviterID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID, out string reason) { Hashtable param = new Hashtable(); param["InviterID"] = inviterID.ToString(); param["InviteID"] = inviteID.ToString(); param["AgentID"] = agentID.ToString(); param["RoleID"] = roleID.ToString(); param["GroupID"] = groupID.ToString(); XmlRpcCall(requestID, "groups.addAgentToGroupInvite", param); reason = "The user has been invited into the group."; return (int)Constants.GenericReturnCodes.SUCCESS; } public GroupInviteInfo GetAgentToGroupInvite(GroupRequestID requestID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentToGroupInvite", param); if (respData.Contains("error")) { return null; } GroupInviteInfo inviteInfo = new GroupInviteInfo(); inviteInfo.InviteID = inviteID; inviteInfo.GroupID = UUID.Parse((string)respData["GroupID"]); inviteInfo.RoleID = UUID.Parse((string)respData["RoleID"]); inviteInfo.AgentID = UUID.Parse((string)respData["AgentID"]); return inviteInfo; } public void RemoveAgentToGroupInvite(GroupRequestID requestID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); XmlRpcCall(requestID, "groups.removeAgentToGroupInvite", param); } public bool AddAgentToGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID, bool skipPermissionChecks) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestID, "groups.addAgentToGroup", param); return true; } public int RemoveAgentFromGroup(GroupRequestID requestID, UUID RequesterID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["RequesterID"] = RequesterID.ToString(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestID, "groups.removeAgentFromGroup", param); return (int)Constants.GenericReturnCodes.SUCCESS; } public void AddAgentToGroupRole(GroupRequestID requestID, UUID RequesterID, UUID AgentID, UUID GroupID, UUID RoleID, bool bypassChecks) { Hashtable param = new Hashtable(); param["RequesterID"] = RequesterID.ToString(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestID, "groups.addAgentToGroupRole", param); } public void RemoveAgentFromGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestID, "groups.removeAgentFromGroupRole", param); } public List<DirGroupsReplyData> FindGroups(GroupRequestID requestID, string search) { Hashtable param = new Hashtable(); param["Search"] = search; Hashtable respData = XmlRpcCall(requestID, "groups.findGroups", param); List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>(); if (!respData.Contains("error")) { Hashtable results = (Hashtable)respData["results"]; foreach (Hashtable groupFind in results.Values) { DirGroupsReplyData data = new DirGroupsReplyData(); data.groupID = new UUID((string)groupFind["GroupID"]); ; data.groupName = (string)groupFind["Name"]; data.members = int.Parse((string)groupFind["Members"]); // data.searchOrder = order; findings.Add(data); } } return findings; } public GroupMembershipData GetAgentGroupMembership(GroupRequestID requestID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentGroupMembership", param); if (respData.Contains("error")) { return null; } GroupMembershipData data = HashTableToGroupMembershipData(respData); return data; } public GroupMembershipData GetAgentActiveMembership(GroupRequestID requestID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentActiveMembership", param); if (respData.Contains("error")) { return null; } return HashTableToGroupMembershipData(respData); } public List<GroupMembershipData> GetAgentGroupMemberships(GroupRequestID requestID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentGroupMemberships", param); List<GroupMembershipData> memberships = new List<GroupMembershipData>(); if (!respData.Contains("error")) { foreach (object membership in respData.Values) { memberships.Add(HashTableToGroupMembershipData((Hashtable)membership)); } } return memberships; } public bool IsAgentInGroup(UUID groupID, UUID agentID) { throw new NotImplementedException(); } public List<GroupRolesData> GetAgentGroupRoles(GroupRequestID requestID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } foreach (Hashtable role in respData.Values) { GroupRolesData data = new GroupRolesData(); data.RoleID = new UUID((string)role["RoleID"]); data.Name = (string)role["Name"]; data.Description = (string)role["Description"]; data.Powers = ulong.Parse((string)role["Powers"]); data.Title = (string)role["Title"]; Roles.Add(data); } return Roles; } public List<GroupRolesData> GetGroupRoles(GroupRequestID requestID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } foreach (Hashtable role in respData.Values) { GroupRolesData data = new GroupRolesData(); data.Description = (string)role["Description"]; data.Members = int.Parse((string)role["Members"]); data.Name = (string)role["Name"]; data.Powers = ulong.Parse((string)role["Powers"]); data.RoleID = new UUID((string)role["RoleID"]); data.Title = (string)role["Title"]; Roles.Add(data); } return Roles; } private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData) { GroupMembershipData data = new GroupMembershipData(); data.AcceptNotices = ((string)respData["AcceptNotices"] == "1"); data.Contribution = int.Parse((string)respData["Contribution"]); data.ListInProfile = ((string)respData["ListInProfile"] == "1"); data.ActiveRole = new UUID((string)respData["SelectedRoleID"]); data.GroupTitle = (string)respData["Title"]; data.GroupPowers = ulong.Parse((string)respData["GroupPowers"]); // Is this group the agent's active group data.GroupID = new UUID((string)respData["GroupID"]); UUID ActiveGroup = new UUID((string)respData["ActiveGroupID"]); data.Active = data.GroupID.Equals(ActiveGroup); data.AllowPublish = ((string)respData["AllowPublish"] == "1"); if (respData.ContainsKey("Charter")) { data.Charter = (string)respData["Charter"]; } data.FounderID = new UUID((string)respData["FounderID"]); data.GroupID = new UUID((string)respData["GroupID"]); data.GroupName = (string)respData["GroupName"]; data.GroupPicture = new UUID((string)respData["InsigniaID"]); data.MaturePublish = ((string)respData["MaturePublish"] == "1"); data.MembershipFee = int.Parse((string)respData["MembershipFee"]); data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1"); data.ShowInList = ((string)respData["ShowInList"] == "1"); return data; } public List<GroupMembersData> GetGroupMembers(GroupRequestID requestID, UUID GroupID, bool ownersOnly) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupMembers", param); List<GroupMembersData> members = new List<GroupMembersData>(); if (respData.Contains("error")) { return members; } foreach (Hashtable membership in respData.Values) { GroupMembersData data = new GroupMembersData(); data.AcceptNotices = ((string)membership["AcceptNotices"]) == "1"; data.AgentID = new UUID((string)membership["AgentID"]); data.Contribution = int.Parse((string)membership["Contribution"]); data.IsOwner = ((string)membership["IsOwner"]) == "1"; data.ListInProfile = ((string)membership["ListInProfile"]) == "1"; data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]); data.Title = (string)membership["Title"]; if (data.IsOwner) members.Add(data); } return members; } public List<GroupRoleMembersData> GetGroupRoleMembers(GroupRequestID requestID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupRoleMembers", param); List<GroupRoleMembersData> members = new List<GroupRoleMembersData>(); if (!respData.Contains("error")) { foreach (Hashtable membership in respData.Values) { GroupRoleMembersData data = new GroupRoleMembersData(); data.MemberID = new UUID((string)membership["AgentID"]); data.RoleID = new UUID((string)membership["RoleID"]); members.Add(data); } } return members; } public List<GroupNoticeData> GetGroupNotices(GroupRequestID requestID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupNotices", param); List<GroupNoticeData> values = new List<GroupNoticeData>(); if (!respData.Contains("error")) { foreach (Hashtable value in respData.Values) { GroupNoticeData data = new GroupNoticeData(); data.NoticeID = UUID.Parse((string)value["NoticeID"]); data.Timestamp = uint.Parse((string)value["Timestamp"]); data.FromName = (string)value["FromName"]; data.Subject = (string)value["Subject"]; data.HasAttachment = false; data.AssetType = 0; values.Add(data); } } return values; } public GroupNoticeInfo GetGroupNotice(GroupRequestID requestID, UUID noticeID) { Hashtable param = new Hashtable(); param["NoticeID"] = noticeID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupNotice", param); if (respData.Contains("error")) { return null; } GroupNoticeInfo data = new GroupNoticeInfo(); data.GroupID = UUID.Parse((string)respData["GroupID"]); data.Message = (string)respData["Message"]; data.BinaryBucket = Utils.HexStringToBytes((string)respData["BinaryBucket"], true); data.noticeData.NoticeID = UUID.Parse((string)respData["NoticeID"]); data.noticeData.Timestamp = uint.Parse((string)respData["Timestamp"]); data.noticeData.FromName = (string)respData["FromName"]; data.noticeData.Subject = (string)respData["Subject"]; data.noticeData.HasAttachment = false; data.noticeData.AssetType = 0; if (data.Message == null) { data.Message = string.Empty; } return data; } public bool AddGroupNotice(GroupRequestID requestID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket) { string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, ""); Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["NoticeID"] = noticeID.ToString(); param["FromName"] = fromName; param["Subject"] = subject; param["Message"] = message; param["BinaryBucket"] = binBucket; param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString(); XmlRpcCall(requestID, "groups.addGroupNotice", param); return true; } private Hashtable XmlRpcCall(GroupRequestID requestID, string function, Hashtable param) { if (requestID == null) { requestID = new GroupRequestID(); } param.Add("RequestingAgentID", requestID.AgentID.ToString()); param.Add("RequestingAgentUserService", requestID.UserServiceURL); param.Add("RequestingSessionID", requestID.SessionID.ToString()); param.Add("ReadKey", m_groupReadKey); param.Add("WriteKey", m_groupWriteKey); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcResponse resp = null; try { XmlRpcRequest req; /* if (!m_disableKeepAlive) req = new XmlRpcRequest(function, parameters); else // This seems to solve a major problem on some windows servers req = new NoKeepAliveXmlRpcRequest(function, parameters); */ req = new XmlRpcRequest(function, parameters); resp = req.Send(Util.XmlRpcRequestURI(m_serviceURL, function), 10000); } catch (Exception e) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: An error has occured while attempting to access the XmlRpcGroups server method: {0}", function); m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} ", e.ToString()); foreach (string key in param.Keys) { m_log.WarnFormat("[XMLRPCGROUPDATA]: {0} :: {1}", key, param[key].ToString()); } Hashtable respData = new Hashtable(); respData.Add("error", e.ToString()); return respData; } if (resp.Value is Hashtable) { Hashtable respData = (Hashtable)resp.Value; if (respData.Contains("error") && !respData.Contains("succeed")) { LogRespDataToConsoleError(respData); } return respData; } m_log.ErrorFormat("[XMLRPCGROUPDATA]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString()); if (resp.Value is ArrayList) { ArrayList al = (ArrayList)resp.Value; m_log.ErrorFormat("[XMLRPCGROUPDATA]: Contains {0} elements", al.Count); foreach (object o in al) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} :: {1}", o.GetType().ToString(), o.ToString()); } } else { m_log.ErrorFormat("[XMLRPCGROUPDATA]: Function returned: {0}", resp.Value.ToString()); } Hashtable error = new Hashtable(); error.Add("error", "invalid return value"); return error; } private void LogRespDataToConsoleError(Hashtable respData) { m_log.Error("[XMLRPCGROUPDATA]: Error:"); foreach (string key in respData.Keys) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: Key: {0}", key); string[] lines = respData[key].ToString().Split(new char[] { '\n' }); foreach (string line in lines) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0}", line); } } } } } /* namespace Nwc.XmlRpc { using System; using System.Collections; using System.IO; using System.Xml; using System.Net; using System.Text; using System.Reflection; /// <summary>Class supporting the request side of an XML-RPC transaction.</summary> public class NoKeepAliveXmlRpcRequest : XmlRpcRequest { private Encoding _encoding = new ASCIIEncoding(); private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer(); private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer(); /// <summary>Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.</summary> /// <param name="methodName"><c>String</c> designating the <i>object.method</i> on the server the request /// should be directed to.</param> /// <param name="parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param> public NoKeepAliveXmlRpcRequest(String methodName, IList parameters) { MethodName = methodName; _params = parameters; } /// <summary>Send the request to the server.</summary> /// <param name="url"><c>String</c> The url of the XML-RPC server.</param> /// <returns><c>XmlRpcResponse</c> The response generated.</returns> public XmlRpcResponse Send(String url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); if (request == null) throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR, XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url); request.Method = "POST"; request.ContentType = "text/xml"; request.AllowWriteStreamBuffering = true; request.KeepAlive = false; Stream stream = request.GetRequestStream(); XmlTextWriter xml = new XmlTextWriter(stream, _encoding); _serializer.Serialize(xml, this); xml.Flush(); xml.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader input = new StreamReader(response.GetResponseStream()); XmlRpcResponse resp = (XmlRpcResponse)_deserializer.Deserialize(input); input.Close(); response.Close(); return resp; } } } */
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using MSCloudIPs.Areas.HelpPage.ModelDescriptions; using MSCloudIPs.Areas.HelpPage.Models; namespace MSCloudIPs.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }