context
stringlengths
2.52k
185k
gt
stringclasses
1 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 System.Collections.Generic; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; namespace System.Data.OleDb { using SysTx = Transactions; internal sealed class OleDbConnectionInternal : DbConnectionInternal, IDisposable { private static volatile OleDbServicesWrapper idataInitialize; private static readonly object dataInitializeLock = new object(); internal readonly OleDbConnectionString ConnectionString; // parsed connection string attributes // A SafeHandle is used instead of a RCW because we need to fake the CLR into not marshalling // OLE DB Services is marked apartment thread, but it actually supports/requires free-threading. // However the CLR doesn't know this and attempts to marshal the interfaces back to their original context. // But the OLE DB doesn't marshal very well if at all. Our workaround is based on the fact // OLE DB is free-threaded and allows the workaround. // Creating DataSource/Session would requiring marshalling DataLins to its original context // and has a severe performance impact (when working with transactions), hence our workaround to not Marshal. // Creating a Command would requiring marshalling Session to its original context and // actually doesn't work correctly, without our workaround you must execute the command in // the same context of the connection open. This doesn't work for pooled objects that contain // an open OleDbConnection. // We don't do extra work at this time to allow the DataReader to be used in a different context // from which the command was executed in. IRowset.GetNextRows will throw InvalidCastException // In V1.0, we worked around the performance impact of creating a DataSource/Session using // WrapIUnknownWithComObject which creates a new RCW without searching for existing RCW // effectively faking out the CLR into thinking the call is in the correct context. // We also would use Marshal.ReleaseComObject to force the release of the 'temporary' RCW. // In V1.1, we worked around the CreateCommand issue with the same WrapIUnknownWithComObject trick. // In V2.0, the performance of using WrapIUnknownWithComObject & ReleaseComObject severly degraded. // Using a SafeHandle (for lifetime control) and a delegate to call the apporiate COM method // offered much better performance. // the "Data Source object". private readonly DataSourceWrapper _datasrcwrp; // the "Session object". private readonly SessionWrapper _sessionwrp; private WeakReference weakTransaction; // When set to true the current connection is enlisted in a transaction that must be // un-enlisted during Deactivate. private bool _unEnlistDuringDeactivate; internal OleDbConnectionInternal(OleDbConnectionString constr, OleDbConnection connection) : base() { Debug.Assert((null != constr) && !constr.IsEmpty, "empty connectionstring"); ConnectionString = constr; if (constr.PossiblePrompt && !System.Environment.UserInteractive) { throw ODB.PossiblePromptNotUserInteractive(); } try { // this is the native DataLinks object which pools the native datasource/session OleDbServicesWrapper wrapper = OleDbConnectionInternal.GetObjectPool(); _datasrcwrp = new DataSourceWrapper(); // DataLinks wrapper will call IDataInitialize::GetDataSource to create the DataSource // uses constr.ActualConnectionString, no InfoMessageEvent checking wrapper.GetDataSource(constr, ref _datasrcwrp); Debug.Assert(!_datasrcwrp.IsInvalid, "bad DataSource"); // initialization is delayed because of OleDbConnectionStringBuilder only wants // pre-Initialize IDBPropertyInfo & IDBProperties on the data source if (null != connection) { _sessionwrp = new SessionWrapper(); // From the DataSource object, will call IDBInitialize.Initialize & IDBCreateSession.CreateSession // We always need both called so we use a single call for a single DangerousAddRef/DangerousRelease pair. OleDbHResult hr = _datasrcwrp.InitializeAndCreateSession(constr, ref _sessionwrp); // process the HResult here instead of from the SafeHandle because the possibility // of an InfoMessageEvent. if ((0 <= hr) && !_sessionwrp.IsInvalid) { // process infonessage events OleDbConnection.ProcessResults(hr, connection, connection); } else { Exception e = OleDbConnection.ProcessResults(hr, null, null); Debug.Assert(null != e, "CreateSessionError"); throw e; } Debug.Assert(!_sessionwrp.IsInvalid, "bad Session"); } } catch { if (null != _sessionwrp) { _sessionwrp.Dispose(); _sessionwrp = null; } if (null != _datasrcwrp) { _datasrcwrp.Dispose(); _datasrcwrp = null; } throw; } } internal OleDbConnection Connection { get { return (OleDbConnection)Owner; } } internal bool HasSession { get { return (null != _sessionwrp); } } internal OleDbTransaction LocalTransaction { get { OleDbTransaction result = null; if (null != weakTransaction) { result = ((OleDbTransaction)weakTransaction.Target); } return result; } set { weakTransaction = null; if (null != value) { weakTransaction = new WeakReference((OleDbTransaction)value); } } } private string Provider { get { return ConnectionString.Provider; } } public override string ServerVersion { // consider making a method, not a property get { object value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DBMSVER); return Convert.ToString(value, CultureInfo.InvariantCulture); } } // grouping the native OLE DB casts togther by required interfaces and optional interfaces, connection then session // want these to be methods, not properties otherwise they appear in VS7 managed debugger which attempts to evaluate them // required interface, safe cast internal IDBPropertiesWrapper IDBProperties() { Debug.Assert(null != _datasrcwrp, "IDBProperties: null datasource"); return _datasrcwrp.IDBProperties(this); } // required interface, safe cast internal IOpenRowsetWrapper IOpenRowset() { Debug.Assert(null != _datasrcwrp, "IOpenRowset: null datasource"); Debug.Assert(null != _sessionwrp, "IOpenRowset: null session"); return _sessionwrp.IOpenRowset(this); } // optional interface, unsafe cast private IDBInfoWrapper IDBInfo() { Debug.Assert(null != _datasrcwrp, "IDBInfo: null datasource"); return _datasrcwrp.IDBInfo(this); } // optional interface, unsafe cast internal IDBSchemaRowsetWrapper IDBSchemaRowset() { Debug.Assert(null != _datasrcwrp, "IDBSchemaRowset: null datasource"); Debug.Assert(null != _sessionwrp, "IDBSchemaRowset: null session"); return _sessionwrp.IDBSchemaRowset(this); } // optional interface, unsafe cast internal ITransactionJoinWrapper ITransactionJoin() { Debug.Assert(null != _datasrcwrp, "ITransactionJoin: null datasource"); Debug.Assert(null != _sessionwrp, "ITransactionJoin: null session"); return _sessionwrp.ITransactionJoin(this); } // optional interface, unsafe cast internal UnsafeNativeMethods.ICommandText ICommandText() { Debug.Assert(null != _datasrcwrp, "IDBCreateCommand: null datasource"); Debug.Assert(null != _sessionwrp, "IDBCreateCommand: null session"); object icommandText = null; OleDbHResult hr = _sessionwrp.CreateCommand(ref icommandText); Debug.Assert((0 <= hr) || (null == icommandText), "CreateICommandText: error with ICommandText"); if (hr < 0) { if (OleDbHResult.E_NOINTERFACE != hr) { ProcessResults(hr); } else { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } return (UnsafeNativeMethods.ICommandText)icommandText; } protected override void Activate(SysTx.Transaction transaction) { throw ADP.NotSupported(); } public override DbTransaction BeginTransaction(IsolationLevel isolationLevel) { OleDbConnection outerConnection = Connection; if (null != LocalTransaction) { throw ADP.ParallelTransactionsNotSupported(outerConnection); } object unknown = null; OleDbTransaction transaction; try { transaction = new OleDbTransaction(outerConnection, null, isolationLevel); Debug.Assert(null != _datasrcwrp, "ITransactionLocal: null datasource"); Debug.Assert(null != _sessionwrp, "ITransactionLocal: null session"); unknown = _sessionwrp.ComWrapper(); UnsafeNativeMethods.ITransactionLocal value = (unknown as UnsafeNativeMethods.ITransactionLocal); if (null == value) { throw ODB.TransactionsNotSupported(Provider, (Exception)null); } transaction.BeginInternal(value); } finally { if (null != unknown) { Marshal.ReleaseComObject(unknown); } } LocalTransaction = transaction; return transaction; } protected override DbReferenceCollection CreateReferenceCollection() { return new OleDbReferenceCollection(); } protected override void Deactivate() { // used by both managed and native pooling NotifyWeakReference(OleDbReferenceCollection.Closing); if (_unEnlistDuringDeactivate) { // Un-enlist transaction as OLEDB connection pool is unaware of managed transactions. EnlistTransactionInternal(null); } OleDbTransaction transaction = LocalTransaction; if (null != transaction) { LocalTransaction = null; // required to rollback any transactions on this connection // before releasing the back to the oledb connection pool transaction.Dispose(); } } public override void Dispose() { Debug.Assert(null == LocalTransaction, "why was Deactivate not called first"); if (null != _sessionwrp) { _sessionwrp.Dispose(); } if (null != _datasrcwrp) { _datasrcwrp.Dispose(); } base.Dispose(); } public override void EnlistTransaction(SysTx.Transaction transaction) { OleDbConnection outerConnection = Connection; if (null != LocalTransaction) { throw ADP.LocalTransactionPresent(); } EnlistTransactionInternal(transaction); } internal void EnlistTransactionInternal(SysTx.Transaction transaction) { SysTx.IDtcTransaction oleTxTransaction = ADP.GetOletxTransaction(transaction); using (ITransactionJoinWrapper transactionJoin = ITransactionJoin()) { if (null == transactionJoin.Value) { throw ODB.TransactionsNotSupported(Provider, (Exception)null); } transactionJoin.Value.JoinTransaction(oleTxTransaction, (int)IsolationLevel.Unspecified, 0, IntPtr.Zero); _unEnlistDuringDeactivate = (null != transaction); } EnlistedTransaction = transaction; } internal object GetDataSourceValue(Guid propertySet, int propertyID) { object value = GetDataSourcePropertyValue(propertySet, propertyID); if ((value is OleDbPropertyStatus) || Convert.IsDBNull(value)) { value = null; } return value; } internal object GetDataSourcePropertyValue(Guid propertySet, int propertyID) { OleDbHResult hr; tagDBPROP[] dbprops; using (IDBPropertiesWrapper idbProperties = IDBProperties()) { using (PropertyIDSet propidset = new PropertyIDSet(propertySet, propertyID)) { using (DBPropSet propset = new DBPropSet(idbProperties.Value, propidset, out hr)) { if (hr < 0) { // OLEDB Data Reader masks provider specific errors by raising "Internal Data Provider error 30." // DBPropSet c-tor will register the exception and it will be raised at GetPropertySet call in case of failure SafeNativeMethods.Wrapper.ClearErrorInfo(); } dbprops = propset.GetPropertySet(0, out propertySet); } } } if (OleDbPropertyStatus.Ok == dbprops[0].dwStatus) { return dbprops[0].vValue; } return dbprops[0].dwStatus; } internal DataTable BuildInfoLiterals() { using (IDBInfoWrapper wrapper = IDBInfo()) { UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value; if (null == dbInfo) { return null; } DataTable table = new DataTable("DbInfoLiterals"); table.Locale = CultureInfo.InvariantCulture; DataColumn literalName = new DataColumn("LiteralName", typeof(string)); DataColumn literalValue = new DataColumn("LiteralValue", typeof(string)); DataColumn invalidChars = new DataColumn("InvalidChars", typeof(string)); DataColumn invalidStart = new DataColumn("InvalidStartingChars", typeof(string)); DataColumn literal = new DataColumn("Literal", typeof(int)); DataColumn maxlen = new DataColumn("Maxlen", typeof(int)); table.Columns.Add(literalName); table.Columns.Add(literalValue); table.Columns.Add(invalidChars); table.Columns.Add(invalidStart); table.Columns.Add(literal); table.Columns.Add(maxlen); OleDbHResult hr; int literalCount = 0; IntPtr literalInfo = ADP.PtrZero; using (DualCoTaskMem handle = new DualCoTaskMem(dbInfo, null, out literalCount, out literalInfo, out hr)) { // All literals were either invalid or unsupported. The provider allocates memory for *prgLiteralInfo and sets the value of the fSupported element in all of the structures to FALSE. The consumer frees this memory when it no longer needs the information. if (OleDbHResult.DB_E_ERRORSOCCURRED != hr) { long offset = literalInfo.ToInt64(); tagDBLITERALINFO tag = new tagDBLITERALINFO(); for (int i = 0; i < literalCount; ++i, offset += ODB.SizeOf_tagDBLITERALINFO) { Marshal.PtrToStructure((IntPtr)offset, tag); DataRow row = table.NewRow(); row[literalName] = ((OleDbLiteral)tag.it).ToString(); row[literalValue] = tag.pwszLiteralValue; row[invalidChars] = tag.pwszInvalidChars; row[invalidStart] = tag.pwszInvalidStartingChars; row[literal] = tag.it; row[maxlen] = tag.cchMaxLen; table.Rows.Add(row); row.AcceptChanges(); } if (hr < 0) { // ignore infomsg ProcessResults(hr); } } else { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } return table; } } internal DataTable BuildInfoKeywords() { DataTable table = new DataTable(ODB.DbInfoKeywords); table.Locale = CultureInfo.InvariantCulture; DataColumn keyword = new DataColumn(ODB.Keyword, typeof(string)); table.Columns.Add(keyword); if (!AddInfoKeywordsToTable(table, keyword)) { table = null; } return table; } internal bool AddInfoKeywordsToTable(DataTable table, DataColumn keyword) { using (IDBInfoWrapper wrapper = IDBInfo()) { UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value; if (null == dbInfo) { return false; } OleDbHResult hr; string keywords; hr = dbInfo.GetKeywords(out keywords); if (hr < 0) { // ignore infomsg ProcessResults(hr); } if (null != keywords) { string[] values = keywords.Split(new char[1] { ',' }); for (int i = 0; i < values.Length; ++i) { DataRow row = table.NewRow(); row[keyword] = values[i]; table.Rows.Add(row); row.AcceptChanges(); } } return true; } } internal DataTable BuildSchemaGuids() { DataTable table = new DataTable(ODB.SchemaGuids); table.Locale = CultureInfo.InvariantCulture; DataColumn schemaGuid = new DataColumn(ODB.Schema, typeof(Guid)); DataColumn restrictionSupport = new DataColumn(ODB.RestrictionSupport, typeof(int)); table.Columns.Add(schemaGuid); table.Columns.Add(restrictionSupport); SchemaSupport[] supportedSchemas = GetSchemaRowsetInformation(); if (null != supportedSchemas) { object[] values = new object[2]; table.BeginLoadData(); for (int i = 0; i < supportedSchemas.Length; ++i) { values[0] = supportedSchemas[i]._schemaRowset; values[1] = supportedSchemas[i]._restrictions; table.LoadDataRow(values, LoadOption.OverwriteChanges); } table.EndLoadData(); } return table; } internal string GetLiteralInfo(int literal) { using (IDBInfoWrapper wrapper = IDBInfo()) { UnsafeNativeMethods.IDBInfo dbInfo = wrapper.Value; if (null == dbInfo) { return null; } string literalValue = null; IntPtr literalInfo = ADP.PtrZero; int literalCount = 0; OleDbHResult hr; using (DualCoTaskMem handle = new DualCoTaskMem(dbInfo, new int[1] { literal }, out literalCount, out literalInfo, out hr)) { // All literals were either invalid or unsupported. The provider allocates memory for *prgLiteralInfo and sets the value of the fSupported element in all of the structures to FALSE. The consumer frees this memory when it no longer needs the information. if (OleDbHResult.DB_E_ERRORSOCCURRED != hr) { if ((1 == literalCount) && Marshal.ReadInt32(literalInfo, ODB.OffsetOf_tagDBLITERALINFO_it) == literal) { literalValue = Marshal.PtrToStringUni(Marshal.ReadIntPtr(literalInfo, 0)); } if (hr < 0) { // ignore infomsg ProcessResults(hr); } } else { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } return literalValue; } } internal SchemaSupport[] GetSchemaRowsetInformation() { OleDbConnectionString constr = ConnectionString; SchemaSupport[] supportedSchemas = constr.SchemaSupport; if (null != supportedSchemas) { return supportedSchemas; } using (IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset()) { UnsafeNativeMethods.IDBSchemaRowset dbSchemaRowset = wrapper.Value; if (null == dbSchemaRowset) { return null; // IDBSchemaRowset not supported } OleDbHResult hr; int schemaCount = 0; IntPtr schemaGuids = ADP.PtrZero; IntPtr schemaRestrictions = ADP.PtrZero; using (DualCoTaskMem safehandle = new DualCoTaskMem(dbSchemaRowset, out schemaCount, out schemaGuids, out schemaRestrictions, out hr)) { dbSchemaRowset = null; if (hr < 0) { // ignore infomsg ProcessResults(hr); } supportedSchemas = new SchemaSupport[schemaCount]; if (ADP.PtrZero != schemaGuids) { for (int i = 0, offset = 0; i < supportedSchemas.Length; ++i, offset += ODB.SizeOf_Guid) { IntPtr ptr = ADP.IntPtrOffset(schemaGuids, i * ODB.SizeOf_Guid); supportedSchemas[i]._schemaRowset = (Guid)Marshal.PtrToStructure(ptr, typeof(Guid)); } } if (ADP.PtrZero != schemaRestrictions) { for (int i = 0; i < supportedSchemas.Length; ++i) { supportedSchemas[i]._restrictions = Marshal.ReadInt32(schemaRestrictions, i * 4); } } } constr.SchemaSupport = supportedSchemas; return supportedSchemas; } } internal DataTable GetSchemaRowset(Guid schema, object[] restrictions) { if (null == restrictions) { restrictions = Array.Empty<object>(); } DataTable dataTable = null; using (IDBSchemaRowsetWrapper wrapper = IDBSchemaRowset()) { UnsafeNativeMethods.IDBSchemaRowset dbSchemaRowset = wrapper.Value; if (null == dbSchemaRowset) { throw ODB.SchemaRowsetsNotSupported(Provider); } UnsafeNativeMethods.IRowset rowset = null; OleDbHResult hr; hr = dbSchemaRowset.GetRowset(ADP.PtrZero, ref schema, restrictions.Length, restrictions, ref ODB.IID_IRowset, 0, ADP.PtrZero, out rowset); if (hr < 0) { // ignore infomsg ProcessResults(hr); } if (null != rowset) { using (OleDbDataReader dataReader = new OleDbDataReader(Connection, null, 0, CommandBehavior.Default)) { dataReader.InitializeIRowset(rowset, ChapterHandle.DB_NULL_HCHAPTER, IntPtr.Zero); dataReader.BuildMetaInfo(); dataReader.HasRowsRead(); dataTable = new DataTable(); dataTable.Locale = CultureInfo.InvariantCulture; dataTable.TableName = OleDbSchemaGuid.GetTextFromValue(schema); OleDbDataAdapter.FillDataTable(dataReader, dataTable); } } return dataTable; } } // returns true if there is an active data reader on the specified command internal bool HasLiveReader(OleDbCommand cmd) { OleDbDataReader reader = null; if (null != ReferenceCollection) { reader = ReferenceCollection.FindItem<OleDbDataReader>(OleDbReferenceCollection.DataReaderTag, (dataReader) => cmd == dataReader.Command); } return (reader != null); } private void ProcessResults(OleDbHResult hr) { OleDbConnection connection = Connection; // get value from weakref only once Exception e = OleDbConnection.ProcessResults(hr, connection, connection); if (null != e) { throw e; } } internal bool SupportSchemaRowset(Guid schema) { SchemaSupport[] schemaSupport = GetSchemaRowsetInformation(); if (null != schemaSupport) { for (int i = 0; i < schemaSupport.Length; ++i) { if (schema == schemaSupport[i]._schemaRowset) { return true; } } } return false; } private static object CreateInstanceDataLinks() { Type datalink = Type.GetTypeFromCLSID(ODB.CLSID_DataLinks, true); return Activator.CreateInstance(datalink, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); } // @devnote: should be multithread safe access to OleDbConnection.idataInitialize, // though last one wins for setting variable. It may be different objects, but // OLE DB will ensure I'll work with just the single pool private static OleDbServicesWrapper GetObjectPool() { OleDbServicesWrapper wrapper = OleDbConnectionInternal.idataInitialize; if (null == wrapper) { lock (dataInitializeLock) { wrapper = OleDbConnectionInternal.idataInitialize; if (null == wrapper) { VersionCheck(); object datalinks; try { datalinks = CreateInstanceDataLinks(); } catch (Exception e) { // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableExceptionType(e)) { throw; } throw ODB.MDACNotAvailable(e); } if (null == datalinks) { throw ODB.MDACNotAvailable(null); } wrapper = new OleDbServicesWrapper(datalinks); OleDbConnectionInternal.idataInitialize = wrapper; } } } Debug.Assert(null != wrapper, "GetObjectPool: null dataInitialize"); return wrapper; } private static void VersionCheck() { // $REVIEW: do we still need this? // if ApartmentUnknown, then CoInitialize may not have been called yet if (ApartmentState.Unknown == Thread.CurrentThread.GetApartmentState()) { SetMTAApartmentState(); } ADP.CheckVersionMDAC(false); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void SetMTAApartmentState() { // we are defaulting to a multithread apartment state Thread.CurrentThread.SetApartmentState(ApartmentState.MTA); } // @devnote: should be multithread safe public static void ReleaseObjectPool() { OleDbConnectionInternal.idataInitialize = null; } internal OleDbTransaction ValidateTransaction(OleDbTransaction transaction, string method) { if (null != this.weakTransaction) { OleDbTransaction head = (OleDbTransaction)this.weakTransaction.Target; if ((null != head) && this.weakTransaction.IsAlive) { head = OleDbTransaction.TransactionUpdate(head); // either we are wrong or finalize was called and object still alive Debug.Assert(null != head, "unexcpted Transaction state"); } // else transaction has finalized on user if (null != head) { if (null == transaction) { // valid transaction exists and cmd doesn't have it throw ADP.TransactionRequired(method); } else { OleDbTransaction tail = OleDbTransaction.TransactionLast(head); if (tail != transaction) { if (tail.Connection != transaction.Connection) { throw ADP.TransactionConnectionMismatch(); } // else cmd has incorrect transaction throw ADP.TransactionCompleted(); } // else cmd has correct transaction return transaction; } } else { // cleanup for Finalized transaction this.weakTransaction = null; } } else if ((null != transaction) && (null != transaction.Connection)) { throw ADP.TransactionConnectionMismatch(); } // else no transaction and cmd is correct // if transactionObject is from this connection but zombied // and no transactions currently exists - then ignore the bogus object return null; } internal Dictionary<string, OleDbPropertyInfo> GetPropertyInfo(Guid[] propertySets) { bool isopen = HasSession; OleDbConnectionString constr = ConnectionString; Dictionary<string, OleDbPropertyInfo> properties = null; if (null == propertySets) { propertySets = Array.Empty<Guid>(); } using (PropertyIDSet propidset = new PropertyIDSet(propertySets)) { using (IDBPropertiesWrapper idbProperties = IDBProperties()) { using (PropertyInfoSet infoset = new PropertyInfoSet(idbProperties.Value, propidset)) { properties = infoset.GetValues(); } } } return properties; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareScalarNotLessThanSingle() { var test = new SimpleBinaryOpTest__CompareScalarNotLessThanSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareScalarNotLessThanSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarNotLessThanSingle testClass) { var result = Sse.CompareScalarNotLessThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarNotLessThanSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarNotLessThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareScalarNotLessThanSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__CompareScalarNotLessThanSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareScalarNotLessThan( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareScalarNotLessThan( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareScalarNotLessThan( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarNotLessThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarNotLessThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarNotLessThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareScalarNotLessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareScalarNotLessThan( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareScalarNotLessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarNotLessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarNotLessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareScalarNotLessThanSingle(); var result = Sse.CompareScalarNotLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareScalarNotLessThanSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarNotLessThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareScalarNotLessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarNotLessThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareScalarNotLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareScalarNotLessThan( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != (!(left[0] < right[0]) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarNotLessThan)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* Copyright (c) 2004-2005 Jan Benda and Ladislav Prosek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Threading; using System.Collections; using System.Runtime.Serialization; using System.Diagnostics; #if SILVERLIGHT using PHP.CoreCLR; #endif namespace PHP.Core { /// <summary> /// Base class for PHP Resources - both built-in and extension-resources. /// Resources rely on GC Finalization - override FreeManaged for cleanup. /// When printing a resource variable in PHP, "Resource id #x" prints out. /// </summary> [Serializable] public class PhpResource : IDisposable, IPhpVariable, ISerializable, IPhpObjectGraphNode { /// <summary>The name of this variable type.</summary> public const string PhpTypeName = "resource"; /// <summary> /// Handles deserialization of <see cref="PhpResource"/> instances in cases when the instance was serialized /// with <see cref="StreamingContextStates.Persistence"/> /// </summary> [Serializable] internal class Deserializer : IObjectReference { #region IObjectReference Members /// <include file='Doc/Common.xml' path='/docs/method[@name="GetRealObject"]/*'/> /// <remarks> /// All PHP resources are deserialized as integer 0. /// </remarks> public object GetRealObject(StreamingContext context) { return 0; } #endregion } /// <summary> /// Allocate a unique identifier for a resource. /// </summary> /// <remarks> /// Internal resources are given even numbers while resources /// allocated by extensions get odd numbers to minimize the communication /// between internal and external resource managers. /// </remarks> /// <returns>The unique identifier of an internal resource (even number starting from 2).</returns> private static int RegisterInternalInstance() { Interlocked.Increment(ref PhpResource.ResourceIdCounter); // Even numbers are reserved for internal use (odd for externals) return PhpResource.ResourceIdCounter * 2; } /// <summary> /// Create a new instance with the given Id. Used by <see cref="PhpExternalResource"/>s. /// </summary> /// <param name="resourceId">Unique resource identifier (odd for external resources).</param> /// <param name="resourceTypeName">The type to be reported to use when dumping a resource.</param> /// <param name="registerInReqContext">Whether to register this instance in current <see cref="RequestContext"/>. Should be <c>false</c> for static resources.</param> protected PhpResource(int resourceId, String resourceTypeName, bool registerInReqContext) { this.mResourceId = resourceId; this.mTypeName = resourceTypeName; if (registerInReqContext) { // register this resource into PhpResourceManager, // so the resource will be automatically disposed at the request end. this.reqContextRegistrationNode = PhpResourceManager.RegisterResource(this); } } /// <summary> /// Create a new instance with the given Id. Used by <see cref="PhpExternalResource"/>s. /// </summary> /// <param name="resourceId">Unique resource identifier (odd for external resources).</param> /// <param name="resourceTypeName">The type to be reported to use when dumping a resource.</param> protected PhpResource(int resourceId, String resourceTypeName) : this(resourceId, resourceTypeName, true) { } /// <summary> /// Create a new instance of a given Type and Name. /// The instance Id is auto-incrementing starting from 1. /// </summary> /// <param name="resourceTypeName">The type to be reported to use when dumping a resource.</param> public PhpResource(String resourceTypeName) : this(resourceTypeName, true) { } /// <summary> /// Create a new instance of a given Type and Name. /// The instance Id is auto-incrementing starting from 1. /// </summary> /// <param name="resourceTypeName">The type to be reported to use when dumping a resource.</param> /// <param name="registerInReqContext">Whether to register this instance in current <see cref="RequestContext"/>. Should be <c>false</c> for static resources.</param> public PhpResource(String resourceTypeName, bool registerInReqContext) : this(PhpResource.RegisterInternalInstance(), resourceTypeName, registerInReqContext) { } #if !SILVERLIGHT /// <include file='Doc/Common.xml' path='/docs/method[@name="serialization.ctor"]/*'/> protected PhpResource(SerializationInfo info, StreamingContext context) { mDisposed = info.GetBoolean("mDisposed"); mResourceId = info.GetInt32("mResourceId"); mTypeName = info.GetString("mTypeName"); } #endif /// <summary> /// Creates a new invalid resource. /// </summary> internal PhpResource() { mDisposed = true; mTypeName = DisposedTypeName; } /// <summary> /// Returns a string that represents the current PhpResource. /// </summary> /// <returns>'Resource id #ID'</returns> public override string ToString() { return String.Concat(PhpTypeName + " id #", this.mResourceId.ToString()); } #region Finalization & Dispose Pattern /// <summary> /// The finalizer. /// </summary> ~PhpResource() { Dispose(false); } /// <summary> /// An alias of <see cref="Dispose"/>. /// </summary> public virtual void Close() { Dispose(); } /// <summary> /// Dosposes the resource. /// </summary> public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } /// <summary> /// Cleans-up the resource. /// </summary> /// <remarks> /// When disposing non-deterministically, only unmanaged resources should be freed. /// <seealso cref="FreeUnmanaged"/> /// </remarks> /// <param name="disposing">Whether the resource is disposed deterministically.</param> private void Dispose(bool disposing) { if (!this.mDisposed) { this.mDisposed = true; // dispose managed resources: if (disposing) { this.FreeManaged(); } // dispose unmanaged resources ("unfinalized"): this.FreeUnmanaged(); // unregister from the RequestContext this.UnregisterResource(); } // shows the user this Resource is no longer valid: this.mTypeName = PhpResource.DisposedTypeName; } /// <summary> /// Unregister this instance of <see cref="PhpResource"/> from current <see cref="RequestContext"/>. /// </summary> private void UnregisterResource() { if (this.reqContextRegistrationNode != null) { PhpResourceManager.UnregisterResource(this.reqContextRegistrationNode); this.reqContextRegistrationNode = null; } } /// <summary> /// Override this virtual method in your descendants to perform /// cleanup of Managed resources - those having a Finalizer of their own. /// </summary> /// <remarks> /// Note that when Disposing explicitly, both FreeManaged and FreeUnmanaged are called. /// </remarks> protected virtual void FreeManaged() { } /// <summary> /// Override this virtual method to cleanup the contained unmanaged objects. /// </summary> /// <remarks> /// Note that when Dispose(false) is called from the Finalizer, /// the order of finalization is random. In other words, contained /// managed objects may have been already finalized - don't reference them. /// </remarks> protected virtual void FreeUnmanaged() { } #endregion /// <summary>Identifier of a PhpResource instance. Unique index starting at 1</summary> public int Id { get { return mResourceId; } } // <summary>Type of PhpResource - used by extensions and get_resource_type()</summary> //REMoved public int Type { get { return mType; }} /// <summary>Type resource name - string to be reported to user when dumping a resource.</summary> public String TypeName { get { return mTypeName; } } /// <summary>false if the resource has been already disposed</summary> public bool IsValid { get { return !this.mDisposed; } } /// <summary>Unique resource identifier (even for internal resources, odd for external ones).</summary> /// <remarks> /// Internal resources are given even numbers while resources /// allocated by extensions get odd numbers to minimize the communication /// between internal and external resource managers. /// </remarks> protected int mResourceId; /// <summary> /// Type resource name - string to be reported to user when dumping a resource. /// </summary> protected String mTypeName; /// <summary> /// Set in Dispose to avoid multiple cleanup attempts. /// </summary> private bool mDisposed = false; /// <summary> /// If this resource is registered into <see cref="RequestContext"/>, this points into linked list containing registered resources. /// </summary> private System.Collections.Generic.LinkedListNode<WeakReference> reqContextRegistrationNode; /// <summary>Static counter for unique PhpResource instance Id's</summary> private static int ResourceIdCounter = 0; /// <summary>The resources' TypeName to be displayed after call to Dispose</summary> private static String DisposedTypeName = "Unknown"; #region IPhpVariable Members /// <summary> /// Defines emptiness of the <see cref="PhpResource"/>. /// </summary> /// <returns><B>false</B>. A valid resource is never empty.</returns> public bool IsEmpty() { return !this.IsValid; } /// <summary> /// Defines whether <see cref="PhpResource"/> is a scalar. /// </summary> /// <returns><B>false</B></returns> public bool IsScalar() { return false; } /// <summary> /// Returns a name of declaring type. /// </summary> /// <returns>The name.</returns> public string GetTypeName() { return PhpTypeName; } #endregion #region IPhpCloneable Members /// <summary>Creates a copy of this instance.</summary> /// <remarks> /// Instances of the PhpResource class are never cloned. /// When assigning a resource to another variable in a script, /// only a shallow copy is performed. /// </remarks> /// <returns>The copy of this instance.</returns> public object Copy(CopyReason reason) { return this; } /// <summary>Creates a copy of this instance.</summary> /// <remarks> /// Instances of the PhpResource class are never cloned. /// When assigning a resource to another variable in a script, /// only a shallow copy is performed. /// </remarks> /// <returns>The copy of this instance.</returns> public object DeepCopy() { return this; } #endregion #region IPhpComparable Members /// <summary> /// Compares this instance with an object of arbitrary PHP.NET type. /// </summary> /// <remarks> /// When compared with other PHP variables, PhpResource behaves like /// its integer representation, i.e. the resource ID (except of the === operator). /// </remarks> /// <include file='Doc/Common.xml' path='docs/method[@name="CompareTo(obj)"]/*'/> public int CompareTo(object obj) { return CompareTo(obj, PhpComparer.Default); } /// <include file='Doc/Common.xml' path='docs/method[@name="CompareTo(obj,comparer)"]/*' /> public int CompareTo(object obj, IComparer/*!*/ comparer) { Debug.Assert(comparer != null); return comparer.Compare(this.mResourceId, obj); } #endregion #region IPhpPrintable interface /// <summary> /// Prints values only. /// 'Resource id #ID' /// </summary> /// <param name="output">The output stream.</param> public void Print(TextWriter output) { output.WriteLine(ToString()); } /// <summary> /// Prints types and values. /// 'resource(ID) of type(TYPE)' /// </summary> /// <param name="output">The output stream.</param> public void Dump(TextWriter output) { output.WriteLine("resource({0}) of type ({1})", this.mResourceId, this.mTypeName); } /// <summary> /// Prints object's definition in PHP language. /// 'NULL' - unexportable /// </summary> /// <param name="output">The output stream.</param> public void Export(TextWriter output) { output.Write("NULL"); } #endregion #region IPhpConvertible Members /// <include file='Doc/Conversions.xml' path='docs/method[@name="GetTypeCode"]/*' /> public PhpTypeCode GetTypeCode() { return PhpTypeCode.PhpResource; } /// <include file='Doc/Conversions.xml' path='docs/method[@name="ToInteger"]/*' /> public int ToInteger() { return this.IsValid ? this.mResourceId : 0; } /// <summary> /// Returns <c>0</c>. /// </summary> /// <returns><c>0</c></returns> public long ToLongInteger() { return this.IsValid ? this.mResourceId : 0; } /// <include file='Doc/Conversions.xml' path='docs/method[@name="ToDouble"]/*' /> public double ToDouble() { return this.IsValid ? this.mResourceId : 0; } /// <include file='Doc/Conversions.xml' path='docs/method[@name="ToBoolean"]/*' /> public bool ToBoolean() { return this.IsValid; } /// <include file='Doc/Conversions.xml' path='docs/method[@name="ToPhpBytes"]/*' /> public PhpBytes ToPhpBytes() { return new PhpBytes(ToString()); } /// <summary> /// Converts instance to its string representation according to PHP conversion algorithm. /// </summary> /// <param name="success">Indicates whether conversion was successful.</param> /// <param name="throwOnError">Throw out 'Notice' when conversion wasn't successful?</param> /// <returns>The converted value.</returns> string IPhpConvertible.ToString(bool throwOnError, out bool success) { success = false; return ToString(); } /// <summary> /// Converts instance to a number of type <see cref="int"/>. /// </summary> /// <param name="doubleValue">The resource id.</param> /// <param name="intValue">The resource id.</param> /// <param name="longValue">The resource id.</param> /// <returns><see cref="Convert.NumberInfo.Integer"/>.</returns> public Convert.NumberInfo ToNumber(out int intValue, out long longValue, out double doubleValue) { doubleValue = this.mResourceId; intValue = this.mResourceId; longValue = this.mResourceId; return Convert.NumberInfo.Integer; } #endregion #region ISerializable Members #if !SILVERLIGHT /// <include file='Doc/Common.xml' path='/docs/method[@name="GetObjectData"]/*'/> [System.Security.SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { if ((context.State & StreamingContextStates.Persistence) == StreamingContextStates.Persistence || !typeof(PhpExternalResource).IsInstanceOfType(this)) { // serialization is requested by user via the serialize() PHP function info.SetType(typeof(Deserializer)); } else { // serialization is requested by Remoting and this this is a PhpExternalResource info.AddValue("mDisposed", mDisposed); info.AddValue("mResourceId", mResourceId); info.AddValue("mTypeName", mTypeName); } } #endif #endregion #region IPhpObjectGraphNode Members /// <summary> /// Walks the object graph rooted in this node. /// </summary> /// <param name="callback">The callback method.</param> /// <param name="context">Current <see cref="ScriptContext"/>.</param> public void Walk(PhpWalkCallback callback, ScriptContext context) { // PhpResources have no child objects, however as they constitute an interesting PHP type, // IPhpObjectGraphNode is implemented } #endregion } /// <summary> /// Represents a resource that was created by an extension and lives in <c>ExtManager</c>. /// </summary> [Serializable] public class PhpExternalResource : PhpResource { /// <summary> /// Creates a new <see cref="PhpExternalResource"/>. /// </summary> /// <param name="resourceId">The resource ID assigned by the external resource manager.</param> /// <param name="typeName">The resource type name.</param> public PhpExternalResource(int resourceId, string typeName) : base(resourceId * 2 + 1, typeName) { } /// <summary> /// Returns the resource ID given when creating this instance. /// </summary> /// <remarks><seealso cref="PhpExternalResource(int,string)"/></remarks> /// <returns>The resource ID.</returns> public int GetId() { return mResourceId / 2; } #region Serialization (CLR only) #if !SILVERLIGHT /// <include file='Doc/Common.xml' path='/docs/method[@name="serialization.ctor"]/*'/> protected PhpExternalResource(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif #endregion } }
// 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.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.MetadataAsSource { internal class CSharpMetadataAsSourceService : AbstractMetadataAsSourceService { private static readonly IFormattingRule s_memberSeparationRule = new FormattingRule(); public CSharpMetadataAsSourceService(HostLanguageServices languageServices) : base(languageServices.GetService<ICodeGenerationService>()) { } protected override async Task<Document> AddAssemblyInfoRegionAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) { string assemblyInfo = MetadataAsSourceHelpers.GetAssemblyInfo(symbol.ContainingAssembly); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); string assemblyPath = MetadataAsSourceHelpers.GetAssemblyDisplay(compilation, symbol.ContainingAssembly); var regionTrivia = SyntaxFactory.RegionDirectiveTrivia(true) .WithTrailingTrivia(new[] { SyntaxFactory.Space, SyntaxFactory.PreprocessingMessage(assemblyInfo) }); var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.WithLeadingTrivia(new[] { SyntaxFactory.Trivia(regionTrivia), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.Comment("// " + assemblyPath), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.Trivia(SyntaxFactory.EndRegionDirectiveTrivia(true)), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.CarriageReturnLineFeed }); return document.WithSyntaxRoot(newRoot); } protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document) { return s_memberSeparationRule.Concat(Formatter.GetDefaultFormattingRules(document)); } protected override async Task<Document> ConvertDocCommentsToRegularComments(Document document, IDocumentationCommentFormattingService docCommentFormattingService, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newSyntaxRoot = DocCommentConverter.ConvertToRegularComments(syntaxRoot, docCommentFormattingService, cancellationToken); return document.WithSyntaxRoot(newSyntaxRoot); } protected override ImmutableArray<AbstractReducer> GetReducers() => ImmutableArray.Create<AbstractReducer>( new CSharpNameReducer(), new CSharpEscapingReducer(), new CSharpParenthesesReducer()); private class FormattingRule : AbstractFormattingRule { protected override AdjustNewLinesOperation GetAdjustNewLinesOperationBetweenMembersAndUsings(SyntaxToken token1, SyntaxToken token2) { var previousToken = token1; var currentToken = token2; // We are not between members or usings if the last token wasn't the end of a statement or if the current token // is the end of a scope. if ((previousToken.Kind() != SyntaxKind.SemicolonToken && previousToken.Kind() != SyntaxKind.CloseBraceToken) || currentToken.Kind() == SyntaxKind.CloseBraceToken) { return null; } SyntaxNode previousMember = FormattingRangeHelper.GetEnclosingMember(previousToken); SyntaxNode nextMember = FormattingRangeHelper.GetEnclosingMember(currentToken); // Is the previous statement an using directive? If so, treat it like a member to add // the right number of lines. if (previousToken.Kind() == SyntaxKind.SemicolonToken && previousToken.Parent.Kind() == SyntaxKind.UsingDirective) { previousMember = previousToken.Parent; } if (previousMember == null || nextMember == null || previousMember == nextMember) { return null; } // If we have two members of the same kind, we won't insert a blank line if (previousMember.Kind() == nextMember.Kind()) { return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines); } // Force a blank line between the two nodes by counting the number of lines of // trivia and adding one to it. var triviaList = token1.TrailingTrivia.Concat(token2.LeadingTrivia); return FormattingOperations.CreateAdjustNewLinesOperation(GetNumberOfLines(triviaList) + 1, AdjustNewLinesOption.ForceLines); } public override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<AnchorIndentationOperation> nextOperation) { return; } protected override bool IsNewLine(char c) { return SyntaxFacts.IsNewLine(c); } } private class DocCommentConverter : CSharpSyntaxRewriter { private readonly IDocumentationCommentFormattingService _formattingService; private readonly CancellationToken _cancellationToken; public static SyntaxNode ConvertToRegularComments(SyntaxNode node, IDocumentationCommentFormattingService formattingService, CancellationToken cancellationToken) { var converter = new DocCommentConverter(formattingService, cancellationToken); return converter.Visit(node); } private DocCommentConverter(IDocumentationCommentFormattingService formattingService, CancellationToken cancellationToken) : base(visitIntoStructuredTrivia: false) { _formattingService = formattingService; _cancellationToken = cancellationToken; } public override SyntaxNode Visit(SyntaxNode node) { _cancellationToken.ThrowIfCancellationRequested(); if (node == null) { return node; } // Process children first node = base.Visit(node); // Check the leading trivia for doc comments. if (node.GetLeadingTrivia().Any(SyntaxKind.SingleLineDocumentationCommentTrivia)) { var newLeadingTrivia = new List<SyntaxTrivia>(); foreach (var trivia in node.GetLeadingTrivia()) { if (trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia) { newLeadingTrivia.Add(SyntaxFactory.Comment("//")); newLeadingTrivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed); var structuredTrivia = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); newLeadingTrivia.AddRange(ConvertDocCommentToRegularComment(structuredTrivia)); } else { newLeadingTrivia.Add(trivia); } } node = node.WithLeadingTrivia(newLeadingTrivia); } return node; } private IEnumerable<SyntaxTrivia> ConvertDocCommentToRegularComment(DocumentationCommentTriviaSyntax structuredTrivia) { var xmlFragment = DocumentationCommentUtilities.ExtractXMLFragment(structuredTrivia.ToFullString()); var docComment = DocumentationComment.FromXmlFragment(xmlFragment); var commentLines = AbstractMetadataAsSourceService.DocCommentFormatter.Format(_formattingService, docComment); foreach (var line in commentLines) { if (!string.IsNullOrWhiteSpace(line)) { yield return SyntaxFactory.Comment("// " + line); } else { yield return SyntaxFactory.Comment("//"); } yield return SyntaxFactory.ElasticCarriageReturnLineFeed; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Umbraco.Core.Auditing; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Services { public class MemberTypeService : ContentTypeServiceBase, IMemberTypeService { private readonly IMemberService _memberService; private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(); public MemberTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory, IMemberService memberService) : base(provider, repositoryFactory, logger, eventMessagesFactory) { if (memberService == null) throw new ArgumentNullException("memberService"); _memberService = memberService; } public IEnumerable<IMemberType> GetAll(params int[] ids) { using (var repository = RepositoryFactory.CreateMemberTypeRepository(UowProvider.GetUnitOfWork())) { return repository.GetAll(ids); } } /// <summary> /// Gets an <see cref="IMemberType"/> object by its Id /// </summary> /// <param name="id">Id of the <see cref="IMemberType"/> to retrieve</param> /// <returns><see cref="IMemberType"/></returns> public IMemberType Get(int id) { using (var repository = RepositoryFactory.CreateMemberTypeRepository(UowProvider.GetUnitOfWork())) { return repository.Get(id); } } /// <summary> /// Gets an <see cref="IMemberType"/> object by its Key /// </summary> /// <param name="key">Key of the <see cref="IMemberType"/> to retrieve</param> /// <returns><see cref="IMemberType"/></returns> public IMemberType Get(Guid key) { using (var repository = RepositoryFactory.CreateMemberTypeRepository(UowProvider.GetUnitOfWork())) { return repository.Get(key); } } /// <summary> /// Gets an <see cref="IMemberType"/> object by its Alias /// </summary> /// <param name="alias">Alias of the <see cref="IMemberType"/> to retrieve</param> /// <returns><see cref="IMemberType"/></returns> public IMemberType Get(string alias) { using (var repository = RepositoryFactory.CreateMemberTypeRepository(UowProvider.GetUnitOfWork())) { return repository.Get(alias); } } public void Save(IMemberType memberType, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMemberType>(memberType), this)) return; if (string.IsNullOrWhiteSpace(memberType.Name)) { throw new ArgumentException("Cannot save MemberType with empty name."); } using (new WriteLock(Locker)) { var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateMemberTypeRepository(uow)) { memberType.CreatorId = userId; repository.AddOrUpdate(memberType); uow.Commit(); } UpdateContentXmlStructure(memberType); } Saved.RaiseEvent(new SaveEventArgs<IMemberType>(memberType, false), this); } public void Save(IEnumerable<IMemberType> memberTypes, int userId = 0) { var asArray = memberTypes.ToArray(); if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMemberType>(asArray), this)) return; using (new WriteLock(Locker)) { var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateMemberTypeRepository(uow)) { foreach (var memberType in asArray) { memberType.CreatorId = userId; repository.AddOrUpdate(memberType); } //save it all in one go uow.Commit(); } UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray()); } Saved.RaiseEvent(new SaveEventArgs<IMemberType>(asArray, false), this); } public void Delete(IMemberType memberType, int userId = 0) { if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IMemberType>(memberType), this)) return; using (new WriteLock(Locker)) { _memberService.DeleteMembersOfType(memberType.Id); var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateMemberTypeRepository(uow)) { repository.Delete(memberType); uow.Commit(); Deleted.RaiseEvent(new DeleteEventArgs<IMemberType>(memberType, false), this); } } } public void Delete(IEnumerable<IMemberType> memberTypes, int userId = 0) { var asArray = memberTypes.ToArray(); if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IMemberType>(asArray), this)) return; using (new WriteLock(Locker)) { foreach (var contentType in asArray) { _memberService.DeleteMembersOfType(contentType.Id); } var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateMemberTypeRepository(uow)) { foreach (var memberType in asArray) { repository.Delete(memberType); } uow.Commit(); Deleted.RaiseEvent(new DeleteEventArgs<IMemberType>(asArray, false), this); } } } /// <summary> /// This is called after an IContentType is saved and is used to update the content xml structures in the database /// if they are required to be updated. /// </summary> /// <param name="contentTypes">A tuple of a content type and a boolean indicating if it is new (HasIdentity was false before committing)</param> private void UpdateContentXmlStructure(params IContentTypeBase[] contentTypes) { var toUpdate = GetContentTypesForXmlUpdates(contentTypes).ToArray(); if (toUpdate.Any()) { //if it is a media type then call the rebuilding methods for media var typedMemberService = _memberService as MemberService; if (typedMemberService != null) { typedMemberService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray()); } } } /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IMemberTypeService, SaveEventArgs<IMemberType>> Saving; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IMemberTypeService, SaveEventArgs<IMemberType>> Saved; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IMemberTypeService, DeleteEventArgs<IMemberType>> Deleting; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IMemberTypeService, DeleteEventArgs<IMemberType>> Deleted; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Xml.Linq; using Umbraco.Core.Configuration; using System.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.DatabaseModelDefinitions; namespace Umbraco.Core.Services { /// <summary> /// A temporary interface until we are in v8, this is used to return a different result for the same method and this interface gets implemented /// explicitly. These methods will replace the normal ones in IContentService in v8 and this will be removed. /// </summary> public interface IMediaServiceOperations { //TODO: Remove this class in v8 //TODO: There's probably more that needs to be added like the EmptyRecycleBin, etc... /// <summary> /// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin /// </summary> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> Attempt<OperationStatus> MoveToRecycleBin(IMedia media, int userId = 0); /// <summary> /// Moves an <see cref="IMedia"/> object to a new location /// </summary> /// <param name="media">The <see cref="IMedia"/> to move</param> /// <param name="parentId">Id of the Media's new Parent</param> /// <param name="userId">Id of the User moving the Media</param> /// <returns>True if moving succeeded, otherwise False</returns> Attempt<OperationStatus> Move(IMedia media, int parentId, int userId = 0); /// <summary> /// Permanently deletes an <see cref="IMedia"/> object /// </summary> /// <remarks> /// Please note that this method will completely remove the Media from the database, /// but current not from the file system. /// </remarks> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> Attempt<OperationStatus> Delete(IMedia media, int userId = 0); /// <summary> /// Saves a single <see cref="IMedia"/> object /// </summary> /// <param name="media">The <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> Attempt<OperationStatus> Save(IMedia media, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IMedia"/> objects /// </summary> /// <param name="medias">Collection of <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> Attempt<OperationStatus> Save(IEnumerable<IMedia> medias, int userId = 0, bool raiseEvents = true); } /// <summary> /// Defines the Media Service, which is an easy access to operations involving <see cref="IMedia"/> /// </summary> public interface IMediaService : IContentServiceBase { /// <summary> /// Gets all XML entries found in the cmsContentXml table based on the given path /// </summary> /// <param name="path">Path starts with</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records the query would return without paging</param> /// <returns>A paged enumerable of XML entries of media items</returns> /// <remarks> /// If -1 is passed, then this will return all media xml entries, otherwise will return all descendents from the path /// </remarks> IEnumerable<XElement> GetPagedXmlEntries(string path, long pageIndex, int pageSize, out long totalRecords); /// <summary> /// Rebuilds all xml content in the cmsContentXml table for all media /// </summary> /// <param name="contentTypeIds"> /// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures /// for all media /// </param> void RebuildXmlStructures(params int[] contentTypeIds); int CountNotTrashed(string contentTypeAlias = null); int Count(string contentTypeAlias = null); int CountChildren(int parentId, string contentTypeAlias = null); int CountDescendants(int parentId, string contentTypeAlias = null); IEnumerable<IMedia> GetByIds(IEnumerable<int> ids); IEnumerable<IMedia> GetByIds(IEnumerable<Guid> ids); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, Guid parentId, string mediaTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = 0); /// <summary> /// Gets an <see cref="IMedia"/> object by Id /// </summary> /// <param name="id">Id of the Content to retrieve</param> /// <returns><see cref="IMedia"/></returns> IMedia GetById(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetChildren(int id); [Obsolete("Use the overload with 'long' parameter types instead")] [EditorBrowsable(EditorBrowsableState.Never)] IEnumerable<IMedia> GetPagedChildren(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="orderBySystemField">Flag to indicate when ordering by system field</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection, bool orderBySystemField, string filter); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="orderBySystemField">Flag to indicate when ordering by system field</param> /// <param name="filter">Search text filter</param> /// <param name="contentTypeFilter">A list of content type Ids to filter the list by</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection, bool orderBySystemField, string filter, int[] contentTypeFilter); [Obsolete("Use the overload with 'long' parameter types instead")] [EditorBrowsable(EditorBrowsableState.Never)] IEnumerable<IMedia> GetPagedDescendants(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="orderBySystemField">Flag to indicate when ordering by system field</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection, bool orderBySystemField, string filter); /// <summary> /// Gets descendants of a <see cref="IMedia"/> object by its Id /// </summary> /// <param name="id">Id of the Parent to retrieve descendants from</param> /// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetDescendants(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by the Id of the <see cref="IContentType"/> /// </summary> /// <param name="id">Id of the <see cref="IMediaType"/></param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetMediaOfMediaType(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which reside at the first level / root /// </summary> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetRootMedia(); /// <summary> /// Gets a collection of an <see cref="IMedia"/> objects, which resides in the Recycle Bin /// </summary> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetMediaInRecycleBin(); /// <summary> /// Moves an <see cref="IMedia"/> object to a new location /// </summary> /// <param name="media">The <see cref="IMedia"/> to move</param> /// <param name="parentId">Id of the Media's new Parent</param> /// <param name="userId">Id of the User moving the Media</param> void Move(IMedia media, int parentId, int userId = 0); /// <summary> /// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin /// </summary> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> void MoveToRecycleBin(IMedia media, int userId = 0); /// <summary> /// Empties the Recycle Bin by deleting all <see cref="IMedia"/> that resides in the bin /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use EmptyRecycleBin with explicit indication of user ID instead")] void EmptyRecycleBin(); /// <summary> /// Empties the Recycle Bin by deleting all <see cref="IMedia"/> that resides in the bin /// </summary> /// <param name="userId">Optional Id of the User emptying the Recycle Bin</param> void EmptyRecycleBin(int userId = 0); /// <summary> /// Deletes all media of specified type. All children of deleted media is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="mediaTypeId">Id of the <see cref="IMediaType"/></param> /// <param name="userId">Optional Id of the user deleting Media</param> void DeleteMediaOfType(int mediaTypeId, int userId = 0); /// <summary> /// Deletes all media of the specified types. All Descendants of deleted media that is not of these types is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="mediaTypeIds">Ids of the <see cref="IMediaType"/>s</param> /// <param name="userId">Optional Id of the user issueing the delete operation</param> void DeleteMediaOfTypes(IEnumerable<int> mediaTypeIds, int userId = 0); /// <summary> /// Permanently deletes an <see cref="IMedia"/> object /// </summary> /// <remarks> /// Please note that this method will completely remove the Media from the database, /// but current not from the file system. /// </remarks> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> void Delete(IMedia media, int userId = 0); /// <summary> /// Saves a single <see cref="IMedia"/> object /// </summary> /// <param name="media">The <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IMedia media, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IMedia"/> objects /// </summary> /// <param name="medias">Collection of <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IEnumerable<IMedia> medias, int userId = 0, bool raiseEvents = true); /// <summary> /// Gets an <see cref="IMedia"/> object by its 'UniqueId' /// </summary> /// <param name="key">Guid key of the Media to retrieve</param> /// <returns><see cref="IMedia"/></returns> IMedia GetById(Guid key); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Level /// </summary> /// <param name="level">The level to retrieve Media from</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetByLevel(int level); /// <summary> /// Gets a specific version of an <see cref="IMedia"/> item. /// </summary> /// <param name="versionId">Id of the version to retrieve</param> /// <returns>An <see cref="IMedia"/> item</returns> IMedia GetByVersion(Guid versionId); /// <summary> /// Gets a collection of an <see cref="IMedia"/> objects versions by Id /// </summary> /// <param name="id"></param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetVersions(int id); /// <summary> /// Checks whether an <see cref="IMedia"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IMedia"/></param> /// <returns>True if the media has any children otherwise False</returns> bool HasChildren(int id); /// <summary> /// Permanently deletes versions from an <see cref="IMedia"/> object prior to a specific date. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> object to delete versions from</param> /// <param name="versionDate">Latest version date</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersions(int id, DateTime versionDate, int userId = 0); /// <summary> /// Permanently deletes specific version(s) from an <see cref="IMedia"/> object. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> object to delete a version from</param> /// <param name="versionId">Id of the version to delete</param> /// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0); /// <summary> /// Gets an <see cref="IMedia"/> object from the path stored in the 'umbracoFile' property. /// </summary> /// <param name="mediaPath">Path of the media item to retrieve (for example: /media/1024/koala_403x328.jpg)</param> /// <returns><see cref="IMedia"/></returns> IMedia GetMediaByPath(string mediaPath); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetAncestors(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media. /// </summary> /// <param name="media"><see cref="IMedia"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetAncestors(IMedia media); /// <summary> /// Gets descendants of a <see cref="IMedia"/> object by its Id /// </summary> /// <param name="media">The Parent <see cref="IMedia"/> object to retrieve descendants from</param> /// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetDescendants(IMedia media); /// <summary> /// Gets the parent of the current media as an <see cref="IMedia"/> item. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IMedia"/> object</returns> IMedia GetParent(int id); /// <summary> /// Gets the parent of the current media as an <see cref="IMedia"/> item. /// </summary> /// <param name="media"><see cref="IMedia"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IMedia"/> object</returns> IMedia GetParent(IMedia media); /// <summary> /// Sorts a collection of <see cref="IMedia"/> objects by updating the SortOrder according /// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="items"></param> /// <param name="userId"></param> /// <param name="raiseEvents"></param> /// <returns>True if sorting succeeded, otherwise False</returns> bool Sort(IEnumerable<IMedia> items, int userId = 0, bool raiseEvents = true); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IMedia"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMediaWithIdentity(string name, IMedia parent, string mediaTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IMedia"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMediaWithIdentity(string name, int parentId, string mediaTypeAlias, int userId = 0); /// <summary> /// Gets the content of a media as a stream. /// </summary> /// <param name="filepath">The filesystem path to the media.</param> /// <returns>The content of the media.</returns> Stream GetMediaFileContentStream(string filepath); /// <summary> /// Sets the content of a media. /// </summary> /// <param name="filepath">The filesystem path to the media.</param> /// <param name="content">The content of the media.</param> void SetMediaFileContent(string filepath, Stream content); /// <summary> /// Gets the size of a media. /// </summary> /// <param name="filepath">The filesystem path to the media.</param> /// <returns>The size of the media.</returns> long GetMediaFileSize(string filepath); /// <summary> /// Deletes a media file and all thumbnails. /// </summary> /// <param name="filepath">The filesystem path to the media.</param> void DeleteMediaFile(string filepath); [Obsolete("This should no longer be used, thumbnail generation should be done via ImageProcessor, Umbraco no longer generates '_thumb' files for media")] void GenerateThumbnails(string filepath, PropertyType propertyType); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using System.IO; using System.Threading; using ManagedBass; using ManagedBass.Fx; using osu.Framework.IO; using System.Threading.Tasks; using osu.Framework.Audio.Callbacks; namespace osu.Framework.Audio.Track { public sealed class TrackBass : Track, IBassAudio { public const int BYTES_PER_SAMPLE = 4; private AsyncBufferStream dataStream; /// <summary> /// Should this track only be used for preview purposes? This suggests it has not yet been fully loaded. /// </summary> public bool Preview { get; private set; } /// <summary> /// The handle for this track, if there is one. /// </summary> private int activeStream; /// <summary> /// The handle for adjusting tempo. /// </summary> private int tempoAdjustStream; /// <summary> /// This marks if the track is paused, or stopped to the end. /// </summary> private bool isPlayed; /// <summary> /// The last position that a seek will succeed for. /// </summary> private double lastSeekablePosition; private FileCallbacks fileCallbacks; private SyncCallback endMixtimeCallback; private SyncCallback stopCallback; private SyncCallback endCallback; private volatile bool isLoaded; public override bool IsLoaded => isLoaded; private readonly BassRelativeFrequencyHandler relativeFrequencyHandler; /// <summary> /// Constructs a new <see cref="TrackBass"/> from provided audio data. /// </summary> /// <param name="data">The sample data stream.</param> /// <param name="quick">If true, the track will not be fully loaded, and should only be used for preview purposes. Defaults to false.</param> public TrackBass(Stream data, bool quick = false) { if (data == null) throw new ArgumentNullException(nameof(data)); relativeFrequencyHandler = new BassRelativeFrequencyHandler { FrequencyChangedToZero = () => stopInternal(), FrequencyChangedFromZero = () => { // Do not resume the track if a play wasn't requested at all or has been paused via Stop(). if (!isPlayed) return; startInternal(); } }; // todo: support this internally to match the underlying Track implementation (which can support this). const float tempo_minimum_supported = 0.05f; AggregateTempo.ValueChanged += t => { if (t.NewValue < tempo_minimum_supported) throw new ArgumentException($"{nameof(TrackBass)} does not support {nameof(Tempo)} specifications below {tempo_minimum_supported}. Use {nameof(Frequency)} instead."); }; EnqueueAction(() => { Preview = quick; activeStream = prepareStream(data, quick); long byteLength = Bass.ChannelGetLength(activeStream); // will be -1 in case of an error double seconds = Bass.ChannelBytes2Seconds(activeStream, byteLength); bool success = seconds >= 0; if (success) { Length = seconds * 1000; // Bass does not allow seeking to the end of the track, so the last available position is 1 sample before. lastSeekablePosition = Bass.ChannelBytes2Seconds(activeStream, byteLength - BYTES_PER_SAMPLE) * 1000; stopCallback = new SyncCallback((a, b, c, d) => RaiseFailed()); endCallback = new SyncCallback((a, b, c, d) => { if (Looping) return; hasCompleted = true; RaiseCompleted(); }); endMixtimeCallback = new SyncCallback((a, b, c, d) => { // this is separate from the above callback as this is required to be invoked on mixtime. // see "BASS_SYNC_MIXTIME" part of http://www.un4seen.com/doc/#bass/BASS_ChannelSetSync.html for reason why. if (Looping) seekInternal(RestartPoint); }); Bass.ChannelSetSync(activeStream, SyncFlags.Stop, 0, stopCallback.Callback, stopCallback.Handle); Bass.ChannelSetSync(activeStream, SyncFlags.End, 0, endCallback.Callback, endCallback.Handle); Bass.ChannelSetSync(activeStream, SyncFlags.End | SyncFlags.Mixtime, 0, endMixtimeCallback.Callback, endMixtimeCallback.Handle); isLoaded = true; relativeFrequencyHandler.SetChannel(activeStream); bassAmplitudeProcessor?.SetChannel(activeStream); } }); InvalidateState(); } private void setLoopFlag(bool value) => EnqueueAction(() => { if (activeStream != 0) Bass.ChannelFlags(activeStream, value ? BassFlags.Loop : BassFlags.Default, BassFlags.Loop); }); private int prepareStream(Stream data, bool quick) { //encapsulate incoming stream with async buffer if it isn't already. dataStream = data as AsyncBufferStream ?? new AsyncBufferStream(data, quick ? 8 : -1); fileCallbacks = new FileCallbacks(new DataStreamFileProcedures(dataStream)); BassFlags flags = Preview ? 0 : BassFlags.Decode | BassFlags.Prescan; int stream = Bass.CreateStream(StreamSystem.NoBuffer, flags, fileCallbacks.Callbacks, fileCallbacks.Handle); bitrate = (int)Math.Round(Bass.ChannelGetAttribute(stream, ChannelAttribute.Bitrate)); if (!Preview) { // We assign the BassFlags.Decode streams to the device "bass_nodevice" to prevent them from getting // cleaned up during a Bass.Free call. This is necessary for seamless switching between audio devices. // Further, we provide the flag BassFlags.FxFreeSource such that freeing the stream also frees // all parent decoding streams. const int bass_nodevice = 0x20000; Bass.ChannelSetDevice(stream, bass_nodevice); tempoAdjustStream = BassFx.TempoCreate(stream, BassFlags.Decode | BassFlags.FxFreeSource); Bass.ChannelSetDevice(tempoAdjustStream, bass_nodevice); stream = BassFx.ReverseCreate(tempoAdjustStream, 5f, BassFlags.Default | BassFlags.FxFreeSource); Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoUseQuickAlgorithm, 1); Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoOverlapMilliseconds, 4); Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoSequenceMilliseconds, 30); } return stream; } /// <summary> /// Returns whether the playback state is considered to be running or not. /// This will only return true for <see cref="PlaybackState.Playing"/> and <see cref="PlaybackState.Stalled"/>. /// </summary> private static bool isRunningState(PlaybackState state) => state == PlaybackState.Playing || state == PlaybackState.Stalled; void IBassAudio.UpdateDevice(int deviceIndex) { Bass.ChannelSetDevice(activeStream, deviceIndex); BassUtils.CheckFaulted(true); // Bass may leave us in an invalid state after the output device changes (this is true for "No sound" device) // if the observed state was playing before change, we should force things into a good state. if (isPlayed) { // While on windows, changing to "No sound" changes the playback state correctly, // on macOS it is left in a playing-but-stalled state. Forcefully stopping first fixes this. stopInternal(); startInternal(); } } private BassAmplitudeProcessor bassAmplitudeProcessor; protected override void UpdateState() { base.UpdateState(); var running = isRunningState(Bass.ChannelIsActive(activeStream)); // because device validity check isn't done frequently, when switching to "No sound" device, // there will be a brief time where this track will be stopped, before we resume it manually (see comments in UpdateDevice(int).) // this makes us appear to be playing, even if we may not be. isRunning = running || (isPlayed && !hasCompleted); updateCurrentTime(); bassAmplitudeProcessor?.Update(); } ~TrackBass() { Dispose(false); } protected override void Dispose(bool disposing) { if (IsDisposed) return; if (activeStream != 0) { isRunning = false; Bass.ChannelStop(activeStream); Bass.StreamFree(activeStream); } activeStream = 0; dataStream?.Dispose(); dataStream = null; fileCallbacks?.Dispose(); fileCallbacks = null; stopCallback?.Dispose(); stopCallback = null; endCallback?.Dispose(); endCallback = null; endMixtimeCallback?.Dispose(); endMixtimeCallback = null; base.Dispose(disposing); } public override bool IsDummyDevice => false; public override void Stop() { base.Stop(); StopAsync().Wait(); } public Task StopAsync() => EnqueueAction(() => { stopInternal(); isPlayed = false; }); private bool stopInternal() => isRunningState(Bass.ChannelIsActive(activeStream)) && Bass.ChannelPause(activeStream); private int direction; private void setDirection(bool reverse) { direction = reverse ? -1 : 1; Bass.ChannelSetAttribute(activeStream, ChannelAttribute.ReverseDirection, direction); } public override void Start() { base.Start(); StartAsync().Wait(); } public Task StartAsync() => EnqueueAction(() => { if (startInternal()) isPlayed = true; }); private bool startInternal() { // ensure state is correct before starting. InvalidateState(); // Bass will restart the track if it has reached its end. This behavior isn't desirable so block locally. if (hasCompleted) return false; if (relativeFrequencyHandler.IsFrequencyZero) return true; setLoopFlag(Looping); return Bass.ChannelPlay(activeStream); } public override bool Looping { get => base.Looping; set { base.Looping = value; setLoopFlag(Looping); } } public override bool Seek(double seek) => SeekAsync(seek).Result; public async Task<bool> SeekAsync(double seek) { // At this point the track may not yet be loaded which is indicated by a 0 length. // In that case we still want to return true, hence the conservative length. double conservativeLength = Length == 0 ? double.MaxValue : lastSeekablePosition; double conservativeClamped = Math.Clamp(seek, 0, conservativeLength); await EnqueueAction(() => seekInternal(seek)).ConfigureAwait(false); return conservativeClamped == seek; } private void seekInternal(double seek) { double clamped = Math.Clamp(seek, 0, Length); if (clamped < Length) hasCompleted = false; long pos = Bass.ChannelSeconds2Bytes(activeStream, clamped / 1000d); if (pos != Bass.ChannelGetPosition(activeStream)) Bass.ChannelSetPosition(activeStream, pos); // current time updates are safe to perform from enqueued actions, // but not always safe to perform from BASS callbacks, since those can sometimes use a separate thread. // if it's not safe to update immediately here, the next UpdateState() call is guaranteed to update the time safely anyway. if (CanPerformInline) updateCurrentTime(); } private void updateCurrentTime() { Debug.Assert(CanPerformInline); var bytePosition = Bass.ChannelGetPosition(activeStream); Interlocked.Exchange(ref currentTime, Bass.ChannelBytes2Seconds(activeStream, bytePosition) * 1000); } private double currentTime; public override double CurrentTime => currentTime; private volatile bool isRunning; public override bool IsRunning => isRunning; private volatile bool hasCompleted; public override bool HasCompleted => hasCompleted; internal override void OnStateChanged() { base.OnStateChanged(); if (activeStream == 0) return; setDirection(AggregateFrequency.Value < 0); Bass.ChannelSetAttribute(activeStream, ChannelAttribute.Volume, AggregateVolume.Value); Bass.ChannelSetAttribute(activeStream, ChannelAttribute.Pan, AggregateBalance.Value); relativeFrequencyHandler.SetFrequency(AggregateFrequency.Value); Bass.ChannelSetAttribute(tempoAdjustStream, ChannelAttribute.Tempo, (Math.Abs(AggregateTempo.Value) - 1) * 100); } private volatile int bitrate; public override int? Bitrate => bitrate; public override ChannelAmplitudes CurrentAmplitudes => (bassAmplitudeProcessor ??= new BassAmplitudeProcessor(activeStream)).CurrentAmplitudes; } }
namespace Macabresoft.Macabre2D.Framework; using System.ComponentModel; using System.Runtime.Serialization; using Macabresoft.Core; using Microsoft.Xna.Framework; /// <summary> /// Interface for an object which has a <see cref="Transform" />. /// </summary> public interface ITransformable { /// <summary> /// Gets the transform. /// </summary> /// <value>The transform.</value> Transform Transform { get; } /// <summary> /// Gets the transform matrix. /// </summary> /// <value>The transform matrix.</value> Matrix TransformMatrix { get; } /// <summary> /// Gets or sets the local position. /// </summary> /// <value>The local position.</value> Vector2 LocalPosition { get; set; } /// <summary> /// Gets or sets the local scale. /// </summary> /// <value>The local scale.</value> Vector2 LocalScale { get; set; } /// <summary> /// Gets the world transform. /// </summary> /// <param name="rotationAngle">The rotation angle.</param> /// <returns>The world transform.</returns> Transform GetWorldTransform(float rotationAngle); /// <summary> /// Gets the world transform. /// </summary> /// <param name="originOffset">The origin offset.</param> /// <returns>The world transform.</returns> Transform GetWorldTransform(Vector2 originOffset); /// <summary> /// Gets the world transform. /// </summary> /// <param name="originOffset">The origin offset.</param> /// <param name="rotationAngle">The rotation angle.</param> /// <returns>The world transform.</returns> Transform GetWorldTransform(Vector2 originOffset, float rotationAngle); /// <summary> /// Gets the world transform. /// </summary> /// <param name="originOffset">The origin offset.</param> /// <param name="overrideScale">An override value for scale.</param> /// <param name="rotationAngle">The rotation angle.</param> /// <returns>The world transform.</returns> Transform GetWorldTransform(Vector2 originOffset, Vector2 overrideScale, float rotationAngle); /// <summary> /// Gets the world transform. /// </summary> /// <param name="originOffset">The origin offset.</param> /// <param name="overrideScale">An override value for scale.</param> /// <returns>The world transform.</returns> Transform GetWorldTransform(Vector2 originOffset, Vector2 overrideScale); /// <summary> /// Sets the world position. /// </summary> /// <param name="position">The position.</param> void SetWorldPosition(Vector2 position); /// <summary> /// Sets the world scale. /// </summary> /// <param name="scale">The scale.</param> void SetWorldScale(Vector2 scale); /// <summary> /// Sets the world transform. /// </summary> /// <param name="position">The position.</param> /// <param name="scale">The scale.</param> void SetWorldTransform(Vector2 position, Vector2 scale); } /// <summary> /// A default implementation of <see cref="ITransformable" /> that handles things in the /// expected way. /// </summary> [DataContract] [Category(CommonCategories.Transform)] public abstract class Transformable : NotifyPropertyChanged, ITransformable { private readonly ResettableLazy<Matrix> _transformMatrix; private bool _isTransformUpToDate; private Vector2 _localPosition; private Vector2 _localScale = Vector2.One; private Transform _transform; /// <summary> /// Initializes a new instance of the <see cref="Transformable" /> class. /// </summary> protected Transformable() { this._transformMatrix = new ResettableLazy<Matrix>(this.GetMatrix); } /// <inheritdoc /> public Transform Transform { get { if (!this._isTransformUpToDate) { this._transform = this.TransformMatrix.DecomposeWithoutRotation2D(); this._isTransformUpToDate = true; } return this._transform; } } /// <inheritdoc /> public Matrix TransformMatrix => this._transformMatrix.Value; /// <summary> /// Gets or sets the local position. /// </summary> /// <value>The local position.</value> [DataMember(Name = "Local Position")] public Vector2 LocalPosition { get => this._localPosition; set { if (this.Set(ref this._localPosition, value)) { this.HandleMatrixOrTransformChanged(); } } } /// <summary> /// Gets or sets the local scale. /// </summary> /// <value>The local scale.</value> [DataMember(Name = "Local Scale")] public Vector2 LocalScale { get => this._localScale; set { if (this.Set(ref this._localScale, value)) { this.HandleMatrixOrTransformChanged(); } } } /// <inheritdoc /> public Transform GetWorldTransform(float rotationAngle) { var transform = this.Transform; var matrix = Matrix.CreateScale(transform.Scale.X, transform.Scale.Y, 1f) * Matrix.CreateRotationZ(rotationAngle) * Matrix.CreateTranslation(transform.Position.X, transform.Position.Y, 0f); return matrix.ToTransform(); } /// <inheritdoc /> public Transform GetWorldTransform(Vector2 originOffset) { var matrix = Matrix.CreateTranslation(originOffset.X, originOffset.Y, 0f) * this.TransformMatrix; return matrix.ToTransform(); } /// <inheritdoc /> public Transform GetWorldTransform(Vector2 originOffset, float rotationAngle) { var transform = this.Transform; var matrix = Matrix.CreateTranslation(originOffset.X, originOffset.Y, 0f) * Matrix.CreateScale(transform.Scale.X, transform.Scale.Y, 1f) * Matrix.CreateRotationZ(rotationAngle) * Matrix.CreateTranslation(transform.Position.X, transform.Position.Y, 0f); return matrix.ToTransform(); } /// <inheritdoc /> public Transform GetWorldTransform(Vector2 originOffset, Vector2 overrideScale, float rotationAngle) { var transform = this.Transform; var matrix = Matrix.CreateScale(overrideScale.X, overrideScale.Y, 1f) * Matrix.CreateTranslation(originOffset.X, originOffset.Y, 0f) * Matrix.CreateRotationZ(rotationAngle) * Matrix.CreateTranslation(transform.Position.X, transform.Position.Y, 0f); return matrix.ToTransform(); } /// <inheritdoc /> public Transform GetWorldTransform(Vector2 originOffset, Vector2 overrideScale) { var transform = this.Transform; var matrix = Matrix.CreateScale(overrideScale.X, overrideScale.Y, 1f) * Matrix.CreateTranslation(originOffset.X, originOffset.Y, 0f) * Matrix.CreateTranslation(transform.Position.X, transform.Position.Y, 0f); return matrix.ToTransform(); } /// <inheritdoc /> public void SetWorldPosition(Vector2 position) { this.SetWorldTransform(position, this.Transform.Scale); } /// <inheritdoc /> public void SetWorldScale(Vector2 scale) { this.SetWorldTransform(this.Transform.Position, scale); } /// <inheritdoc /> public void SetWorldTransform(Vector2 position, Vector2 scale) { var matrix = Matrix.CreateScale(scale.X, scale.Y, 1f) * Matrix.CreateTranslation(position.X, position.Y, 0f); var parent = this.GetParentTransformable(); if (parent != this) { matrix *= Matrix.Invert(parent.TransformMatrix); } var localTransform = matrix.ToTransform(); this._localPosition = localTransform.Position; this._localScale = localTransform.Scale; this.HandleMatrixOrTransformChanged(); this.RaisePropertyChanged(nameof(this.LocalPosition)); this.RaisePropertyChanged(nameof(this.LocalScale)); } /// <summary> /// Gets the parent transformable. /// </summary> /// <returns>The parent transformable.</returns> protected abstract ITransformable GetParentTransformable(); /// <summary> /// Handles the matrix or transform changed. /// </summary> protected void HandleMatrixOrTransformChanged() { this._transformMatrix.Reset(); this._isTransformUpToDate = false; this.RaisePropertyChanged(true, nameof(this.Transform)); } private Matrix GetMatrix() { var transformMatrix = Matrix.CreateScale(this.LocalScale.X, this.LocalScale.Y, 1f) * Matrix.CreateTranslation(this.LocalPosition.X, this.LocalPosition.Y, 0f); var parent = this.GetParentTransformable(); if (parent != this) { transformMatrix *= parent.TransformMatrix; } return transformMatrix; } internal class EmptyTransformable : ITransformable { /// <inheritdoc /> public Transform Transform => Transform.Origin; /// <inheritdoc /> public Matrix TransformMatrix => Matrix.Identity; /// <inheritdoc /> public Vector2 LocalPosition { get => Vector2.Zero; set { } } /// <inheritdoc /> public Vector2 LocalScale { get => Vector2.One; set { } } /// <inheritdoc /> public Transform GetWorldTransform(float rotationAngle) { return this.Transform; } /// <inheritdoc /> public Transform GetWorldTransform(Vector2 originOffset) { return this.Transform; } /// <inheritdoc /> public Transform GetWorldTransform(Vector2 originOffset, float rotationAngle) { return this.Transform; } /// <inheritdoc /> public Transform GetWorldTransform(Vector2 originOffset, Vector2 overrideScale, float rotationAngle) { return this.Transform; } /// <inheritdoc /> public Transform GetWorldTransform(Vector2 originOffset, Vector2 overrideScale) { return this.Transform; } /// <inheritdoc /> public void SetWorldPosition(Vector2 position) { } /// <inheritdoc /> public void SetWorldScale(Vector2 scale) { } /// <inheritdoc /> public void SetWorldTransform(Vector2 position, Vector2 scale) { } } }
#region Copyright (C) 2014 Dennis Bappert // The MIT License (MIT) // Copyright (c) 2014 Dennis Bappert // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using MobileDB.Common; using MobileDB.Common.Utilities; using MobileDB.FileSystem; using MobileDB.FileSystem.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Bson; namespace MobileDB.Stores { public class BsonStore : StoreBase { private readonly ReaderWriterLockSlim _lock; private readonly FileSystemPath _path; private readonly JsonSerializer _serializer; public BsonStore( FileSystemBase fileSystem, Type entityType) : base(fileSystem, entityType) { _lock = new ReaderWriterLockSlim(); _serializer = JsonSerializer.CreateDefault(); _path = FileSystemPath.Root.AppendDirectory(EntityType.ToFriendlyName()); } public override FileSystemPath Path { get { return _path; } } private async Task EnsureInitializedAsync() { if (!await AsyncFileSystem.ExistsAsync(Path)) { await AsyncFileSystem.CreateDirectoryAsync(Path); } } private void EnsureInitialized() { if (!FileSystem.Exists(Path)) { FileSystem.CreateDirectory(Path); } } private async Task ApplyChangeAsync( object key, object entity, EntityState entityState) { var targetPath = Path.AppendFile(key.ToString()); switch (entityState) { case EntityState.Deleted: await AsyncFileSystem.DeleteAsync(targetPath); break; case EntityState.Added: var metadata = EntityMetadata(key, entity, EntityState.Added, null); using (var stream = await AsyncFileSystem.CreateFileAsync(targetPath)) Serialize(stream, metadata); break; case EntityState.Updated: var updatedMetadata = EntityMetadata(key, entity, EntityState.Updated, await FindByIdInternalAsync(key)); using (var stream = await AsyncFileSystem.CreateFileAsync(targetPath)) Serialize(stream, updatedMetadata); break; } } private void ApplyChange( object key, object entity, EntityState entityState) { var targetPath = Path.AppendFile(key.ToString()); switch (entityState) { case EntityState.Deleted: FileSystem.Delete(targetPath); break; case EntityState.Added: var metadata = EntityMetadata(key, entity, EntityState.Added, null); using (var stream = FileSystem.CreateFile(targetPath)) Serialize(stream, metadata); break; case EntityState.Updated: var updatedMetadata = EntityMetadata(key, entity, EntityState.Updated, FindByIdInternal(key)); using (var stream = FileSystem.CreateFile(targetPath)) Serialize(stream, updatedMetadata); break; } } private void Serialize(Stream stream, object entity) { using (var writer = new BsonWriter(stream)) { _serializer.Serialize(writer, entity); } } private MetadataEntity Deserialize(Stream stream) { using (var reader = new BsonReader(stream)) { return _serializer.Deserialize<MetadataEntity>(reader); } } public override async Task<int> SaveChangesAsync(ChangeSet changeSet) { var affectedEntities = 0; using (_lock.WriteLock()) { await EnsureInitializedAsync(); foreach (var change in changeSet) { await ApplyChangeAsync( change.Key.GetKeyFromEntity(), change.Key, change.Value ); affectedEntities++; } } return affectedEntities; } public override async Task<int> CountAsync() { using (_lock.ReadLock()) { await EnsureInitializedAsync(); return (await AsyncFileSystem.GetEntitiesAsync(Path)).Count(); } } public override int SaveChanges(ChangeSet changeSet) { var affectedEntities = 0; using (_lock.WriteLock()) { EnsureInitialized(); foreach (var change in changeSet) { ApplyChange( change.Key.GetKeyFromEntity(), change.Key, change.Value ); affectedEntities++; } } return affectedEntities; } public override object FindById(object key) { using (_lock.ReadLock()) { EnsureInitialized(); return (FindByIdInternal(key)).EntityOfType(EntityType); } } public override int Count() { using (_lock.ReadLock()) { EnsureInitialized(); return (FileSystem.GetEntities(Path)).Count(); } } private async Task<MetadataEntity> FindByIdInternalAsync(object key) { await EnsureInitializedAsync(); var targetPath = Path.AppendFile(key.ToString()); using (var stream = await AsyncFileSystem.OpenFileAsync(targetPath, DesiredFileAccess.Read)) return Deserialize(stream); } private MetadataEntity FindByIdInternal(object key) { EnsureInitialized(); var targetPath = Path.AppendFile(key.ToString()); using (var stream = FileSystem.OpenFile(targetPath, DesiredFileAccess.Read)) return Deserialize(stream); } public override async Task<object> FindByIdAsync(object key) { using (_lock.ReadLock()) { await EnsureInitializedAsync(); return (await FindByIdInternalAsync(key)).EntityOfType(EntityType); } } } }
// 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. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; namespace Baseline { [ContractClass(typeof(RepositoryContract))] abstract class Repository { public Repository() { } #region exceptions public class ExeInvokeException : Exception { public ExeInvokeException() { } public ExeInvokeException(string message) : base(message) { } public ExeInvokeException(string message, Exception inner) : base(message, inner) { } } public class ExeNotInstalledException : Exception { public ExeNotInstalledException() { } public ExeNotInstalledException(string message) : base(message) { } public ExeNotInstalledException(string message, Exception inner) : base(message, inner) { } } #endregion exceptions #region contracts [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.WorkingDirectory != null); Contract.Invariant(this.Url != null); Contract.Invariant(this.Name != null); } [ContractClassFor(typeof(Repository))] abstract class RepositoryContract : Repository { public override IEnumerable<string> GetVersionNumbers() { Contract.Ensures(Contract.Result<IEnumerable<string>>() != null); return default(IEnumerable<string>); } public override string Checkout(string version) { Contract.Requires(version != null); Contract.Ensures(Contract.Result<string>() == null || CheckedOut(version)); return default(string); } public override bool Build(string version) { Contract.Requires(version != null); Contract.Ensures(Contract.Result<bool>() == false || Built(version)); return default(bool); } public override bool CheckedOut(string version) { Contract.Requires(version != null); return default(bool); } public override bool Built(string version) { Contract.Requires(version != null); return default(bool); } } #endregion #region members, constants, constructor(s) public readonly string WorkingDirectory; public readonly string Url; public readonly string Name; protected const int shortTimeout = 10000; // 10s protected const int mediumTimeout = 120000; // 2min protected const int longTimeout = 36000000; // 10h public Repository(string workingDirectory, string url, string name) { Contract.Requires(workingDirectory != null); //Initialize(); this.WorkingDirectory = Path.Combine(workingDirectory, name); this.Url = url; this.Name = name; } #endregion #region abstract methods /// <summary> /// Return enumerable containing all version numbers (descending) /// </summary> /// <returns></returns> public abstract IEnumerable<string> GetVersionNumbers(); /// <summary> /// Check out single version of the repository /// </summary> /// <param name="versionNum"></param> /// <returns></returns> public abstract string Checkout(string version); /// <summary> /// Build single version of the repository /// </summary> /// <param name="version"></param> /// <returns></returns> public abstract bool Build(string version); /// <summary> /// Is version already built? /// </summary> /// <param name="version"></param> /// <returns></returns> [Pure] public abstract bool Built(string version); /// <summary> /// Is version already checked out? /// </summary> /// <param name="version"></param> /// <returns></returns> [Pure] public abstract bool CheckedOut(string version); #endregion abstract methods #region implemented methods #region initialization //static private string ExeFileName; abstract protected string ExeName { get; } virtual protected string FallbackLocateExe() { return null; } public string MakeRepoPath(string versionNum) { Contract.Requires(versionNum != null); Contract.Ensures(Contract.Result<string>() != null); return Path.Combine(this.WorkingDirectory, this.Name + "-" + versionNum); } private string LocateExe() { var envPath = Environment.GetEnvironmentVariable("PATH"); if (envPath == null) return null; foreach (var path in envPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { var fileName = Path.Combine(path, this.ExeName); if (File.Exists(fileName)) return fileName; } return this.FallbackLocateExe(); } static private bool initialized = false; /* public void Initialize() { if (initialized) return; ExeFileName = this.LocateExe(); if (String.IsNullOrWhiteSpace(ExeFileName)) { throw new ExeNotInstalledException(); } initialized = true; } */ #endregion /// <summary> /// Check out and build all versions of this repository /// </summary> public void CheckoutAndRebuildAll() { CheckoutAllImpl(true, true); } /// <summary> /// Check out all versions of this repository and build versions that aren't already built /// </summary> public void CheckoutAndBuildAll() { CheckoutAllImpl(true); } /// <summary> /// Check out all versions of this repository; don't build /// </summary> public void CheckoutAll() { CheckoutAllImpl(); } // check out and optionally build all versions of repo private void CheckoutAllImpl(bool build = false, bool rebuild = false) { foreach (string version in GetVersionNumbers()) { string repoPath = Checkout(version); // get repo if (repoPath == null) continue; // checkout failed if (build) { if (rebuild || !Built(version)) { Build(version); } else { Console.WriteLine(version + " already built"); } } } } /// <summary> /// Returns true if incovation succeeded /// </summary> /// <param name="arguments"></param> /// <param name="timeoutMilliseconds"></param> /// <returns></returns> protected bool InvokeSourceManager(string arguments, string workingDir, int timeoutMilliseconds = 0) {/* var info = new ProcessStartInfo(arguments); info.FileName = ExeName; info.WorkingDirectory = this.WorkingDirectory; var process = Process.Start(info); Console.WriteLine("waiting for process..."); //process.WaitForInputIdle(); process.WaitForExit(); while (process.Responding) { } return true; */ Contract.Requires(!String.IsNullOrWhiteSpace(arguments)); var psi = new ProcessStartInfo { Arguments = arguments, //CreateNoWindow = true, //ErrorDialog = false, FileName = ExeName, //RedirectStandardError = true, //RedirectStandardInput = true, //RedirectStandardOutput = true, //UseShellExecute = false, //WindowStyle = ProcessWindowStyle.Hidden, //WorkingDirectory = this.WorkingDirectory WorkingDirectory = workingDir }; try { var process = new Process(); process.StartInfo = psi; process.Start(); Console.WriteLine("waiting for process..."); process.WaitForExit(); Console.WriteLine("done waiting."); //return true; return process.ExitCode == 0; } catch (Exception e) { throw new ExeInvokeException("Arguments = \"" + arguments + "\". Refer to inner exception for details.", e); } } protected string InvokeSourceManagerForOutput(string arguments, int timeoutMilliseconds = 0) { Contract.Requires(!String.IsNullOrWhiteSpace(arguments)); Contract.Ensures(Contract.Result<String>() != null); var psi = new ProcessStartInfo { Arguments = arguments, CreateNoWindow = true, ErrorDialog = false, FileName = ExeName, RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden, //WorkingDirectory = this.WorkingDirectory WorkingDirectory = Environment.CurrentDirectory }; try { var process = new Process(); process.StartInfo = psi; process.Start(); return process.StandardOutput.ReadToEnd(); } catch (Exception e) { throw new ExeInvokeException("Arguments = \"" + arguments + "\". Refer to inner exception for details.", e); } } #endregion implemented methods } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.Threading; using System.Windows.Forms; using Medo.Configuration; using QText.Plugins; namespace QText { internal static class App { public static TrayContext TrayContext; public static QText.Document Document; public static Medo.Windows.Forms.Hotkey Hotkey = new Medo.Windows.Forms.Hotkey(); private static bool ArgHide; private static bool ArgRestart; private static bool ArgSetup; [STAThread] public static void Main() { var mutexSecurity = new MutexSecurity(); mutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow)); using (var setupMutex = new Mutex(false, @"Global\JosipMedved_QText", out var createdNew, mutexSecurity)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Thread.CurrentThread.CurrentUICulture = new CultureInfo(Medo.Configuration.Settings.Read("CultureName", "en-US")); ArgHide = Medo.Application.Args.Current.ContainsKey("hide"); ArgSetup = Medo.Application.Args.Current.ContainsKey("setup"); ArgRestart = Medo.Application.Args.Current.ContainsKey("restart"); if (ArgSetup) { Legacy.OrderedFiles.Upgrade(); } Medo.Application.UnhandledCatch.ThreadException += new System.EventHandler<ThreadExceptionEventArgs>(UnhandledException); Medo.Application.UnhandledCatch.Attach(); Medo.Application.Restart.Register("/restart"); Application.ApplicationExit += new System.EventHandler(ApplicationExit); Medo.Windows.Forms.State.NoRegistryWrites = Settings.Current.NoRegistryWrites; Medo.Diagnostics.ErrorReport.DisableAutomaticSaveToTemp = Settings.Current.NoRegistryWrites; if (!Config.IsAssumedInstalled) { Medo.Windows.Forms.State.ReadState += delegate (object sender, Medo.Windows.Forms.StateReadEventArgs e) { e.Value = Config.Read("State!" + e.Name.Replace("QText.", ""), e.DefaultValue); }; Medo.Windows.Forms.State.WriteState += delegate (object sender, Medo.Windows.Forms.StateWriteEventArgs e) { Config.Write("State!" + e.Name.Replace("QText.", ""), e.Value); }; } #region Init document try { OpenDocument(); } catch (DirectoryNotFoundException) { //try to create it try { Helper.CreatePath(Settings.Current.FilesLocation); OpenDocument(); } catch (DirectoryNotFoundException) { //try to create it if (Medo.MessageBox.ShowError(null, "Directory " + Settings.Current.FilesLocation + " cannot be found.\n\nDo you wish to use default location at " + Settings.Current.DefaultFilesLocation + "?", MessageBoxButtons.YesNo) == DialogResult.Yes) { Settings.Current.FilesLocation = Settings.Current.DefaultFilesLocation; Helper.CreatePath(Settings.Current.FilesLocation); OpenDocument(); } else { return; } } catch (InvalidOperationException) { //try to create it if (Medo.MessageBox.ShowError(null, "Directory " + Settings.Current.FilesLocation + " cannot be used.\n\nDo you wish to use default location at " + Settings.Current.DefaultFilesLocation + "?", MessageBoxButtons.YesNo) == DialogResult.Yes) { Settings.Current.FilesLocation = Settings.Current.DefaultFilesLocation; Helper.CreatePath(Settings.Current.FilesLocation); OpenDocument(); } else { return; } } } catch (NotSupportedException) { //path is invalid if (Medo.MessageBox.ShowError(null, "Directory " + Settings.Current.FilesLocation + " is invalid.\n\nDo you wish to use default location at " + Settings.Current.DefaultFilesLocation + "?", MessageBoxButtons.YesNo) == DialogResult.Yes) { Settings.Current.FilesLocation = Settings.Current.DefaultFilesLocation; Helper.CreatePath(Settings.Current.FilesLocation); OpenDocument(); } else { return; } } catch (InvalidOperationException ex) { Medo.MessageBox.ShowError(null, "Fatal startup error: " + ex.Message); return; } #endregion Medo.Application.SingleInstance.NewInstanceDetected += new EventHandler<Medo.Application.NewInstanceEventArgs>(SingleInstance_NewInstanceDetected); if (Medo.Application.SingleInstance.IsOtherInstanceRunning) { var currProcess = Process.GetCurrentProcess(); foreach (var iProcess in Process.GetProcessesByName(currProcess.ProcessName)) { try { if (iProcess.Id != currProcess.Id) { NativeMethods.AllowSetForegroundWindow(iProcess.Id); break; } } catch (Win32Exception) { } } } Medo.Application.SingleInstance.Attach(); try { Helper.CreatePath(Settings.Current.FilesLocation); } catch (Exception ex) { switch (Medo.MessageBox.ShowQuestion(null, ex.Message + Environment.NewLine + "Do you wish to try using default location instead?", MessageBoxButtons.YesNo)) { case DialogResult.Yes: try { var defaultPath = Settings.Current.DefaultFilesLocation; Helper.CreatePath(defaultPath); Settings.Current.FilesLocation = defaultPath; } catch (Exception ex2) { global::Medo.MessageBox.ShowError(null, ex2.Message, MessageBoxButtons.OK); Application.Exit(); System.Environment.Exit(0); } break; case DialogResult.No: break; } } App.TrayContext = new TrayContext(new MainForm()); App.TrayContext.ShowIcon(); App.Hotkey.HotkeyActivated += new EventHandler<EventArgs>(Hotkey_HotkeyActivated); if (Settings.Current.ActivationHotkey != Keys.None) { try { App.Hotkey.Register(Settings.Current.ActivationHotkey); } catch (InvalidOperationException) { Medo.MessageBox.ShowWarning(null, "Hotkey is already in use."); } } //initialize plugins foreach (var plugin in App.GetEnabledPlugins()) { plugin.Initialize(App.TrayContext); } if (!ArgHide && !ArgRestart) { App.TrayContext.ShowForm(); } Application.Run(App.TrayContext); } } private static void OpenDocument() { App.Document = new Document(Settings.Current.FilesLocation) { DeleteToRecycleBin = Settings.Current.FilesDeleteToRecycleBin, CarbonCopyRootPath = Settings.Current.CarbonCopyUse ? Settings.Current.CarbonCopyDirectory : null, CarbonCopyIgnoreErrors = Settings.Current.CarbonCopyIgnoreErrors }; } private static void SingleInstance_NewInstanceDetected(object sender, Medo.Application.NewInstanceEventArgs e) { if (!ArgHide && !ArgRestart) { App.TrayContext.ShowForm(); } } private static void Hotkey_HotkeyActivated(object sender, EventArgs e) { var doShow = true; if (Settings.Current.HotkeyTogglesVisibility) { var activeHwnd = NativeMethods.GetForegroundWindow(); if (activeHwnd != IntPtr.Zero) { NativeMethods.GetWindowThreadProcessId(activeHwnd, out var activeProcess); doShow = !(activeProcess == Process.GetCurrentProcess().Id); //hide if already active } } if (doShow) { App.TrayContext.ShowForm(); } else { App.TrayContext.HideForm(); } } private static void ApplicationExit(object sender, System.EventArgs e) { if (App.Hotkey.IsRegistered) { App.Hotkey.Unregister(); } Environment.Exit(0); } private static void UnhandledException(object sender, ThreadExceptionEventArgs e) { #if !DEBUG foreach (Form form in Application.OpenForms) { if (form.TopMost) { Medo.Diagnostics.ErrorReport.TopMost = true; break; } } Medo.Diagnostics.ErrorReport.ShowDialog(null, e.Exception, new Uri("https://medo64.com/feedback/")); if (Medo.Application.Restart.IsRegistered) { throw e.Exception; } #else throw e.Exception; #endif } #region Plugins private static ReadOnlyCollection<IPlugin> AllPlugins; public static IEnumerable<IPlugin> GetEnabledPlugins() { if (App.AllPlugins == null) { //TODO: Dynamic loading whenever I have more plugins var list = new List<IPlugin> { new Plugins.Reminder.ReminderPlugin() }; App.AllPlugins = list.AsReadOnly(); } foreach (var plugin in App.AllPlugins) { yield return plugin; } } #endregion Plugins private static class NativeMethods { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern int GetWindowThreadProcessId(IntPtr handle, out int processId); [DllImport("user32.dll", EntryPoint = "AllowSetForegroundWindow")] [return: MarshalAsAttribute(UnmanagedType.Bool)] public static extern bool AllowSetForegroundWindow(int dwProcessId); } } }
using System; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using stellar_dotnet_sdk; namespace stellar_dotnet_sdk_test { [TestClass] public class WebAuthenticationTest { [TestMethod] public void TestBuildChallengeTransaction() { var serverKeypair = KeyPair.Random(); var clientAccountId = "GBDIT5GUJ7R5BXO3GJHFXJ6AZ5UQK6MNOIDMPQUSMXLIHTUNR2Q5CFNF"; var anchorName = "NET"; Network.UseTestNetwork(); var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientAccountId, anchorName); var serializedTx = tx.ToEnvelopeXdrBase64(); var back = Transaction.FromEnvelopeXdr(serializedTx); var timeout = back.TimeBounds.MaxTime - back.TimeBounds.MinTime; Assert.AreEqual(300, timeout); CheckAccounts(back, serverKeypair); CheckOperation(back, clientAccountId); } [TestMethod] public void TestBuildChallengeTransactionWithOptions() { var serverKeypair = KeyPair.Random(); var clientAccountId = "GBDIT5GUJ7R5BXO3GJHFXJ6AZ5UQK6MNOIDMPQUSMXLIHTUNR2Q5CFNF"; var anchorName = "NET"; var nonce = new byte[48]; Array.Clear(nonce, 0, nonce.Length); var now = new DateTimeOffset(); var duration = TimeSpan.FromMinutes(10.0); var tx = WebAuthentication .BuildChallengeTransaction(serverKeypair, clientAccountId, anchorName, nonce, now, duration, Network.Test()); var serializedTx = tx.ToEnvelopeXdrBase64(); var back = Transaction.FromEnvelopeXdr(serializedTx); var timeout = back.TimeBounds.MaxTime - back.TimeBounds.MinTime; Assert.AreEqual(600, timeout); CheckAccounts(back, serverKeypair); CheckOperation(back, clientAccountId); } [TestMethod] public void TestVerifyChallengeTransactionReturnsTrueForValidTransaction() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientKeypair.AccountId, anchorName, now: now); tx.Sign(clientKeypair); Assert.IsTrue(WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now)); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfSequenceIsNotZero() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var nonce = new byte[64]; var tx = new Transaction .Builder(new Account(serverKeypair.AccountId, 0)) .AddOperation(new ManageDataOperation.Builder("NET auth", nonce).Build()) .Build(); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfServerAccountIdIsDifferent() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientKeypair.AccountId, anchorName, now: now); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, KeyPair.Random().AccountId, now: now); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfTransactionHasNoManageDataOperation() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = new Transaction .Builder(new Account(serverKeypair.AccountId, -1)) .AddOperation( new AccountMergeOperation.Builder(serverKeypair) .SetSourceAccount(clientKeypair) .Build()) .Build(); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfOperationHasNoSourceAccount() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var nonce = new byte[64]; var tx = new Transaction .Builder(new Account(serverKeypair.AccountId, -1)) .AddOperation(new ManageDataOperation.Builder("NET auth", nonce).Build()) .Build(); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfOperationDataIsNotBase64Encoded() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var nonce = new byte[64]; var tx = new Transaction .Builder(new Account(serverKeypair.AccountId, -1)) .AddOperation( new ManageDataOperation .Builder("NET auth", nonce) .SetSourceAccount(clientKeypair) .Build()) .Build(); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfNotSignedByServer() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientKeypair.AccountId, anchorName, now: now); tx.Signatures.Clear(); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfSignedByServerOnDifferentNetwork() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientKeypair.AccountId, anchorName, now: now); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now, network: Network.Public()); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfNotSignedByClient() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientKeypair.AccountId, anchorName, now: now); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfSignedByClientOnDifferentNetwork() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientKeypair.AccountId, anchorName, now: now); tx.Sign(clientKeypair, Network.Public()); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now, network: Network.Test()); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfItsTooEarly() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientKeypair.AccountId, anchorName, now: now); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now.Subtract(TimeSpan.FromDays(1.0))); }); } [TestMethod] public void TestVerifyChallengeTransactionThrowsIfItsTooLate() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var tx = WebAuthentication.BuildChallengeTransaction(serverKeypair, clientKeypair.AccountId, anchorName, now: now); tx.Sign(clientKeypair); Assert.ThrowsException<InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now.Add(TimeSpan.FromDays(1.0))); }); } private void CheckAccounts(Transaction tx, KeyPair serverKeypair) { Assert.AreEqual(0, tx.SequenceNumber); Assert.AreEqual(serverKeypair.AccountId, tx.SourceAccount.AccountId); } private void CheckOperation(Transaction tx, string clientAccountId) { Assert.AreEqual(1, tx.Operations.Length); var operation = tx.Operations[0] as ManageDataOperation; Assert.IsNotNull(operation); Assert.AreEqual("NET auth", operation.Name); Assert.AreEqual(clientAccountId, operation.SourceAccount.AccountId); Assert.AreEqual(64, operation.Value.Length); var bytes = Convert.FromBase64String(Encoding.UTF8.GetString(operation.Value)); Assert.AreEqual(48, bytes.Length); } } }
// // Copyright 2012, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; using Xamarin.Utilities; #if PLATFORM_IOS #if __UNIFIED__ using UIKit; using AuthenticateUIType = UIKit.UIViewController; #else using MonoTouch.UIKit; using AuthenticateUIType = MonoTouch.UIKit.UIViewController; #endif #elif PLATFORM_ANDROID using AuthenticateUIType = Android.Content.Intent; using UIContext = Android.Content.Context; using Android.App; #else using AuthenticateUIType = System.Object; #endif namespace Xamarin.Auth { /// <summary> /// A process and user interface to authenticate a user. /// </summary> #if XAMARIN_AUTH_INTERNAL internal abstract class Authenticator #else public abstract class Authenticator #endif { /// <summary> /// Gets or sets the title of any UI elements that need to be presented for this authenticator. /// </summary> /// <value><c>"Authenticate" by default.</c></value> public string Title { get; set; } /// <summary> /// Gets or sets whether to allow user cancellation. /// </summary> /// <value><c>true</c> by default.</value> public bool AllowCancel { get; set; } /// <summary> /// Occurs when authentication has been successfully or unsuccessfully completed. /// Consult the <see cref="AuthenticatorCompletedEventArgs.IsAuthenticated"/> event argument to determine if /// authentication was successful. /// </summary> public event EventHandler<AuthenticatorCompletedEventArgs> Completed; /// <summary> /// Occurs when there an error is encountered when authenticating. /// </summary> public event EventHandler<AuthenticatorErrorEventArgs> Error; /// <summary> /// Gets whether this authenticator has completed its interaction with the user. /// </summary> /// <value><c>true</c> if authorization has been completed, <c>false</c> otherwise.</value> public bool HasCompleted { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.Authenticator"/> class. /// </summary> public Authenticator () { Title = "Authenticate"; HasCompleted = false; AllowCancel = true; } #if PLATFORM_ANDROID UIContext context; public AuthenticateUIType GetUI (UIContext context) { this.context = context; return GetPlatformUI (context); } protected abstract AuthenticateUIType GetPlatformUI (UIContext context); #else /// <summary> /// Gets the UI for this authenticator. /// </summary> /// <returns> /// The UI that needs to be presented. /// </returns> public AuthenticateUIType GetUI () { return GetPlatformUI (); } /// <summary> /// Gets the UI for this authenticator. /// </summary> /// <returns> /// The UI that needs to be presented. /// </returns> protected abstract AuthenticateUIType GetPlatformUI (); #endif /// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='account'> /// The authenticated account. /// </param> public void OnSucceeded (Account account) { if (HasCompleted) return; HasCompleted = true; BeginInvokeOnUIThread (delegate { var ev = Completed; if (ev != null) { ev (this, new AuthenticatorCompletedEventArgs (account)); } }); } /// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='username'> /// User name of the account. /// </param> /// <param name='accountProperties'> /// Additional data, such as access tokens, that need to be stored with the account. This /// information is secured. /// </param> public void OnSucceeded (string username, IDictionary<string, string> accountProperties) { OnSucceeded (new Account (username, accountProperties)); } /// <summary> /// Implementations must call this function when they have cancelled the operation. /// </summary> public void OnCancelled () { if (HasCompleted) return; HasCompleted = true; BeginInvokeOnUIThread (delegate { var ev = Completed; if (ev != null) { ev (this, new AuthenticatorCompletedEventArgs (null)); } }); } /// <summary> /// Implementations must call this function when they have failed to authenticate. /// </summary> /// <param name='message'> /// The reason that this authentication has failed. /// </param> public void OnError (string message) { BeginInvokeOnUIThread (delegate { var ev = Error; if (ev != null) { ev (this, new AuthenticatorErrorEventArgs (message)); } }); } /// <summary> /// Implementations must call this function when they have failed to authenticate. /// </summary> /// <param name='exception'> /// The reason that this authentication has failed. /// </param> public void OnError (Exception exception) { BeginInvokeOnUIThread (delegate { var ev = Error; if (ev != null) { ev (this, new AuthenticatorErrorEventArgs (exception)); } }); } void BeginInvokeOnUIThread (Action action) { #if PLATFORM_IOS UIApplication.SharedApplication.BeginInvokeOnMainThread (delegate { action (); }); #elif PLATFORM_ANDROID var a = context as Activity; if (a != null) { a.RunOnUiThread (action); } else { action (); } #else action (); #endif } } /// <summary> /// Authenticator completed event arguments. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class AuthenticatorCompletedEventArgs : EventArgs #else public class AuthenticatorCompletedEventArgs : EventArgs #endif { /// <summary> /// Whether the authentication succeeded and there is a valid <see cref="Account"/>. /// </summary> /// <value> /// <see langword="true"/> if the user is authenticated; otherwise, <see langword="false"/>. /// </value> public bool IsAuthenticated { get { return Account != null; } } /// <summary> /// Gets the account created that represents this authentication. /// </summary> /// <value> /// The account. /// </value> public Account Account { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorCompletedEventArgs"/> class. /// </summary> /// <param name='account'> /// The account created or <see langword="null"/> if authentication failed or was canceled. /// </param> public AuthenticatorCompletedEventArgs (Account account) { Account = account; } } /// <summary> /// Authenticator error event arguments. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class AuthenticatorErrorEventArgs : EventArgs #else public class AuthenticatorErrorEventArgs : EventArgs #endif { /// <summary> /// Gets a message describing the error. /// </summary> /// <value> /// The message. /// </value> public string Message { get; private set; } /// <summary> /// Gets the exception that signaled the error if there was one. /// </summary> /// <value> /// The exception or <see langword="null"/>. /// </value> public Exception Exception { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorErrorEventArgs"/> class /// with a message but no exception. /// </summary> /// <param name='message'> /// A message describing the error. /// </param> public AuthenticatorErrorEventArgs (string message) { Message = message; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorErrorEventArgs"/> class with an exception. /// </summary> /// <param name='exception'> /// The exception signaling the error. The message of this object is retrieved from this exception or /// its inner exceptions. /// </param> public AuthenticatorErrorEventArgs (Exception exception) { Message = exception.GetUserMessage (); Exception = exception; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker; using Moq; using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Xunit; using Microsoft.VisualStudio.Services.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults; using TestRunContext = Microsoft.TeamFoundation.TestClient.PublishTestResults.TestRunContext; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.TestResults { public class TestRunPublisherTests : IDisposable { private static Mock<IExecutionContext> _ec; private static string _attachmentFilePath; private static TestRunContext _testRunContext; private static ITestRunPublisher _publisher; private static Mock<IResultReader> _reader; private static Mock<ITestResultsServer> _testResultServer; private TestRunData _testRunData; private int _runId; private string _projectId; private TestRunData _testRun; private TestAttachmentRequestModel _attachmentRequestModel; private TestCaseResult[] _resultCreateModels; private Dictionary<int, List<TestAttachmentRequestModel>> _resultsLevelAttachments = new Dictionary<int, List<TestAttachmentRequestModel>>(); private Dictionary<int, Dictionary<int, List<TestAttachmentRequestModel>>> _subResultsLevelAttachments = new Dictionary<int, Dictionary<int, List<TestAttachmentRequestModel>>>(); private RunUpdateModel _updateProperties; private List<int> _batchSizes = new List<int>(); private string _resultsFilepath; private TestRunContext _runContext; public TestRunPublisherTests() { _attachmentFilePath = "attachment.txt"; File.WriteAllText(_attachmentFilePath, "asdf"); _testRunContext = new TestRunContext("owner", "platform", "config", 1, "builduri", "releaseuri", "releaseenvuri"); _reader = new Mock<IResultReader>(); _reader.Setup(x => x.ReadResults(It.IsAny<IExecutionContext>(), It.IsAny<string>(), It.IsAny<TestRunContext>())) .Callback<IExecutionContext, string, TestRunContext> ((executionContext, filePath, runContext) => { _runContext = runContext; _resultsFilepath = filePath; }) .Returns((IExecutionContext executionContext, string filePath, TestRunContext runContext) => { TestRunData trd = new TestRunData( name: "xyz", buildId: runContext.BuildId, completedDate: "", state: "InProgress", isAutomated: true, dueDate: "", type: "", buildFlavor: runContext.Configuration, buildPlatform: runContext.Platform, releaseUri: runContext.ReleaseUri, releaseEnvironmentUri: runContext.ReleaseEnvironmentUri ); trd.Attachments = new string[] { "attachment.txt" }; return trd; }); _testResultServer = new Mock<ITestResultsServer>(); _testResultServer.Setup(x => x.InitializeServer(It.IsAny<VssConnection>(), It.IsAny<IExecutionContext>())); _testResultServer.Setup(x => x.AddTestResultsToTestRunAsync(It.IsAny<TestCaseResult[]>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<CancellationToken>())) .Callback<TestCaseResult[], string, int, CancellationToken> ((currentBatch, projectName, testRunId, cancellationToken) => { _batchSizes.Add(currentBatch.Length); _resultCreateModels = currentBatch; }) .Returns(() => { List<TestCaseResult> resultsList = new List<TestCaseResult>(); int i = 0; int j = 1; foreach (TestCaseResult resultCreateModel in _resultCreateModels) { List <TestSubResult> SubResults = null; if (resultCreateModel.SubResults != null) { SubResults = new List<TestSubResult>(); foreach (var subresultdata in resultCreateModel.SubResults) { var subResult = new TestSubResult(); subResult.Id = j++; SubResults.Add(subResult); } } resultsList.Add(new TestCaseResult() { Id = ++i, SubResults = SubResults }); } return Task.FromResult(resultsList); }); _testResultServer.Setup(x => x.CreateTestRunAsync(It.IsAny<string>(), It.IsAny<RunCreateModel>(), It.IsAny<CancellationToken>())) .Callback<string, RunCreateModel, CancellationToken> ((projectName, testRunData, cancellationToken) => { _projectId = projectName; _testRun = (TestRunData)testRunData; }) .Returns(Task.FromResult(new TestRun() { Name = "TestRun", Id = 1 })); _testResultServer.Setup(x => x.UpdateTestRunAsync(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<RunUpdateModel>(), It.IsAny<CancellationToken>())) .Callback<string, int, RunUpdateModel, CancellationToken> ((projectName, testRunId, updateModel, cancellationToken) => { _runId = testRunId; _projectId = projectName; _updateProperties = updateModel; }) .Returns(Task.FromResult(new TestRun() { Name = "TestRun", Id = 1 })); _testResultServer.Setup(x => x.CreateTestRunAttachmentAsync( It.IsAny<TestAttachmentRequestModel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<CancellationToken>())) .Callback<TestAttachmentRequestModel, string, int, CancellationToken> ((reqModel, projectName, testRunId, cancellationToken) => { _attachmentRequestModel = reqModel; _projectId = projectName; _runId = testRunId; }) .Returns(Task.FromResult(new TestAttachmentReference())); _testResultServer.Setup(x => x.CreateTestResultAttachmentAsync(It.IsAny<TestAttachmentRequestModel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>())) .Callback<TestAttachmentRequestModel, string, int, int, CancellationToken> ((reqModel, projectName, testRunId, testCaseResultId, cancellationToken) => { if (_resultsLevelAttachments.ContainsKey(testCaseResultId)) { _resultsLevelAttachments[testCaseResultId].Add(reqModel); } else { _resultsLevelAttachments.Add(testCaseResultId, new List<TestAttachmentRequestModel>() { reqModel }); } }) .Returns(Task.FromResult(new TestAttachmentReference())); _testResultServer.Setup(x => x.CreateTestSubResultAttachmentAsync(It.IsAny<TestAttachmentRequestModel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>())) .Callback<TestAttachmentRequestModel, string, int, int, int, CancellationToken> ((reqModel, projectName, testRunId, testCaseResultId, testSubResultId, cancellationToken) => { if (_subResultsLevelAttachments.ContainsKey(testCaseResultId)) { if(_subResultsLevelAttachments[testCaseResultId].ContainsKey(testSubResultId)) { _subResultsLevelAttachments[testCaseResultId][testSubResultId].Add(reqModel); } else { _subResultsLevelAttachments[testCaseResultId].Add(testSubResultId, new List<TestAttachmentRequestModel>() { reqModel }); } } else { Dictionary<int, List<TestAttachmentRequestModel>> subResulAtt = new Dictionary<int, List<TestAttachmentRequestModel>>(); subResulAtt.Add(testSubResultId, new List<TestAttachmentRequestModel>() { reqModel }); _subResultsLevelAttachments.Add(testCaseResultId, subResulAtt); } }) .Returns(Task.FromResult(new TestAttachmentReference())); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsSendsRunTitleToReader() { SetupMocks(); _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath", "runName"); Assert.Equal("runName", _runContext.RunName); } #if OS_LINUX [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] #endif public void HavingColonInAttachmentFileNameIsReplaced() { SetupMocks(); File.WriteAllText("colon:1:2:3.trx", "asdf"); ResetValues(); _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); var result = new TestCaseResultData(); var testRun = new TestRun { Id = 1 }; result.AttachmentData = new AttachmentData(); result.AttachmentData.AttachmentsFilePathList = new string[] { "colon:1:2:3.trx" }; _publisher.AddResultsAsync(testRun, new TestCaseResultData[] { result }).Wait(); Assert.Equal("colon_1_2_3.trx", _resultsLevelAttachments[1][0].FileName); try { File.Delete("colon:1:2:3.trx"); } catch { } } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void AddResultsWithAttachmentsCallsRightApi() { SetupMocks(); //Add results _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData); var result = new TestCaseResultData(); var testRun = new TestRun { Id = 1 }; result.AttachmentData = new AttachmentData(); result.AttachmentData.AttachmentsFilePathList = new string[] { "attachment.txt" }; _publisher.AddResultsAsync(testRun, new TestCaseResultData[] { result }).Wait(); Assert.Equal(_resultsLevelAttachments.Count, 1); Assert.Equal(_resultsLevelAttachments[1].Count, 1); Assert.Equal(_resultsLevelAttachments[1][0].AttachmentType, AttachmentType.GeneralAttachment.ToString()); Assert.Equal(_resultsLevelAttachments[1][0].Comment, ""); Assert.Equal(_resultsLevelAttachments[1][0].FileName, "attachment.txt"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void AddResultsWithSubResultsAttachmentsCallsRightApi() { SetupMocks(); //Add results _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData); var result = new TestCaseResultData(); result.TestCaseSubResultData = new List<TestCaseSubResultData> { new TestCaseSubResultData()}; var testRun = new TestRun { Id = 1 }; result.TestCaseSubResultData[0].AttachmentData = new AttachmentData(); result.TestCaseSubResultData[0].AttachmentData.AttachmentsFilePathList = new string[] { "attachment.txt" }; _publisher.AddResultsAsync(testRun, new TestCaseResultData[] { result }).Wait(); Assert.Equal(_subResultsLevelAttachments.Count, 1); Assert.Equal(_subResultsLevelAttachments[1].Count, 1); Assert.Equal(_subResultsLevelAttachments[1][1].Count, 1); Assert.Equal(_subResultsLevelAttachments[1][1][0].AttachmentType, AttachmentType.GeneralAttachment.ToString()); Assert.Equal(_subResultsLevelAttachments[1][1][0].Comment, ""); Assert.Equal(_subResultsLevelAttachments[1][1][0].FileName, "attachment.txt"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void AddResultsWithMultiHierarchySubResultsExceedMaxLevel() { SetupMocks(); //Add results _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData); var result = new TestCaseResultData(); var testRun = new TestRun { Id = 1 }; result.Outcome = "Failed"; result.TestCaseSubResultData = new List<TestCaseSubResultData>(); var mockSubResult = new TestCaseSubResultData() { Outcome = "Failed", SubResultData = new List<TestCaseSubResultData>() { new TestCaseSubResultData() { Outcome = "Failed", SubResultData = new List<TestCaseSubResultData>() { new TestCaseSubResultData() { Outcome = "Failed", SubResultData = new List<TestCaseSubResultData>() { new TestCaseSubResultData() { Outcome = "Failed" } } } } } } }; for (int i = 0; i < 1010; i++) { result.TestCaseSubResultData.Add(mockSubResult); } _publisher.AddResultsAsync(testRun, new TestCaseResultData[] { result }).Wait(); // validate foreach (TestCaseResult resultCreateModel in _resultCreateModels) { Assert.Equal(resultCreateModel.SubResults.Count, 1000); Assert.Equal(resultCreateModel.SubResults[0].SubResults[0].SubResults.Count, 1); Assert.Null(resultCreateModel.SubResults[0].SubResults[0].SubResults[0].SubResults); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void TrxFileUploadsWithCorrectAttachmentType() { SetupMocks(); File.WriteAllText("sampleTrx.trx", "asdf"); ResetValues(); _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); var result = new TestCaseResultData(); var testRun = new TestRun { Id = 1 }; result.AttachmentData = new AttachmentData(); result.AttachmentData.AttachmentsFilePathList = new string[] { "sampleTrx.trx" }; _publisher.AddResultsAsync(testRun, new TestCaseResultData[] { result }).Wait(); Assert.Equal(_resultsLevelAttachments.Count, 1); Assert.Equal(_resultsLevelAttachments[1].Count, 1); Assert.Equal(_resultsLevelAttachments[1][0].AttachmentType, AttachmentType.TmiTestRunSummary.ToString()); try { File.Delete("sampleTrx.trx"); } catch { } } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void TestImpactFileUploadsWithCorrectAttachmentType() { SetupMocks(); File.WriteAllText("testimpact.xml", "asdf"); ResetValues(); _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); var result = new TestCaseResultData(); var testRun = new TestRun { Id = 1 }; result.AttachmentData = new AttachmentData(); result.AttachmentData.AttachmentsFilePathList = new string[] { "testimpact.xml" }; _publisher.AddResultsAsync(testRun, new TestCaseResultData[] { result }).Wait(); Assert.Equal(_resultsLevelAttachments.Count, 1); Assert.Equal(_resultsLevelAttachments[1].Count, 1); Assert.Equal(_resultsLevelAttachments[1][0].AttachmentType, AttachmentType.TestImpactDetails.ToString()); try { File.Delete("testimpact.xml"); } catch { } } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void SystemInformationFileUploadsWithCorrectAttachmentType() { SetupMocks(); File.WriteAllText("SystemInformation.xml", "asdf"); ResetValues(); _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); TestCaseResultData result = new TestCaseResultData(); result.AttachmentData = new AttachmentData(); result.AttachmentData.AttachmentsFilePathList = new string[] { "SystemInformation.xml" }; var testRun = new TestRun { Id = 1 }; _publisher.AddResultsAsync(testRun, new TestCaseResultData[] { result }).Wait(); Assert.Equal(_resultsLevelAttachments.Count, 1); Assert.Equal(_resultsLevelAttachments[1].Count, 1); Assert.Equal(_resultsLevelAttachments[1][0].AttachmentType, AttachmentType.IntermediateCollectorData.ToString()); try { File.Delete("SystemInformation.xml"); } catch { } } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void StartTestRunCallsRightApi() { SetupMocks(); _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); Assert.Equal(_testRunContext, _runContext); Assert.Equal("filepath", _resultsFilepath); //Start run _publisher.StartTestRunAsync(_testRunData).Wait(); Assert.Equal(_projectId, "Project1"); Assert.Equal(_testRunData, _testRun); Assert.Equal(_projectId, "Project1"); Assert.Equal(_runId, 0); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void EndTestRunCallsRightApi() { SetupMocks(); _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); _projectId = ""; //End run. _publisher.EndTestRunAsync(_testRunData, 1).Wait(); Assert.Equal(_runId, 1); Assert.Equal(_projectId, "Project1"); Assert.Equal(_updateProperties.State, "Completed"); Assert.Equal(_attachmentRequestModel.AttachmentType, AttachmentType.GeneralAttachment.ToString()); Assert.Equal(_attachmentRequestModel.FileName, "attachment.txt"); Assert.Equal(_attachmentRequestModel.Comment, ""); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void EndTestRunWithArchiveCallsRightApi() { SetupMocks(); _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); _projectId = ""; //End run. _publisher.EndTestRunAsync(_testRunData, 1, publishAttachmentsAsArchive: true).Wait(); Assert.Equal(_runId, 1); Assert.Equal(_projectId, "Project1"); Assert.Equal(_updateProperties.State, "Completed"); Assert.Equal(_attachmentRequestModel.AttachmentType, AttachmentType.GeneralAttachment.ToString()); Assert.Equal(_attachmentRequestModel.FileName, "TestResults_1.zip"); Assert.Equal(_attachmentRequestModel.Comment, ""); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void BatchSizeIsCorrect() { SetupMocks(); int batchSize = 1000; ResetValues(); _publisher.StartTestRunAsync(new TestRunData()).Wait(); List<TestCaseResultData> testCaseResultData = new List<TestCaseResultData>(); for (int i = 0; i < batchSize + 1; i++) { testCaseResultData.Add(new TestCaseResultData()); testCaseResultData[i].AttachmentData = new AttachmentData(); } var testRun = new TestRun { Id = 1 }; _publisher.AddResultsAsync(testRun, testCaseResultData.ToArray()).Wait(); Assert.Equal(2, _batchSizes.Count); Assert.Equal(batchSize, _batchSizes[0]); Assert.Equal(1, _batchSizes[1]); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishConsoleLogIsSuccessful() { SetupMocks(); ResetValues(); TestCaseResultData testResultWithLog = new TestCaseResultData(); testResultWithLog.AttachmentData = new AttachmentData(); testResultWithLog.AttachmentData.ConsoleLog = "Publish console log is successfully logged"; TestCaseResultData testResultWithNoLog = new TestCaseResultData(); testResultWithNoLog.AttachmentData = new AttachmentData(); testResultWithNoLog.AttachmentData.ConsoleLog = ""; TestCaseResultData testResultDefault = new TestCaseResultData(); testResultDefault.AttachmentData = new AttachmentData(); List<TestCaseResultData> testResults = new List<TestCaseResultData>() { testResultWithLog, testResultWithNoLog, testResultDefault }; // execute publish task _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); var testRun = new TestRun { Id = 1 }; _publisher.AddResultsAsync(testRun, testResults.ToArray()).Wait(); _publisher.EndTestRunAsync(_testRunData, 1).Wait(); // validate Assert.Equal(_resultsLevelAttachments.Count, 1); Assert.Equal(_resultsLevelAttachments[1].Count, 1); Assert.Equal(_resultsLevelAttachments[1][0].AttachmentType, AttachmentType.ConsoleLog.ToString()); string encodedData = _resultsLevelAttachments[1][0].Stream; byte[] bytes = Convert.FromBase64String(encodedData); string decodedData = System.Text.Encoding.UTF8.GetString(bytes); Assert.Equal(decodedData, testResultWithLog.AttachmentData.ConsoleLog); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishStandardErrorLogIsSuccessful() { SetupMocks(); ResetValues(); TestCaseResultData testResultWithStandardError = new TestCaseResultData(); testResultWithStandardError.AttachmentData = new AttachmentData(); testResultWithStandardError.AttachmentData.StandardError = "Publish standard error is successfully logged"; TestCaseResultData testResultWithNoStandardError = new TestCaseResultData(); testResultWithNoStandardError.AttachmentData = new AttachmentData(); testResultWithNoStandardError.AttachmentData.StandardError = ""; TestCaseResultData testResultDefault = new TestCaseResultData(); testResultDefault.AttachmentData = new AttachmentData(); List<TestCaseResultData> testResults = new List<TestCaseResultData>() { testResultWithStandardError, testResultWithNoStandardError, testResultDefault }; // execute publish task _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); var testRun = new TestRun { Id = 1 }; _publisher.AddResultsAsync(testRun, testResults.ToArray()).Wait(); _publisher.EndTestRunAsync(_testRunData, 1).Wait(); // validate Assert.Equal(_resultsLevelAttachments.Count, 1); Assert.Equal(_resultsLevelAttachments[1].Count, 1); Assert.Equal(_resultsLevelAttachments[1][0].AttachmentType, AttachmentType.ConsoleLog.ToString()); string encodedData = _resultsLevelAttachments[1][0].Stream; byte[] bytes = Convert.FromBase64String(encodedData); string decodedData = System.Text.Encoding.UTF8.GetString(bytes); Assert.Equal(decodedData, testResultWithStandardError.AttachmentData.StandardError); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PublishStandardErrorLogWithMultiupleResultsIsSuccessful() { SetupMocks(); ResetValues(); TestCaseResultData testResultWithStandardError1 = new TestCaseResultData(); testResultWithStandardError1.AttachmentData = new AttachmentData(); testResultWithStandardError1.AttachmentData.StandardError = "Publish standard error is successfully logged for result 1"; TestCaseResultData testResultWithStandardError2 = new TestCaseResultData(); testResultWithStandardError2.AttachmentData = new AttachmentData(); testResultWithStandardError2.AttachmentData.StandardError = "Publish standard error is successfully logged for result 2"; TestCaseResultData testResultWithNoStandardError = new TestCaseResultData(); testResultWithNoStandardError.AttachmentData = new AttachmentData(); testResultWithNoStandardError.AttachmentData.StandardError = ""; TestCaseResultData testResultDefault = new TestCaseResultData(); testResultDefault.AttachmentData = new AttachmentData(); List<TestCaseResultData> testResults = new List<TestCaseResultData>() { testResultWithStandardError1, testResultWithStandardError2, testResultWithNoStandardError, testResultDefault }; // execute publish task _testRunData = _publisher.ReadResultsFromFile(_testRunContext, "filepath"); _publisher.StartTestRunAsync(_testRunData).Wait(); var testRun = new TestRun { Id = 1 }; _publisher.AddResultsAsync(testRun, testResults.ToArray()).Wait(); _publisher.EndTestRunAsync(_testRunData, 1).Wait(); // validate Assert.Equal(_resultsLevelAttachments.Count, 2); Assert.Equal(_resultsLevelAttachments[1].Count, 1); Assert.Equal(_resultsLevelAttachments[2].Count, 1); Assert.Equal(_resultsLevelAttachments[1][0].AttachmentType, AttachmentType.ConsoleLog.ToString()); Assert.Equal(_resultsLevelAttachments[2][0].AttachmentType, AttachmentType.ConsoleLog.ToString()); string encodedData1 = _resultsLevelAttachments[1][0].Stream; byte[] bytes1 = Convert.FromBase64String(encodedData1); string decodedData1 = System.Text.Encoding.UTF8.GetString(bytes1); Assert.Equal(decodedData1, testResultWithStandardError1.AttachmentData.StandardError); string encodedData2 = _resultsLevelAttachments[2][0].Stream; byte[] bytes2 = Convert.FromBase64String(encodedData2); string decodedData2 = System.Text.Encoding.UTF8.GetString(bytes2); Assert.Equal(decodedData2, testResultWithStandardError2.AttachmentData.StandardError); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { try { File.Delete(_attachmentFilePath); } catch { } } } private void ResetValues() { _runId = 0; _projectId = ""; _attachmentRequestModel = null; _resultCreateModels = null; _resultsLevelAttachments = new Dictionary<int, List<TestAttachmentRequestModel>>(); _updateProperties = null; _batchSizes = new List<int>(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "VssConnection+TestHostContext")] private void SetupMocks([CallerMemberName] string name = "") { TestHostContext hc = new TestHostContext(this, name); _ec = new Mock<IExecutionContext>(); List<string> warnings; var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings); _ec.Setup(x => x.Variables).Returns(variables); hc.SetSingleton<ITestResultsServer>(_testResultServer.Object); _publisher = new TestRunPublisher(); _publisher.Initialize(hc); _publisher.InitializePublisher(_ec.Object, new VssConnection(new Uri("http://dummyurl"), new Common.VssCredentials()), "Project1", _reader.Object); } } }
/* * 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> /// OrderReplacement /// </summary> [DataContract] public partial class OrderReplacement : IEquatable<OrderReplacement>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="OrderReplacement" /> class. /// </summary> /// <param name="additionalMerchantNotesNewOrder">Additional merchant notes to append to the new order.</param> /// <param name="additionalMerchantNotesOriginalOrder">Additional merchant notes to append to the original order.</param> /// <param name="customField1">Custom field 1.</param> /// <param name="customField2">Custom field 2.</param> /// <param name="customField3">Custom field 3.</param> /// <param name="customField4">Custom field 4.</param> /// <param name="customField5">Custom field 5.</param> /// <param name="customField6">Custom field 6.</param> /// <param name="customField7">Custom field 7.</param> /// <param name="free">Set to true if this replacement shipment should be free for the customer..</param> /// <param name="immediateCharge">Set to true if you want to immediately charge the payment on this order, otherwise it will go to Accounts Receivable..</param> /// <param name="items">Items to include in the replacement order.</param> /// <param name="originalOrderId">Original order id.</param> /// <param name="shippingMethod">Shipping method to use. If not specified or invalid then least cost shipping will take place..</param> /// <param name="skipPayment">Set to true if you want to skip the payment as if it was successful..</param> public OrderReplacement(string additionalMerchantNotesNewOrder = default(string), string additionalMerchantNotesOriginalOrder = default(string), string customField1 = default(string), string customField2 = default(string), string customField3 = default(string), string customField4 = default(string), string customField5 = default(string), string customField6 = default(string), string customField7 = default(string), bool? free = default(bool?), bool? immediateCharge = default(bool?), List<OrderReplacementItem> items = default(List<OrderReplacementItem>), string originalOrderId = default(string), string shippingMethod = default(string), bool? skipPayment = default(bool?)) { this.AdditionalMerchantNotesNewOrder = additionalMerchantNotesNewOrder; this.AdditionalMerchantNotesOriginalOrder = additionalMerchantNotesOriginalOrder; this.CustomField1 = customField1; this.CustomField2 = customField2; this.CustomField3 = customField3; this.CustomField4 = customField4; this.CustomField5 = customField5; this.CustomField6 = customField6; this.CustomField7 = customField7; this.Free = free; this.ImmediateCharge = immediateCharge; this.Items = items; this.OriginalOrderId = originalOrderId; this.ShippingMethod = shippingMethod; this.SkipPayment = skipPayment; } /// <summary> /// Additional merchant notes to append to the new order /// </summary> /// <value>Additional merchant notes to append to the new order</value> [DataMember(Name="additional_merchant_notes_new_order", EmitDefaultValue=false)] public string AdditionalMerchantNotesNewOrder { get; set; } /// <summary> /// Additional merchant notes to append to the original order /// </summary> /// <value>Additional merchant notes to append to the original order</value> [DataMember(Name="additional_merchant_notes_original_order", EmitDefaultValue=false)] public string AdditionalMerchantNotesOriginalOrder { get; set; } /// <summary> /// Custom field 1 /// </summary> /// <value>Custom field 1</value> [DataMember(Name="custom_field1", EmitDefaultValue=false)] public string CustomField1 { get; set; } /// <summary> /// Custom field 2 /// </summary> /// <value>Custom field 2</value> [DataMember(Name="custom_field2", EmitDefaultValue=false)] public string CustomField2 { get; set; } /// <summary> /// Custom field 3 /// </summary> /// <value>Custom field 3</value> [DataMember(Name="custom_field3", EmitDefaultValue=false)] public string CustomField3 { get; set; } /// <summary> /// Custom field 4 /// </summary> /// <value>Custom field 4</value> [DataMember(Name="custom_field4", EmitDefaultValue=false)] public string CustomField4 { get; set; } /// <summary> /// Custom field 5 /// </summary> /// <value>Custom field 5</value> [DataMember(Name="custom_field5", EmitDefaultValue=false)] public string CustomField5 { get; set; } /// <summary> /// Custom field 6 /// </summary> /// <value>Custom field 6</value> [DataMember(Name="custom_field6", EmitDefaultValue=false)] public string CustomField6 { get; set; } /// <summary> /// Custom field 7 /// </summary> /// <value>Custom field 7</value> [DataMember(Name="custom_field7", EmitDefaultValue=false)] public string CustomField7 { get; set; } /// <summary> /// Set to true if this replacement shipment should be free for the customer. /// </summary> /// <value>Set to true if this replacement shipment should be free for the customer.</value> [DataMember(Name="free", EmitDefaultValue=false)] public bool? Free { get; set; } /// <summary> /// Set to true if you want to immediately charge the payment on this order, otherwise it will go to Accounts Receivable. /// </summary> /// <value>Set to true if you want to immediately charge the payment on this order, otherwise it will go to Accounts Receivable.</value> [DataMember(Name="immediate_charge", EmitDefaultValue=false)] public bool? ImmediateCharge { get; set; } /// <summary> /// Items to include in the replacement order /// </summary> /// <value>Items to include in the replacement order</value> [DataMember(Name="items", EmitDefaultValue=false)] public List<OrderReplacementItem> Items { get; set; } /// <summary> /// Original order id /// </summary> /// <value>Original order id</value> [DataMember(Name="original_order_id", EmitDefaultValue=false)] public string OriginalOrderId { get; set; } /// <summary> /// Shipping method to use. If not specified or invalid then least cost shipping will take place. /// </summary> /// <value>Shipping method to use. If not specified or invalid then least cost shipping will take place.</value> [DataMember(Name="shipping_method", EmitDefaultValue=false)] public string ShippingMethod { get; set; } /// <summary> /// Set to true if you want to skip the payment as if it was successful. /// </summary> /// <value>Set to true if you want to skip the payment as if it was successful.</value> [DataMember(Name="skip_payment", EmitDefaultValue=false)] public bool? SkipPayment { 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 OrderReplacement {\n"); sb.Append(" AdditionalMerchantNotesNewOrder: ").Append(AdditionalMerchantNotesNewOrder).Append("\n"); sb.Append(" AdditionalMerchantNotesOriginalOrder: ").Append(AdditionalMerchantNotesOriginalOrder).Append("\n"); sb.Append(" CustomField1: ").Append(CustomField1).Append("\n"); sb.Append(" CustomField2: ").Append(CustomField2).Append("\n"); sb.Append(" CustomField3: ").Append(CustomField3).Append("\n"); sb.Append(" CustomField4: ").Append(CustomField4).Append("\n"); sb.Append(" CustomField5: ").Append(CustomField5).Append("\n"); sb.Append(" CustomField6: ").Append(CustomField6).Append("\n"); sb.Append(" CustomField7: ").Append(CustomField7).Append("\n"); sb.Append(" Free: ").Append(Free).Append("\n"); sb.Append(" ImmediateCharge: ").Append(ImmediateCharge).Append("\n"); sb.Append(" Items: ").Append(Items).Append("\n"); sb.Append(" OriginalOrderId: ").Append(OriginalOrderId).Append("\n"); sb.Append(" ShippingMethod: ").Append(ShippingMethod).Append("\n"); sb.Append(" SkipPayment: ").Append(SkipPayment).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 OrderReplacement); } /// <summary> /// Returns true if OrderReplacement instances are equal /// </summary> /// <param name="input">Instance of OrderReplacement to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderReplacement input) { if (input == null) return false; return ( this.AdditionalMerchantNotesNewOrder == input.AdditionalMerchantNotesNewOrder || (this.AdditionalMerchantNotesNewOrder != null && this.AdditionalMerchantNotesNewOrder.Equals(input.AdditionalMerchantNotesNewOrder)) ) && ( this.AdditionalMerchantNotesOriginalOrder == input.AdditionalMerchantNotesOriginalOrder || (this.AdditionalMerchantNotesOriginalOrder != null && this.AdditionalMerchantNotesOriginalOrder.Equals(input.AdditionalMerchantNotesOriginalOrder)) ) && ( this.CustomField1 == input.CustomField1 || (this.CustomField1 != null && this.CustomField1.Equals(input.CustomField1)) ) && ( this.CustomField2 == input.CustomField2 || (this.CustomField2 != null && this.CustomField2.Equals(input.CustomField2)) ) && ( this.CustomField3 == input.CustomField3 || (this.CustomField3 != null && this.CustomField3.Equals(input.CustomField3)) ) && ( this.CustomField4 == input.CustomField4 || (this.CustomField4 != null && this.CustomField4.Equals(input.CustomField4)) ) && ( this.CustomField5 == input.CustomField5 || (this.CustomField5 != null && this.CustomField5.Equals(input.CustomField5)) ) && ( this.CustomField6 == input.CustomField6 || (this.CustomField6 != null && this.CustomField6.Equals(input.CustomField6)) ) && ( this.CustomField7 == input.CustomField7 || (this.CustomField7 != null && this.CustomField7.Equals(input.CustomField7)) ) && ( this.Free == input.Free || (this.Free != null && this.Free.Equals(input.Free)) ) && ( this.ImmediateCharge == input.ImmediateCharge || (this.ImmediateCharge != null && this.ImmediateCharge.Equals(input.ImmediateCharge)) ) && ( this.Items == input.Items || this.Items != null && this.Items.SequenceEqual(input.Items) ) && ( this.OriginalOrderId == input.OriginalOrderId || (this.OriginalOrderId != null && this.OriginalOrderId.Equals(input.OriginalOrderId)) ) && ( this.ShippingMethod == input.ShippingMethod || (this.ShippingMethod != null && this.ShippingMethod.Equals(input.ShippingMethod)) ) && ( this.SkipPayment == input.SkipPayment || (this.SkipPayment != null && this.SkipPayment.Equals(input.SkipPayment)) ); } /// <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.AdditionalMerchantNotesNewOrder != null) hashCode = hashCode * 59 + this.AdditionalMerchantNotesNewOrder.GetHashCode(); if (this.AdditionalMerchantNotesOriginalOrder != null) hashCode = hashCode * 59 + this.AdditionalMerchantNotesOriginalOrder.GetHashCode(); if (this.CustomField1 != null) hashCode = hashCode * 59 + this.CustomField1.GetHashCode(); if (this.CustomField2 != null) hashCode = hashCode * 59 + this.CustomField2.GetHashCode(); if (this.CustomField3 != null) hashCode = hashCode * 59 + this.CustomField3.GetHashCode(); if (this.CustomField4 != null) hashCode = hashCode * 59 + this.CustomField4.GetHashCode(); if (this.CustomField5 != null) hashCode = hashCode * 59 + this.CustomField5.GetHashCode(); if (this.CustomField6 != null) hashCode = hashCode * 59 + this.CustomField6.GetHashCode(); if (this.CustomField7 != null) hashCode = hashCode * 59 + this.CustomField7.GetHashCode(); if (this.Free != null) hashCode = hashCode * 59 + this.Free.GetHashCode(); if (this.ImmediateCharge != null) hashCode = hashCode * 59 + this.ImmediateCharge.GetHashCode(); if (this.Items != null) hashCode = hashCode * 59 + this.Items.GetHashCode(); if (this.OriginalOrderId != null) hashCode = hashCode * 59 + this.OriginalOrderId.GetHashCode(); if (this.ShippingMethod != null) hashCode = hashCode * 59 + this.ShippingMethod.GetHashCode(); if (this.SkipPayment != null) hashCode = hashCode * 59 + this.SkipPayment.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) { // CustomField1 (string) maxLength if(this.CustomField1 != null && this.CustomField1.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField1, length must be less than 50.", new [] { "CustomField1" }); } // CustomField2 (string) maxLength if(this.CustomField2 != null && this.CustomField2.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField2, length must be less than 50.", new [] { "CustomField2" }); } // CustomField3 (string) maxLength if(this.CustomField3 != null && this.CustomField3.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField3, length must be less than 50.", new [] { "CustomField3" }); } // CustomField4 (string) maxLength if(this.CustomField4 != null && this.CustomField4.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField4, length must be less than 50.", new [] { "CustomField4" }); } // CustomField5 (string) maxLength if(this.CustomField5 != null && this.CustomField5.Length > 75) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField5, length must be less than 75.", new [] { "CustomField5" }); } // CustomField6 (string) maxLength if(this.CustomField6 != null && this.CustomField6.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField6, length must be less than 50.", new [] { "CustomField6" }); } // CustomField7 (string) maxLength if(this.CustomField7 != null && this.CustomField7.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField7, length must be less than 50.", new [] { "CustomField7" }); } yield break; } } }
// // SegmentedBar.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Gtk; using Cairo; using Hyena.Gui; namespace Hyena.Widgets { public class SegmentedBar : Widget { public delegate string BarValueFormatHandler (Segment segment); public class Segment { private string title; private double percent; private Cairo.Color color; private bool show_in_bar; public Segment (string title, double percent, Cairo.Color color) : this (title, percent, color, true) { } public Segment (string title, double percent, Cairo.Color color, bool showInBar) { this.title = title; this.percent = percent; this.color = color; this.show_in_bar = showInBar; } public string Title { get { return title; } set { title = value; } } public double Percent { get { return percent; } set { percent = value; } } public Cairo.Color Color { get { return color; } set { color = value; } } public bool ShowInBar { get { return show_in_bar; } set { show_in_bar = value; } } internal int LayoutWidth; internal int LayoutHeight; } // State private List<Segment> segments = new List<Segment> (); private int layout_width; private int layout_height; // Properties private int bar_height = 26; private int bar_label_spacing = 8; private int segment_label_spacing = 16; private int segment_box_size = 12; private int segment_box_spacing = 6; private int h_padding = 0; private bool show_labels = true; private bool reflect = true; private Color remainder_color = CairoExtensions.RgbToColor (0xeeeeee); private BarValueFormatHandler format_handler; public SegmentedBar () { WidgetFlags |= WidgetFlags.NoWindow; } protected override void OnRealized () { GdkWindow = Parent.GdkWindow; base.OnRealized (); } #region Size Calculations protected override void OnSizeRequested (ref Requisition requisition) { requisition.Width = 200; requisition.Height = 0; } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { int _bar_height = reflect ? (int)Math.Ceiling (bar_height * 1.75) : bar_height; if (show_labels) { ComputeLayoutSize (); HeightRequest = Math.Max (bar_height + bar_label_spacing + layout_height, _bar_height); WidthRequest = layout_width + (2 * h_padding); } else { HeightRequest = _bar_height; WidthRequest = bar_height + (2 * h_padding); } base.OnSizeAllocated (allocation); } private void ComputeLayoutSize () { if (segments.Count == 0) { return; } Pango.Layout layout = null; layout_width = layout_height = 0; for (int i = 0, n = segments.Count; i < n; i++) { int aw, ah, bw, bh; layout = CreateAdaptLayout (layout, false, true); layout.SetText (FormatSegmentText (segments[i])); layout.GetPixelSize (out aw, out ah); layout = CreateAdaptLayout (layout, true, false); layout.SetText (FormatSegmentValue (segments[i])); layout.GetPixelSize (out bw, out bh); int w = Math.Max (aw, bw); int h = ah + bh; segments[i].LayoutWidth = w; segments[i].LayoutHeight = Math.Max (h, segment_box_size * 2); layout_width += segments[i].LayoutWidth + segment_box_size + segment_box_spacing + (i < n - 1 ? segment_label_spacing : 0); layout_height = Math.Max (layout_height, segments[i].LayoutHeight); } layout.Dispose (); } #endregion #region Public Methods public void AddSegmentRgba (string title, double percent, uint rgbaColor) { AddSegment (title, percent, CairoExtensions.RgbaToColor (rgbaColor)); } public void AddSegmentRgb (string title, double percent, uint rgbColor) { AddSegment (title, percent, CairoExtensions.RgbToColor (rgbColor)); } public void AddSegment (string title, double percent, Color color) { AddSegment (new Segment (title, percent, color, true)); } public void AddSegment (string title, double percent, Color color, bool showInBar) { AddSegment (new Segment (title, percent, color, showInBar)); } public void AddSegment (Segment segment) { lock (segments) { segments.Add (segment); QueueDraw (); } } public void UpdateSegment (int index, double percent) { segments[index].Percent = percent; QueueDraw (); } #endregion #region Public Properties public BarValueFormatHandler ValueFormatter { get { return format_handler; } set { format_handler = value; } } public Color RemainderColor { get { return remainder_color; } set { remainder_color = value; QueueDraw (); } } public int BarHeight { get { return bar_height; } set { if (bar_height != value) { bar_height = value; QueueResize (); } } } public bool ShowReflection { get { return reflect; } set { if (reflect != value) { reflect = value; QueueResize (); } } } public bool ShowLabels { get { return show_labels; } set { if (show_labels != value) { show_labels = value; QueueResize (); } } } public int SegmentLabelSpacing { get { return segment_label_spacing; } set { if (segment_label_spacing != value) { segment_label_spacing = value; QueueResize (); } } } public int SegmentBoxSize { get { return segment_box_size; } set { if (segment_box_size != value) { segment_box_size = value; QueueResize (); } } } public int SegmentBoxSpacing { get { return segment_box_spacing; } set { if (segment_box_spacing != value) { segment_box_spacing = value; QueueResize (); } } } public int BarLabelSpacing { get { return bar_label_spacing; } set { if (bar_label_spacing != value) { bar_label_spacing = value; QueueResize (); } } } public int HorizontalPadding { get { return h_padding; } set { if (h_padding != value) { h_padding = value; QueueResize (); } } } #endregion #region Rendering protected override bool OnExposeEvent (Gdk.EventExpose evnt) { if (evnt.Window != GdkWindow) { return base.OnExposeEvent (evnt); } Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window); if (reflect) { CairoExtensions.PushGroup (cr); } cr.Operator = Operator.Over; cr.Translate (Allocation.X + h_padding, Allocation.Y); cr.Rectangle (0, 0, Allocation.Width - h_padding, Math.Max (2 * bar_height, bar_height + bar_label_spacing + layout_height)); cr.Clip (); Pattern bar = RenderBar (Allocation.Width - 2 * h_padding, bar_height); cr.Save (); cr.Source = bar; cr.Paint (); cr.Restore (); if (reflect) { cr.Save (); cr.Rectangle (0, bar_height, Allocation.Width - h_padding, bar_height); cr.Clip (); Matrix matrix = new Matrix (); matrix.InitScale (1, -1); matrix.Translate (0, -(2 * bar_height) + 1); cr.Transform (matrix); cr.Pattern = bar; LinearGradient mask = new LinearGradient (0, 0, 0, bar_height); mask.AddColorStop (0.25, new Color (0, 0, 0, 0)); mask.AddColorStop (0.5, new Color (0, 0, 0, 0.125)); mask.AddColorStop (0.75, new Color (0, 0, 0, 0.4)); mask.AddColorStop (1.0, new Color (0, 0, 0, 0.7)); cr.Mask (mask); mask.Destroy (); cr.Restore (); CairoExtensions.PopGroupToSource (cr); cr.Paint (); } if (show_labels) { cr.Translate ((reflect ? Allocation.X : -h_padding) + (Allocation.Width - layout_width) / 2, (reflect ? Allocation.Y : 0) + bar_height + bar_label_spacing); RenderLabels (cr); } bar.Destroy (); ((IDisposable)cr.Target).Dispose (); ((IDisposable)cr).Dispose (); return true; } private Pattern RenderBar (int w, int h) { ImageSurface s = new ImageSurface (Format.Argb32, w, h); Context cr = new Context (s); RenderBar (cr, w, h, h / 2); // TODO Implement the new ctor - see http://bugzilla.gnome.org/show_bug.cgi?id=561394 #pragma warning disable 0618 Pattern pattern = new Pattern (s); #pragma warning restore 0618 s.Destroy (); ((IDisposable)cr).Dispose (); return pattern; } private void RenderBar (Context cr, int w, int h, int r) { RenderBarSegments (cr, w, h, r); RenderBarStrokes (cr, w, h, r); } private void RenderBarSegments (Context cr, int w, int h, int r) { LinearGradient grad = new LinearGradient (0, 0, w, 0); double last = 0.0; foreach (Segment segment in segments) { if (segment.Percent > 0) { grad.AddColorStop (last, segment.Color); grad.AddColorStop (last += segment.Percent, segment.Color); } } CairoExtensions.RoundedRectangle (cr, 0, 0, w, h, r); cr.Pattern = grad; cr.FillPreserve (); cr.Pattern.Destroy (); grad = new LinearGradient (0, 0, 0, h); grad.AddColorStop (0.0, new Color (1, 1, 1, 0.125)); grad.AddColorStop (0.35, new Color (1, 1, 1, 0.255)); grad.AddColorStop (1, new Color (0, 0, 0, 0.4)); cr.Pattern = grad; cr.Fill (); cr.Pattern.Destroy (); } private void RenderBarStrokes (Context cr, int w, int h, int r) { LinearGradient stroke = MakeSegmentGradient (h, CairoExtensions.RgbaToColor (0x00000040)); LinearGradient seg_sep_light = MakeSegmentGradient (h, CairoExtensions.RgbaToColor (0xffffff20)); LinearGradient seg_sep_dark = MakeSegmentGradient (h, CairoExtensions.RgbaToColor (0x00000020)); cr.LineWidth = 1; double seg_w = 20; double x = seg_w > r ? seg_w : r; while (x <= w - r) { cr.MoveTo (x - 0.5, 1); cr.LineTo (x - 0.5, h - 1); cr.Pattern = seg_sep_light; cr.Stroke (); cr.MoveTo (x + 0.5, 1); cr.LineTo (x + 0.5, h - 1); cr.Pattern = seg_sep_dark; cr.Stroke (); x += seg_w; } CairoExtensions.RoundedRectangle (cr, 0.5, 0.5, w - 1, h - 1, r); cr.Pattern = stroke; cr.Stroke (); stroke.Destroy (); seg_sep_light.Destroy (); seg_sep_dark.Destroy (); } private LinearGradient MakeSegmentGradient (int h, Color color) { return MakeSegmentGradient (h, color, false); } private LinearGradient MakeSegmentGradient (int h, Color color, bool diag) { LinearGradient grad = new LinearGradient (0, 0, 0, h); grad.AddColorStop (0, CairoExtensions.ColorShade (color, 1.1)); grad.AddColorStop (0.35, CairoExtensions.ColorShade (color, 1.2)); grad.AddColorStop (1, CairoExtensions.ColorShade (color, 0.8)); return grad; } private void RenderLabels (Context cr) { if (segments.Count == 0) { return; } Pango.Layout layout = null; Color text_color = CairoExtensions.GdkColorToCairoColor (Style.Foreground (State)); Color box_stroke_color = new Color (0, 0, 0, 0.6); int x = 0; foreach (Segment segment in segments) { cr.LineWidth = 1; cr.Rectangle (x + 0.5, 2 + 0.5, segment_box_size - 1, segment_box_size - 1); LinearGradient grad = MakeSegmentGradient (segment_box_size, segment.Color, true); cr.Pattern = grad; cr.FillPreserve (); cr.Color = box_stroke_color; cr.Stroke (); grad.Destroy (); x += segment_box_size + segment_box_spacing; int lw, lh; layout = CreateAdaptLayout (layout, false, true); layout.SetText (FormatSegmentText (segment)); layout.GetPixelSize (out lw, out lh); cr.MoveTo (x, 0); text_color.A = 0.9; cr.Color = text_color; PangoCairoHelper.ShowLayout (cr, layout); cr.Fill (); layout = CreateAdaptLayout (layout, true, false); layout.SetText (FormatSegmentValue (segment)); cr.MoveTo (x, lh); text_color.A = 0.75; cr.Color = text_color; PangoCairoHelper.ShowLayout (cr, layout); cr.Fill (); x += segment.LayoutWidth + segment_label_spacing; } layout.Dispose (); } #endregion #region Utilities private int pango_size_normal; private Pango.Layout CreateAdaptLayout (Pango.Layout layout, bool small, bool bold) { if (layout == null) { Pango.Context context = CreatePangoContext (); layout = new Pango.Layout (context); layout.FontDescription = context.FontDescription; pango_size_normal = layout.FontDescription.Size; } layout.FontDescription.Size = small ? (int)(layout.FontDescription.Size * Pango.Scale.Small) : pango_size_normal; layout.FontDescription.Weight = bold ? Pango.Weight.Bold : Pango.Weight.Normal; return layout; } private string FormatSegmentText (Segment segment) { return segment.Title; } private string FormatSegmentValue (Segment segment) { return format_handler == null ? String.Format ("{0}%", segment.Percent * 100.0) : format_handler (segment); } #endregion } #region Test Module [TestModule ("Segmented Bar")] internal class SegmentedBarTestModule : Window { private SegmentedBar bar; private VBox box; public SegmentedBarTestModule () : base ("Segmented Bar") { BorderWidth = 10; AppPaintable = true; box = new VBox (); box.Spacing = 10; Add (box); int space = 55; bar = new SegmentedBar (); bar.HorizontalPadding = bar.BarHeight / 2; bar.AddSegmentRgb ("Audio", 0.00187992456702332, 0x3465a4); bar.AddSegmentRgb ("Other", 0.0788718162651326, 0xf57900); bar.AddSegmentRgb ("Video", 0.0516869922033282, 0x73d216); bar.AddSegment ("Free Space", 0.867561266964516, bar.RemainderColor, false); bar.ValueFormatter = delegate (SegmentedBar.Segment segment) { return String.Format ("{0} GB", space * segment.Percent); }; HBox controls = new HBox (); controls.Spacing = 5; Label label = new Label ("Height:"); controls.PackStart (label, false, false, 0); SpinButton height = new SpinButton (new Adjustment (bar.BarHeight, 5, 100, 1, 1, 1), 1, 0); height.Activated += delegate { bar.BarHeight = height.ValueAsInt; }; height.Changed += delegate { bar.BarHeight = height.ValueAsInt; bar.HorizontalPadding = bar.BarHeight / 2; }; controls.PackStart (height, false, false, 0); CheckButton reflect = new CheckButton ("Reflection"); reflect.Active = bar.ShowReflection; reflect.Toggled += delegate { bar.ShowReflection = reflect.Active; }; controls.PackStart (reflect, false, false, 0); CheckButton labels = new CheckButton ("Labels"); labels.Active = bar.ShowLabels; labels.Toggled += delegate { bar.ShowLabels = labels.Active; }; controls.PackStart (labels, false, false, 0); box.PackStart (controls, false, false, 0); box.PackStart (new HSeparator (), false, false, 0); box.PackStart (bar, false, false, 0); box.ShowAll (); SetSizeRequest (350, -1); Gdk.Geometry limits = new Gdk.Geometry (); limits.MinWidth = SizeRequest ().Width; limits.MaxWidth = Gdk.Screen.Default.Width; limits.MinHeight = -1; limits.MaxHeight = -1; SetGeometryHints (this, limits, Gdk.WindowHints.MaxSize | Gdk.WindowHints.MinSize); } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Runtime.InteropServices.WindowsRuntime.Tests { public class WindowsRuntimeMarshalTests { [Fact] public void AddEventHandler_RemoveMethodHasTarget_Success() { bool addMethodCalled = false; bool removeMethodCalled = false; Delegate handler = new EventHandler(EventHandlerMethod1); Func<Delegate, EventRegistrationToken> addMethod = eventHandler => { Assert.False(addMethodCalled); addMethodCalled = true; Assert.Same(handler, eventHandler); return new EventRegistrationToken(); }; WindowsRuntimeMarshal.AddEventHandler(addMethod, token => removeMethodCalled = true, handler); Assert.True(addMethodCalled); Assert.False(removeMethodCalled); } [Fact] public void AddEventHandler_RemoveMethodHasNoTarget_Success() { bool removeMethodCalled = false; ExpectedHandler = new EventHandler(EventHandlerMethod1); WindowsRuntimeMarshal.AddEventHandler(AddMethod, token => removeMethodCalled = true, ExpectedHandler); Assert.True(AddMethodCalled); Assert.False(removeMethodCalled); } private static bool AddMethodCalled { get; set; } private static Delegate ExpectedHandler { get; set; } private static EventRegistrationToken AddMethod(Delegate eventHandler) { Assert.False(AddMethodCalled); AddMethodCalled = true; Assert.Same(ExpectedHandler, eventHandler); return new EventRegistrationToken(); } [Fact] public void AddEventHandler_NullHandler_Nop() { bool addMethodCalled = false; bool removeMethodCalled = false; WindowsRuntimeMarshal.AddEventHandler<Delegate>(eventHandler => { addMethodCalled = true; return new EventRegistrationToken(); }, token => removeMethodCalled = true, null); Assert.False(addMethodCalled); Assert.False(removeMethodCalled); } [Fact] public void AddEventHandler_NullAddMethod_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("addMethod", () => WindowsRuntimeMarshal.AddEventHandler(null, token => { }, new EventHandler(EventHandlerMethod1))); } [Fact] public void AddEventHandler_NullRemoveMethod_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("removeMethod", () => WindowsRuntimeMarshal.AddEventHandler(eventHandler => new EventRegistrationToken(), null, new EventHandler(EventHandlerMethod1))); } [Fact] public void RemoveEventHandler_RemoveMethodHasTarget_Success() { bool removeMethodCalled = false; Delegate handler = new EventHandler(EventHandlerMethod1); var tokenTable = new EventRegistrationTokenTable<Delegate>(); EventRegistrationToken addToken = tokenTable.AddEventHandler(handler); Action<EventRegistrationToken> removeMethod = token => { Assert.False(removeMethodCalled); removeMethodCalled = true; Assert.Equal(addToken, token); }; WindowsRuntimeMarshal.AddEventHandler(eventHandler => addToken, removeMethod, handler); // Removing with the same handler but with a different method is a nop. WindowsRuntimeMarshal.RemoveEventHandler(token => removeMethodCalled = true, handler); Assert.False(removeMethodCalled); WindowsRuntimeMarshal.RemoveEventHandler(DifferentRemoveMethod, handler); Assert.False(removeMethodCalled); // Removing with a different handler but with the same method is a nop. WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, new EventHandler(EventHandlerMethod2)); Assert.False(removeMethodCalled); // Removing the same handler and the same method works. WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, handler); Assert.True(removeMethodCalled); } [Fact] public void RemoveEventHandler_RemoveMethodHasNoTarget_Success() { Delegate handler = new EventHandler(EventHandlerMethod1); var tokenTable = new EventRegistrationTokenTable<Delegate>(); ExpectedRemoveToken = tokenTable.AddEventHandler(handler); Action<EventRegistrationToken> removeMethod = RemoveMethod; WindowsRuntimeMarshal.AddEventHandler(eventHandler => ExpectedRemoveToken, removeMethod, handler); // Removing with the same handler but with a different method is a nop. WindowsRuntimeMarshal.RemoveEventHandler(token => RemoveMethodCalled = true, handler); Assert.False(RemoveMethodCalled); WindowsRuntimeMarshal.RemoveEventHandler(DifferentRemoveMethod, handler); Assert.False(RemoveMethodCalled); // Removing with a different handler but with the same method is a nop. WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, new EventHandler(EventHandlerMethod2)); Assert.False(RemoveMethodCalled); // Removing the same handler and the same method works. WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, handler); Assert.True(RemoveMethodCalled); } private static EventRegistrationToken ExpectedRemoveToken { get; set; } private static bool RemoveMethodCalled { get; set; } private static void RemoveMethod(EventRegistrationToken token) { Assert.False(RemoveMethodCalled); RemoveMethodCalled = true; Assert.Equal(ExpectedRemoveToken, token); } private static void DifferentRemoveMethod(EventRegistrationToken token) => RemoveMethodCalled = true; [Fact] public void RemoveEventHandler_NullHandler_Nop() { bool removeMethodCalled = false; Delegate handler = new EventHandler(EventHandlerMethod1); var tokenTable = new EventRegistrationTokenTable<Delegate>(); EventRegistrationToken addToken = tokenTable.AddEventHandler(handler); Action<EventRegistrationToken> removeMethod = token => removeMethodCalled = true; WindowsRuntimeMarshal.AddEventHandler(eventHandler => addToken, removeMethod, handler); WindowsRuntimeMarshal.RemoveEventHandler<Delegate>(removeMethod, null); Assert.False(removeMethodCalled); } [Fact] public void RemoveEventHandler_NullRemoveMethod_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("removeMethod", () => WindowsRuntimeMarshal.RemoveEventHandler<Delegate>(null, new EventHandler(EventHandlerMethod1))); } [Fact] public void RemoveAllEventHandlers_RemoveMethodHasTarget_Success() { Delegate handler = new EventHandler(EventHandlerMethod1); var tokenTable = new EventRegistrationTokenTable<Delegate>(); EventRegistrationToken token1 = tokenTable.AddEventHandler(handler); EventRegistrationToken token2 = tokenTable.AddEventHandler(handler); EventRegistrationToken token3 = tokenTable.AddEventHandler(handler); var removedTokens = new List<EventRegistrationToken>(); Action<EventRegistrationToken> removeMethod = token => removedTokens.Add(token); WindowsRuntimeMarshal.AddEventHandler(eventHandler => token1, removeMethod, handler); WindowsRuntimeMarshal.AddEventHandler(eventHandler => token2, removeMethod, handler); bool removeMethodWithTargetCalled = false; WindowsRuntimeMarshal.AddEventHandler(eventHandler => token3, token => removeMethodWithTargetCalled = false, handler); // Removing with the same handler but with a different method is a nop. WindowsRuntimeMarshal.RemoveAllEventHandlers(token => RemoveMethodCalled = true); Assert.Empty(removedTokens); Assert.False(DifferentRemoveAllMethodCalled); Assert.False(removeMethodWithTargetCalled); WindowsRuntimeMarshal.RemoveAllEventHandlers(DifferentRemoveAllMethod); Assert.Empty(removedTokens); Assert.False(DifferentRemoveAllMethodCalled); Assert.False(removeMethodWithTargetCalled); // Removing the same handler and the same method works. WindowsRuntimeMarshal.RemoveAllEventHandlers(removeMethod); Assert.Equal(new EventRegistrationToken[] { token1, token2 }, removedTokens); Assert.False(DifferentRemoveAllMethodCalled); Assert.False(removeMethodWithTargetCalled); } [Fact] public void RemoveAllEventHandlers_RemoveMethodHasNoTarget_Success() { Delegate handler = new EventHandler(EventHandlerMethod1); var tokenTable = new EventRegistrationTokenTable<Delegate>(); EventRegistrationToken token1 = tokenTable.AddEventHandler(handler); EventRegistrationToken token2 = tokenTable.AddEventHandler(handler); EventRegistrationToken token3 = tokenTable.AddEventHandler(handler); Action<EventRegistrationToken> removeMethod = RemoveAllMethod; WindowsRuntimeMarshal.AddEventHandler(eventHandler => token1, removeMethod, handler); WindowsRuntimeMarshal.AddEventHandler(eventHandler => token2, removeMethod, handler); bool removeMethodWithTargetCalled = false; WindowsRuntimeMarshal.AddEventHandler(eventHandler => token3, token => removeMethodWithTargetCalled = false, handler); // Removing with the same handler but with a different method is a nop. WindowsRuntimeMarshal.RemoveAllEventHandlers(token => RemoveMethodCalled = true); Assert.Empty(RemoveAllTokens); Assert.False(DifferentRemoveAllMethodCalled); Assert.False(removeMethodWithTargetCalled); WindowsRuntimeMarshal.RemoveAllEventHandlers(DifferentRemoveAllMethod); Assert.Empty(RemoveAllTokens); Assert.False(DifferentRemoveAllMethodCalled); Assert.False(removeMethodWithTargetCalled); // Removing the same handler and the same method works. WindowsRuntimeMarshal.RemoveAllEventHandlers(removeMethod); Assert.Equal(new EventRegistrationToken[] { token1, token2 }, RemoveAllTokens); Assert.False(DifferentRemoveAllMethodCalled); Assert.False(removeMethodWithTargetCalled); } private static List<EventRegistrationToken> RemoveAllTokens { get; } = new List<EventRegistrationToken>(); private static void RemoveAllMethod(EventRegistrationToken token) => RemoveAllTokens.Add(token); private static bool DifferentRemoveAllMethodCalled { get; set; } private static void DifferentRemoveAllMethod(EventRegistrationToken token) => DifferentRemoveAllMethodCalled = true; [Fact] public void RemoveAllEventHandlers_NullRemoveMethod_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("removeMethod", () => WindowsRuntimeMarshal.RemoveAllEventHandlers(null)); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRTSupported))] [InlineData("")] [InlineData("HString")] public void StringToHString_PtrToHString_ReturnsExpected(string s) { IntPtr ptr = WindowsRuntimeMarshal.StringToHString(s); try { if (s.Length == 0) { Assert.Equal(IntPtr.Zero, ptr); } else { Assert.NotEqual(IntPtr.Zero, ptr); } Assert.Equal(s, WindowsRuntimeMarshal.PtrToStringHString(ptr)); } finally { WindowsRuntimeMarshal.FreeHString(ptr); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRTSupported))] public void StringToHString_NullString_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("s", () => WindowsRuntimeMarshal.StringToHString(null)); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWinRTSupported))] public void StringToHString_WinRTNotSupported_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => WindowsRuntimeMarshal.StringToHString(null)); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWinRTSupported))] public void PtrToStringHString_WinRTNotSupported_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => WindowsRuntimeMarshal.PtrToStringHString(IntPtr.Zero)); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWinRTSupported))] public void FreeHString_WinRTNotSupported_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => WindowsRuntimeMarshal.FreeHString(IntPtr.Zero)); } [Fact] public void GetActivationFactory_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => WindowsRuntimeMarshal.GetActivationFactory(null)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "No reliable way to check if a type is WinRT in AOT")] public void GetActivationFactory_NotExportedType_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("type", () => WindowsRuntimeMarshal.GetActivationFactory(typeof(int))); } private static void EventHandlerMethod1(object sender, EventArgs e) { } private static void EventHandlerMethod2(object sender, EventArgs e) { } } }
// 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.Collections; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class HttpHeaderValueCollectionTest { private const string knownHeader = "known-header"; private static readonly Uri specialValue = new Uri("http://special/"); private static readonly Uri invalidValue = new Uri("http://invalid/"); private static readonly TransferCodingHeaderValue specialChunked = new TransferCodingHeaderValue("chunked"); // Note that this type just forwards calls to HttpHeaders. So this test method focusses on making sure // the correct calls to HttpHeaders are made. This test suite will not test HttpHeaders functionality. [Fact] public void IsReadOnly_CallProperty_AlwaysFalse() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string))); HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers); Assert.False(collection.IsReadOnly); } [Fact] public void Count_AddSingleValueThenQueryCount_ReturnsValueCountWithSpecialValues() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string))); HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers, "special"); Assert.Equal(0, collection.Count); headers.Add(knownHeader, "value2"); Assert.Equal(1, collection.Count); headers.Clear(); headers.Add(knownHeader, "special"); Assert.Equal(1, collection.Count); headers.Add(knownHeader, "special"); headers.Add(knownHeader, "special"); Assert.Equal(3, collection.Count); } [Fact] public void Count_AddMultipleValuesThenQueryCount_ReturnsValueCountWithSpecialValues() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string))); HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers, "special"); Assert.Equal(0, collection.Count); collection.Add("value1"); headers.Add(knownHeader, "special"); Assert.Equal(2, collection.Count); headers.Add(knownHeader, "special"); headers.Add(knownHeader, "value2"); headers.Add(knownHeader, "special"); Assert.Equal(5, collection.Count); } [Fact] public void Add_CallWithNullValue_Throw() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); Assert.Throws<ArgumentNullException>(() => { collection.Add(null); }); } [Fact] public void Add_AddValues_AllValuesAdded() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); Assert.Equal(3, collection.Count); } [Fact] public void Add_UseSpecialValue_Success() { HttpRequestHeaders headers = new HttpRequestHeaders(); Assert.Null(headers.TransferEncodingChunked); Assert.Equal(0, headers.TransferEncoding.Count); Assert.Equal(String.Empty, headers.TransferEncoding.ToString()); headers.TransferEncoding.Add(specialChunked); Assert.True((bool)headers.TransferEncodingChunked); Assert.Equal(1, headers.TransferEncoding.Count); Assert.Equal(specialChunked, headers.TransferEncoding.First()); Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString()); } [Fact] public void Add_UseSpecialValueWithSpecialAlreadyPresent_AddsDuplicate() { HttpRequestHeaders headers = new HttpRequestHeaders(); headers.TransferEncodingChunked = true; Assert.True((bool)headers.TransferEncodingChunked); Assert.Equal(1, headers.TransferEncoding.Count); Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString()); headers.TransferEncoding.Add(specialChunked); Assert.True((bool)headers.TransferEncodingChunked); Assert.Equal(2, headers.TransferEncoding.Count); Assert.Equal("chunked, chunked", headers.TransferEncoding.ToString()); // removes first instance of headers.TransferEncodingChunked = false; Assert.True((bool)headers.TransferEncodingChunked); Assert.Equal(1, headers.TransferEncoding.Count); Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString()); // does not add duplicate headers.TransferEncodingChunked = true; Assert.True((bool)headers.TransferEncodingChunked); Assert.Equal(1, headers.TransferEncoding.Count); Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString()); } [Fact] public void ParseAdd_CallWithNullValue_NothingAdded() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.ParseAdd(null); Assert.False(collection.IsSpecialValueSet); Assert.Equal(0, collection.Count); Assert.Equal(String.Empty, collection.ToString()); } [Fact] public void ParseAdd_AddValues_AllValuesAdded() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.ParseAdd("http://www.example.org/1/"); collection.ParseAdd("http://www.example.org/2/"); collection.ParseAdd("http://www.example.org/3/"); Assert.Equal(3, collection.Count); } [Fact] public void ParseAdd_UseSpecialValue_Added() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.ParseAdd(specialValue.AbsoluteUri); Assert.True(collection.IsSpecialValueSet); Assert.Equal(specialValue.ToString(), collection.ToString()); } [Fact] public void ParseAdd_AddBadValue_Throws() { HttpResponseHeaders headers = new HttpResponseHeaders(); string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess"; Assert.Throws<FormatException>(() => { headers.WwwAuthenticate.ParseAdd(input); }); } [Fact] public void TryParseAdd_CallWithNullValue_NothingAdded() { HttpResponseHeaders headers = new HttpResponseHeaders(); Assert.True(headers.WwwAuthenticate.TryParseAdd(null)); Assert.False(headers.WwwAuthenticate.IsSpecialValueSet); Assert.Equal(0, headers.WwwAuthenticate.Count); Assert.Equal(String.Empty, headers.WwwAuthenticate.ToString()); } [Fact] public void TryParseAdd_AddValues_AllAdded() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); Assert.True(collection.TryParseAdd("http://www.example.org/1/")); Assert.True(collection.TryParseAdd("http://www.example.org/2/")); Assert.True(collection.TryParseAdd("http://www.example.org/3/")); Assert.Equal(3, collection.Count); } [Fact] public void TryParseAdd_UseSpecialValue_Added() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); Assert.True(collection.TryParseAdd(specialValue.AbsoluteUri)); Assert.True(collection.IsSpecialValueSet); Assert.Equal(specialValue.ToString(), collection.ToString()); } [Fact] public void TryParseAdd_AddBadValue_False() { HttpResponseHeaders headers = new HttpResponseHeaders(); string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess"; Assert.False(headers.WwwAuthenticate.TryParseAdd(input)); Assert.Equal(string.Empty, headers.WwwAuthenticate.ToString()); Assert.Equal(string.Empty, headers.ToString()); } [Fact] public void TryParseAdd_AddBadAfterGoodValue_False() { HttpResponseHeaders headers = new HttpResponseHeaders(); headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Negotiate")); string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess"; Assert.False(headers.WwwAuthenticate.TryParseAdd(input)); Assert.Equal("Negotiate", headers.WwwAuthenticate.ToString()); Assert.Equal("WWW-Authenticate: Negotiate\r\n", headers.ToString()); } [Fact] public void Clear_AddValuesThenClear_NoElementsInCollection() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); Assert.Equal(3, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); } [Fact] public void Clear_AddValuesAndSpecialValueThenClear_EverythingCleared() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.SetSpecialValue(); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); Assert.Equal(4, collection.Count); Assert.True(collection.IsSpecialValueSet, "Special value not set."); collection.Clear(); Assert.Equal(0, collection.Count); Assert.False(collection.IsSpecialValueSet, "Special value was removed by Clear()."); } [Fact] public void Contains_CallWithNullValue_Throw() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); Assert.Throws<ArgumentNullException>(() => { collection.Contains(null); }); } [Fact] public void Contains_AddValuesThenCallContains_ReturnsTrueForExistingItemsFalseOtherwise() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); Assert.True(collection.Contains(new Uri("http://www.example.org/2/")), "Expected true for existing item."); Assert.False(collection.Contains(new Uri("http://www.example.org/4/")), "Expected false for non-existing item."); } [Fact] public void Contains_UseSpecialValueWhenEmpty_False() { HttpRequestHeaders headers = new HttpRequestHeaders(); Assert.False(headers.TransferEncoding.Contains(specialChunked)); } [Fact] public void Contains_UseSpecialValueWithProperty_True() { HttpRequestHeaders headers = new HttpRequestHeaders(); headers.TransferEncodingChunked = true; Assert.True(headers.TransferEncoding.Contains(specialChunked)); headers.TransferEncodingChunked = false; Assert.False(headers.TransferEncoding.Contains(specialChunked)); } [Fact] public void Contains_UseSpecialValueWhenSpecilValueIsPresent_True() { HttpRequestHeaders headers = new HttpRequestHeaders(); headers.TransferEncoding.Add(specialChunked); Assert.True(headers.TransferEncoding.Contains(specialChunked)); headers.TransferEncoding.Remove(specialChunked); Assert.False(headers.TransferEncoding.Contains(specialChunked)); } [Fact] public void CopyTo_CallWithStartIndexPlusElementCountGreaterArrayLength_Throw() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); Uri[] array = new Uri[2]; // startIndex + Count = 1 + 2 > array.Length Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 1); }); } [Fact] public void CopyTo_EmptyToEmpty_Success() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); Uri[] array = new Uri[0]; collection.CopyTo(array, 0); } [Fact] public void CopyTo_NoValues_DoesNotChangeArray() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); Uri[] array = new Uri[4]; collection.CopyTo(array, 0); for (int i = 0; i < array.Length; i++) { Assert.Null(array[i]); } } [Fact] public void CopyTo_AddSingleValue_ContainsSingleValue() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.Add(new Uri("http://www.example.org/")); Uri[] array = new Uri[1]; collection.CopyTo(array, 0); Assert.Equal(new Uri("http://www.example.org/"), array[0]); // Now only set the special value: nothing should be added to the array. headers.Clear(); headers.Add(knownHeader, specialValue.ToString()); array[0] = null; collection.CopyTo(array, 0); Assert.Equal(specialValue, array[0]); } [Fact] public void CopyTo_AddMultipleValues_ContainsAllValuesInTheRightOrder() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); Uri[] array = new Uri[5]; collection.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new Uri("http://www.example.org/1/"), array[1]); Assert.Equal(new Uri("http://www.example.org/2/"), array[2]); Assert.Equal(new Uri("http://www.example.org/3/"), array[3]); Assert.Null(array[4]); } [Fact] public void CopyTo_AddValuesAndSpecialValue_AllValuesCopied() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.SetSpecialValue(); collection.Add(new Uri("http://www.example.org/3/")); Uri[] array = new Uri[5]; collection.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new Uri("http://www.example.org/1/"), array[1]); Assert.Equal(new Uri("http://www.example.org/2/"), array[2]); Assert.Equal(specialValue, array[3]); Assert.Equal(new Uri("http://www.example.org/3/"), array[4]); Assert.True(collection.IsSpecialValueSet, "Special value not set."); } [Fact] public void CopyTo_OnlySpecialValue_Copied() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.SetSpecialValue(); headers.Add(knownHeader, specialValue.ToString()); headers.Add(knownHeader, specialValue.ToString()); headers.Add(knownHeader, specialValue.ToString()); Uri[] array = new Uri[4]; array[0] = null; collection.CopyTo(array, 0); Assert.Equal(specialValue, array[0]); Assert.Equal(specialValue, array[1]); Assert.Equal(specialValue, array[2]); Assert.Equal(specialValue, array[3]); Assert.True(collection.IsSpecialValueSet, "Special value not set."); } [Fact] public void CopyTo_OnlySpecialValueEmptyDestination_Copied() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.SetSpecialValue(); headers.Add(knownHeader, specialValue.ToString()); Uri[] array = new Uri[2]; collection.CopyTo(array, 0); Assert.Equal(specialValue, array[0]); Assert.Equal(specialValue, array[1]); Assert.True(collection.IsSpecialValueSet, "Special value not set."); } [Fact] public void CopyTo_ArrayTooSmall_Throw() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string))); HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers, "special"); string[] array = new string[1]; array[0] = null; collection.CopyTo(array, 0); // no exception Assert.Null(array[0]); Assert.Throws<ArgumentNullException>(() => { collection.CopyTo(null, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, -1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, 2); }); headers.Add(knownHeader, "special"); array = new string[0]; Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); }); headers.Add(knownHeader, "special"); headers.Add(knownHeader, "special"); array = new string[1]; Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); }); headers.Add(knownHeader, "value1"); array = new string[0]; Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); }); headers.Add(knownHeader, "value2"); array = new string[1]; Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); }); array = new string[2]; Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 1); }); } [Fact] public void Remove_CallWithNullValue_Throw() { MockHeaders headers = new MockHeaders(); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); Assert.Throws<ArgumentNullException>(() => { collection.Remove(null); }); } [Fact] public void Remove_AddValuesThenCallRemove_ReturnsTrueWhenRemovingExistingValuesFalseOtherwise() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); Assert.True(collection.Remove(new Uri("http://www.example.org/2/")), "Expected true for existing item."); Assert.False(collection.Remove(new Uri("http://www.example.org/4/")), "Expected false for non-existing item."); } [Fact] public void Remove_UseSpecialValue_FalseWhenEmpty() { HttpRequestHeaders headers = new HttpRequestHeaders(); Assert.Null(headers.TransferEncodingChunked); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.TransferEncoding.Remove(specialChunked)); Assert.Null(headers.TransferEncodingChunked); Assert.Equal(0, headers.TransferEncoding.Count); } [Fact] public void Remove_UseSpecialValueWhenSetWithProperty_True() { HttpRequestHeaders headers = new HttpRequestHeaders(); headers.TransferEncodingChunked = true; Assert.True((bool)headers.TransferEncodingChunked); Assert.Equal(1, headers.TransferEncoding.Count); Assert.True(headers.TransferEncoding.Contains(specialChunked)); Assert.True(headers.TransferEncoding.Remove(specialChunked)); Assert.False((bool)headers.TransferEncodingChunked); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.TransferEncoding.Contains(specialChunked)); } [Fact] public void Remove_UseSpecialValueWhenAdded_True() { HttpRequestHeaders headers = new HttpRequestHeaders(); headers.TransferEncoding.Add(specialChunked); Assert.True((bool)headers.TransferEncodingChunked); Assert.Equal(1, headers.TransferEncoding.Count); Assert.True(headers.TransferEncoding.Contains(specialChunked)); Assert.True(headers.TransferEncoding.Remove(specialChunked)); Assert.Null(headers.TransferEncodingChunked); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.TransferEncoding.Contains(specialChunked)); } [Fact] public void GetEnumerator_AddSingleValueAndGetEnumerator_AllValuesReturned() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.Add(new Uri("http://www.example.org/")); bool started = false; foreach (var item in collection) { Assert.False(started, "We have more than one element returned by the enumerator."); Assert.Equal(new Uri("http://www.example.org/"), item); } } [Fact] public void GetEnumerator_AddValuesAndGetEnumerator_AllValuesReturned() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); int i = 1; foreach (var item in collection) { Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item); i++; } } [Fact] public void GetEnumerator_NoValues_EmptyEnumerator() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); IEnumerator<Uri> enumerator = collection.GetEnumerator(); Assert.False(enumerator.MoveNext(), "No items expected in enumerator."); } [Fact] public void GetEnumerator_AddValuesAndGetEnumeratorFromInterface_AllValuesReturned() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); System.Collections.IEnumerable enumerable = collection; int i = 1; foreach (var item in enumerable) { Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item); i++; } } [Fact] public void GetEnumerator_AddValuesAndSpecialValueAndGetEnumeratorFromInterface_AllValuesReturned() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.Add(new Uri("http://www.example.org/3/")); collection.SetSpecialValue(); System.Collections.IEnumerable enumerable = collection; // The "special value" should be ignored and not part of the resulting collection. int i = 1; bool specialFound = false; foreach (var item in enumerable) { if (item.Equals(specialValue)) { specialFound = true; } else { Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item); i++; } } Assert.True(specialFound); Assert.True(collection.IsSpecialValueSet, "Special value not set."); } [Fact] public void GetEnumerator_AddValuesAndSpecialValue_AllValuesReturned() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.SetSpecialValue(); collection.Add(new Uri("http://www.example.org/3/")); System.Collections.IEnumerable enumerable = collection; // The special value we added above, must be part of the collection returned by GetEnumerator(). int i = 1; bool specialFound = false; foreach (var item in enumerable) { if (item.Equals(specialValue)) { specialFound = true; } else { Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item); i++; } } Assert.True(specialFound); Assert.True(collection.IsSpecialValueSet, "Special value not set."); } [Fact] public void IsSpecialValueSet_NoSpecialValueUsed_ReturnsFalse() { // Create a new collection _without_ specifying a special value. MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, null, null); Assert.False(collection.IsSpecialValueSet, "Special value is set even though collection doesn't define a special value."); } [Fact] public void RemoveSpecialValue_AddRemoveSpecialValue_SpecialValueGetsRemoved() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.SetSpecialValue(); Assert.True(collection.IsSpecialValueSet, "Special value not set."); Assert.Equal(1, headers.GetValues(knownHeader).Count()); collection.RemoveSpecialValue(); Assert.False(collection.IsSpecialValueSet, "Special value is set."); // Since the only header value was the "special value", removing it will remove the whole header // from the collection. Assert.False(headers.Contains(knownHeader)); } [Fact] public void RemoveSpecialValue_AddValueAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.Add(new Uri("http://www.example.org/")); collection.SetSpecialValue(); Assert.True(collection.IsSpecialValueSet, "Special value not set."); Assert.Equal(2, headers.GetValues(knownHeader).Count()); collection.RemoveSpecialValue(); Assert.False(collection.IsSpecialValueSet, "Special value is set."); Assert.Equal(1, headers.GetValues(knownHeader).Count()); } [Fact] public void RemoveSpecialValue_AddTwoValuesAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue); collection.Add(new Uri("http://www.example.org/1/")); collection.Add(new Uri("http://www.example.org/2/")); collection.SetSpecialValue(); Assert.True(collection.IsSpecialValueSet, "Special value not set."); Assert.Equal(3, headers.GetValues(knownHeader).Count()); // The difference between this test and the previous one is that HttpHeaders in this case will use // a List<T> to store the two remaining values, whereas in the previous case it will just store // the remaining value (no list). collection.RemoveSpecialValue(); Assert.False(collection.IsSpecialValueSet, "Special value is set."); Assert.Equal(2, headers.GetValues(knownHeader).Count()); } [Fact] public void Ctor_ProvideValidator_ValidatorIsUsedWhenAddingValues() { MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, MockValidator); // Adding an arbitrary Uri should not throw. collection.Add(new Uri("http://some/")); // When we add 'invalidValue' our MockValidator will throw. Assert.Throws<MockException>(() => { collection.Add(invalidValue); }); } [Fact] public void Ctor_ProvideValidator_ValidatorIsUsedWhenRemovingValues() { // Use different ctor overload than in previous test to make sure all ctor overloads work correctly. MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri))); HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers, specialValue, MockValidator); // When we remove 'invalidValue' our MockValidator will throw. Assert.Throws<MockException>(() => { collection.Remove(invalidValue); }); } [Fact] public void ToString_SpecialValues_Success() { HttpRequestMessage request = new HttpRequestMessage(); request.Headers.TransferEncodingChunked = true; string result = request.Headers.TransferEncoding.ToString(); Assert.Equal("chunked", result); request.Headers.ExpectContinue = true; result = request.Headers.Expect.ToString(); Assert.Equal("100-continue", result); request.Headers.ConnectionClose = true; result = request.Headers.Connection.ToString(); Assert.Equal("close", result); } [Fact] public void ToString_SpecialValueAndExtra_Success() { HttpRequestMessage request = new HttpRequestMessage(); request.Headers.Add(HttpKnownHeaderNames.TransferEncoding, "bla1"); request.Headers.TransferEncodingChunked = true; request.Headers.Add(HttpKnownHeaderNames.TransferEncoding, "bla2"); string result = request.Headers.TransferEncoding.ToString(); Assert.Equal("bla1, chunked, bla2", result); } [Fact] public void ToString_SingleValue_Success() { HttpResponseMessage response = new HttpResponseMessage(); string input = "Basic"; response.Headers.Add(HttpKnownHeaderNames.WWWAuthenticate, input); string result = response.Headers.WwwAuthenticate.ToString(); Assert.Equal(input, result); } [Fact] public void ToString_MultipleValue_Success() { HttpResponseMessage response = new HttpResponseMessage(); string input = "Basic, NTLM, Negotiate, Custom"; response.Headers.Add(HttpKnownHeaderNames.WWWAuthenticate, input); string result = response.Headers.WwwAuthenticate.ToString(); Assert.Equal(input, result); } [Fact] public void ToString_EmptyValue_Success() { HttpResponseMessage response = new HttpResponseMessage(); string result = response.Headers.WwwAuthenticate.ToString(); Assert.Equal(string.Empty, result); } #region Helper methods private static void MockValidator(HttpHeaderValueCollection<Uri> collection, Uri value) { if (value == invalidValue) { throw new MockException(); } } public class MockException : Exception { public MockException() { } public MockException(string message) : base(message) { } public MockException(string message, Exception inner) : base(message, inner) { } } private class MockHeaders : HttpHeaders { public MockHeaders() { } public MockHeaders(string headerName, HttpHeaderParser parser) { Dictionary<string, HttpHeaderParser> parserStore = new Dictionary<string, HttpHeaderParser>(); parserStore.Add(headerName, parser); SetConfiguration(parserStore, new HashSet<string>()); } } private class MockHeaderParser : HttpHeaderParser { private static MockComparer comparer = new MockComparer(); private Type valueType; public override IEqualityComparer Comparer { get { return comparer; } } public MockHeaderParser(Type valueType) : base(true) { Assert.Contains(valueType, new[] { typeof(string), typeof(Uri) }); this.valueType = valueType; } public override bool TryParseValue(string value, object storeValue, ref int index, out object parsedValue) { parsedValue = null; if (value == null) { return true; } index = value.Length; // Just return the raw string (as string or Uri depending on the value type) parsedValue = (valueType == typeof(Uri) ? (object)new Uri(value) : value); return true; } } private class MockComparer : IEqualityComparer { public int EqualsCount { get; private set; } public int GetHashCodeCount { get; private set; } #region IEqualityComparer Members public new bool Equals(object x, object y) { EqualsCount++; return x.Equals(y); } public int GetHashCode(object obj) { GetHashCodeCount++; return obj.GetHashCode(); } #endregion } #endregion } }
using System; using System.Collections; using System.Web; using System.Xml; using StackExchange.Profiling; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Web; using Umbraco.Core.Profiling; using Umbraco.Core.Strings; namespace umbraco { /// <summary> /// /// </summary> public class item { private String _fieldContent = ""; private readonly String _fieldName; public String FieldContent { get { return _fieldContent; } } public item(string itemValue, IDictionary attributes) { _fieldContent = itemValue; ParseItem(attributes); } /// <summary> /// Creates a new Legacy item /// </summary> /// <param name="elements"></param> /// <param name="attributes"></param> public item(IDictionary elements, IDictionary attributes) : this(null, elements, attributes) { } /// <summary> /// Creates an Item with a publishedContent item in order to properly recurse and return the value. /// </summary> /// <param name="publishedContent"></param> /// <param name="elements"></param> /// <param name="attributes"></param> /// <remarks> /// THIS ENTIRE CLASS WILL BECOME LEGACY, THE FIELD RENDERING NEEDS TO BE REPLACES SO THAT IS WHY THIS /// CTOR IS INTERNAL. /// </remarks> internal item(IPublishedContent publishedContent, IDictionary elements, IDictionary attributes) { _fieldName = helper.FindAttribute(attributes, "field"); if (_fieldName.StartsWith("#")) { _fieldContent = library.GetDictionaryItem(_fieldName.Substring(1, _fieldName.Length - 1)); } else { // Loop through XML children we need to find the fields recursive if (helper.FindAttribute(attributes, "recursive") == "true") { if (publishedContent == null) { var recursiveVal = GetRecursiveValueLegacy(elements); _fieldContent = recursiveVal.IsNullOrWhiteSpace() ? _fieldContent : recursiveVal; } else { var pval = publishedContent.GetPropertyValue(_fieldName, true); var rval = pval == null ? string.Empty : pval.ToString(); _fieldContent = rval.IsNullOrWhiteSpace() ? _fieldContent : rval; } } else { //check for published content and get its value using that if (publishedContent != null && publishedContent.HasProperty(_fieldName)) { var pval = publishedContent.GetPropertyValue(_fieldName); var rval = pval == null ? string.Empty : pval.ToString(); _fieldContent = rval.IsNullOrWhiteSpace() ? _fieldContent : rval; } else { //get the vaue the legacy way (this will not parse locallinks, etc... since that is handled with ipublishedcontent) var elt = elements[_fieldName]; if (elt != null && string.IsNullOrEmpty(elt.ToString()) == false) _fieldContent = elt.ToString().Trim(); } //now we check if the value is still empty and if so we'll check useIfEmpty if (string.IsNullOrEmpty(_fieldContent)) { var altFieldName = helper.FindAttribute(attributes, "useIfEmpty"); if (string.IsNullOrEmpty(altFieldName) == false) { if (publishedContent != null && publishedContent.HasProperty(altFieldName)) { var pval = publishedContent.GetPropertyValue(altFieldName); var rval = pval == null ? string.Empty : pval.ToString(); _fieldContent = rval.IsNullOrWhiteSpace() ? _fieldContent : rval; } else { //get the vaue the legacy way (this will not parse locallinks, etc... since that is handled with ipublishedcontent) var elt = elements[altFieldName]; if (elt != null && string.IsNullOrEmpty(elt.ToString()) == false) _fieldContent = elt.ToString().Trim(); } } } } } ParseItem(attributes); } /// <summary> /// Returns the recursive value using a legacy strategy of looking at the xml cache and the splitPath in the elements collection /// </summary> /// <param name="elements"></param> /// <returns></returns> private string GetRecursiveValueLegacy(IDictionary elements) { using (DisposableTimer.DebugDuration<item>("Checking recusively")) { var content = ""; var umbracoXml = presentation.UmbracoContext.Current.GetXml(); var splitpath = (String[])elements["splitpath"]; for (int i = 0; i < splitpath.Length - 1; i++) { XmlNode element = umbracoXml.GetElementById(splitpath[splitpath.Length - i - 1]); if (element == null) continue; var xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "./data [@alias = '{0}']" : "./{0}"; var currentNode = element.SelectSingleNode(string.Format(xpath, _fieldName)); //continue if all is null if (currentNode == null || currentNode.FirstChild == null || string.IsNullOrEmpty(currentNode.FirstChild.Value) || string.IsNullOrEmpty(currentNode.FirstChild.Value.Trim())) continue; HttpContext.Current.Trace.Write("item.recursive", "Item loaded from " + splitpath[splitpath.Length - i - 1]); content = currentNode.FirstChild.Value; break; } return content; } } private void ParseItem(IDictionary attributes) { using (DisposableTimer.DebugDuration<item>("Start parsing " + _fieldName)) { HttpContext.Current.Trace.Write("item", "Start parsing '" + _fieldName + "'"); if (helper.FindAttribute(attributes, "textIfEmpty") != "" && _fieldContent == "") _fieldContent = helper.FindAttribute(attributes, "textIfEmpty"); _fieldContent = _fieldContent.Trim(); // DATE FORMATTING FUNCTIONS if (helper.FindAttribute(attributes, "formatAsDateWithTime") == "true") { if (_fieldContent == "") _fieldContent = DateTime.Now.ToString(); _fieldContent = Convert.ToDateTime(_fieldContent).ToLongDateString() + helper.FindAttribute(attributes, "formatAsDateWithTimeSeparator") + Convert.ToDateTime(_fieldContent).ToShortTimeString(); } else if (helper.FindAttribute(attributes, "formatAsDate") == "true") { if (_fieldContent == "") _fieldContent = DateTime.Now.ToString(); _fieldContent = Convert.ToDateTime(_fieldContent).ToLongDateString(); } // TODO: Needs revision to check if parameter-tags has attributes if (helper.FindAttribute(attributes, "stripParagraph") == "true" && _fieldContent.Length > 5) { _fieldContent = _fieldContent.Trim(); string fieldContentLower = _fieldContent.ToLower(); // the field starts with an opening p tag if (fieldContentLower.Substring(0, 3) == "<p>" // it ends with a closing p tag && fieldContentLower.Substring(_fieldContent.Length - 4, 4) == "</p>" // it doesn't contain multiple p-tags && fieldContentLower.IndexOf("<p>", 1) < 0) { _fieldContent = _fieldContent.Substring(3, _fieldContent.Length - 7); } } // CASING if (helper.FindAttribute(attributes, "case") == "lower") _fieldContent = _fieldContent.ToLower(); else if (helper.FindAttribute(attributes, "case") == "upper") _fieldContent = _fieldContent.ToUpper(); else if (helper.FindAttribute(attributes, "case") == "title") _fieldContent = _fieldContent.ToCleanString(CleanStringType.Ascii | CleanStringType.Alias | CleanStringType.PascalCase); // OTHER FORMATTING FUNCTIONS // If we use masterpages, this is moved to the ItemRenderer to add support for before/after in inline XSLT if (!UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages) { if (_fieldContent != "" && helper.FindAttribute(attributes, "insertTextBefore") != "") _fieldContent = HttpContext.Current.Server.HtmlDecode(helper.FindAttribute(attributes, "insertTextBefore")) + _fieldContent; if (_fieldContent != "" && helper.FindAttribute(attributes, "insertTextAfter") != "") _fieldContent += HttpContext.Current.Server.HtmlDecode(helper.FindAttribute(attributes, "insertTextAfter")); } if (helper.FindAttribute(attributes, "urlEncode") == "true") _fieldContent = HttpUtility.UrlEncode(_fieldContent); if (helper.FindAttribute(attributes, "htmlEncode") == "true") _fieldContent = HttpUtility.HtmlEncode(_fieldContent); if (helper.FindAttribute(attributes, "convertLineBreaks") == "true") _fieldContent = _fieldContent.Replace("\n", "<br/>\n"); HttpContext.Current.Trace.Write("item", "Done parsing '" + _fieldName + "'"); } } } }
/*************************************************************************** * Folder.cs * * Copyright (C) 2006-2007 Alan McGovern * Authors: * Alan McGovern (alan.mcgovern@gmail.com) ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Mtp { public class Folder { private MtpDevice device; private uint folderId; private uint parentId; private string name; internal uint FolderId { get { return folderId; } } public string Name { get { return name; } } internal uint ParentId { get { return parentId; } } internal Folder (uint folderId, uint parentId, string name, MtpDevice device) { this.device = device; this.folderId = folderId; this.parentId = parentId; this.name = name; } internal Folder (FolderStruct folder, MtpDevice device) : this (folder.folder_id, folder.parent_id, folder.name, device) { } public Folder AddChild(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); // First create the folder on the device and check for error uint id = CreateFolder (device.Handle, name, FolderId); FolderStruct f = new FolderStruct(); f.folder_id = id; f.parent_id = FolderId; f.name = name; return new Folder(f, device); } public List<Folder> GetChildren () { IntPtr root = GetFolderList(device.Handle); IntPtr ptr = Find (root, folderId); FolderStruct f = (FolderStruct)Marshal.PtrToStructure(ptr, typeof(FolderStruct)); ptr = f.child; List<Folder> folders = new List<Folder>(); while (ptr != IntPtr.Zero) { FolderStruct folder = (FolderStruct)Marshal.PtrToStructure(ptr, typeof(FolderStruct)); folders.Add(new Folder(folder, device)); ptr = folder.sibling; } LIBMTP_destroy_folder_t (root); return folders; } public void Remove() { MtpDevice.DeleteObject(device.Handle, FolderId); } public override string ToString () { return String.Format ("{0} (id {1}, parent id {2})", Name, FolderId, ParentId); } internal static List<Folder> GetRootFolders (MtpDevice device) { List<Folder> folders = new List<Folder>(); IntPtr root = GetFolderList (device.Handle); try { for (IntPtr ptr = root; ptr != IntPtr.Zero;) { FolderStruct folder = (FolderStruct)Marshal.PtrToStructure(ptr, typeof(FolderStruct)); folders.Add(new Folder (folder, device)); ptr = folder.sibling; } } finally { // Recursively destroy the folder tree LIBMTP_destroy_folder_t (root); } return folders; } internal static uint CreateFolder (MtpDeviceHandle handle, string name, uint parentId) { #if LIBMTP8 uint result = LIBMTP_Create_Folder (handle, name, parentId, 0); #else uint result = LIBMTP_Create_Folder (handle, name, parentId); #endif if (result == 0) { LibMtpException.CheckErrorStack(handle); throw new LibMtpException(ErrorCode.General, "Could not create folder on the device"); } return result; } internal static void DestroyFolder (IntPtr folder) { LIBMTP_destroy_folder_t (folder); } internal static IntPtr Find (IntPtr folderList, uint folderId ) { return LIBMTP_Find_Folder (folderList, folderId); } internal static IntPtr GetFolderList (MtpDeviceHandle handle) { return LIBMTP_Get_Folder_List (handle); } // Folder Management //[DllImport("libmtp.dll")] //private static extern IntPtr LIBMTP_new_folder_t (); // LIBMTP_folder_t* [DllImport("libmtp.dll")] private static extern void LIBMTP_destroy_folder_t (IntPtr folder); [DllImport("libmtp.dll")] private static extern IntPtr LIBMTP_Get_Folder_List (MtpDeviceHandle handle); // LIBMTP_folder_t* [DllImport("libmtp.dll")] private static extern IntPtr LIBMTP_Find_Folder (IntPtr folderList, uint folderId); // LIBMTP_folder_t* #if LIBMTP8 [DllImport("libmtp.dll")] private static extern uint LIBMTP_Create_Folder (MtpDeviceHandle handle, string name, uint parentId, uint storageId); #else [DllImport("libmtp.dll")] private static extern uint LIBMTP_Create_Folder (MtpDeviceHandle handle, string name, uint parentId); #endif } [StructLayout(LayoutKind.Sequential)] internal struct FolderStruct { public uint folder_id; public uint parent_id; #if LIBMTP8 public uint storage_id; #endif [MarshalAs(UnmanagedType.LPStr)] public string name; public IntPtr sibling; // LIBMTP_folder_t* public IntPtr child; // LIBMTP_folder_t* /* public object NextSibling { get { if(sibling == IntPtr.Zero) return null; return (FolderStruct)Marshal.PtrToStructure(sibling, typeof(Folder)); } } public object NextChild { get { if(child == IntPtr.Zero) return null; return (FolderStruct)Marshal.PtrToStructure(child, typeof(Folder)); } } public Folder? Sibling { get { if (sibling == IntPtr.Zero) return null; return (Folder)Marshal.PtrToStructure(sibling, typeof(Folder)); } } public Folder? Child { get { if (child == IntPtr.Zero) return null; return (Folder)Marshal.PtrToStructure(child, typeof(Folder)); } }*/ /*public IEnumerable<Folder> Children() { Folder? current = Child; while(current.HasValue) { yield return current.Value; current = current.Value.Child; } }*/ /*public IEnumerable<Folder> Siblings() { Folder? current = Sibling; while(current.HasValue) { yield return current.Value; current = current.Value.Sibling; } }*/ } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Security.Auth.Callback.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Javax.Security.Auth.Callback { /// <summary> /// <para>Needs to be implemented by classes that want to handle authentication Callbacks. A single method handle(Callback[]) must be provided that checks the type of the incoming <c> Callback </c> s and reacts accordingly. <c> CallbackHandler </c> s can be installed per application. It is also possible to configure a system-default <c> CallbackHandler </c> by setting the <c> auth.login.defaultCallbackHandler </c> property in the standard <c> security.properties </c> file. </para> /// </summary> /// <java-name> /// javax/security/auth/callback/CallbackHandler /// </java-name> [Dot42.DexImport("javax/security/auth/callback/CallbackHandler", AccessFlags = 1537)] public partial interface ICallbackHandler /* scope: __dot42__ */ { /// <summary> /// <para>Handles the actual Callback. A <c> CallbackHandler </c> needs to implement this method. In the method, it is free to select which <c> Callback </c> s it actually wants to handle and in which way. For example, a console-based <c> CallbackHandler </c> might choose to sequentially ask the user for login and password, if it implements these <c> Callback </c> s, whereas a GUI-based one might open a single dialog window for both values. If a <c> CallbackHandler </c> is not able to handle a specific <c> Callback </c> , it needs to throw an UnsupportedCallbackException.</para><para></para> /// </summary> /// <java-name> /// handle /// </java-name> [Dot42.DexImport("handle", "([Ljavax/security/auth/callback/Callback;)V", AccessFlags = 1025)] void Handle(global::Javax.Security.Auth.Callback.ICallback[] callbacks) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Used in conjunction with a CallbackHandler to retrieve a password when needed. </para> /// </summary> /// <java-name> /// javax/security/auth/callback/PasswordCallback /// </java-name> [Dot42.DexImport("javax/security/auth/callback/PasswordCallback", AccessFlags = 33)] public partial class PasswordCallback : global::Javax.Security.Auth.Callback.ICallback, global::Java.Io.ISerializable /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> PasswordCallback </c> instance.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Z)V", AccessFlags = 1)] public PasswordCallback(string prompt, bool echoOn) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the prompt that was specified when creating this <c> PasswordCallback </c></para><para></para> /// </summary> /// <returns> /// <para>the prompt </para> /// </returns> /// <java-name> /// getPrompt /// </java-name> [Dot42.DexImport("getPrompt", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPrompt() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Queries whether this <c> PasswordCallback </c> expects user input to be echoed, which is specified during the creation of the object.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if (and only if) user input should be echoed </para> /// </returns> /// <java-name> /// isEchoOn /// </java-name> [Dot42.DexImport("isEchoOn", "()Z", AccessFlags = 1)] public virtual bool IsEchoOn() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Sets the password. The CallbackHandler that performs the actual provisioning or input of the password needs to call this method to hand back the password to the security service that requested it.</para><para></para> /// </summary> /// <java-name> /// setPassword /// </java-name> [Dot42.DexImport("setPassword", "([C)V", AccessFlags = 1)] public virtual void SetPassword(char[] password) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the password. The security service that needs the password usually calls this method once the CallbackHandler has finished its work.</para><para></para> /// </summary> /// <returns> /// <para>the password. A copy of the internal password is created and returned, so subsequent changes to the internal password do not affect the result. </para> /// </returns> /// <java-name> /// getPassword /// </java-name> [Dot42.DexImport("getPassword", "()[C", AccessFlags = 1)] public virtual char[] GetPassword() /* MethodBuilder.Create */ { return default(char[]); } /// <summary> /// <para>Clears the password stored in this <c> PasswordCallback </c> . </para> /// </summary> /// <java-name> /// clearPassword /// </java-name> [Dot42.DexImport("clearPassword", "()V", AccessFlags = 1)] public virtual void ClearPassword() /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PasswordCallback() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the prompt that was specified when creating this <c> PasswordCallback </c></para><para></para> /// </summary> /// <returns> /// <para>the prompt </para> /// </returns> /// <java-name> /// getPrompt /// </java-name> public string Prompt { [Dot42.DexImport("getPrompt", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPrompt(); } } /// <summary> /// <para>Returns the password. The security service that needs the password usually calls this method once the CallbackHandler has finished its work.</para><para></para> /// </summary> /// <returns> /// <para>the password. A copy of the internal password is created and returned, so subsequent changes to the internal password do not affect the result. </para> /// </returns> /// <java-name> /// getPassword /// </java-name> public char[] Password { [Dot42.DexImport("getPassword", "()[C", AccessFlags = 1)] get{ return GetPassword(); } [Dot42.DexImport("setPassword", "([C)V", AccessFlags = 1)] set{ SetPassword(value); } } } /// <summary> /// <para>Thrown when a CallbackHandler does not support a particular Callback. </para> /// </summary> /// <java-name> /// javax/security/auth/callback/UnsupportedCallbackException /// </java-name> [Dot42.DexImport("javax/security/auth/callback/UnsupportedCallbackException", AccessFlags = 33)] public partial class UnsupportedCallbackException : global::System.Exception /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new exception instance and initializes it with just the unsupported <c> Callback </c> , but no error message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljavax/security/auth/callback/Callback;)V", AccessFlags = 1)] public UnsupportedCallbackException(global::Javax.Security.Auth.Callback.ICallback callback) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new exception instance and initializes it with both the unsupported <c> Callback </c> and an error message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljavax/security/auth/callback/Callback;Ljava/lang/String;)V", AccessFlags = 1)] public UnsupportedCallbackException(global::Javax.Security.Auth.Callback.ICallback callback, string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the unsupported <c> Callback </c> that triggered this exception.</para><para></para> /// </summary> /// <returns> /// <para>the <c> Callback </c> </para> /// </returns> /// <java-name> /// getCallback /// </java-name> [Dot42.DexImport("getCallback", "()Ljavax/security/auth/callback/Callback;", AccessFlags = 1)] public virtual global::Javax.Security.Auth.Callback.ICallback GetCallback() /* MethodBuilder.Create */ { return default(global::Javax.Security.Auth.Callback.ICallback); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal UnsupportedCallbackException() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the unsupported <c> Callback </c> that triggered this exception.</para><para></para> /// </summary> /// <returns> /// <para>the <c> Callback </c> </para> /// </returns> /// <java-name> /// getCallback /// </java-name> public global::Javax.Security.Auth.Callback.ICallback Callback { [Dot42.DexImport("getCallback", "()Ljavax/security/auth/callback/Callback;", AccessFlags = 1)] get{ return GetCallback(); } } } /// <summary> /// <para>Defines an empty base interface for all <c> Callback </c> s used during authentication. </para> /// </summary> /// <java-name> /// javax/security/auth/callback/Callback /// </java-name> [Dot42.DexImport("javax/security/auth/callback/Callback", AccessFlags = 1537)] public partial interface ICallback /* scope: __dot42__ */ { } }
using System; using System.Collections; using NUnit.Framework; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509.Extension; namespace Org.BouncyCastle.Tests { [TestFixture] public class Pkcs10CertRequestTest : SimpleTest { private static readonly byte[] gost3410EC_A = Base64.Decode( "MIIBOzCB6wIBADB/MQ0wCwYDVQQDEwR0ZXN0MRUwEwYDVQQKEwxEZW1vcyBDbyBMdGQxHjAcBgNV" +"BAsTFUNyeXB0b2dyYXBoeSBkaXZpc2lvbjEPMA0GA1UEBxMGTW9zY293MQswCQYDVQQGEwJydTEZ" +"MBcGCSqGSIb3DQEJARYKc2RiQGRvbC5ydTBjMBwGBiqFAwICEzASBgcqhQMCAiMBBgcqhQMCAh4B" +"A0MABEBYx0P2D7YuuZo5HgdIAUKAXcLBDZ+4LYFgbKjrfStVfH59lc40BQ2FZ7M703hLpXK8GiBQ" +"GEYpKaAuQZnMIpByoAAwCAYGKoUDAgIDA0EAgXMcTrhdOY2Er2tHOSAgnMezqrYxocZTWhxmW5Rl" +"JY6lbXH5rndCn4swFzXU+YhgAsJv1wQBaoZEWRl5WV4/nA=="); private static readonly byte[] gost3410EC_B = Base64.Decode( "MIIBPTCB7QIBADCBgDENMAsGA1UEAxMEdGVzdDEWMBQGA1UEChMNRGVtb3MgQ28gTHRkLjEeMBwG" +"A1UECxMVQ3J5cHRvZ3JhcGh5IGRpdmlzaW9uMQ8wDQYDVQQHEwZNb3Njb3cxCzAJBgNVBAYTAnJ1" +"MRkwFwYJKoZIhvcNAQkBFgpzZGJAZG9sLnJ1MGMwHAYGKoUDAgITMBIGByqFAwICIwIGByqFAwIC" +"HgEDQwAEQI5SLoWT7dZVilbV9j5B/fyIDuDs6x4pjqNC2TtFYbpRHrk/Wc5g/mcHvD80tsm5o1C7" +"7cizNzkvAVUM4VT4Dz6gADAIBgYqhQMCAgMDQQAoT5TwJ8o+bSrxckymyo3diwG7ZbSytX4sRiKy" +"wXPWRS9LlBvPO2NqwpS2HUnxSU8rzfL9fJcybATf7Yt1OEVq"); private static readonly byte[] gost3410EC_C = Base64.Decode( "MIIBRDCB9AIBADCBhzEVMBMGA1UEAxMMdGVzdCByZXF1ZXN0MRUwEwYDVQQKEwxEZW1vcyBDbyBM" +"dGQxHjAcBgNVBAsTFUNyeXB0b2dyYXBoeSBkaXZpc2lvbjEPMA0GA1UEBxMGTW9zY293MQswCQYD" +"VQQGEwJydTEZMBcGCSqGSIb3DQEJARYKc2RiQGRvbC5ydTBjMBwGBiqFAwICEzASBgcqhQMCAiMD" +"BgcqhQMCAh4BA0MABEBcmGh7OmR4iqqj+ycYo1S1fS7r5PhisSQU2Ezuz8wmmmR2zeTZkdMYCOBa" +"UTMNms0msW3wuYDho7nTDNscHTB5oAAwCAYGKoUDAgIDA0EAVoOMbfyo1Un4Ss7WQrUjHJoiaYW8" +"Ime5LeGGU2iW3ieAv6es/FdMrwTKkqn5dhd3aL/itFg5oQbhyfXw5yw/QQ=="); private static readonly byte[] gost3410EC_ExA = Base64.Decode( "MIIBOzCB6wIBADB/MQ0wCwYDVQQDEwR0ZXN0MRUwEwYDVQQKEwxEZW1vcyBDbyBMdGQxHjAcBgNV" + "BAsTFUNyeXB0b2dyYXBoeSBkaXZpc2lvbjEPMA0GA1UEBxMGTW9zY293MQswCQYDVQQGEwJydTEZ" + "MBcGCSqGSIb3DQEJARYKc2RiQGRvbC5ydTBjMBwGBiqFAwICEzASBgcqhQMCAiQABgcqhQMCAh4B" + "A0MABEDkqNT/3f8NHj6EUiWnK4JbVZBh31bEpkwq9z3jf0u8ZndG56Vt+K1ZB6EpFxLT7hSIos0w" + "weZ2YuTZ4w43OgodoAAwCAYGKoUDAgIDA0EASk/IUXWxoi6NtcUGVF23VRV1L3undB4sRZLp4Vho" + "gQ7m3CMbZFfJ2cPu6QyarseXGYHmazoirH5lGjEo535c1g=="); private static readonly byte[] gost3410EC_ExB = Base64.Decode( "MIIBPTCB7QIBADCBgDENMAsGA1UEAxMEdGVzdDEWMBQGA1UEChMNRGVtb3MgQ28gTHRkLjEeMBwG" + "A1UECxMVQ3J5cHRvZ3JhcGh5IGRpdmlzaW9uMQ8wDQYDVQQHEwZNb3Njb3cxCzAJBgNVBAYTAnJ1" + "MRkwFwYJKoZIhvcNAQkBFgpzZGJAZG9sLnJ1MGMwHAYGKoUDAgITMBIGByqFAwICJAEGByqFAwIC" + "HgEDQwAEQMBWYUKPy/1Kxad9ChAmgoSWSYOQxRnXo7KEGLU5RNSXA4qMUvArWzvhav+EYUfTbWLh" + "09nELDyHt2XQcvgQHnSgADAIBgYqhQMCAgMDQQAdaNhgH/ElHp64mbMaEo1tPCg9Q22McxpH8rCz" + "E0QBpF4H5mSSQVGI5OAXHToetnNuh7gHHSynyCupYDEHTbkZ"); public override string Name { get { return "PKCS10CertRequest"; } } private void generationTest( int keySize, string keyName, string sigName) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator(keyName); // kpg.initialize(keySize); kpg.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); IDictionary attrs = new Hashtable(); attrs.Add(X509Name.C, "AU"); attrs.Add(X509Name.O, "The Legion of the Bouncy Castle"); attrs.Add(X509Name.L, "Melbourne"); attrs.Add(X509Name.ST, "Victoria"); attrs.Add(X509Name.EmailAddress, "feedback-crypto@bouncycastle.org"); IList order = new ArrayList(); order.Add(X509Name.C); order.Add(X509Name.O); order.Add(X509Name.L); order.Add(X509Name.ST); order.Add(X509Name.EmailAddress); X509Name subject = new X509Name(order, attrs); Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest( sigName, subject, kp.Public, null, kp.Private); byte[] bytes = req1.GetEncoded(); Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes); if (!req2.Verify()) { Fail(sigName + ": Failed Verify check."); } if (!req2.GetPublicKey().Equals(req1.GetPublicKey())) { Fail(keyName + ": Failed public key check."); } } /* * we generate a self signed certificate for the sake of testing - SHA224withECDSA */ private void createECRequest( string algorithm, DerObjectIdentifier algOid) { FPCurve curve = new FPCurve( new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p) new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b ECDomainParameters spec = new ECDomainParameters( curve, // curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d spec); ECPublicKeyParameters pubKey = new ECPublicKeyParameters( // curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q spec); // // // // set up the keys // // // IAsymmetricKeyParameter privKey; // IAsymmetricKeyParameter pubKey; // // KeyFactory fact = KeyFactory.getInstance("ECDSA"); // // privKey = fact.generatePrivate(privKeySpec); // pubKey = fact.generatePublic(pubKeySpec); Pkcs10CertificationRequest req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC encoded."); } // // try with point compression turned off // // ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); FPPoint q = (FPPoint) pubKey.Q; pubKey = new ECPublicKeyParameters( pubKey.AlgorithmName, new FPPoint(q.Curve, q.X, q.Y, false), pubKey.Parameters); req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC uncompressed."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC uncompressed encoded."); } if (!req.SignatureAlgorithm.ObjectID.Equals(algOid)) { Fail("ECDSA oid incorrect."); } if (req.SignatureAlgorithm.Parameters != null) { Fail("ECDSA parameters incorrect."); } ISigner sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, pubKey); byte[] b = req.GetCertificationRequestInfo().GetEncoded(); sig.BlockUpdate(b, 0, b.Length); if (!sig.VerifySignature(req.Signature.GetBytes())) { Fail("signature not mapped correctly."); } } private void createECGostRequest() { string algorithm = "GOST3411withECGOST3410"; IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); ecGostKpg.Init( new ECKeyGenerationParameters( CryptoProObjectIdentifiers.GostR3410x2001CryptoProA, new SecureRandom())); // // set up the keys // IAsymmetricCipherKeyPair pair = ecGostKpg.GenerateKeyPair(); IAsymmetricKeyParameter privKey = pair.Private; IAsymmetricKeyParameter pubKey = pair.Public; Pkcs10CertificationRequest req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC encoded."); } if (!req.SignatureAlgorithm.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001)) { Fail("ECGOST oid incorrect."); } if (req.SignatureAlgorithm.Parameters != null) { Fail("ECGOST parameters incorrect."); } ISigner sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, pubKey); byte[] b = req.GetCertificationRequestInfo().GetEncoded(); sig.BlockUpdate(b, 0, b.Length); if (!sig.VerifySignature(req.Signature.GetBytes())) { Fail("signature not mapped correctly."); } } private void createPssTest( string algorithm) { // RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( RsaKeyParameters pubKey = new RsaKeyParameters(false, new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); // RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16), new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16), new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16), new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16), new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16), new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16), new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16)); // KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); // // PrivateKey privKey = fact.generatePrivate(privKeySpec); // PublicKey pubKey = fact.generatePublic(pubKeySpec); Pkcs10CertificationRequest req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed verify check PSS."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed verify check PSS encoded."); } if (!req.SignatureAlgorithm.ObjectID.Equals(PkcsObjectIdentifiers.IdRsassaPss)) { Fail("PSS oid incorrect."); } if (req.SignatureAlgorithm.Parameters == null) { Fail("PSS parameters incorrect."); } ISigner sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, pubKey); byte[] encoded = req.GetCertificationRequestInfo().GetEncoded(); sig.BlockUpdate(encoded, 0, encoded.Length); if (!sig.VerifySignature(req.Signature.GetBytes())) { Fail("signature not mapped correctly."); } } // previous code found to cause a NullPointerException private void nullPointerTest() { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); IAsymmetricCipherKeyPair pair = keyGen.GenerateKeyPair(); IList oids = new ArrayList(); IList values = new ArrayList(); oids.Add(X509Extensions.BasicConstraints); values.Add(new X509Extension(true, new DerOctetString(new BasicConstraints(true)))); oids.Add(X509Extensions.KeyUsage); values.Add(new X509Extension(true, new DerOctetString( new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign)))); SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pair.Public); X509Extension ski = new X509Extension(false, new DerOctetString(subjectKeyIdentifier)); oids.Add(X509Extensions.SubjectKeyIdentifier); values.Add(ski); AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(oids, values))); Pkcs10CertificationRequest p1 = new Pkcs10CertificationRequest( "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private); Pkcs10CertificationRequest p2 = new Pkcs10CertificationRequest( "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private); if (!p1.Equals(p2)) { Fail("cert request comparison failed"); } } public override void PerformTest() { generationTest(512, "RSA", "SHA1withRSA"); generationTest(512, "GOST3410", "GOST3411withGOST3410"); // if (Security.getProvider("SunRsaSign") != null) // { // generationTest(512, "RSA", "SHA1withRSA", "SunRsaSign"); // } // elliptic curve GOST A parameter set Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(gost3410EC_A); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_A."); } // elliptic curve GOST B parameter set req = new Pkcs10CertificationRequest(gost3410EC_B); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_B."); } // elliptic curve GOST C parameter set req = new Pkcs10CertificationRequest(gost3410EC_C); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_C."); } // elliptic curve GOST ExA parameter set req = new Pkcs10CertificationRequest(gost3410EC_ExA); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_ExA."); } // elliptic curve GOST ExB parameter set req = new Pkcs10CertificationRequest(gost3410EC_ExB); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_ExA."); } // elliptic curve openSSL IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); ECCurve curve = new FPCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); IAsymmetricCipherKeyPair kp = g.GenerateKeyPair(); req = new Pkcs10CertificationRequest( "ECDSAWITHSHA1", new X509Name("CN=XXX"), kp.Public, null, kp.Private); if (!req.Verify()) { Fail("Failed Verify check EC."); } createECRequest("SHA1withECDSA", X9ObjectIdentifiers.ECDsaWithSha1); createECRequest("SHA224withECDSA", X9ObjectIdentifiers.ECDsaWithSha224); createECRequest("SHA256withECDSA", X9ObjectIdentifiers.ECDsaWithSha256); createECRequest("SHA384withECDSA", X9ObjectIdentifiers.ECDsaWithSha384); createECRequest("SHA512withECDSA", X9ObjectIdentifiers.ECDsaWithSha512); createECGostRequest(); // TODO The setting of parameters for MGF algorithms is not implemented // createPssTest("SHA1withRSAandMGF1"); // createPssTest("SHA224withRSAandMGF1"); // createPssTest("SHA256withRSAandMGF1"); // createPssTest("SHA384withRSAandMGF1"); nullPointerTest(); } public static void Main( string[] args) { RunTest(new Pkcs10CertRequestTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using UnityEngine; using System.Collections; using System; using System.Net; using System.Net.Sockets; namespace tk { public class TcpClient : MonoBehaviour { public bool debug = false; private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private byte[] _recieveBuffer = new byte[8142]; private TcpServer _server = null; public delegate void OnDataRecv(byte[] data); public OnDataRecv onDataRecvCB; public delegate void OnConnected(); public OnConnected onConnectedCB; // Flag to let us know a connection has dropped. private bool dropped = false; public float time_check_dropped = 0.0f; public float time_check_dropped_freq = 3.0f; /// <summary> /// Connect will establish a new TCP socket connection to a remote ip, port. This method is the first method /// called to start using this object. /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <returns></returns> public bool Connect(string ip, int port) { if (_clientSocket.Connected) return false; try { IPAddress address = IPAddress.Parse(ip); _clientSocket.Connect(new IPEndPoint(address, port)); } catch (SocketException ex) { Debug.Log(ex.Message); return false; } dropped = false; _clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null); return true; } /// <summary> /// OnServerAccept is an alternate form of client initialization that occurs when a server has accepted a client /// connection already and passes that socket in clientSock in a connected state. This also then passes a pointer /// to the server which can be used by the clients to broadcast messages to all the peers. /// </summary> /// <param name="clientSock"></param> /// <param name="server"></param> /// <returns></returns> public bool OnServerAccept(Socket clientSock, TcpServer server) { if (!clientSock.Connected) return false; _clientSocket = clientSock; _server = server; dropped = false; _clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null); return true; } public void ClientFinishedConnect() { if(onConnectedCB != null) onConnectedCB.Invoke(); } public void ReleaseServer() { _server = null; } public void Disconnect() { try { if (_clientSocket.Connected) { _clientSocket.Shutdown(SocketShutdown.Both); if (!IsDropped()) { _clientSocket.Disconnect(true); } } } catch(SocketException e) { Debug.Log(e.ToString()); } finally { _clientSocket.Close(); } if (_server != null) _server.RemoveClient(this); } void OnDestroy() { Disconnect(); } public bool IsDropped() { return dropped; } public void Update() { // Update our drop detection... if(_clientSocket != null && !IsDropped()) { time_check_dropped += Time.deltaTime; if(!_clientSocket.Connected) { dropped = true; } else if(time_check_dropped > time_check_dropped_freq) { time_check_dropped = 0.0f; try { // this is the minimal form of message for a JsonTCPClient string msg = "{}\n"; System.Text.Encoding encoding = System.Text.Encoding.Default; _clientSocket.Send(encoding.GetBytes(msg)); } catch(SocketException e) { Debug.LogWarning("connection dropped."); dropped = true; } } } } private void ReceiveCallback(IAsyncResult AR) { //Check how much bytes are recieved and call EndRecieve to finalize handshake int recieved = 0; try { recieved = _clientSocket.EndReceive(AR); } catch(SocketException e) { recieved = 0; dropped = true; Debug.LogWarning("Exception on recv. Connection dropped."); } if (recieved <= 0) return; //Copy the recieved data into new buffer , to avoid null bytes byte[] recData = new byte[recieved]; Buffer.BlockCopy(_recieveBuffer, 0, recData, 0, recieved); if (debug) { Debug.Log("recv:" + System.Text.Encoding.Default.GetString(recData)); } //Process data here the way you want , all your bytes will be stored in recData if (onDataRecvCB != null) onDataRecvCB.Invoke(recData); // Reset our drop connection test timer, since we just got data. time_check_dropped = 0.0f; //Start receiving again _clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null); } public bool SendData(byte[] data) { if (!_clientSocket.Connected) return false; SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs(); socketAsyncData.SetBuffer(data, 0, data.Length); _clientSocket.SendAsync(socketAsyncData); if (debug) { Debug.Log("sent:" + System.Text.Encoding.Default.GetString(data)); } return true; } public bool SendDataToPeers(byte[] data) { if (!_clientSocket.Connected || _server == null) return false; _server.SendData(data, this); return true; } public void SetDebug(bool _debug) { debug = _debug; } } } //end namepace tk
using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Web; #if !MONO #endif namespace bv.common.Core { public class Utils { public const long SEARCH_MODE_ID = -2; /// ----------------------------------------------------------------------------- /// <summary> /// Returns safe string representation of object. /// </summary> /// <param name="o"> object that should be converted to string </param> /// <returns> Returns string representation of passed object. If passed object is <b>Nothing</b> or <b>DBNull.Value</b> the method returns empty string. </returns> /// <history>[Mike] 03.04.2006 Created</history> /// ----------------------------------------------------------------------------- public static string Str(object o) { return Str(o, ""); } public static string Str(object o, string defaultString) { if (o == null || o == DBNull.Value) { return defaultString; } return o.ToString(); } public static double Dbl(object o) { if (o == null || o == DBNull.Value) { return 0.0; } try { return Convert.ToDouble(o); } catch (Exception) { return 0.0; } } /// ----------------------------------------------------------------------------- /// <summary> /// Checks if the passed object represents the valid typed object. /// </summary> /// <param name="o"> object to check </param> /// <returns> False if passed object is <b>Nothing</b> or <b>DBNull.Value</b> or its string representation is empty string and True in other case. </returns> /// <history>[Mike] 03.04.2006 Created</history> /// ----------------------------------------------------------------------------- public static bool IsEmpty(object o) { if (o == null || o == DBNull.Value) { return true; } if (o.ToString().Trim() == "") { return true; } return false; } /// ----------------------------------------------------------------------------- /// <summary> /// Appends the default string with other separating them with some separator /// </summary> /// <param name="s"> default string to append </param> /// <param name="val"> string that should be appended </param> /// <param name="separator"> string that should separate default and appended strings </param> /// <remarks> /// method inserts the separator between strings only if default string is not empty. /// </remarks> /// <history>[Mike] 03.04.2006 Created</history> /// ----------------------------------------------------------------------------- public static void AppendLine(ref string s, object val, string separator) { if (val == DBNull.Value || val.ToString().Trim().Length == 0) { return; } if (s.Length == 0) { s += val.ToString(); } else { s += separator + val; } } public static string Join(string separator, IEnumerable collection) { var result = new StringBuilder(); object item; foreach (object tempLoopVarItem in collection) { item = tempLoopVarItem; if (item == null || string.IsNullOrWhiteSpace(item.ToString())) { continue; } if (result.Length > 0) { result.Append(separator); } result.Append(item.ToString()); } return result.ToString(); } /// ----------------------------------------------------------------------------- /// <summary> /// Checks if directory exists and creates it if it is absent /// </summary> /// <param name="dir"> directory to check </param> /// <returns> Returns <b>True</b> if requested directory exists or was created successfully and <b>False</b> if requested directory can't be created </returns> /// <history>[Mike] 03.04.2006 Created</history> /// ----------------------------------------------------------------------------- public static bool ForceDirectories(string dir) { int pos = 0; try { do { pos = dir.IndexOf(Path.DirectorySeparatorChar, pos); if (pos < 0) { break; } string dirName = dir.Substring(0, pos); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } pos++; } while (true); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } return Directory.Exists(dir); } catch { return false; } } #if !MONO public static Bitmap LoadBitmapFromResource(string resName, Type aType) { //open the executing assembly Assembly oAssembly = Assembly.GetAssembly(aType); //create stream for image (icon) in assembly Stream oStream = oAssembly.GetManifestResourceStream(resName); //create new bitmap from stream if (oStream != null) { var oBitmap = (Bitmap) (Image.FromStream(oStream)); return oBitmap; } return null; } #endif public static bool IsGuid(object g) { string s = Str(g); if (s.Length != 36) { return false; } try { new Guid(s); return true; } catch (Exception) { return false; } } /* public static bool IsEIDSS { get { return (ApplicationContext.ApplicationName.ToLowerInvariant() == "eidss"); } } public static bool IsPACS { get { return (ApplicationContext.ApplicationName.ToLowerInvariant() == "pacs_main"); } } */ public static T CheckNotNull<T>(T param, string paramName) { if (ReferenceEquals(param, null)) { throw (new ArgumentNullException(paramName)); } return param; } public static string CheckNotNullOrEmpty(string param, string paramName) { if (CheckNotNull(param, paramName) == string.Empty) { throw (new ArgumentException(paramName + " cannot be empty string")); } return param; } public static string GetParentDirectoryPath(string dirName) { string appLocation = GetExecutingPath(); dirName = dirName.ToLowerInvariant(); var dir = new DirectoryInfo(Path.GetDirectoryName(appLocation)); while (dir != null && dir.Name.ToLowerInvariant() != dirName) { foreach (DirectoryInfo subDir in dir.GetDirectories()) { if (subDir.Name.ToLower(CultureInfo.InvariantCulture) == dirName) { return subDir.FullName + "\\"; } } dir = dir.Parent; } if (dir != null) { return string.Format("{0}\\", dir.FullName); } return null; } //It is assumed that assembly is placed in the project that is located in solution directory; public static string GetSolutionPath() { string binPath = GetParentDirectoryPath("bin"); var dir = new DirectoryInfo(Path.GetDirectoryName(binPath)); return string.Format("{0}\\", dir.Parent.Parent.FullName); } public static string GetExecutingPath() { DirectoryInfo appDir; #if !MONO if (HttpContext.Current != null) { try { appDir = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath); if (appDir != null) { return string.Format("{0}\\", appDir.FullName); } } catch { } } #endif Assembly asm = Assembly.GetExecutingAssembly(); if (!asm.GetName().Name.StartsWith("nunit")) { appDir = new DirectoryInfo(Path.GetDirectoryName(GetAssemblyLocation(asm))); return string.Format("{0}\\", appDir.FullName); } asm = Assembly.GetCallingAssembly(); appDir = new DirectoryInfo(Path.GetDirectoryName(GetAssemblyLocation(asm))); return string.Format("{0}\\", appDir.FullName); } public static string GetAssemblyLocation(Assembly asm) { if (asm.CodeBase.StartsWith("file:///")) { return asm.CodeBase.Substring(8).Replace("/", "\\"); } return asm.Location; } public static string GetFilePathNearAssembly(Assembly asm, string fileName) { string location = ConvertFileNane(asm.Location); string locationFileName = string.Format(@"{0}\{1}", Path.GetDirectoryName(location), fileName); if (File.Exists(locationFileName)) { return locationFileName; } string codeBase = ConvertFileNane(asm.CodeBase); string codeBaseFileName = string.Format(@"{0}\{1}", Path.GetDirectoryName(codeBase), fileName); if (File.Exists(codeBaseFileName)) { return codeBaseFileName; } throw new FileNotFoundException( string.Format("Could not find file placed neither {0} nor {1}", locationFileName, codeBaseFileName), fileName); } public static string ConvertFileNane(string fileName) { if (fileName.StartsWith("file:///")) { return fileName.Substring(8).Replace("/", "\\"); } return fileName; } public static string GetConfigFileName() { #if !MONO if (HttpContext.Current != null) { return "Web.config"; } #endif Assembly asm = Assembly.GetEntryAssembly(); if (asm != null) { return Path.GetFileName(asm.Location) + ".config"; } return ""; } public static long? ToNullableLong(object val) { if (IsEmpty(val)) { return null; } return (long) val; } public static bool IsCalledFromUnitTest() { var stack = new StackTrace(); int frameCount = stack.FrameCount - 1; for (int frame = 0; frame <= frameCount; frame++) { StackFrame stackFrame = stack.GetFrame(frame); if (stackFrame != null) { MethodBase method = stackFrame.GetMethod(); if (method != null) { string moduleName = method.Module.Name; if (moduleName.Contains("tests")) { return true; } } } } return false; } private static string GetAssemblyCodeBaseLocation(Assembly asm) { if (asm.CodeBase.StartsWith("file:///")) { return asm.CodeBase.Substring(8).Replace("/", "\\"); } return asm.Location; } public static string GetExecutingAssembly() { string app; #if !MONO if (HttpContext.Current != null) { return HttpContext.Current.Request.PhysicalApplicationPath; } #endif Assembly asm = Assembly.GetEntryAssembly(); if (asm == null) { asm = Assembly.GetExecutingAssembly(); } if (!asm.GetName().Name.StartsWith("nunit")) { app = GetAssemblyCodeBaseLocation(asm); if (app != null) { return app; } } asm = Assembly.GetCallingAssembly(); app = GetAssemblyCodeBaseLocation(asm); if (app != null) { return app; } return null; } public static object ToDbValue(object val) { if (val == null) { return DBNull.Value; } return val; } public static long ToLong(object o, long defValue = 0) { if (o == null || o == DBNull.Value) { return defValue; } try { return Convert.ToInt64(o); } catch (Exception) { return defValue; } } public static string GetCurrentMethodName() { return GetMethodName(2); } public static string GetPreviousMethodName() { return GetMethodName(3); } private static string GetMethodName(int index) { var stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(index); string name = stackFrame != null ? stackFrame.GetMethod().Name : "CANNOT_GET_METHOD_NAME"; return name; } } }
#region File Description //----------------------------------------------------------------------------- // ParticleSystem.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics.PackedVector; #endregion namespace AsteroidDestroyer.Particles { /// <summary> /// The main component in charge of displaying particles. /// </summary> public abstract class ParticleSystem : DrawableGameComponent { #region Fields // Settings class controls the appearance and animation of this particle system. ParticleSettings settings = new ParticleSettings(); // For loading the effect and particle texture. ContentManager content; // Custom effect for drawing particles. This computes the particle // animation entirely in the vertex shader: no per-particle CPU work required! Effect particleEffect; // Shortcuts for accessing frequently changed effect parameters. EffectParameter effectViewParameter; EffectParameter effectProjectionParameter; EffectParameter effectViewportScaleParameter; EffectParameter effectTimeParameter; // An array of particles, treated as a circular queue. ParticleVertex[] particles; // A vertex buffer holding our particles. This contains the same data as // the particles array, but copied across to where the GPU can access it. DynamicVertexBuffer vertexBuffer; // Index buffer turns sets of four vertices into particle quads (pairs of triangles). IndexBuffer indexBuffer; // The particles array and vertex buffer are treated as a circular queue. // Initially, the entire contents of the array are free, because no particles // are in use. When a new particle is created, this is allocated from the // beginning of the array. If more than one particle is created, these will // always be stored in a consecutive block of array elements. Because all // particles last for the same amount of time, old particles will always be // removed in order from the start of this active particle region, so the // active and free regions will never be intermingled. Because the queue is // circular, there can be times when the active particle region wraps from the // end of the array back to the start. The queue uses modulo arithmetic to // handle these cases. For instance with a four entry queue we could have: // // 0 // 1 - first active particle // 2 // 3 - first free particle // // In this case, particles 1 and 2 are active, while 3 and 4 are free. // Using modulo arithmetic we could also have: // // 0 // 1 - first free particle // 2 // 3 - first active particle // // Here, 3 and 0 are active, while 1 and 2 are free. // // But wait! The full story is even more complex. // // When we create a new particle, we add them to our managed particles array. // We also need to copy this new data into the GPU vertex buffer, but we don't // want to do that straight away, because setting new data into a vertex buffer // can be an expensive operation. If we are going to be adding several particles // in a single frame, it is faster to initially just store them in our managed // array, and then later upload them all to the GPU in one single call. So our // queue also needs a region for storing new particles that have been added to // the managed array but not yet uploaded to the vertex buffer. // // Another issue occurs when old particles are retired. The CPU and GPU run // asynchronously, so the GPU will often still be busy drawing the previous // frame while the CPU is working on the next frame. This can cause a // synchronization problem if an old particle is retired, and then immediately // overwritten by a new one, because the CPU might try to change the contents // of the vertex buffer while the GPU is still busy drawing the old data from // it. Normally the graphics driver will take care of this by waiting until // the GPU has finished drawing inside the VertexBuffer.SetData call, but we // don't want to waste time waiting around every time we try to add a new // particle! To avoid this delay, we can specify the SetDataOptions.NoOverwrite // flag when we write to the vertex buffer. This basically means "I promise I // will never try to overwrite any data that the GPU might still be using, so // you can just go ahead and update the buffer straight away". To keep this // promise, we must avoid reusing vertices immediately after they are drawn. // // So in total, our queue contains four different regions: // // Vertices between firstActiveParticle and firstNewParticle are actively // being drawn, and exist in both the managed particles array and the GPU // vertex buffer. // // Vertices between firstNewParticle and firstFreeParticle are newly created, // and exist only in the managed particles array. These need to be uploaded // to the GPU at the start of the next draw call. // // Vertices between firstFreeParticle and firstRetiredParticle are free and // waiting to be allocated. // // Vertices between firstRetiredParticle and firstActiveParticle are no longer // being drawn, but were drawn recently enough that the GPU could still be // using them. These need to be kept around for a few more frames before they // can be reallocated. int firstActiveParticle; int firstNewParticle; int firstFreeParticle; int firstRetiredParticle; // Store the current time, in seconds. float currentTime; // Count how many times Draw has been called. This is used to know // when it is safe to retire old particles back into the free list. int drawCounter; // Shared random number generator. static Random random = new Random(); #endregion #region Initialization /// <summary> /// Constructor. /// </summary> protected ParticleSystem(Game game, ContentManager content) : base(game) { this.content = content; } /// <summary> /// Initializes the component. /// </summary> public override void Initialize() { InitializeSettings(settings); // Allocate the particle array, and fill in the corner fields (which never change). particles = new ParticleVertex[settings.MaxParticles * 4]; for (int i = 0; i < settings.MaxParticles; i++) { particles[i * 4 + 0].Corner = new Short2(-1, -1); particles[i * 4 + 1].Corner = new Short2(1, -1); particles[i * 4 + 2].Corner = new Short2(1, 1); particles[i * 4 + 3].Corner = new Short2(-1, 1); } base.Initialize(); } /// <summary> /// Derived particle system classes should override this method /// and use it to initalize their tweakable settings. /// </summary> protected abstract void InitializeSettings(ParticleSettings settings); /// <summary> /// Loads graphics for the particle system. /// </summary> protected override void LoadContent() { LoadParticleEffect(); // Create a dynamic vertex buffer. vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, ParticleVertex.VertexDeclaration, settings.MaxParticles * 4, BufferUsage.WriteOnly); // Create and populate the index buffer. ushort[] indices = new ushort[settings.MaxParticles * 6]; for (int i = 0; i < settings.MaxParticles; i++) { indices[i * 6 + 0] = (ushort)(i * 4 + 0); indices[i * 6 + 1] = (ushort)(i * 4 + 1); indices[i * 6 + 2] = (ushort)(i * 4 + 2); indices[i * 6 + 3] = (ushort)(i * 4 + 0); indices[i * 6 + 4] = (ushort)(i * 4 + 2); indices[i * 6 + 5] = (ushort)(i * 4 + 3); } indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly); indexBuffer.SetData(indices); } /// <summary> /// Helper for loading and initializing the particle effect. /// </summary> void LoadParticleEffect() { Effect effect = content.Load<Effect>(@"Effect\ParticleEffect"); // If we have several particle systems, the content manager will return // a single shared effect instance to them all. But we want to preconfigure // the effect with parameters that are specific to this particular // particle system. By cloning the effect, we prevent one particle system // from stomping over the parameter settings of another. particleEffect = effect.Clone(); EffectParameterCollection parameters = particleEffect.Parameters; // Look up shortcuts for parameters that change every frame. effectViewParameter = parameters["View"]; effectProjectionParameter = parameters["Projection"]; effectViewportScaleParameter = parameters["ViewportScale"]; effectTimeParameter = parameters["CurrentTime"]; // Set the values of parameters that do not change. parameters["Duration"].SetValue((float)settings.Duration.TotalSeconds); parameters["DurationRandomness"].SetValue(settings.DurationRandomness); parameters["Gravity"].SetValue(settings.Gravity); parameters["EndVelocity"].SetValue(settings.EndVelocity); parameters["MinColor"].SetValue(settings.MinColor.ToVector4()); parameters["MaxColor"].SetValue(settings.MaxColor.ToVector4()); parameters["RotateSpeed"].SetValue( new Vector2(settings.MinRotateSpeed, settings.MaxRotateSpeed)); parameters["StartSize"].SetValue( new Vector2(settings.MinStartSize, settings.MaxStartSize)); parameters["EndSize"].SetValue( new Vector2(settings.MinEndSize, settings.MaxEndSize)); // Load the particle texture, and set it onto the effect. Texture2D texture = content.Load<Texture2D>(settings.TextureName); parameters["Texture"].SetValue(texture); } #endregion #region Update and Draw /// <summary> /// Updates the particle system. /// </summary> public override void Update(GameTime gameTime) { if (gameTime == null) throw new ArgumentNullException("gameTime"); currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; RetireActiveParticles(); FreeRetiredParticles(); // If we let our timer go on increasing for ever, it would eventually // run out of floating point precision, at which point the particles // would render incorrectly. An easy way to prevent this is to notice // that the time value doesn't matter when no particles are being drawn, // so we can reset it back to zero any time the active queue is empty. if (firstActiveParticle == firstFreeParticle) currentTime = 0; if (firstRetiredParticle == firstActiveParticle) drawCounter = 0; } /// <summary> /// Helper for checking when active particles have reached the end of /// their life. It moves old particles from the active area of the queue /// to the retired section. /// </summary> void RetireActiveParticles() { float particleDuration = (float)settings.Duration.TotalSeconds; while (firstActiveParticle != firstNewParticle) { // Is this particle old enough to retire? // We multiply the active particle index by four, because each // particle consists of a quad that is made up of four vertices. float particleAge = currentTime - particles[firstActiveParticle * 4].Time; if (particleAge < particleDuration) break; // Remember the time at which we retired this particle. particles[firstActiveParticle * 4].Time = drawCounter; // Move the particle from the active to the retired queue. firstActiveParticle++; if (firstActiveParticle >= settings.MaxParticles) firstActiveParticle = 0; } } /// <summary> /// Helper for checking when retired particles have been kept around long /// enough that we can be sure the GPU is no longer using them. It moves /// old particles from the retired area of the queue to the free section. /// </summary> void FreeRetiredParticles() { while (firstRetiredParticle != firstActiveParticle) { // Has this particle been unused long enough that // the GPU is sure to be finished with it? // We multiply the retired particle index by four, because each // particle consists of a quad that is made up of four vertices. int age = drawCounter - (int)particles[firstRetiredParticle * 4].Time; // The GPU is never supposed to get more than 2 frames behind the CPU. // We add 1 to that, just to be safe in case of buggy drivers that // might bend the rules and let the GPU get further behind. if (age < 3) break; // Move the particle from the retired to the free queue. firstRetiredParticle++; if (firstRetiredParticle >= settings.MaxParticles) firstRetiredParticle = 0; } } /// <summary> /// Draws the particle system. /// </summary> public override void Draw(GameTime gameTime) { GraphicsDevice device = GraphicsDevice; // Restore the vertex buffer contents if the graphics device was lost. if (vertexBuffer.IsContentLost) { vertexBuffer.SetData(particles); } // If there are any particles waiting in the newly added queue, // we'd better upload them to the GPU ready for drawing. if (firstNewParticle != firstFreeParticle) { AddNewParticlesToVertexBuffer(); } // If there are any active particles, draw them now! if (firstActiveParticle != firstFreeParticle) { device.BlendState = settings.BlendState; device.DepthStencilState = DepthStencilState.DepthRead; // Set an effect parameter describing the viewport size. This is // needed to convert particle sizes into screen space point sizes. effectViewportScaleParameter.SetValue(new Vector2(0.5f / device.Viewport.AspectRatio, -0.5f)); // Set an effect parameter describing the current time. All the vertex // shader particle animation is keyed off this value. effectTimeParameter.SetValue(currentTime); // Set the particle vertex and index buffer. device.SetVertexBuffer(vertexBuffer); device.Indices = indexBuffer; // Activate the particle effect. foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes) { pass.Apply(); if (firstActiveParticle < firstFreeParticle) { // If the active particles are all in one consecutive range, // we can draw them all in a single call. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, firstActiveParticle * 4, (firstFreeParticle - firstActiveParticle) * 4, firstActiveParticle * 6, (firstFreeParticle - firstActiveParticle) * 2); } else { // If the active particle range wraps past the end of the queue // back to the start, we must split them over two draw calls. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, firstActiveParticle * 4, (settings.MaxParticles - firstActiveParticle) * 4, firstActiveParticle * 6, (settings.MaxParticles - firstActiveParticle) * 2); if (firstFreeParticle > 0) { device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, firstFreeParticle * 4, 0, firstFreeParticle * 2); } } } // Reset some of the renderstates that we changed, // so as not to mess up any other subsequent drawing. device.DepthStencilState = DepthStencilState.Default; } drawCounter++; } /// <summary> /// Helper for uploading new particles from our managed /// array to the GPU vertex buffer. /// </summary> void AddNewParticlesToVertexBuffer() { int stride = ParticleVertex.SizeInBytes; if (firstNewParticle < firstFreeParticle) { // If the new particles are all in one consecutive range, // we can upload them all in a single call. vertexBuffer.SetData(firstNewParticle * stride * 4, particles, firstNewParticle * 4, (firstFreeParticle - firstNewParticle) * 4, stride, SetDataOptions.NoOverwrite); } else { // If the new particle range wraps past the end of the queue // back to the start, we must split them over two upload calls. vertexBuffer.SetData(firstNewParticle * stride * 4, particles, firstNewParticle * 4, (settings.MaxParticles - firstNewParticle) * 4, stride, SetDataOptions.NoOverwrite); if (firstFreeParticle > 0) { vertexBuffer.SetData(0, particles, 0, firstFreeParticle * 4, stride, SetDataOptions.NoOverwrite); } } // Move the particles we just uploaded from the new to the active queue. firstNewParticle = firstFreeParticle; } #endregion #region Public Methods /// <summary> /// Sets the camera view and projection matrices /// that will be used to draw this particle system. /// </summary> public void SetCamera(Matrix view, Matrix projection) { effectViewParameter.SetValue(view); effectProjectionParameter.SetValue(projection); } /// <summary> /// Adds a new particle to the system. /// </summary> public void AddParticle(Vector3 position, Vector3 velocity) { // Figure out where in the circular queue to allocate the new particle. int nextFreeParticle = firstFreeParticle + 1; if (nextFreeParticle >= settings.MaxParticles) nextFreeParticle = 0; // If there are no free particles, we just have to give up. if (nextFreeParticle == firstRetiredParticle) return; // Adjust the input velocity based on how much // this particle system wants to be affected by it. velocity *= settings.EmitterVelocitySensitivity; // Add in some random amount of horizontal velocity. float horizontalVelocity = MathHelper.Lerp(settings.MinHorizontalVelocity, settings.MaxHorizontalVelocity, (float)random.NextDouble()); double horizontalAngle = random.NextDouble() * MathHelper.TwoPi; velocity.X += horizontalVelocity * (float)Math.Cos(horizontalAngle); velocity.Z += horizontalVelocity * (float)Math.Sin(horizontalAngle); // Add in some random amount of vertical velocity. velocity.Y += MathHelper.Lerp(settings.MinVerticalVelocity, settings.MaxVerticalVelocity, (float)random.NextDouble()); // Choose four random control values. These will be used by the vertex // shader to give each particle a different size, rotation, and color. Color randomValues = new Color((byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255)); // Fill in the particle vertex structure. for (int i = 0; i < 4; i++) { particles[firstFreeParticle * 4 + i].Position = position; particles[firstFreeParticle * 4 + i].Velocity = velocity; particles[firstFreeParticle * 4 + i].Random = randomValues; particles[firstFreeParticle * 4 + i].Time = currentTime; } firstFreeParticle = nextFreeParticle; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="PaperSize.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Drawing.Printing { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; using System; using System.Drawing; using System.ComponentModel; using Microsoft.Win32; using System.Globalization; /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize"]/*' /> /// <devdoc> /// <para> /// Specifies /// the size of a piece of paper. /// </para> /// </devdoc> [Serializable] public class PaperSize { private PaperKind kind; private string name; // standard hundredths of an inch units private int width; private int height; private bool createdByDefaultConstructor; /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize.PaperSize2"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Printing.PaperSize'/> class with default properties. /// This constructor is required for the serialization of the <see cref='System.Drawing.Printing.PaperSize'/> class. /// </para> /// </devdoc> public PaperSize() { this.kind = PaperKind.Custom; this.name = String.Empty; this.createdByDefaultConstructor = true; } internal PaperSize(PaperKind kind, string name, int width, int height) { this.kind = kind; this.name = name; this.width = width; this.height = height; } /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize.PaperSize"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Printing.PaperSize'/> class. /// </para> /// </devdoc> public PaperSize(string name, int width, int height) { this.kind = PaperKind.Custom; this.name = name; this.width = width; this.height = height; } /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize.Height"]/*' /> /// <devdoc> /// <para>Gets or sets /// the height of the paper, in hundredths of an inch.</para> /// </devdoc> public int Height { get { return height; } set { if (kind != PaperKind.Custom && !this.createdByDefaultConstructor) throw new ArgumentException(SR.GetString(SR.PSizeNotCustom)); height = value; } } /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize.Kind"]/*' /> /// <devdoc> /// <para> /// Gets the type of paper. /// /// </para> /// </devdoc> public PaperKind Kind { get { if (kind <= (PaperKind)SafeNativeMethods.DMPAPER_LAST && !(kind == (PaperKind)SafeNativeMethods.DMPAPER_RESERVED_48 || kind == (PaperKind)SafeNativeMethods.DMPAPER_RESERVED_49)) return kind; else return PaperKind.Custom; } } /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize.PaperName"]/*' /> /// <devdoc> /// <para>Gets /// or sets the name of the type of paper.</para> /// </devdoc> public string PaperName { get { return name;} set { if (kind != PaperKind.Custom && !this.createdByDefaultConstructor) throw new ArgumentException(SR.GetString(SR.PSizeNotCustom)); name = value; } } /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize.RawKind"]/*' /> /// <devdoc> /// <para> /// Same as Kind, but values larger than or equal to DMPAPER_LAST do not map to PaperKind.Custom. /// This property is needed for serialization of the PrinterSettings object. /// </para> /// </devdoc> public int RawKind { get { return unchecked((int) kind); } set { kind = unchecked((PaperKind) value); } } /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize.Width"]/*' /> /// <devdoc> /// <para>Gets or sets /// the width of the paper, in hundredths of an inch.</para> /// </devdoc> public int Width { get { return width; } set { if (kind != PaperKind.Custom && !createdByDefaultConstructor) throw new ArgumentException(SR.GetString(SR.PSizeNotCustom)); width = value; } } // I don't think we need this anymore #if false private Point Dimensions { get { Point result; // Most of these numbers came straight from the header files. // The Japanese envelope ones came from [....]. switch (Kind) { case PaperKind.Custom: result = new Point(width, height); break; case PaperKind.Letter: result = Inches(8.5, 11); break; case PaperKind.Legal: result = Inches(8.5, 14); break; case PaperKind.A4: result = Millimeters(210, 297); break; case PaperKind.CSheet: result = Inches(17, 22); break; case PaperKind.DSheet: result = Inches(22, 34); break; case PaperKind.ESheet: result = Inches(34, 44); break; case PaperKind.LetterSmall: result = Inches(8.5, 11); break; case PaperKind.Tabloid: result = Inches(11, 17); break; case PaperKind.Ledger: result = Inches(17, 11); break; case PaperKind.Statement: result = Inches(5.5, 8.5); break; case PaperKind.Executive: result = Inches(7.25, 10.5); break; case PaperKind.A3: result = Millimeters(297, 420); break; case PaperKind.A4Small: result = Millimeters(210, 297); break; case PaperKind.A5: result = Millimeters(148, 210); break; case PaperKind.B4: result = Millimeters(250, 354); break; case PaperKind.B5: result = Millimeters(182, 257); break; case PaperKind.Folio: result = Inches(8.5, 13); break; case PaperKind.Quarto: result = Millimeters(215, 275); break; case PaperKind.Standard10x14: result = Inches(10, 14); break; case PaperKind.Standard11x17: result = Inches(11, 17); break; case PaperKind.Note: result = Inches(8.5, 11); break; case PaperKind.Number9Envelope: result = Inches(3.875, 8.875); break; case PaperKind.Number10Envelope: result = Inches(4.125, 9.5); break; case PaperKind.Number11Envelope: result = Inches(4.5, 10.375); break; case PaperKind.Number12Envelope: result = Inches(4.75, 11); break; case PaperKind.Number14Envelope: result = Inches(5, 11.5); break; case PaperKind.DLEnvelope: result = Millimeters(110, 220); break; case PaperKind.C5Envelope: result = Millimeters(162, 229); break; case PaperKind.C3Envelope: result = Millimeters(324, 458); break; case PaperKind.C4Envelope: result = Millimeters(229, 324); break; case PaperKind.C6Envelope: result = Millimeters(114, 162); break; case PaperKind.C65Envelope: result = Millimeters(114, 229); break; case PaperKind.B4Envelope: result = Millimeters(250, 353); break; case PaperKind.B5Envelope: result = Millimeters(176, 250); break; case PaperKind.B6Envelope: result = Millimeters(176, 125); break; case PaperKind.ItalyEnvelope: result = Millimeters(110, 230); break; case PaperKind.MonarchEnvelope: result = Inches(3.875, 7.5); break; case PaperKind.PersonalEnvelope: result = Inches(3.625, 6.5); break; case PaperKind.USStandardFanfold: result = Inches(14.875, 11); break; case PaperKind.GermanStandardFanfold: result = Inches(8.5, 12); break; case PaperKind.GermanLegalFanfold: result = Inches(8.5, 13); break; case PaperKind.ISOB4: result = Millimeters(250, 353); break; case PaperKind.JapanesePostcard: result = Millimeters(100, 148); break; case PaperKind.Standard9x11: result = Inches(9, 11); break; case PaperKind.Standard10x11: result = Inches(10, 11); break; case PaperKind.Standard15x11: result = Inches(15, 11); break; case PaperKind.InviteEnvelope: result = Millimeters(220, 220); break; //= SafeNativeMethods.DMPAPER_RESERVED_48, //= SafeNativeMethods.DMPAPER_RESERVED_49, case PaperKind.LetterExtra: result = Inches(9.275, 12); break; case PaperKind.LegalExtra: result = Inches(9.275, 15); break; case PaperKind.TabloidExtra: result = Inches(11.69, 18); break; case PaperKind.A4Extra: result = Inches(9.27, 12.69); break; case PaperKind.LetterTransverse: result = Inches(8.275, 11); break; case PaperKind.A4Transverse: result = Millimeters(210, 297); break; case PaperKind.LetterExtraTransverse: result = Inches(9.275, 12); break; case PaperKind.APlus: result = Millimeters(227, 356); break; case PaperKind.BPlus: result = Millimeters(305, 487); break; case PaperKind.LetterPlus: result = Inches(8.5, 12.69); break; case PaperKind.A4Plus: result = Millimeters(210, 330); break; case PaperKind.A5Transverse: result = Millimeters(148, 210); break; case PaperKind.B5Transverse: result = Millimeters(182, 257); break; case PaperKind.A3Extra: result = Millimeters(322, 445); break; case PaperKind.A5Extra: result = Millimeters(174, 235); break; case PaperKind.B5Extra: result = Millimeters(201, 276); break; case PaperKind.A2: result = Millimeters(420, 594); break; case PaperKind.A3Transverse: result = Millimeters(297, 420); break; case PaperKind.A3ExtraTransverse: result = Millimeters(322, 445); break; case PaperKind.JapaneseDoublePostcard: result = Millimeters(200, 148); break; case PaperKind.A6: result = Millimeters(105, 148); break; case PaperKind.JapaneseEnvelopeKakuNumber2: result = Millimeters(240, 332); break; case PaperKind.JapaneseEnvelopeKakuNumber3: result = Millimeters(216, 277); break; case PaperKind.JapaneseEnvelopeChouNumber3: result = Millimeters(120, 235); break; case PaperKind.JapaneseEnvelopeChouNumber4: result = Millimeters(90, 205); break; case PaperKind.LetterRotated: result = Inches(11, 8.5); break; case PaperKind.A3Rotated: result = Millimeters(420, 297); break; case PaperKind.A4Rotated: result = Millimeters(297, 210); break; case PaperKind.A5Rotated: result = Millimeters(210, 148); break; case PaperKind.B4JISRotated: result = Millimeters(364, 257); break; case PaperKind.B5JISRotated: result = Millimeters(257, 182); break; case PaperKind.JapanesePostcardRotated: result = Millimeters(148, 100); break; case PaperKind.JapaneseDoublePostcardRotated: result = Millimeters(148, 200); break; case PaperKind.A6Rotated: result = Millimeters(148, 105); break; case PaperKind.JapaneseEnvelopeKakuNumber2Rotated: result = Millimeters(332, 240); break; case PaperKind.JapaneseEnvelopeKakuNumber3Rotated: result = Millimeters(277, 216); break; case PaperKind.JapaneseEnvelopeChouNumber3Rotated: result = Millimeters(235, 120); break; case PaperKind.JapaneseEnvelopeChouNumber4Rotated: result = Millimeters(205, 90); break; case PaperKind.B6JIS: result = Millimeters(128, 182); break; case PaperKind.B6JISRotated: result = Millimeters(182, 128); break; case PaperKind.Standard12x11: result = Inches(12, 11); break; case PaperKind.JapaneseEnvelopeYouNumber4: result = Millimeters(105, 235); break; case PaperKind.JapaneseEnvelopeYouNumber4Rotated: result = Millimeters(235, 105); break; case PaperKind.PRC16K: result = Millimeters(146, 215); break; case PaperKind.PRC32K: result = Millimeters(97, 151); break; case PaperKind.PRC32KBig: result = Millimeters(97, 151); break; case PaperKind.PRCEnvelopeNumber1: result = Millimeters(102, 165); break; case PaperKind.PRCEnvelopeNumber2: result = Millimeters(102, 176); break; case PaperKind.PRCEnvelopeNumber3: result = Millimeters(125, 176); break; case PaperKind.PRCEnvelopeNumber4: result = Millimeters(110, 208); break; case PaperKind.PRCEnvelopeNumber5: result = Millimeters(110, 220); break; case PaperKind.PRCEnvelopeNumber6: result = Millimeters(120, 230); break; case PaperKind.PRCEnvelopeNumber7: result = Millimeters(160, 230); break; case PaperKind.PRCEnvelopeNumber8: result = Millimeters(120, 309); break; case PaperKind.PRCEnvelopeNumber9: result = Millimeters(229, 324); break; case PaperKind.PRCEnvelopeNumber10: result = Millimeters(324, 458); break; case PaperKind.PRC16KRotated: result = Millimeters(215, 146); break; case PaperKind.PRC32KRotated: result = Millimeters(151, 97); break; case PaperKind.PRC32KBigRotated: result = Millimeters(151, 97); break; case PaperKind.PRCEnvelopeNumber1Rotated: result = Millimeters(165, 102); break; case PaperKind.PRCEnvelopeNumber2Rotated: result = Millimeters(176, 102); break; case PaperKind.PRCEnvelopeNumber3Rotated: result = Millimeters(176, 125); break; case PaperKind.PRCEnvelopeNumber4Rotated: result = Millimeters(208, 110); break; case PaperKind.PRCEnvelopeNumber5Rotated: result = Millimeters(220, 110); break; case PaperKind.PRCEnvelopeNumber6Rotated: result = Millimeters(230, 120); break; case PaperKind.PRCEnvelopeNumber7Rotated: result = Millimeters(230, 160); break; case PaperKind.PRCEnvelopeNumber8Rotated: result = Millimeters(309, 120); break; case PaperKind.PRCEnvelopeNumber9Rotated: result = Millimeters(324, 229); break; case PaperKind.PRCEnvelopeNumber10Rotated: result = Millimeters(458, 324); break; default: Debug.Fail("Unknown paper kind " + unchecked((int) kind)); result = new Point(0, 0); break; } return result; } } private static Point Inches(double width, double height) { Debug.Assert(width < 20 && height < 20, "You said inches, but you probably meant millimeters (" + width + ", " + height + ")"); float conversion = 254; return new Point((int) (width * conversion), (int) (height * conversion)); } private static Point Millimeters(double width, double height) { Debug.Assert(width > 20 && height > 20, "You said millimeters, but you probably meant inches (" + width + ", " + height + ")"); float conversion = 10; return new Point((int) (width * conversion), (int) (height * conversion)); } #endif /// <include file='doc\PaperSize.uex' path='docs/doc[@for="PaperSize.ToString"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Provides some interesting information about the PaperSize in /// String form. /// </para> /// </devdoc> public override string ToString() { return "[PaperSize " + PaperName + " Kind=" + unchecked(TypeDescriptor.GetConverter(typeof(PaperKind)).ConvertToString((int) Kind)) + " Height=" + Height.ToString(CultureInfo.InvariantCulture) + " Width=" + Width.ToString(CultureInfo.InvariantCulture) + "]"; } } }
using Hangfire; using Hangfire.Server; using Microsoft.Extensions.Options; using MongoDB.Driver; using MongoDB.Driver.Linq; using Newtonsoft.Json.Linq; using ShareDB; using ShareDB.RichText; using SIL.XForge.WebApi.Server.DataAccess; using SIL.XForge.WebApi.Server.Models; using SIL.XForge.WebApi.Server.Models.Translate; using SIL.XForge.WebApi.Server.Options; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; namespace SIL.XForge.WebApi.Server.Services { public class SendReceiveRunner { private readonly IRepository<User> _userRepo; private readonly IRepository<SendReceiveJob> _jobRepo; private readonly IRepository<TranslateProject> _projectRepo; private readonly ParatextService _paratextService; private readonly IOptions<SendReceiveOptions> _options; private readonly IProjectRepositoryFactory<TranslateDocumentSet> _docSetRepoFactory; public SendReceiveRunner(IOptions<SendReceiveOptions> options, IRepository<User> userRepo, IRepository<SendReceiveJob> jobRepo, IRepository<TranslateProject> projectRepo, ParatextService paratextService, IProjectRepositoryFactory<TranslateDocumentSet> docSetRepoFactory) { _options = options; _userRepo = userRepo; _jobRepo = jobRepo; _projectRepo = projectRepo; _paratextService = paratextService; _docSetRepoFactory = docSetRepoFactory; } public async Task RunAsync(PerformContext context, IJobCancellationToken cancellationToken, string userId, string jobId) { SendReceiveJob job = await _jobRepo.UpdateAsync(j => j.Id == jobId, u => u .Set(j => j.BackgroundJobId, context.BackgroundJob.Id) .Set(j => j.State, SendReceiveJob.SyncingState)); if (job == null) return; try { SendReceiveOptions options = _options.Value; if ((await _userRepo.TryGetAsync(userId)).TryResult(out User user)) { if ((await _projectRepo.TryGetAsync(job.ProjectRef)).TryResult(out TranslateProject project)) { if (!Directory.Exists(options.TranslateDir)) Directory.CreateDirectory(options.TranslateDir); IRepository<TranslateDocumentSet> docSetRepo = _docSetRepoFactory.Create(project); using (var conn = new Connection(new Uri(options.ShareDBUrl))) { await conn.ConnectAsync(); ParatextProject sourceParatextProject = project.Config.Source.ParatextProject; IReadOnlyList<string> sourceBookIds = await GetBooksAsync(user, sourceParatextProject); ParatextProject targetParatextProject = project.Config.Target.ParatextProject; IReadOnlyList<string> targetBookIds = await GetBooksAsync(user, targetParatextProject); string[] bookIds = sourceBookIds.Intersect(targetBookIds).ToArray(); int processedCount = 0; foreach (string bookId in bookIds) { await SendReceiveBookAsync(user, conn, project, docSetRepo, sourceParatextProject, "source", bookId); await SendReceiveBookAsync(user, conn, project, docSetRepo, targetParatextProject, "target", bookId); processedCount++; double percentCompleted = ((double) processedCount / bookIds.Length) * 100.0; job = await _jobRepo.UpdateAsync(job, u => u .Set(j => j.PercentCompleted, percentCompleted)); } DeleteBookTextFiles(project, sourceParatextProject, sourceBookIds); DeleteBookTextFiles(project, targetParatextProject, targetBookIds); await conn.CloseAsync(); } job = await _jobRepo.UpdateAsync(job, u => u .Set(j => j.State, SendReceiveJob.IdleState) .Unset(j => j.BackgroundJobId)); await _projectRepo.UpdateAsync(project, u => u.Set(p => p.LastSyncedDate, job.DateModified)); } } } catch (Exception) { await _jobRepo.UpdateAsync(job, u => u .Set(j => j.State, SendReceiveJob.HoldState) .Unset(j => j.BackgroundJobId)); } } private async Task<IReadOnlyList<string>> GetBooksAsync(User user, ParatextProject paratextProject) { if ((await _paratextService.TryGetBooksAsync(user, paratextProject.Id)) .TryResult(out IReadOnlyList<string> bookIds)) { return bookIds; } throw new InvalidOperationException("Error occurred while getting list of books from ParaTExt server."); } private void DeleteBookTextFiles(TranslateProject project, ParatextProject paratextProject, IEnumerable<string> bookIds) { string projectPath = GetProjectPath(project, paratextProject); var booksToRemove = new HashSet<string>(Directory.EnumerateFiles(projectPath) .Select(p => Path.GetFileNameWithoutExtension(p))); booksToRemove.ExceptWith(bookIds); foreach (string bookId in booksToRemove) File.Delete(GetBookTextFileName(projectPath, bookId)); } private async Task SendReceiveBookAsync(User user, Connection conn, TranslateProject project, IRepository<TranslateDocumentSet> docSetRepo, ParatextProject paratextProject, string docType, string bookId) { string projectPath = GetProjectPath(project, paratextProject); if (!Directory.Exists(projectPath)) Directory.CreateDirectory(projectPath); TranslateDocumentSet docSet = await docSetRepo.Query() .FirstOrDefaultAsync(ds => ds.BookId == bookId && !ds.IsDeleted); if (docSet == null) { // TODO: get book name from book id docSet = new TranslateDocumentSet { Name = bookId, BookId = bookId }; await docSetRepo.InsertAsync(docSet); } Document<Delta> doc = GetShareDBDocument(conn, project, docSet, docType); string fileName = GetBookTextFileName(projectPath, bookId); if (File.Exists(fileName)) await SyncBookAsync(user, paratextProject, fileName, bookId, doc); else await CloneBookAsync(user, paratextProject, fileName, bookId, doc); } private async Task SyncBookAsync(User user, ParatextProject paratextProject, string fileName, string bookId, Document<Delta> doc) { await doc.FetchAsync(); XElement bookTextElem = await LoadBookTextAsync(fileName); XElement oldUsxElem = bookTextElem.Element("usx"); XElement bookElem = oldUsxElem.Element("book"); XElement newUsxElem = DeltaUsxMapper.ToUsx((string) oldUsxElem.Attribute("version"), (string) bookElem.Attribute("code"), (string) bookElem, doc.Data); var revision = (string) bookTextElem.Attribute("revision"); string bookText; if (XNode.DeepEquals(oldUsxElem, newUsxElem)) { if (!(await _paratextService.TryGetBookTextAsync(user, paratextProject.Id, bookId)) .TryResult(out bookText)) { throw new InvalidOperationException("Error occurred while getting book text from ParaTExt server."); } } else if (!(await _paratextService.TryUpdateBookTextAsync(user, paratextProject.Id, bookId, revision, newUsxElem.ToString())).TryResult(out bookText)) { throw new InvalidOperationException("Error occurred while updating book text on ParaTExt server."); } bookTextElem = XElement.Parse(bookText); Delta delta = DeltaUsxMapper.ToDelta(bookTextElem.Element("usx")); Delta diffDelta = doc.Data.Diff(delta); await doc.SubmitOpAsync(diffDelta); await SaveBookTextAsync(bookTextElem, fileName); } private async Task CloneBookAsync(User user, ParatextProject paratextProject, string fileName, string bookId, Document<Delta> doc) { if (!(await _paratextService.TryGetBookTextAsync(user, paratextProject.Id, bookId)) .TryResult(out string bookText)) { throw new InvalidOperationException("Error occurred while getting book text from ParaTExt server."); } var bookTextElem = XElement.Parse(bookText); Delta delta = DeltaUsxMapper.ToDelta(bookTextElem.Element("usx")); await doc.CreateAsync(delta); await SaveBookTextAsync(bookTextElem, fileName); } private async Task<XElement> LoadBookTextAsync(string fileName) { using (var stream = new FileStream(fileName, FileMode.Open)) { return await XElement.LoadAsync(stream, LoadOptions.None, CancellationToken.None); } } private async Task SaveBookTextAsync(XElement bookTextElem, string fileName) { using (var stream = new FileStream(fileName, FileMode.Create)) { await bookTextElem.SaveAsync(stream, SaveOptions.None, CancellationToken.None); } } private string GetProjectPath(TranslateProject project, ParatextProject paratextProject) { return Path.Combine(_options.Value.TranslateDir, project.ProjectCode, paratextProject.Id); } private string GetBookTextFileName(string projectPath, string bookId) { return Path.Combine(projectPath, bookId + ".xml"); } private Document<Delta> GetShareDBDocument(Connection conn, TranslateProject project, TranslateDocumentSet docSet, string docType) { return conn.Get<Delta>($"sf_{project.ProjectCode}", $"{docSet.Id}:{docType}"); } } }
using UnityEngine; using System.Collections.Generic; using Pathfinding.WindowsStore; using System; #if NETFX_CORE using System.Linq; using WinRTLegacy; #endif namespace Pathfinding.Serialization { public class JsonMemberAttribute : System.Attribute {} public class JsonOptInAttribute : System.Attribute {} /** A very tiny json serializer. * It is not supposed to have lots of features, it is only intended to be able to serialize graph settings * well enough. */ public class TinyJsonSerializer { System.Text.StringBuilder output = new System.Text.StringBuilder(); Dictionary<Type, Action<System.Object> > serializers = new Dictionary<Type, Action<object> >(); static readonly System.Globalization.CultureInfo invariantCulture = System.Globalization.CultureInfo.InvariantCulture; public static void Serialize (System.Object obj, System.Text.StringBuilder output) { new TinyJsonSerializer() { output = output }.Serialize(obj); } TinyJsonSerializer () { serializers[typeof(float)] = v => output.Append(((float)v).ToString("R", invariantCulture)); serializers[typeof(bool)] = v => output.Append((bool)v ? "true" : "false"); serializers[typeof(Version)] = serializers[typeof(uint)] = serializers[typeof(int)] = v => output.Append(v.ToString()); serializers[typeof(string)] = v => output.AppendFormat("\"{0}\"", v.ToString().Replace("\"", "\\\"")); serializers[typeof(Vector2)] = v => output.AppendFormat("{{ \"x\": {0}, \"y\": {1} }}", ((Vector2)v).x.ToString("R", invariantCulture), ((Vector2)v).y.ToString("R", invariantCulture)); serializers[typeof(Vector3)] = v => output.AppendFormat("{{ \"x\": {0}, \"y\": {1}, \"z\": {2} }}", ((Vector3)v).x.ToString("R", invariantCulture), ((Vector3)v).y.ToString("R", invariantCulture), ((Vector3)v).z.ToString("R", invariantCulture)); serializers[typeof(Pathfinding.Util.Guid)] = v => output.AppendFormat("{{ \"value\": \"{0}\" }}", v.ToString()); serializers[typeof(LayerMask)] = v => output.AppendFormat("{{ \"value\": {0} }}", ((int)(LayerMask)v).ToString()); } void Serialize (System.Object obj) { if (obj == null) { output.Append("null"); return; } var type = obj.GetType(); var typeInfo = WindowsStoreCompatibility.GetTypeInfo(type); if (serializers.ContainsKey(type)) { serializers[type] (obj); } else if (typeInfo.IsEnum) { output.Append('"' + obj.ToString() + '"'); } else if (obj is System.Collections.IList) { output.Append("["); var arr = obj as System.Collections.IList; for (int i = 0; i < arr.Count; i++) { if (i != 0) output.Append(", "); Serialize(arr[i]); } output.Append("]"); } else if (obj is UnityEngine.Object) { SerializeUnityObject(obj as UnityEngine.Object); } else { #if NETFX_CORE var optIn = tpInfo.CustomAttributes.Any(attr => attr.GetType() == typeof(JsonOptInAttribute)); #else var optIn = typeInfo.GetCustomAttributes(typeof(JsonOptInAttribute), true).Length > 0; #endif output.Append("{"); #if NETFX_CORE var fields = tpInfo.DeclaredFields.Where(f => !f.IsStatic).ToArray(); #else var fields = type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); #endif bool earlier = false; foreach (var field in fields) { if ((!optIn && field.IsPublic) || #if NETFX_CORE field.CustomAttributes.Any(attr => attr.GetType() == typeof(JsonMemberAttribute)) #else field.GetCustomAttributes(typeof(JsonMemberAttribute), true).Length > 0 #endif ) { if (earlier) { output.Append(", "); } earlier = true; output.AppendFormat("\"{0}\": ", field.Name); Serialize(field.GetValue(obj)); } } output.Append("}"); } } void QuotedField (string name, string contents) { output.AppendFormat("\"{0}\": \"{1}\"", name, contents); } void SerializeUnityObject (UnityEngine.Object obj) { // Note that a unityengine can be destroyed as well if (obj == null) { Serialize(null); return; } output.Append("{"); QuotedField("Name", obj.name); output.Append(", "); QuotedField("Type", obj.GetType().FullName); //Write scene path if the object is a Component or GameObject var component = obj as Component; var go = obj as GameObject; if (component != null || go != null) { if (component != null && go == null) { go = component.gameObject; } var helper = go.GetComponent<UnityReferenceHelper>(); if (helper == null) { Debug.Log("Adding UnityReferenceHelper to Unity Reference '"+obj.name+"'"); helper = go.AddComponent<UnityReferenceHelper>(); } //Make sure it has a unique GUID helper.Reset(); output.Append(", "); QuotedField("GUID", helper.GetGUID().ToString()); } output.Append("}"); } } /** A very tiny json deserializer. * It is not supposed to have lots of features, it is only intended to be able to deserialize graph settings * well enough. Not much validation of the input is done. */ public class TinyJsonDeserializer { System.IO.TextReader reader; static readonly System.Globalization.NumberFormatInfo numberFormat = System.Globalization.NumberFormatInfo.InvariantInfo; /** Deserializes an object of the specified type. * Will load all fields into the \a populate object if it is set (only works for classes). */ public static System.Object Deserialize (string text, Type type, System.Object populate = null) { return new TinyJsonDeserializer() { reader = new System.IO.StringReader(text) }.Deserialize(type, populate); } /** Deserializes an object of type tp. * Will load all fields into the \a populate object if it is set (only works for classes). */ System.Object Deserialize (Type tp, System.Object populate = null) { var tpInfo = WindowsStoreCompatibility.GetTypeInfo(tp); if (tpInfo.IsEnum) { return Enum.Parse(tp, EatField()); } else if (TryEat('n')) { Eat("ull"); TryEat(','); return null; } else if (Type.Equals(tp, typeof(float))) { return float.Parse(EatField(), numberFormat); } else if (Type.Equals(tp, typeof(int))) { return int.Parse(EatField(), numberFormat); } else if (Type.Equals(tp, typeof(uint))) { return uint.Parse(EatField(), numberFormat); } else if (Type.Equals(tp, typeof(bool))) { return bool.Parse(EatField()); } else if (Type.Equals(tp, typeof(string))) { return EatField(); } else if (Type.Equals(tp, typeof(Version))) { return new Version(EatField()); } else if (Type.Equals(tp, typeof(Vector2))) { Eat("{"); var result = new Vector2(); EatField(); result.x = float.Parse(EatField(), numberFormat); EatField(); result.y = float.Parse(EatField(), numberFormat); Eat("}"); return result; } else if (Type.Equals(tp, typeof(Vector3))) { Eat("{"); var result = new Vector3(); EatField(); result.x = float.Parse(EatField(), numberFormat); EatField(); result.y = float.Parse(EatField(), numberFormat); EatField(); result.z = float.Parse(EatField(), numberFormat); Eat("}"); return result; } else if (Type.Equals(tp, typeof(Pathfinding.Util.Guid))) { Eat("{"); EatField(); var result = Pathfinding.Util.Guid.Parse(EatField()); Eat("}"); return result; } else if (Type.Equals(tp, typeof(LayerMask))) { Eat("{"); EatField(); var result = (LayerMask)int.Parse(EatField()); Eat("}"); return result; } else if (Type.Equals(tp, typeof(List<string>))) { System.Collections.IList result = new List<string>(); Eat("["); while (!TryEat(']')) { result.Add(Deserialize(typeof(string))); TryEat(','); } return result; } else if (tpInfo.IsArray) { List<System.Object> ls = new List<System.Object>(); Eat("["); while (!TryEat(']')) { ls.Add(Deserialize(tp.GetElementType())); TryEat(','); } var arr = Array.CreateInstance(tp.GetElementType(), ls.Count); ls.ToArray().CopyTo(arr, 0); return arr; } else if (Type.Equals(tp, typeof(Mesh)) || Type.Equals(tp, typeof(Texture2D)) || Type.Equals(tp, typeof(Transform)) || Type.Equals(tp, typeof(GameObject))) { return DeserializeUnityObject(); } else { var obj = populate ?? Activator.CreateInstance(tp); Eat("{"); while (!TryEat('}')) { var name = EatField(); var field = tp.GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); if (field == null) { SkipFieldData(); } else { field.SetValue(obj, Deserialize(field.FieldType)); } TryEat(','); } return obj; } } UnityEngine.Object DeserializeUnityObject () { Eat("{"); var result = DeserializeUnityObjectInner(); Eat("}"); return result; } UnityEngine.Object DeserializeUnityObjectInner () { // Ignore InstanceID field (compatibility only) var fieldName = EatField(); if (fieldName == "InstanceID") { EatField(); fieldName = EatField(); } if (fieldName != "Name") throw new Exception("Expected 'Name' field"); string name = EatField(); if (name == null) return null; if (EatField() != "Type") throw new Exception("Expected 'Type' field"); string typename = EatField(); // Remove assembly information if (typename.IndexOf(',') != -1) { typename = typename.Substring(0, typename.IndexOf(',')); } // Note calling through assembly is more stable on e.g WebGL var type = WindowsStoreCompatibility.GetTypeInfo(typeof(AstarPath)).Assembly.GetType(typename); type = type ?? WindowsStoreCompatibility.GetTypeInfo(typeof(Transform)).Assembly.GetType(typename); if (Type.Equals(type, null)) { Debug.LogError("Could not find type '"+typename+"'. Cannot deserialize Unity reference"); return null; } // Check if there is another field there EatWhitespace(); if ((char)reader.Peek() == '"') { if (EatField() != "GUID") throw new Exception("Expected 'GUID' field"); string guid = EatField(); foreach (var helper in UnityEngine.Object.FindObjectsOfType<UnityReferenceHelper>()) { if (helper.GetGUID() == guid) { if (Type.Equals(type, typeof(GameObject))) { return helper.gameObject; } else { return helper.GetComponent(type); } } } } // Try to load from resources UnityEngine.Object[] objs = Resources.LoadAll(name, type); for (int i = 0; i < objs.Length; i++) { if (objs[i].name == name || objs.Length == 1) { return objs[i]; } } return null; } void EatWhitespace () { while (char.IsWhiteSpace((char)reader.Peek())) reader.Read(); } void Eat (string s) { EatWhitespace(); for (int i = 0; i < s.Length; i++) { var c = (char)reader.Read(); if (c != s[i]) { throw new Exception("Expected '" + s[i] + "' found '" + c + "'\n\n..." + reader.ReadLine()); } } } System.Text.StringBuilder builder = new System.Text.StringBuilder(); string EatUntil (string c, bool inString) { builder.Length = 0; bool escape = false; while (true) { var readInt = reader.Peek(); if (!escape && (char)readInt == '"') { inString = !inString; } var readChar = (char)readInt; if (readInt == -1) { throw new Exception("Unexpected EOF"); } else if (!escape && readChar == '\\') { escape = true; reader.Read(); } else if (!inString && c.IndexOf(readChar) != -1) { break; } else { builder.Append(readChar); reader.Read(); escape = false; } } return builder.ToString(); } bool TryEat (char c) { EatWhitespace(); if ((char)reader.Peek() == c) { reader.Read(); return true; } return false; } string EatField () { var result = EatUntil("\",}]", TryEat('"')); TryEat('\"'); TryEat(':'); TryEat(','); return result; } void SkipFieldData () { var indent = 0; while (true) { EatUntil(",{}[]", false); var last = (char)reader.Peek(); switch (last) { case '{': case '[': indent++; break; case '}': case ']': indent--; if (indent < 0) return; break; case ',': if (indent == 0) { reader.Read(); return; } break; default: throw new System.Exception("Should not reach this part"); } reader.Read(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System.Collections.ObjectModel { [Serializable] [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ReadOnlyCollection<T> : IList<T>, IList, IReadOnlyList<T> { private IList<T> list; // Do not rename (binary serialization) public ReadOnlyCollection(IList<T> list) { if (list == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } this.list = list; } public int Count { get { return list.Count; } } public T this[int index] { get { return list[index]; } } public bool Contains(T value) { return list.Contains(value); } public void CopyTo(T[] array, int index) { list.CopyTo(array, index); } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } public int IndexOf(T value) { return list.IndexOf(value); } protected IList<T> Items { get { return list; } } bool ICollection<T>.IsReadOnly { get { return true; } } T IList<T>.this[int index] { get { return list[index]; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } void ICollection<T>.Add(T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<T>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList<T>.Insert(int index, T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<T>.Remove(T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } void IList<T>.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)list).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return (list is ICollection coll) ? coll.SyncRoot : this; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } if (array is T[] items) { list.CopyTo(items, index); } else { // // Catch the obvious case assignment will fail. // We can't find all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType()!; Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object?[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = list.Count; try { for (int i = 0; i < count; i++) { objects[index++] = list[i]; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } object? IList.this[int index] { get { return list[index]; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } int IList.Add(object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return -1; } void IList.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } private static bool IsCompatibleObject(object? value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T)! == null)); } bool IList.Contains(object? value) { if (IsCompatibleObject(value)) { return Contains((T)value!); } return false; } int IList.IndexOf(object? value) { if (IsCompatibleObject(value)) { return IndexOf((T)value!); } return -1; } void IList.Insert(int index, object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList.Remove(object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { public partial class RangeAttributeTests { #region Shared specs public static IEnumerable<Type> TestedParameterTypes() => new[] { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal) }; // See XML docs for the ParamAttributeTypeConversions class. private static readonly Type[] Int32RangeConvertibleToParameterTypes = { typeof(int), typeof(sbyte), typeof(byte), typeof(short), typeof(decimal), typeof(long), typeof(double) }; private static readonly Type[] UInt32RangeConvertibleToParameterTypes = { typeof(uint) }; private static readonly Type[] Int64RangeConvertibleToParameterTypes = { typeof(long) }; private static readonly Type[] UInt64RangeConvertibleToParameterTypes = { typeof(ulong) }; private static readonly Type[] SingleRangeConvertibleToParameterTypes = { typeof(float) }; private static readonly Type[] DoubleRangeConvertibleToParameterTypes = { typeof(double), typeof(decimal) }; #endregion [Test] public void MultipleAttributes() { Test test = TestBuilder.MakeParameterizedMethodSuite(typeof(RangeTestFixture), nameof(RangeTestFixture.MethodWithMultipleRanges)); var arguments = from testCase in test.Tests select testCase.Arguments[0]; Assert.That(arguments, Is.EquivalentTo(new[] { 1, 2, 3, 10, 11, 12 })); } #region Forward public static IEnumerable<RangeWithExpectedConversions> ForwardRangeCases => new[] { new RangeWithExpectedConversions(new RangeAttribute(11, 15), Int32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11u, 15u), UInt32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11L, 15L), Int64RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11UL, 15UL), UInt64RangeConvertibleToParameterTypes) }; [Test] public static void ForwardRange( [ValueSource(nameof(ForwardRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions, [ValueSource(nameof(TestedParameterTypes))] Type parameterType) { rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence( parameterType, new[] { 11, 12, 13, 14, 15 }); } #endregion #region Backward public static IEnumerable<RangeWithExpectedConversions> BackwardRangeCases => new[] { new RangeWithExpectedConversions(new RangeAttribute(15, 11), Int32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(15L, 11L), Int64RangeConvertibleToParameterTypes) }; [Test] public static void BackwardRange( [ValueSource(nameof(BackwardRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions, [ValueSource(nameof(TestedParameterTypes))] Type parameterType) { rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence( parameterType, new[] { 15, 14, 13, 12, 11 }); } [Test] public static void BackwardRangeDisallowed_UInt32() { Assert.That(() => new RangeAttribute(15u, 11u), Throws.InstanceOf<ArgumentException>()); } [Test] public static void BackwardRangeDisallowed_UInt64() { Assert.That(() => new RangeAttribute(15UL, 11UL), Throws.InstanceOf<ArgumentException>()); } #endregion #region Degenerate public static IEnumerable<RangeWithExpectedConversions> DegenerateRangeCases => new[] { new RangeWithExpectedConversions(new RangeAttribute(11, 11), Int32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11u, 11u), UInt32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11L, 11L), Int64RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11UL, 11UL), UInt64RangeConvertibleToParameterTypes) }; [Test] public static void DegenerateRange( [ValueSource(nameof(DegenerateRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions, [ValueSource(nameof(TestedParameterTypes))] Type parameterType) { rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence( parameterType, new[] { 11 }); } public static IEnumerable<RangeWithExpectedConversions> DegeneratePositiveStepRangeCases => new[] { new RangeWithExpectedConversions(new RangeAttribute(11, 11, 2), Int32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11u, 11u, 2u), UInt32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11L, 11L, 2L), Int64RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11UL, 11UL, 2UL), UInt64RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11f, 11f, 2f), SingleRangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11d, 11d, 2d), DoubleRangeConvertibleToParameterTypes) }; [Test] public static void DegeneratePositiveStepRangeDisallowed_Int32( [ValueSource(nameof(DegeneratePositiveStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions, [ValueSource(nameof(TestedParameterTypes))] Type parameterType) { rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence( parameterType, new[] { 11 }); } public static IEnumerable<RangeWithExpectedConversions> DegenerateNegativeStepRangeCases => new[] { new RangeWithExpectedConversions(new RangeAttribute(11, 11, -2), Int32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11L, 11L, -2L), Int64RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11f, 11f, -2f), SingleRangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11d, 11d, -2d), DoubleRangeConvertibleToParameterTypes) }; [Test] public static void DegenerateNegativeStepRange( [ValueSource(nameof(DegenerateNegativeStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions, [ValueSource(nameof(TestedParameterTypes))] Type parameterType) { rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence( parameterType, new[] { 11 }); } [Test] public static void DegenerateZeroStepRangeDisallowed_Int32() { Assert.That(() => new RangeAttribute(11, 11, 0), Throws.InstanceOf<ArgumentException>()); } [Test] public static void DegenerateZeroStepRangeDisallowed_Int64() { Assert.That(() => new RangeAttribute(11L, 11L, 0L), Throws.InstanceOf<ArgumentException>()); } [Test] public static void DegenerateZeroStepRangeDisallowed_Single() { Assert.That(() => new RangeAttribute(11f, 11f, 0f), Throws.InstanceOf<ArgumentException>()); } [Test] public static void DegenerateZeroStepRangeDisallowed_Double() { Assert.That(() => new RangeAttribute(11d, 11d, 0d), Throws.InstanceOf<ArgumentException>()); } #endregion #region Forward step public static IEnumerable<RangeWithExpectedConversions> ForwardStepRangeCases => new[] { new RangeWithExpectedConversions(new RangeAttribute(11, 15, 2), Int32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11u, 15u, 2u), UInt32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11L, 15L, 2L), Int64RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11UL, 15UL, 2UL), UInt64RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11f, 15f, 2f), SingleRangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(11d, 15d, 2d), DoubleRangeConvertibleToParameterTypes) }; [Test] public static void ForwardStepRange( [ValueSource(nameof(ForwardStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions, [ValueSource(nameof(TestedParameterTypes))] Type parameterType) { rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence( parameterType, new[] { 11, 13, 15 }); } #endregion #region Backward step public static IEnumerable<RangeWithExpectedConversions> BackwardStepRangeCases => new[] { new RangeWithExpectedConversions(new RangeAttribute(15, 11, -2), Int32RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(15L, 11L, -2L), Int64RangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(15f, 11f, -2f), SingleRangeConvertibleToParameterTypes), new RangeWithExpectedConversions(new RangeAttribute(15d, 11d, -2d), DoubleRangeConvertibleToParameterTypes) }; [Test] public static void BackwardStepRange( [ValueSource(nameof(BackwardStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions, [ValueSource(nameof(TestedParameterTypes))] Type parameterType) { rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence( parameterType, new[] { 15, 13, 11 }); } #endregion #region Zero step [Test] public static void ZeroStepRangeDisallowed_Int32() { Assert.That(() => new RangeAttribute(11, 15, 0), Throws.InstanceOf<ArgumentException>()); } [Test] public static void ZeroStepRangeDisallowed_UInt32() { Assert.That(() => new RangeAttribute(11u, 15u, 0u), Throws.InstanceOf<ArgumentException>()); } [Test] public static void ZeroStepRangeDisallowed_Int64() { Assert.That(() => new RangeAttribute(11L, 15L, 0L), Throws.InstanceOf<ArgumentException>()); } [Test] public static void ZeroStepRangeDisallowed_UInt64() { Assert.That(() => new RangeAttribute(11UL, 15UL, 0UL), Throws.InstanceOf<ArgumentException>()); } [Test] public static void ZeroStepRangeDisallowed_Single() { Assert.That(() => new RangeAttribute(11f, 15f, 0f), Throws.InstanceOf<ArgumentException>()); } [Test] public static void ZeroStepRangeDisallowed_Double() { Assert.That(() => new RangeAttribute(11d, 15d, 0d), Throws.InstanceOf<ArgumentException>()); } #endregion #region Opposing step [Test] public static void OpposingStepForwardRangeDisallowed_Int32() { Assert.That(() => new RangeAttribute(11, 15, -2), Throws.InstanceOf<ArgumentException>()); } [Test] public static void OpposingStepBackwardRangeDisallowed_Int32() { Assert.That(() => new RangeAttribute(15, 11, 2), Throws.InstanceOf<ArgumentException>()); } [Test] public static void OppositeStepForwardRangeDisallowed_Int64() { Assert.That(() => new RangeAttribute(11L, 15L, -2L), Throws.InstanceOf<ArgumentException>()); } [Test] public static void OpposingStepBackwardRangeDisallowed_Int64() { Assert.That(() => new RangeAttribute(15L, 11L, 2L), Throws.InstanceOf<ArgumentException>()); } [Test] public static void OppositeStepForwardRangeDisallowed_Single() { Assert.That(() => new RangeAttribute(11f, 15f, -2f), Throws.InstanceOf<ArgumentException>()); } [Test] public static void OpposingStepBackwardRangeDisallowed_Single() { Assert.That(() => new RangeAttribute(15f, 11f, 2f), Throws.InstanceOf<ArgumentException>()); } [Test] public static void OppositeForwardRangeDisallowed_Double() { Assert.That(() => new RangeAttribute(11d, 15d, -2d), Throws.InstanceOf<ArgumentException>()); } [Test] public static void OpposingStepBackwardRangeDisallowed_Double() { Assert.That(() => new RangeAttribute(15d, 11d, 2d), Throws.InstanceOf<ArgumentException>()); } #endregion // The smallest distance from MaxValue or MinValue which results in a different number, // overcoming loss of precision. // Calculated by hand by flipping bits. Used the round-trip format and double-checked. private const float SingleExtremaEpsilon = 2.028241E+31f; private const double DoubleExtremaEpsilon = 1.99584030953472E+292; private const double LargestDoubleConvertibleToDecimal = 7.9228162514264329E+28; private const double NextLargestDoubleConvertibleToLowerDecimal = 7.92281625142642E+28; #region MaxValue [Test] public static void MaxValueRange_Byte() { Assert.That( GetData(new RangeAttribute(byte.MaxValue - 2, byte.MaxValue), typeof(byte)), Is.EqualTo(new[] { byte.MaxValue - 2, byte.MaxValue - 1, byte.MaxValue })); } [Test] public static void MaxValueRange_SByte() { Assert.That( GetData(new RangeAttribute(sbyte.MaxValue - 2, sbyte.MaxValue), typeof(sbyte)), Is.EqualTo(new[] { sbyte.MaxValue - 2, sbyte.MaxValue - 1, sbyte.MaxValue })); } [Test] public static void MaxValueRange_Int16() { Assert.That( GetData(new RangeAttribute(short.MaxValue - 2, short.MaxValue), typeof(short)), Is.EqualTo(new[] { short.MaxValue - 2, short.MaxValue - 1, short.MaxValue })); } [Test] public static void MaxValueRange_Int32() { Assert.That( GetData(new RangeAttribute(int.MaxValue - 2, int.MaxValue), typeof(int)), Is.EqualTo(new[] { int.MaxValue - 2, int.MaxValue - 1, int.MaxValue })); } [Test] public static void MaxValueRange_UInt32() { Assert.That( GetData(new RangeAttribute(uint.MaxValue - 2, uint.MaxValue), typeof(uint)), Is.EqualTo(new[] { uint.MaxValue - 2, uint.MaxValue - 1, uint.MaxValue })); } [Test] public static void MaxValueRange_Int64() { Assert.That( GetData(new RangeAttribute(long.MaxValue - 2, long.MaxValue), typeof(long)), Is.EqualTo(new[] { long.MaxValue - 2, long.MaxValue - 1, long.MaxValue })); } [Test] public static void MaxValueRange_UInt64() { Assert.That( GetData(new RangeAttribute(ulong.MaxValue - 2, ulong.MaxValue), typeof(ulong)), Is.EqualTo(new[] { ulong.MaxValue - 2, ulong.MaxValue - 1, ulong.MaxValue })); } [Test] public static void MaxValueRange_Single() { Assert.That( GetData(new RangeAttribute(float.MaxValue - SingleExtremaEpsilon * 2, float.MaxValue, SingleExtremaEpsilon), typeof(float)), Is.EqualTo(new[] { float.MaxValue - SingleExtremaEpsilon * 2, float.MaxValue - SingleExtremaEpsilon, float.MaxValue })); } [Test] public static void MaxValueRangeLosingPrecision_Single() { Assert.That(() => GetData(new RangeAttribute(float.MaxValue - SingleExtremaEpsilon, float.MaxValue, SingleExtremaEpsilon / 2), typeof(float)), Throws.InstanceOf<ArithmeticException>()); } [Test] public static void MaxValueRange_Double() { Assert.That( GetData(new RangeAttribute(double.MaxValue - DoubleExtremaEpsilon * 2, double.MaxValue, DoubleExtremaEpsilon), typeof(double)), Is.EqualTo(new[] { double.MaxValue - DoubleExtremaEpsilon * 2, double.MaxValue - DoubleExtremaEpsilon, double.MaxValue })); } [Test] public static void MaxValueRangeLosingPrecision_Double() { Assert.That(() => GetData(new RangeAttribute(double.MaxValue - DoubleExtremaEpsilon, double.MaxValue, DoubleExtremaEpsilon / 2), typeof(double)), Throws.InstanceOf<ArithmeticException>()); } [Test] public static void MaxValueRange_Decimal() { const decimal fromDecimal = (decimal)NextLargestDoubleConvertibleToLowerDecimal; const decimal toDecimal = (decimal)LargestDoubleConvertibleToDecimal; const double step = (double)((toDecimal - fromDecimal) / 2); Assert.That( GetData(new RangeAttribute(NextLargestDoubleConvertibleToLowerDecimal, LargestDoubleConvertibleToDecimal, step), typeof(decimal)), Is.EqualTo(new[] { fromDecimal, fromDecimal + (decimal)step, fromDecimal + (decimal)step * 2 })); } [Test] public static void MaxValueRangeLosingPrecision_Decimal() { Assert.That(() => GetData(new RangeAttribute(NextLargestDoubleConvertibleToLowerDecimal, LargestDoubleConvertibleToDecimal, 0.1), typeof(decimal)), Throws.InstanceOf<ArithmeticException>()); } #endregion #region MinValue [Test] public static void MinValueRange_Byte() { Assert.That( GetData(new RangeAttribute(byte.MinValue + 2, byte.MinValue), typeof(byte)), Is.EqualTo(new[] { byte.MinValue + 2, byte.MinValue + 1, byte.MinValue })); } [Test] public static void MinValueRange_SByte() { Assert.That( GetData(new RangeAttribute(sbyte.MinValue + 2, sbyte.MinValue), typeof(sbyte)), Is.EqualTo(new[] { sbyte.MinValue + 2, sbyte.MinValue + 1, sbyte.MinValue })); } [Test] public static void MinValueRange_Int16() { Assert.That( GetData(new RangeAttribute(short.MinValue + 2, short.MinValue), typeof(short)), Is.EqualTo(new[] { short.MinValue + 2, short.MinValue + 1, short.MinValue })); } [Test] public static void MinValueRange_Int32() { Assert.That( GetData(new RangeAttribute(int.MinValue + 2, int.MinValue), typeof(int)), Is.EqualTo(new[] { int.MinValue + 2, int.MinValue + 1, int.MinValue })); } [Test] public static void MinValueRange_Int64() { Assert.That( GetData(new RangeAttribute(long.MinValue + 2, long.MinValue), typeof(long)), Is.EqualTo(new[] { long.MinValue + 2, long.MinValue + 1, long.MinValue })); } [Test] public static void MinValueRange_Single() { Assert.That( GetData(new RangeAttribute(float.MinValue + SingleExtremaEpsilon * 2, float.MinValue, -SingleExtremaEpsilon), typeof(float)), Is.EqualTo(new[] { float.MinValue + SingleExtremaEpsilon * 2, float.MinValue + SingleExtremaEpsilon, float.MinValue })); } [Test] public static void MinValueRangeLosingPrecision_Single() { Assert.That(() => GetData(new RangeAttribute(float.MinValue + SingleExtremaEpsilon, float.MinValue, -SingleExtremaEpsilon / 2), typeof(float)), Throws.InstanceOf<ArithmeticException>()); } [Test] public static void MinValueRange_Double() { Assert.That( GetData(new RangeAttribute(double.MinValue + DoubleExtremaEpsilon * 2, double.MinValue, -DoubleExtremaEpsilon), typeof(double)), Is.EqualTo(new[] { double.MinValue + DoubleExtremaEpsilon * 2, double.MinValue + DoubleExtremaEpsilon, double.MinValue })); } [Test] public static void MinValueRangeLosingPrecision_Double() { Assert.That(() => GetData(new RangeAttribute(double.MinValue + DoubleExtremaEpsilon, double.MinValue, -DoubleExtremaEpsilon / 2), typeof(double)), Throws.InstanceOf<ArithmeticException>()); } [Test] public static void MinValueRange_Decimal() { const decimal fromDecimal = -(decimal)NextLargestDoubleConvertibleToLowerDecimal; const decimal toDecimal = -(decimal)LargestDoubleConvertibleToDecimal; const double step = (double)((toDecimal - fromDecimal) / 2); Assert.That( GetData(new RangeAttribute(-NextLargestDoubleConvertibleToLowerDecimal, -LargestDoubleConvertibleToDecimal, step), typeof(decimal)), Is.EqualTo(new[] { fromDecimal, fromDecimal + (decimal)step, fromDecimal + (decimal)step * 2 })); } [Test] public static void MinValueRangeLosingPrecision_Decimal() { Assert.That(() => GetData(new RangeAttribute(-NextLargestDoubleConvertibleToLowerDecimal, -LargestDoubleConvertibleToDecimal, -0.1), typeof(decimal)), Throws.InstanceOf<ArithmeticException>()); } #endregion private static object[] GetData(RangeAttribute rangeAttribute, Type parameterType) { return rangeAttribute.GetData(new StubParameterInfo(parameterType)).Cast<object>().ToArray(); } private sealed class StubParameterInfo : IParameterInfo { public StubParameterInfo(Type parameterType) { ParameterType = parameterType; } public Type ParameterType { get; } public bool IsOptional { get { throw new NotImplementedException(); } } public IMethodInfo Method { get { throw new NotImplementedException(); } } public ParameterInfo ParameterInfo { get { throw new NotImplementedException(); } } public T[] GetCustomAttributes<T>(bool inherit) where T : class { throw new NotImplementedException(); } public bool IsDefined<T>(bool inherit) where T : class { throw new NotImplementedException(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Research.DataStructures { using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; using System.Linq; using System.Diagnostics.Contracts; /// <summary> /// A dummy empty type like void that can be used for generic instances /// </summary> public struct Unit : IEquatable<Unit> { public static readonly Unit Value; // Thread-safe #region IEquatable<Unit> Members public bool Equals(Unit other) { return true; } #endregion } /// <summary> /// An abstraction over sequences /// </summary> public partial interface IIndexable<T> { int Count { get; } T this[int index] { get; } } #region IIndexable contract binding [ContractClass(typeof(IIndexableContract<>))] public partial interface IIndexable<T> { } [ContractClassFor(typeof(IIndexable<>))] internal abstract class IIndexableContract<T> : IIndexable<T> { public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new NotImplementedException(); } } public T this[int index] { get { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); throw new NotImplementedException(); } } } #endregion public struct IndexableEnumerable<T, IndexT> : IEnumerable<T> where IndexT : IIndexable<T> { private IndexT indexable; public IndexableEnumerable(IndexT indexable) { Contract.Requires(indexable != null); this.indexable = indexable; } public struct Enumerator : IEnumerator<T> { private IndexT indexable; private int position; public Enumerator(IndexT indexable) { this.indexable = indexable; position = -1; } public T Current { get { if (position >= 0 && position < indexable.Count) { return this.indexable[position]; } throw new InvalidOperationException(); } } object System.Collections.IEnumerator.Current { get { return this.Current; } } public bool MoveNext() { position++; return position < indexable.Count; } public void Reset() { position = -1; } void IDisposable.Dispose() { } } public Enumerator GetEnumerator() { return new Enumerator(indexable); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } } [Serializable] public struct EmptyIndexable<T> : IIndexable<T>, IEnumerable<T> { #region IIndexable<T> Members public int Count { get { return 0; } } public T this[int index] { get { throw new IndexOutOfRangeException(); } } #endregion public static readonly EmptyIndexable<T> Empty = new EmptyIndexable<T>(); // Thread-safe public IEnumerator<T> GetEnumerator() { yield break; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { yield break; } } public struct ThreeValued { private int value; // 0 undetermined, 1 false, 2 true public ThreeValued(bool truth) { if (truth) value = 2; else value = 1; } public bool IsTrue { get { return value == 2; } } public bool IsFalse { get { return value == 1; } } public bool IsDetermined { get { return value != 0; } } public bool Truth { get { if (IsTrue) return true; if (IsFalse) return false; throw new InvalidOperationException(); } } } [Serializable] public struct UnitIndexable : IIndexable<Unit>, IEnumerable<Unit> { private int count; [ContractInvariantMethod] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")] private void ObjectInvariant() { Contract.Invariant(count >= 0); } public UnitIndexable(int count) { Contract.Requires(count >= 0); this.count = count; } #region IIndexable<Unit> Members public int Count { get { return count; } } public Unit this[int index] { get { return Unit.Value; } } #endregion #region IEnumerable<Unit> Members public IEnumerator<Unit> GetEnumerator() { for (int i = 0; i < count; i++) { yield return Unit.Value; } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { for (int i = 0; i < count; i++) { yield return Unit.Value; } } #endregion } [Serializable] public struct TailIndexable<T> : IIndexable<T>, IEnumerable<T> { private IIndexable<T> underlying; [ContractInvariantMethod] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")] private void ObjectInvariant() { Contract.Invariant(underlying != null); } public TailIndexable(IIndexable<T> underlying) { Contract.Requires(underlying != null); this.underlying = underlying; } #region IIndexable<T> Members public int Count { get { Contract.Ensures(Contract.Result<int>() == 0 || Contract.Result<int>() == underlying.Count - 1); var c = underlying.Count; if (c > 0) return c - 1; return 0; } } public T this[int index] { get { Contract.Assert(this.Count > 0, "helping the static checker"); return underlying[index + 1]; } } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return this[i]; } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion } [Serializable] public struct ArrayIndexable<T> : IIndexable<T>, IEnumerable<T> { private T[]/*?*/ array; public ArrayIndexable(T[]/*?*/ array) { Contract.Ensures(array == null && Contract.ValueAtReturn(out this).Count == 0 || Contract.ValueAtReturn(out this).Count == array.Length); this.array = array; } public int Count { get { Contract.Ensures(Contract.Result<int>() == 0 || array != null && Contract.Result<int>() == array.Length); return (array == null) ? 0 : array.Length; } } public T this[int index] { get { Contract.Assert(this.Count > 0, "helping the static checker"); return array[index]; } } #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return array[i]; } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion } [Serializable] public struct EnumerableIndexable<T> : IIndexable<T>, IEnumerable<T> { private List<T> list; [NonSerialized] private IEnumerator<T> enumerator; /// <summary> /// Produce an IIndexable from the given IEnumerable. The IEnumerable is expanded on /// demand up to capacity elements. The count of the IIndexable is the minimum of either the /// actual number of elements in the enumeration, or the capacity specified. /// </summary> /// <param name="capacity">maximal expansion</param> public EnumerableIndexable(IEnumerable<T> enumerable, int maxCapacity) { Contract.Requires(enumerable != null); Contract.Requires(maxCapacity >= 0); list = new List<T>(maxCapacity); enumerator = enumerable.GetEnumerator(); } /// <summary> /// Does enumerate the full enumerable and computes the final list /// </summary> /// <param name="enumerable"></param> public EnumerableIndexable(IEnumerable<T> enumerable) { Contract.Requires(enumerable != null); list = enumerable.ToList(); enumerator = null; } public T this[int index] { get { tryAgain: if (index >= list.Count) { if (enumerator != null && index < list.Capacity) { if (enumerator.MoveNext()) { list.Add(enumerator.Current); goto tryAgain; } else { enumerator = null; } } // done enumerating throw new IndexOutOfRangeException(); } return list[index]; } } public int Count { get { ForceEnumeration(); return list.Count; } } private void ForceEnumeration() { while (enumerator != null && list.Count < list.Capacity) { if (enumerator.MoveNext()) { list.Add(enumerator.Current); } else { enumerator = null; } } } [System.Runtime.Serialization.OnSerializing] private void OnSerializing(System.Runtime.Serialization.StreamingContext context) { this.ForceEnumeration(); } #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return this[i]; } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion } [Serializable] public struct ListIndexable<T> : IIndexable<T>, IEnumerable<T> { private List<T> list; [ContractInvariantMethod] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")] private void ObjectInvariant() { Contract.Invariant(list != null); } public ListIndexable(List<T> list) { Contract.Requires(list != null); Contract.Ensures(Contract.ValueAtReturn(out this).Count == list.Count); this.list = list; } public int Count { get { Contract.Ensures(Contract.Result<int>() == list.Count); return list.Count; } } public T this[int index] { get { Contract.Assert(this.Count > 0, "help static checker"); return list[index]; } } #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion } public static class IndexableExtensions { public static IndexableEnumerable<T, IIndexable<T>> Enumerate<T>(this IIndexable<T> arg) { return new IndexableEnumerable<T, IIndexable<T>>(arg); } public static EnumerableIndexable<T> AsIndexable<T>(this IEnumerable<T> arg, int capacity) { return new EnumerableIndexable<T>(arg, capacity); } public static EnumerableIndexable<T> AsIndexable<T>(this IEnumerable<T> arg) { return new EnumerableIndexable<T>(arg); } public static EnumerableIndexable<T> AsIndexable<From, T>(this IEnumerable<From> arg, Func<From, T> convert) { return new EnumerableIndexable<T>(arg.Select(convert)); } public static ListIndexable<T> AsIndexable<T>(this List<T> list) { return new ListIndexable<T>(list); } public static TailIndexable<T> Tail<T>(this IIndexable<T> underlying) { return new TailIndexable<T>(underlying); } public static ArrayIndexable<T> AsIndexable<T>(this T[] array) { return new ArrayIndexable<T>(array); } } /// <summary> /// Optional struct that works for all T, not just value types. /// </summary> [Serializable] public struct Optional<T> { public readonly bool IsValid; private T value; public Optional(T value) { this.value = value; IsValid = true; } public T Value { get { return value; } } public static implicit operator Optional<T>(T value) { return new Optional<T>(value); } } public interface IVisibilityCheck<Member> { bool IsAsVisibleAs(Member member); bool IsVisibleFrom(Member member); bool RootImpliesParameterOrResultOrStatic { get; } bool IsTopOfStack(int localStackDepth); bool IsStackTemp { get; } } /// <summary> /// Filter for access paths /// </summary> public class AccessPathFilter<Member, Type> { private enum MemberFilter { NO_FILTER, FROM_PRECONDITION, FROM_POSTCONDITION, FROM_INSIDE_METHOD, FROM_INSIDE_METHOD_OR_CALLED_POST, } [Flags] private enum Flags { AllowLocals = 0x01, RequireParameter = 0x02, AvoidCompilerGenerated = 0x04 } private readonly Member member; private readonly MemberFilter memberFilter; private readonly Flags flags; private Type returnType; public int LocalStackDepth { get; private set; } public static AccessPathFilter<Member, Type> NoFilter = new AccessPathFilter<Member, Type>(); // Thread-safe public static AccessPathFilter<Member, Type> FromPrecondition(Member member) { Contract.Ensures(Contract.Result<AccessPathFilter<Member, Type>>() != null); return new AccessPathFilter<Member, Type>(member, MemberFilter.FROM_PRECONDITION); } public static AccessPathFilter<Member, Type> FromPostcondition(Member member, Type returnType) { Contract.Ensures(Contract.Result<AccessPathFilter<Member, Type>>() != null); return new AccessPathFilter<Member, Type>(member, MemberFilter.FROM_POSTCONDITION, returnType) { LocalStackDepth = 1 }; } public static AccessPathFilter<Member, Type> IsVisibleFrom(Member member) { Contract.Ensures(Contract.Result<AccessPathFilter<Member, Type>>() != null); return new AccessPathFilter<Member, Type>(member, MemberFilter.FROM_INSIDE_METHOD); } public static AccessPathFilter<Member, Type> IsVisibleFromMethodOrCalledPost(Member member, Type returnType, int localStackDepth) { Contract.Ensures(Contract.Result<AccessPathFilter<Member, Type>>() != null); return new AccessPathFilter<Member, Type>(member, MemberFilter.FROM_INSIDE_METHOD_OR_CALLED_POST, returnType) { LocalStackDepth = localStackDepth }; } private AccessPathFilter(Member member, MemberFilter memberFilter) { this.member = member; this.memberFilter = memberFilter; } private AccessPathFilter(Member member, MemberFilter memberFilter, Type returnType) : this(member, memberFilter) { // We do not want compiler generated in postconditions if (memberFilter.HasFlag(MemberFilter.FROM_POSTCONDITION)) { flags |= Flags.AvoidCompilerGenerated; } this.returnType = returnType; } private AccessPathFilter() { flags |= Flags.AllowLocals; memberFilter = MemberFilter.NO_FILTER; } public bool FilterOutPathElement<P>(P element) where P : IVisibilityCheck<Member> { switch (memberFilter) { case MemberFilter.FROM_INSIDE_METHOD: return element.IsStackTemp || !element.IsVisibleFrom(member); case MemberFilter.FROM_PRECONDITION: return element.IsStackTemp || !element.IsAsVisibleAs(member); case MemberFilter.FROM_POSTCONDITION: return !element.RootImpliesParameterOrResultOrStatic || !element.IsVisibleFrom(member); case MemberFilter.FROM_INSIDE_METHOD_OR_CALLED_POST: return element.IsStackTemp && !element.IsTopOfStack(this.LocalStackDepth) || !element.IsVisibleFrom(member); case MemberFilter.NO_FILTER: default: return element.IsStackTemp; // ignore stack temporaries (s0, s1, ...) } } public bool AllowLocal { get { return (memberFilter == MemberFilter.NO_FILTER && ((flags & Flags.AllowLocals) != 0)) || memberFilter == MemberFilter.FROM_INSIDE_METHOD || memberFilter == MemberFilter.FROM_INSIDE_METHOD_OR_CALLED_POST; } } public bool AvoidCompilerGenerated { get { return (flags & Flags.AvoidCompilerGenerated) != 0; } } public bool HasVisibilityMember { get { return memberFilter != MemberFilter.NO_FILTER; } } public bool AllowReturnValue { get { switch (memberFilter) { case MemberFilter.FROM_INSIDE_METHOD_OR_CALLED_POST: case MemberFilter.FROM_POSTCONDITION: return true; default: return false; } } } /// <summary> /// Returns the underlying member used to determine visibility. /// </summary> public Member VisibilityMember { get { return member; } } public Type ReturnValueType { get { Contract.Requires(this.AllowReturnValue); return returnType; } } public bool AllowCompilerLocal { get { return memberFilter == MemberFilter.FROM_INSIDE_METHOD_OR_CALLED_POST; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A vector of type bool with 4 components. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct bvec4 : IEnumerable<bool>, IEquatable<bvec4> { #region Fields /// <summary> /// x-component /// </summary> public bool x; /// <summary> /// y-component /// </summary> public bool y; /// <summary> /// z-component /// </summary> public bool z; /// <summary> /// w-component /// </summary> public bool w; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public bvec4(bool x, bool y, bool z, bool w) { this.x = x; this.y = y; this.z = z; this.w = w; } /// <summary> /// all-same-value constructor /// </summary> public bvec4(bool v) { this.x = v; this.y = v; this.z = v; this.w = v; } /// <summary> /// from-vector constructor (empty fields are zero/false) /// </summary> public bvec4(bvec2 v) { this.x = v.x; this.y = v.y; this.z = false; this.w = false; } /// <summary> /// from-vector-and-value constructor (empty fields are zero/false) /// </summary> public bvec4(bvec2 v, bool z) { this.x = v.x; this.y = v.y; this.z = z; this.w = false; } /// <summary> /// from-vector-and-value constructor /// </summary> public bvec4(bvec2 v, bool z, bool w) { this.x = v.x; this.y = v.y; this.z = z; this.w = w; } /// <summary> /// from-vector constructor (empty fields are zero/false) /// </summary> public bvec4(bvec3 v) { this.x = v.x; this.y = v.y; this.z = v.z; this.w = false; } /// <summary> /// from-vector-and-value constructor /// </summary> public bvec4(bvec3 v, bool w) { this.x = v.x; this.y = v.y; this.z = v.z; this.w = w; } /// <summary> /// from-vector constructor /// </summary> public bvec4(bvec4 v) { this.x = v.x; this.y = v.y; this.z = v.z; this.w = v.w; } /// <summary> /// Generic from-array constructor (superfluous values are ignored, missing values are zero-filled). /// </summary> public bvec4(Object[] v) { var c = v.Length; this.x = c < 0 ? false : (bool)v[0]; this.y = c < 1 ? false : (bool)v[1]; this.z = c < 2 ? false : (bool)v[2]; this.w = c < 3 ? false : (bool)v[3]; } /// <summary> /// From-array constructor (superfluous values are ignored, missing values are zero-filled). /// </summary> public bvec4(bool[] v) { var c = v.Length; this.x = c < 0 ? false : v[0]; this.y = c < 1 ? false : v[1]; this.z = c < 2 ? false : v[2]; this.w = c < 3 ? false : v[3]; } /// <summary> /// From-array constructor with base index (superfluous values are ignored, missing values are zero-filled). /// </summary> public bvec4(bool[] v, int startIndex) { var c = v.Length; this.x = c + startIndex < 0 ? false : v[0 + startIndex]; this.y = c + startIndex < 1 ? false : v[1 + startIndex]; this.z = c + startIndex < 2 ? false : v[2 + startIndex]; this.w = c + startIndex < 3 ? false : v[3 + startIndex]; } /// <summary> /// From-IEnumerable constructor (superfluous values are ignored, missing values are zero-filled). /// </summary> public bvec4(IEnumerable<bool> v) : this(new List<bool>(v).ToArray()) { } #endregion #region Explicit Operators /// <summary> /// Explicitly converts this to a ivec2. /// </summary> public static explicit operator ivec2(bvec4 v) => new ivec2(v.x ? 1 : 0, v.y ? 1 : 0); /// <summary> /// Explicitly converts this to a ivec3. /// </summary> public static explicit operator ivec3(bvec4 v) => new ivec3(v.x ? 1 : 0, v.y ? 1 : 0, v.z ? 1 : 0); /// <summary> /// Explicitly converts this to a ivec4. /// </summary> public static explicit operator ivec4(bvec4 v) => new ivec4(v.x ? 1 : 0, v.y ? 1 : 0, v.z ? 1 : 0, v.w ? 1 : 0); /// <summary> /// Explicitly converts this to a uvec2. /// </summary> public static explicit operator uvec2(bvec4 v) => new uvec2(v.x ? 1u : 0u, v.y ? 1u : 0u); /// <summary> /// Explicitly converts this to a uvec3. /// </summary> public static explicit operator uvec3(bvec4 v) => new uvec3(v.x ? 1u : 0u, v.y ? 1u : 0u, v.z ? 1u : 0u); /// <summary> /// Explicitly converts this to a uvec4. /// </summary> public static explicit operator uvec4(bvec4 v) => new uvec4(v.x ? 1u : 0u, v.y ? 1u : 0u, v.z ? 1u : 0u, v.w ? 1u : 0u); /// <summary> /// Explicitly converts this to a vec2. /// </summary> public static explicit operator vec2(bvec4 v) => new vec2(v.x ? 1f : 0f, v.y ? 1f : 0f); /// <summary> /// Explicitly converts this to a vec3. /// </summary> public static explicit operator vec3(bvec4 v) => new vec3(v.x ? 1f : 0f, v.y ? 1f : 0f, v.z ? 1f : 0f); /// <summary> /// Explicitly converts this to a vec4. /// </summary> public static explicit operator vec4(bvec4 v) => new vec4(v.x ? 1f : 0f, v.y ? 1f : 0f, v.z ? 1f : 0f, v.w ? 1f : 0f); /// <summary> /// Explicitly converts this to a hvec2. /// </summary> public static explicit operator hvec2(bvec4 v) => new hvec2(v.x ? Half.One : Half.Zero, v.y ? Half.One : Half.Zero); /// <summary> /// Explicitly converts this to a hvec3. /// </summary> public static explicit operator hvec3(bvec4 v) => new hvec3(v.x ? Half.One : Half.Zero, v.y ? Half.One : Half.Zero, v.z ? Half.One : Half.Zero); /// <summary> /// Explicitly converts this to a hvec4. /// </summary> public static explicit operator hvec4(bvec4 v) => new hvec4(v.x ? Half.One : Half.Zero, v.y ? Half.One : Half.Zero, v.z ? Half.One : Half.Zero, v.w ? Half.One : Half.Zero); /// <summary> /// Explicitly converts this to a dvec2. /// </summary> public static explicit operator dvec2(bvec4 v) => new dvec2(v.x ? 1.0 : 0.0, v.y ? 1.0 : 0.0); /// <summary> /// Explicitly converts this to a dvec3. /// </summary> public static explicit operator dvec3(bvec4 v) => new dvec3(v.x ? 1.0 : 0.0, v.y ? 1.0 : 0.0, v.z ? 1.0 : 0.0); /// <summary> /// Explicitly converts this to a dvec4. /// </summary> public static explicit operator dvec4(bvec4 v) => new dvec4(v.x ? 1.0 : 0.0, v.y ? 1.0 : 0.0, v.z ? 1.0 : 0.0, v.w ? 1.0 : 0.0); /// <summary> /// Explicitly converts this to a decvec2. /// </summary> public static explicit operator decvec2(bvec4 v) => new decvec2(v.x ? 1m : 0m, v.y ? 1m : 0m); /// <summary> /// Explicitly converts this to a decvec3. /// </summary> public static explicit operator decvec3(bvec4 v) => new decvec3(v.x ? 1m : 0m, v.y ? 1m : 0m, v.z ? 1m : 0m); /// <summary> /// Explicitly converts this to a decvec4. /// </summary> public static explicit operator decvec4(bvec4 v) => new decvec4(v.x ? 1m : 0m, v.y ? 1m : 0m, v.z ? 1m : 0m, v.w ? 1m : 0m); /// <summary> /// Explicitly converts this to a lvec2. /// </summary> public static explicit operator lvec2(bvec4 v) => new lvec2(v.x ? 1 : 0, v.y ? 1 : 0); /// <summary> /// Explicitly converts this to a lvec3. /// </summary> public static explicit operator lvec3(bvec4 v) => new lvec3(v.x ? 1 : 0, v.y ? 1 : 0, v.z ? 1 : 0); /// <summary> /// Explicitly converts this to a lvec4. /// </summary> public static explicit operator lvec4(bvec4 v) => new lvec4(v.x ? 1 : 0, v.y ? 1 : 0, v.z ? 1 : 0, v.w ? 1 : 0); /// <summary> /// Explicitly converts this to a bvec2. /// </summary> public static explicit operator bvec2(bvec4 v) => new bvec2((bool)v.x, (bool)v.y); /// <summary> /// Explicitly converts this to a bvec3. /// </summary> public static explicit operator bvec3(bvec4 v) => new bvec3((bool)v.x, (bool)v.y, (bool)v.z); /// <summary> /// Explicitly converts this to a bool array. /// </summary> public static explicit operator bool[](bvec4 v) => new [] { v.x, v.y, v.z, v.w }; /// <summary> /// Explicitly converts this to a generic object array. /// </summary> public static explicit operator Object[](bvec4 v) => new Object[] { v.x, v.y, v.z, v.w }; #endregion #region Indexer /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public bool this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: throw new ArgumentOutOfRangeException("index"); } } set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; case 3: w = value; break; default: throw new ArgumentOutOfRangeException("index"); } } } #endregion #region Properties /// <summary> /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy) /// </summary> public swizzle_bvec4 swizzle => new swizzle_bvec4(x, y, z, w); /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 xy { get { return new bvec2(x, y); } set { x = value.x; y = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 xz { get { return new bvec2(x, z); } set { x = value.x; z = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 yz { get { return new bvec2(y, z); } set { y = value.x; z = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec3 xyz { get { return new bvec3(x, y, z); } set { x = value.x; y = value.y; z = value.z; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 xw { get { return new bvec2(x, w); } set { x = value.x; w = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 yw { get { return new bvec2(y, w); } set { y = value.x; w = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec3 xyw { get { return new bvec3(x, y, w); } set { x = value.x; y = value.y; w = value.z; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 zw { get { return new bvec2(z, w); } set { z = value.x; w = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec3 xzw { get { return new bvec3(x, z, w); } set { x = value.x; z = value.y; w = value.z; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec3 yzw { get { return new bvec3(y, z, w); } set { y = value.x; z = value.y; w = value.z; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec4 xyzw { get { return new bvec4(x, y, z, w); } set { x = value.x; y = value.y; z = value.z; w = value.w; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 rg { get { return new bvec2(x, y); } set { x = value.x; y = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 rb { get { return new bvec2(x, z); } set { x = value.x; z = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 gb { get { return new bvec2(y, z); } set { y = value.x; z = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec3 rgb { get { return new bvec3(x, y, z); } set { x = value.x; y = value.y; z = value.z; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 ra { get { return new bvec2(x, w); } set { x = value.x; w = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 ga { get { return new bvec2(y, w); } set { y = value.x; w = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec3 rga { get { return new bvec3(x, y, w); } set { x = value.x; y = value.y; w = value.z; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec2 ba { get { return new bvec2(z, w); } set { z = value.x; w = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec3 rba { get { return new bvec3(x, z, w); } set { x = value.x; z = value.y; w = value.z; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec3 gba { get { return new bvec3(y, z, w); } set { y = value.x; z = value.y; w = value.z; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bvec4 rgba { get { return new bvec4(x, y, z, w); } set { x = value.x; y = value.y; z = value.z; w = value.w; } } /// <summary> /// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bool r { get { return x; } set { x = value; } } /// <summary> /// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bool g { get { return y; } set { y = value; } } /// <summary> /// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bool b { get { return z; } set { z = value; } } /// <summary> /// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public bool a { get { return w; } set { w = value; } } /// <summary> /// Returns an array with all values /// </summary> public bool[] Values => new[] { x, y, z, w }; /// <summary> /// Returns the number of components (4). /// </summary> public int Count => 4; /// <summary> /// Returns the minimal component of this vector. /// </summary> public bool MinElement => ((x && y) && (z && w)); /// <summary> /// Returns the maximal component of this vector. /// </summary> public bool MaxElement => ((x || y) || (z || w)); /// <summary> /// Returns true if all component are true. /// </summary> public bool All => ((x && y) && (z && w)); /// <summary> /// Returns true if any component is true. /// </summary> public bool Any => ((x || y) || (z || w)); #endregion #region Static Properties /// <summary> /// Predefined all-zero vector /// </summary> public static bvec4 Zero { get; } = new bvec4(false, false, false, false); /// <summary> /// Predefined all-ones vector /// </summary> public static bvec4 Ones { get; } = new bvec4(true, true, true, true); /// <summary> /// Predefined unit-X vector /// </summary> public static bvec4 UnitX { get; } = new bvec4(true, false, false, false); /// <summary> /// Predefined unit-Y vector /// </summary> public static bvec4 UnitY { get; } = new bvec4(false, true, false, false); /// <summary> /// Predefined unit-Z vector /// </summary> public static bvec4 UnitZ { get; } = new bvec4(false, false, true, false); /// <summary> /// Predefined unit-W vector /// </summary> public static bvec4 UnitW { get; } = new bvec4(false, false, false, true); #endregion #region Operators /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator==(bvec4 lhs, bvec4 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator!=(bvec4 lhs, bvec4 rhs) => !lhs.Equals(rhs); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public IEnumerator<bool> GetEnumerator() { yield return x; yield return y; yield return z; yield return w; } /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <summary> /// Returns a string representation of this vector using ', ' as a seperator. /// </summary> public override string ToString() => ToString(", "); /// <summary> /// Returns a string representation of this vector using a provided seperator. /// </summary> public string ToString(string sep) => ((x + sep + y) + sep + (z + sep + w)); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format provider for each component. /// </summary> public string ToString(string sep, IFormatProvider provider) => ((x.ToString(provider) + sep + y.ToString(provider)) + sep + (z.ToString(provider) + sep + w.ToString(provider))); /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(bvec4 rhs) => ((x.Equals(rhs.x) && y.Equals(rhs.y)) && (z.Equals(rhs.z) && w.Equals(rhs.w))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is bvec4 && Equals((bvec4) obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((x.GetHashCode()) * 2) ^ y.GetHashCode()) * 2) ^ z.GetHashCode()) * 2) ^ w.GetHashCode(); } } #endregion #region Static Functions /// <summary> /// Converts the string representation of the vector into a vector representation (using ', ' as a separator). /// </summary> public static bvec4 Parse(string s) => Parse(s, ", "); /// <summary> /// Converts the string representation of the vector into a vector representation (using a designated separator). /// </summary> public static bvec4 Parse(string s, string sep) { var kvp = s.Split(new[] { sep }, StringSplitOptions.None); if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts"); return new bvec4(bool.Parse(kvp[0].Trim()), bool.Parse(kvp[1].Trim()), bool.Parse(kvp[2].Trim()), bool.Parse(kvp[3].Trim())); } /// <summary> /// Tries to convert the string representation of the vector into a vector representation (using ', ' as a separator), returns false if string was invalid. /// </summary> public static bool TryParse(string s, out bvec4 result) => TryParse(s, ", ", out result); /// <summary> /// Tries to convert the string representation of the vector into a vector representation (using a designated separator), returns false if string was invalid. /// </summary> public static bool TryParse(string s, string sep, out bvec4 result) { result = Zero; if (string.IsNullOrEmpty(s)) return false; var kvp = s.Split(new[] { sep }, StringSplitOptions.None); if (kvp.Length != 4) return false; bool x = false, y = false, z = false, w = false; var ok = ((bool.TryParse(kvp[0].Trim(), out x) && bool.TryParse(kvp[1].Trim(), out y)) && (bool.TryParse(kvp[2].Trim(), out z) && bool.TryParse(kvp[3].Trim(), out w))); result = ok ? new bvec4(x, y, z, w) : Zero; return ok; } /// <summary> /// Returns a bvec4 with independent and identically distributed random true/false values (the probability for 'true' can be configured). /// </summary> public static bvec4 Random(Random random, float trueProbability = 0.5f) => new bvec4(random.NextDouble() < trueProbability, random.NextDouble() < trueProbability, random.NextDouble() < trueProbability, random.NextDouble() < trueProbability); #endregion #region Component-Wise Static Functions /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(bvec4 lhs, bvec4 rhs) => new bvec4(lhs.x == rhs.x, lhs.y == rhs.y, lhs.z == rhs.z, lhs.w == rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(bvec4 lhs, bool rhs) => new bvec4(lhs.x == rhs, lhs.y == rhs, lhs.z == rhs, lhs.w == rhs); /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(bool lhs, bvec4 rhs) => new bvec4(lhs == rhs.x, lhs == rhs.y, lhs == rhs.z, lhs == rhs.w); /// <summary> /// Returns a bvec from the application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(bool lhs, bool rhs) => new bvec4(lhs == rhs); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(bvec4 lhs, bvec4 rhs) => new bvec4(lhs.x != rhs.x, lhs.y != rhs.y, lhs.z != rhs.z, lhs.w != rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(bvec4 lhs, bool rhs) => new bvec4(lhs.x != rhs, lhs.y != rhs, lhs.z != rhs, lhs.w != rhs); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(bool lhs, bvec4 rhs) => new bvec4(lhs != rhs.x, lhs != rhs.y, lhs != rhs.z, lhs != rhs.w); /// <summary> /// Returns a bvec from the application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(bool lhs, bool rhs) => new bvec4(lhs != rhs); /// <summary> /// Returns a bvec4 from component-wise application of Not (!v). /// </summary> public static bvec4 Not(bvec4 v) => new bvec4(!v.x, !v.y, !v.z, !v.w); /// <summary> /// Returns a bvec from the application of Not (!v). /// </summary> public static bvec4 Not(bool v) => new bvec4(!v); /// <summary> /// Returns a bvec4 from component-wise application of And (lhs &amp;&amp; rhs). /// </summary> public static bvec4 And(bvec4 lhs, bvec4 rhs) => new bvec4(lhs.x && rhs.x, lhs.y && rhs.y, lhs.z && rhs.z, lhs.w && rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of And (lhs &amp;&amp; rhs). /// </summary> public static bvec4 And(bvec4 lhs, bool rhs) => new bvec4(lhs.x && rhs, lhs.y && rhs, lhs.z && rhs, lhs.w && rhs); /// <summary> /// Returns a bvec4 from component-wise application of And (lhs &amp;&amp; rhs). /// </summary> public static bvec4 And(bool lhs, bvec4 rhs) => new bvec4(lhs && rhs.x, lhs && rhs.y, lhs && rhs.z, lhs && rhs.w); /// <summary> /// Returns a bvec from the application of And (lhs &amp;&amp; rhs). /// </summary> public static bvec4 And(bool lhs, bool rhs) => new bvec4(lhs && rhs); /// <summary> /// Returns a bvec4 from component-wise application of Nand (!(lhs &amp;&amp; rhs)). /// </summary> public static bvec4 Nand(bvec4 lhs, bvec4 rhs) => new bvec4(!(lhs.x && rhs.x), !(lhs.y && rhs.y), !(lhs.z && rhs.z), !(lhs.w && rhs.w)); /// <summary> /// Returns a bvec4 from component-wise application of Nand (!(lhs &amp;&amp; rhs)). /// </summary> public static bvec4 Nand(bvec4 lhs, bool rhs) => new bvec4(!(lhs.x && rhs), !(lhs.y && rhs), !(lhs.z && rhs), !(lhs.w && rhs)); /// <summary> /// Returns a bvec4 from component-wise application of Nand (!(lhs &amp;&amp; rhs)). /// </summary> public static bvec4 Nand(bool lhs, bvec4 rhs) => new bvec4(!(lhs && rhs.x), !(lhs && rhs.y), !(lhs && rhs.z), !(lhs && rhs.w)); /// <summary> /// Returns a bvec from the application of Nand (!(lhs &amp;&amp; rhs)). /// </summary> public static bvec4 Nand(bool lhs, bool rhs) => new bvec4(!(lhs && rhs)); /// <summary> /// Returns a bvec4 from component-wise application of Or (lhs || rhs). /// </summary> public static bvec4 Or(bvec4 lhs, bvec4 rhs) => new bvec4(lhs.x || rhs.x, lhs.y || rhs.y, lhs.z || rhs.z, lhs.w || rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of Or (lhs || rhs). /// </summary> public static bvec4 Or(bvec4 lhs, bool rhs) => new bvec4(lhs.x || rhs, lhs.y || rhs, lhs.z || rhs, lhs.w || rhs); /// <summary> /// Returns a bvec4 from component-wise application of Or (lhs || rhs). /// </summary> public static bvec4 Or(bool lhs, bvec4 rhs) => new bvec4(lhs || rhs.x, lhs || rhs.y, lhs || rhs.z, lhs || rhs.w); /// <summary> /// Returns a bvec from the application of Or (lhs || rhs). /// </summary> public static bvec4 Or(bool lhs, bool rhs) => new bvec4(lhs || rhs); /// <summary> /// Returns a bvec4 from component-wise application of Nor (!(lhs || rhs)). /// </summary> public static bvec4 Nor(bvec4 lhs, bvec4 rhs) => new bvec4(!(lhs.x || rhs.x), !(lhs.y || rhs.y), !(lhs.z || rhs.z), !(lhs.w || rhs.w)); /// <summary> /// Returns a bvec4 from component-wise application of Nor (!(lhs || rhs)). /// </summary> public static bvec4 Nor(bvec4 lhs, bool rhs) => new bvec4(!(lhs.x || rhs), !(lhs.y || rhs), !(lhs.z || rhs), !(lhs.w || rhs)); /// <summary> /// Returns a bvec4 from component-wise application of Nor (!(lhs || rhs)). /// </summary> public static bvec4 Nor(bool lhs, bvec4 rhs) => new bvec4(!(lhs || rhs.x), !(lhs || rhs.y), !(lhs || rhs.z), !(lhs || rhs.w)); /// <summary> /// Returns a bvec from the application of Nor (!(lhs || rhs)). /// </summary> public static bvec4 Nor(bool lhs, bool rhs) => new bvec4(!(lhs || rhs)); /// <summary> /// Returns a bvec4 from component-wise application of Xor (lhs != rhs). /// </summary> public static bvec4 Xor(bvec4 lhs, bvec4 rhs) => new bvec4(lhs.x != rhs.x, lhs.y != rhs.y, lhs.z != rhs.z, lhs.w != rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of Xor (lhs != rhs). /// </summary> public static bvec4 Xor(bvec4 lhs, bool rhs) => new bvec4(lhs.x != rhs, lhs.y != rhs, lhs.z != rhs, lhs.w != rhs); /// <summary> /// Returns a bvec4 from component-wise application of Xor (lhs != rhs). /// </summary> public static bvec4 Xor(bool lhs, bvec4 rhs) => new bvec4(lhs != rhs.x, lhs != rhs.y, lhs != rhs.z, lhs != rhs.w); /// <summary> /// Returns a bvec from the application of Xor (lhs != rhs). /// </summary> public static bvec4 Xor(bool lhs, bool rhs) => new bvec4(lhs != rhs); /// <summary> /// Returns a bvec4 from component-wise application of Xnor (lhs == rhs). /// </summary> public static bvec4 Xnor(bvec4 lhs, bvec4 rhs) => new bvec4(lhs.x == rhs.x, lhs.y == rhs.y, lhs.z == rhs.z, lhs.w == rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of Xnor (lhs == rhs). /// </summary> public static bvec4 Xnor(bvec4 lhs, bool rhs) => new bvec4(lhs.x == rhs, lhs.y == rhs, lhs.z == rhs, lhs.w == rhs); /// <summary> /// Returns a bvec4 from component-wise application of Xnor (lhs == rhs). /// </summary> public static bvec4 Xnor(bool lhs, bvec4 rhs) => new bvec4(lhs == rhs.x, lhs == rhs.y, lhs == rhs.z, lhs == rhs.w); /// <summary> /// Returns a bvec from the application of Xnor (lhs == rhs). /// </summary> public static bvec4 Xnor(bool lhs, bool rhs) => new bvec4(lhs == rhs); #endregion #region Component-Wise Operator Overloads /// <summary> /// Returns a bvec4 from component-wise application of operator! (!v). /// </summary> public static bvec4 operator!(bvec4 v) => new bvec4(!v.x, !v.y, !v.z, !v.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&amp; (lhs &amp;&amp; rhs). /// </summary> public static bvec4 operator&(bvec4 lhs, bvec4 rhs) => new bvec4(lhs.x && rhs.x, lhs.y && rhs.y, lhs.z && rhs.z, lhs.w && rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&amp; (lhs &amp;&amp; rhs). /// </summary> public static bvec4 operator&(bvec4 lhs, bool rhs) => new bvec4(lhs.x && rhs, lhs.y && rhs, lhs.z && rhs, lhs.w && rhs); /// <summary> /// Returns a bvec4 from component-wise application of operator&amp; (lhs &amp;&amp; rhs). /// </summary> public static bvec4 operator&(bool lhs, bvec4 rhs) => new bvec4(lhs && rhs.x, lhs && rhs.y, lhs && rhs.z, lhs && rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator| (lhs || rhs). /// </summary> public static bvec4 operator|(bvec4 lhs, bvec4 rhs) => new bvec4(lhs.x || rhs.x, lhs.y || rhs.y, lhs.z || rhs.z, lhs.w || rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator| (lhs || rhs). /// </summary> public static bvec4 operator|(bvec4 lhs, bool rhs) => new bvec4(lhs.x || rhs, lhs.y || rhs, lhs.z || rhs, lhs.w || rhs); /// <summary> /// Returns a bvec4 from component-wise application of operator| (lhs || rhs). /// </summary> public static bvec4 operator|(bool lhs, bvec4 rhs) => new bvec4(lhs || rhs.x, lhs || rhs.y, lhs || rhs.z, lhs || rhs.w); #endregion } }
using System.Collections.Generic; using JoinRpg.Domain; namespace JoinRpg.DataModel.Mocks { public class MockedProject { public Project Project { get; } public CharacterGroup Group { get; } public User Player { get; } = new User() { UserId = 1, PrefferedName = "Player", Email = "player@example.com" }; public User Master { get; } = new User() { UserId = 2, PrefferedName = "Master", Email = "master@example.com" }; public ProjectField MasterOnlyField { get; } public ProjectField CharacterField { get; } public ProjectField ConditionalField { get; } public ProjectField HideForUnApprovedClaim { get; } public ProjectField PublicField { get; } public ProjectField ConditionalHeader { get; } public Character Character { get; } public Character CharacterWithoutGroup { get; } private static void FixProjectSubEntities(Project project1) { var id = 0; foreach (ProjectField field in project1.ProjectFields) { id++; field.ProjectFieldId = id; field.Project = project1; field.ProjectId = project1.ProjectId; } id = 0; foreach (Character field in project1.Characters) { id++; field.CharacterId = id; field.Project = project1; field.ProjectId = project1.ProjectId; } id = 0; foreach (var field in project1.CharacterGroups) { id++; field.CharacterGroupId = id; field.Project = project1; field.ProjectId = project1.ProjectId; } } public MockedProject() { MasterOnlyField = new ProjectField() { CanPlayerEdit = false, CanPlayerView = false, IsActive = true, ShowOnUnApprovedClaims = true }; CharacterField = new ProjectField() { CanPlayerEdit = true, CanPlayerView = true, IsActive = true, FieldBoundTo = FieldBoundTo.Character, ShowOnUnApprovedClaims = true, AvailableForCharacterGroupIds = new int[0] }; ConditionalField = new ProjectField() { CanPlayerEdit = true, CanPlayerView = true, IsActive = true, ShowOnUnApprovedClaims = true, FieldBoundTo = FieldBoundTo.Character, AvailableForCharacterGroupIds = new int[0] }; HideForUnApprovedClaim = new ProjectField() { CanPlayerEdit = true, CanPlayerView = true, IsActive = true, FieldBoundTo = FieldBoundTo.Character, ShowOnUnApprovedClaims = false, AvailableForCharacterGroupIds = new int[0] }; PublicField = new ProjectField() { CanPlayerEdit = false, CanPlayerView = true, IsPublic = true, IsActive = true, FieldBoundTo = FieldBoundTo.Character, AvailableForCharacterGroupIds = new int[0], ShowOnUnApprovedClaims = true, }; ConditionalHeader = new ProjectField() { CanPlayerEdit = true, CanPlayerView = true, IsActive = true, ShowOnUnApprovedClaims = true, FieldBoundTo = FieldBoundTo.Character, AvailableForCharacterGroupIds = new int[0], FieldType = ProjectFieldType.Header }; var characterFieldValue = new FieldWithValue(CharacterField, "Value"); var publicFieldValue = new FieldWithValue(PublicField, "Public"); Character = new Character { IsActive = true, IsAcceptingClaims = true, ParentCharacterGroupIds = new int[0] }; CharacterWithoutGroup = new Character { IsActive = true, IsAcceptingClaims = true, ParentCharacterGroupIds = new int[0] }; Group = new CharacterGroup() { AvaiableDirectSlots = 0, HaveDirectSlots = true }; Project = new Project() { Active = true, IsAcceptingClaims = true, ProjectAcls = new List<ProjectAcl> { ProjectAcl.CreateRootAcl(Master.UserId, isOwner: true) }, ProjectFields = new List<ProjectField>() { MasterOnlyField, CharacterField, ConditionalField, HideForUnApprovedClaim, PublicField, ConditionalHeader }, Characters = new List<Character>() { Character, CharacterWithoutGroup }, CharacterGroups = new List<CharacterGroup> { Group}, Claims = new List<Claim>() }; FixProjectSubEntities(Project); //That needs to happen after FixProjectSubEntities(..) Character.JsonData = new[] { characterFieldValue, publicFieldValue }.SerializeFields(); Character.ParentCharacterGroupIds = new[] {Group.CharacterGroupId}; ConditionalField.AvailableForCharacterGroupIds = new[] {Group.CharacterGroupId}; ConditionalHeader.AvailableForCharacterGroupIds = new[] { Group.CharacterGroupId }; } public Claim CreateClaim(Character mockCharacter, User mockUser) { var claim = new Claim { Project = Project, Character = mockCharacter, CharacterId = mockCharacter.CharacterId, Player = mockUser, PlayerUserId = mockUser.UserId }; Project.Claims.Add(claim); return claim; } public Claim CreateClaim(CharacterGroup mockGroup, User mockUser) { var claim = new Claim { Project = Project, CharacterGroupId = mockGroup.CharacterGroupId, Group = mockGroup, Player = mockUser, PlayerUserId = mockUser.UserId }; Project.Claims.Add(claim); return claim; } public Claim CreateApprovedClaim(Character character, User player) { var claim = CreateClaim(character, player); claim.ClaimStatus = Claim.Status.Approved; character.ApprovedClaim = claim; return claim; } } }
/* files.c - Transscription, recording and playback * Copyright (c) 1995-1997 Stefan Jokisch * * This file is part of Frotz. * * Frotz 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. * * Frotz 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 zword = System.UInt16; using zbyte = System.Byte; using Frotz; using Frotz.Constants; namespace Frotz.Generic { internal static class Files { internal static string script_name = General.DEFAULT_SCRIPT_NAME; internal static string command_name = General.DEFAULT_COMMAND_NAME; static int script_width = 0; static System.IO.StreamWriter sfp = null; static System.IO.StreamWriter rfp = null; static System.IO.FileStream pfp = null; #region Script /* * script_open * * Open the transscript file. 'AMFV' makes this more complicated as it * turns transscription on/off several times to exclude some text from * the transscription file. This wasn't a problem for the original V4 * interpreters which always sent transscription to the printer, but it * means a problem to modern interpreters that offer to open a new file * every time transscription is turned on. Our solution is to append to * the old transscription file in V1 to V4, and to ask for a new file * name in V5+. * */ static bool script_valid = false; internal static void script_open() { string new_name = null; main.h_flags &= (zword)~ZMachine.SCRIPTING_FLAG; if (main.h_version >= ZMachine.V5 || !script_valid) { if (os_.read_file_name(out new_name, General.DEFAULT_SCRIPT_NAME, FileTypes.FILE_SCRIPT) != true) goto done; script_name = new_name; } if ((sfp = new System.IO.StreamWriter(script_name, true)) != null) { main.h_flags |= ZMachine.SCRIPTING_FLAG; script_valid = true; main.ostream_script = true; script_width = 0; sfp.AutoFlush = true; } else Text.print_string("Cannot open file\n"); done: FastMem.SET_WORD(ZMachine.H_FLAGS, main.h_flags); }/* script_open */ /* * script_close * * Stop transscription. * */ internal static void script_close() { main.h_flags &= (ushort)~ZMachine.SCRIPTING_FLAG; FastMem.SET_WORD(ZMachine.H_FLAGS, main.h_flags); sfp.Close(); main.ostream_script = false; }/* script_close */ /* * script_new_line * * Write a newline to the transscript file. * */ internal static void script_new_line() { sfp.WriteLine(); script_width = 0; }/* script_new_line */ /* * script_char * * Write a single character to the transscript file. * */ internal static void script_char(zword c) { if (c == CharCodes.ZC_INDENT && script_width != 0) c = ' '; if (c == CharCodes.ZC_INDENT) { script_char(' '); script_char(' '); script_char(' '); return; } if (c == CharCodes.ZC_GAP) { script_char(' '); script_char(' '); return; } if (c > 0xff) { script_char('?'); return; } sfp.Write((char)c); script_width++; }/* script_char */ /* * script_word * * Write a string to the transscript file. * */ internal static void script_word(zword[] s) { int width; int i; int pos = 0; if (s[pos] == CharCodes.ZC_INDENT && script_width != 0) { script_char(s[pos++]); } for (i = pos, width = 0; i < s.Length && s[i] != 0; i++) { if (s[i] == CharCodes.ZC_NEW_STYLE || s[i] == CharCodes.ZC_NEW_FONT) i++; else if (s[i] == CharCodes.ZC_GAP) width += 3; else if (s[i] == CharCodes.ZC_INDENT) width += 2; else width += 1; } if (main.option_script_cols != 0 && script_width + width > main.option_script_cols) { if (s[pos] == ' ' || s[pos] == CharCodes.ZC_INDENT || s[pos] == CharCodes.ZC_GAP) pos++; script_new_line(); } for (i = pos; i < s.Length && s[i] != 0; i++) if (s[i] == CharCodes.ZC_NEW_FONT || s[i] == CharCodes.ZC_NEW_STYLE) i++; else script_char(s[i]); }/* script_word */ /* * script_write_input * * Send an input line to the transscript file. * */ internal static void script_write_input(zword[] buf, zword key) { int width; int i; for (i = 0, width = 0; buf[i] != 0; i++) width++; if (main.option_script_cols != 0 && script_width + width > main.option_script_cols) script_new_line(); for (i = 0; buf[i] != 0; i++) script_char(buf[i]); if (key == CharCodes.ZC_RETURN) script_new_line(); }/* script_write_input */ /* * script_erase_input * * Remove an input line from the transscript file. * */ internal static void script_erase_input(zword[] buf) { int width; int i; for (i = 0, width = 0; buf[i] != 0; i++) width++; sfp.BaseStream.SetLength(sfp.BaseStream.Length - width); script_width -= width; }/* script_erase_input */ /* * script_mssg_on * * Start sending a "debugging" message to the transscript file. * */ internal static void script_mssg_on() { if (Files.script_width != 0) script_new_line(); script_char(CharCodes.ZC_INDENT); }/* script_mssg_on */ /* * script_mssg_off * * Stop writing a "debugging" message. * */ internal static void script_mssg_off() { script_new_line(); }/* script_mssg_off */ #endregion #region Record /* * record_open * * Open a file to record the player's input. * */ internal static void record_open() { string new_name = null; if (os_.read_file_name(out new_name, command_name, FileTypes.FILE_RECORD) == true) { command_name = new_name; if ((rfp = new System.IO.StreamWriter(command_name, false)) != null) { main.ostream_record = true; rfp.AutoFlush = true; } else { Text.print_string("Cannot open file\n"); } } }/* record_open */ /* * record_close * * Stop recording the player's input. * */ internal static void record_close() { rfp.Close(); main.ostream_record = false; }/* record_close */ ///* // * record_code // * // * Helper function for record_char. // * // */ private static void record_code(int c, bool force_encoding) { if (force_encoding || c == '[' || c < 0x20 || c > 0x7e) { int i; rfp.Write('['); for (i = 10000; i != 0; i /= 10) if (c >= i || i == 1) rfp.Write((char)('0' + (c / i) % 10)); rfp.Write(']'); } else rfp.Write((char)c); }/* record_code */ /* * record_char * * Write a character to the command file. * */ private static void record_char(zword c) { if (c != CharCodes.ZC_RETURN) { if (c < CharCodes.ZC_HKEY_MIN || c > CharCodes.ZC_HKEY_MAX) { record_code(Text.translate_to_zscii(c), false); if (c == CharCodes.ZC_SINGLE_CLICK || c == CharCodes.ZC_DOUBLE_CLICK) { record_code(main.mouse_x, true); record_code(main.mouse_y, true); } } else record_code(1000 + c - CharCodes.ZC_HKEY_MIN, true); } }/* record_char */ /* * record_write_key * * Copy a keystroke to the command file. * */ internal static void record_write_key(zword key) { record_char(key); rfp.Write('\n'); }/* record_write_key */ /* * record_write_input * * Copy a line of input to a command file. * */ internal static void record_write_input(zword[] buf, zword key) { //zword c; for (int i = 0; i < buf.Length && buf[i] != 0; i++ ) { record_char(buf[i]); } record_char (key); rfp.Write('\n'); }/* record_write_input */ #endregion #region Replay /* * replay_open * * Open a file of commands for playback. * */ internal static void replay_open() { string new_name = null; if (os_.read_file_name(out new_name, command_name, FileTypes.FILE_PLAYBACK)) { command_name = new_name; if ( (pfp = new System.IO.FileStream(new_name, System.IO.FileMode.Open)) != null) { Screen.set_more_prompts (Input.read_yes_or_no ("Do you want MORE prompts")); main.istream_replay = true; } else Text.print_string ("Cannot open file\n"); } }/* replay_open */ /* * replay_close * * Stop playback of commands. * */ internal static void replay_close() { Screen.set_more_prompts(true); pfp.Close(); main.istream_replay = false; }/* replay_close */ /* * replay_code * * Helper function for replay_key and replay_line. * */ static int replay_code () { int c; if ( (c = pfp.ReadByte()) == '[') { int c2; c = 0; while ((c2 = pfp.ReadByte()) != -1 && c2 >= '0' && c2 <= '9') c = 10 * c + c2 - '0'; return (c2 == ']') ? c : -1; } else return c; }/* replay_code */ /* * replay_char * * Read a character from the command file. * */ static zword replay_char () { int c; if ((c = replay_code ()) != -1) { if (c != '\n') { if (c < 1000) { c = Text.translate_from_zscii((byte)c); if (c == CharCodes.ZC_SINGLE_CLICK || c == CharCodes.ZC_DOUBLE_CLICK) { main.mouse_x = (zword)replay_code(); main.mouse_y = (zword)replay_code(); } return (zword)c; } else return (zword)(CharCodes.ZC_HKEY_MIN + c - 1000); } pfp.Position--; pfp.WriteByte((byte)'\n'); return CharCodes.ZC_RETURN; } else return CharCodes.ZC_BAD; }/* replay_char */ /* * replay_read_key * * Read a keystroke from a command file. * */ internal static zword replay_read_key() { zword key = replay_char(); if (pfp.ReadByte() != '\n') { replay_close(); return CharCodes.ZC_BAD; } else return key; }/* replay_read_key */ /* * replay_read_input * * Read a line of input from a command file. * */ internal static zword replay_read_input(zword[] buf) { zword c; int pos = 0; for (; ; ) { c = replay_char(); if (c == CharCodes.ZC_BAD || Input.is_terminator(c)) break; buf[pos++] = c; } pos = 0; //if ( pfp.ReadByte() != '\n') { // replay_close(); // return CharCodes.ZC_BAD; //} else return c; return c; }/* replay_read_input */ #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Nop.Core; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Common; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Directory; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Shipping; using Nop.Core.Domain.Tax; using Nop.Core.Plugins; using Nop.Services.Common; using Nop.Services.Directory; using Nop.Services.Logging; namespace Nop.Services.Tax { /// <summary> /// Tax service /// </summary> public partial class TaxService : ITaxService { #region Fields private readonly IAddressService _addressService; private readonly IWorkContext _workContext; private readonly IStoreContext _storeContext; private readonly TaxSettings _taxSettings; private readonly IPluginFinder _pluginFinder; private readonly IGeoLookupService _geoLookupService; private readonly ICountryService _countryService; private readonly IStateProvinceService _stateProvinceService; private readonly ILogger _logger; private readonly CustomerSettings _customerSettings; private readonly ShippingSettings _shippingSettings; private readonly AddressSettings _addressSettings; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="addressService">Address service</param> /// <param name="workContext">Work context</param> /// <param name="storeContext">Store context</param> /// <param name="taxSettings">Tax settings</param> /// <param name="pluginFinder">Plugin finder</param> /// <param name="geoLookupService">GEO lookup service</param> /// <param name="countryService">Country service</param> /// <param name="stateProvinceService">State province service</param> /// <param name="logger">Logger service</param> /// <param name="customerSettings">Customer settings</param> /// <param name="shippingSettings">Shipping settings</param> /// <param name="addressSettings">Address settings</param> public TaxService(IAddressService addressService, IWorkContext workContext, IStoreContext storeContext, TaxSettings taxSettings, IPluginFinder pluginFinder, IGeoLookupService geoLookupService, ICountryService countryService, IStateProvinceService stateProvinceService, ILogger logger, CustomerSettings customerSettings, ShippingSettings shippingSettings, AddressSettings addressSettings) { this._addressService = addressService; this._workContext = workContext; this._storeContext = storeContext; this._taxSettings = taxSettings; this._pluginFinder = pluginFinder; this._geoLookupService = geoLookupService; this._countryService = countryService; this._stateProvinceService = stateProvinceService; this._logger = logger; this._customerSettings = customerSettings; this._shippingSettings = shippingSettings; this._addressSettings = addressSettings; } #endregion #region Utilities /// <summary> /// Get a value indicating whether a customer is consumer (a person, not a company) located in Europe Union /// </summary> /// <param name="customer">Customer</param> /// <returns>Result</returns> protected virtual bool IsEuConsumer(Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); Country country = null; //get country from billing address if (_addressSettings.CountryEnabled && customer.BillingAddress != null) country = customer.BillingAddress.Country; //get country specified during registration? if (country == null && _customerSettings.CountryEnabled) { var countryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId); country = _countryService.GetCountryById(countryId); } //get country by IP address if (country == null) { var ipAddress = customer.LastIpAddress; //ipAddress = _webHelper.GetCurrentIpAddress(); var countryIsoCode = _geoLookupService.LookupCountryIsoCode(ipAddress); country = _countryService.GetCountryByTwoLetterIsoCode(countryIsoCode); } //we cannot detect country if (country == null) return false; //outside EU if (!country.SubjectToVat) return false; //company (business) or consumer? var customerVatStatus = (VatNumberStatus)customer.GetAttribute<int>(SystemCustomerAttributeNames.VatNumberStatusId); if (customerVatStatus == VatNumberStatus.Valid) return false; //TODO: use specified company name? (both address and registration one) //consumer return true; } /// <summary> /// Create request for tax calculation /// </summary> /// <param name="product">Product</param> /// <param name="taxCategoryId">Tax category identifier</param> /// <param name="customer">Customer</param> /// <param name="price">Price</param> /// <returns>Package for tax calculation</returns> protected virtual CalculateTaxRequest CreateCalculateTaxRequest(Product product, int taxCategoryId, Customer customer, decimal price) { if (customer == null) throw new ArgumentNullException("customer"); var calculateTaxRequest = new CalculateTaxRequest { Customer = customer, Product = product, Price = price, TaxCategoryId = taxCategoryId > 0 ? taxCategoryId : (product != null ? product.TaxCategoryId : 0) }; var basedOn = _taxSettings.TaxBasedOn; //new EU VAT rules starting January 1st 2015 //find more info at http://ec.europa.eu/taxation_customs/taxation/vat/how_vat_works/telecom/index_en.htm#new_rules var overridenBasedOn = _taxSettings.EuVatEnabled //EU VAT enabled? && product != null && product.IsTelecommunicationsOrBroadcastingOrElectronicServices //telecommunications, broadcasting and electronic services? && DateTime.UtcNow > new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc) //January 1st 2015 passed? && IsEuConsumer(customer); //Europe Union consumer? if (overridenBasedOn) { //We must charge VAT in the EU country where the customer belongs (not where the business is based) basedOn = TaxBasedOn.BillingAddress; } //tax is based on pickup point address if (!overridenBasedOn && _taxSettings.TaxBasedOnPickupPointAddress && _shippingSettings.AllowPickUpInStore) { var pickupPoint = customer.GetAttribute<PickupPoint>(SystemCustomerAttributeNames.SelectedPickupPoint, _storeContext.CurrentStore.Id); if (pickupPoint != null) { var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation); calculateTaxRequest.Address = new Address { Address1 = pickupPoint.Address, City = pickupPoint.City, Country = country, CountryId = country.Return(c => c.Id, 0), StateProvince = state, StateProvinceId = state.Return(sp => sp.Id, 0), ZipPostalCode = pickupPoint.ZipPostalCode, CreatedOnUtc = DateTime.UtcNow }; return calculateTaxRequest; } } if (basedOn == TaxBasedOn.BillingAddress && customer.BillingAddress == null || basedOn == TaxBasedOn.ShippingAddress && customer.ShippingAddress == null) { basedOn = TaxBasedOn.DefaultAddress; } switch (basedOn) { case TaxBasedOn.BillingAddress: calculateTaxRequest.Address = customer.BillingAddress; break; case TaxBasedOn.ShippingAddress: calculateTaxRequest.Address = customer.ShippingAddress; break; case TaxBasedOn.DefaultAddress: default: calculateTaxRequest.Address = _addressService.GetAddressById(_taxSettings.DefaultTaxAddressId); break; } return calculateTaxRequest; } /// <summary> /// Calculated price /// </summary> /// <param name="price">Price</param> /// <param name="percent">Percent</param> /// <param name="increase">Increase</param> /// <returns>New price</returns> protected virtual decimal CalculatePrice(decimal price, decimal percent, bool increase) { if (percent == decimal.Zero) return price; decimal result; if (increase) { result = price * (1 + percent / 100); } else { result = price - (price) / (100 + percent) * percent; } return result; } /// <summary> /// Gets tax rate /// </summary> /// <param name="product">Product</param> /// <param name="taxCategoryId">Tax category identifier</param> /// <param name="customer">Customer</param> /// <param name="price">Price (taxable value)</param> /// <param name="taxRate">Calculated tax rate</param> /// <param name="isTaxable">A value indicating whether a request is taxable</param> protected virtual void GetTaxRate(Product product, int taxCategoryId, Customer customer, decimal price, out decimal taxRate, out bool isTaxable) { taxRate = decimal.Zero; isTaxable = true; //active tax provider var activeTaxProvider = LoadActiveTaxProvider(customer); if (activeTaxProvider == null) return; //tax request var calculateTaxRequest = CreateCalculateTaxRequest(product, taxCategoryId, customer, price); //tax exempt if (IsTaxExempt(product, calculateTaxRequest.Customer)) { isTaxable = false; } //make EU VAT exempt validation (the European Union Value Added Tax) if (isTaxable && _taxSettings.EuVatEnabled && IsVatExempt(calculateTaxRequest.Address, calculateTaxRequest.Customer)) { //VAT is not chargeable isTaxable = false; } //get tax rate var calculateTaxResult = activeTaxProvider.GetTaxRate(calculateTaxRequest); if (calculateTaxResult.Success) { //ensure that tax is equal or greater than zero if (calculateTaxResult.TaxRate < decimal.Zero) calculateTaxResult.TaxRate = decimal.Zero; taxRate = calculateTaxResult.TaxRate; } else if (_taxSettings.LogErrors) { foreach (var error in calculateTaxResult.Errors) { _logger.Error(string.Format("{0} - {1}", activeTaxProvider.PluginDescriptor.FriendlyName, error), null, customer); } } } #endregion #region Methods #region Tax providers /// <summary> /// Load active tax provider /// </summary> /// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param> /// <returns>Active tax provider</returns> public virtual ITaxProvider LoadActiveTaxProvider(Customer customer = null) { var taxProvider = LoadTaxProviderBySystemName(_taxSettings.ActiveTaxProviderSystemName); if (taxProvider == null) taxProvider = LoadAllTaxProviders(customer).FirstOrDefault(); return taxProvider; } /// <summary> /// Load tax provider by system name /// </summary> /// <param name="systemName">System name</param> /// <returns>Found tax provider</returns> public virtual ITaxProvider LoadTaxProviderBySystemName(string systemName) { var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<ITaxProvider>(systemName); if (descriptor != null) return descriptor.Instance<ITaxProvider>(); return null; } /// <summary> /// Load all tax providers /// </summary> /// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param> /// <returns>Tax providers</returns> public virtual IList<ITaxProvider> LoadAllTaxProviders(Customer customer = null) { return _pluginFinder.GetPlugins<ITaxProvider>(customer: customer).ToList(); } #endregion #region Product price /// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="price">Price</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetProductPrice(Product product, decimal price, out decimal taxRate) { var customer = _workContext.CurrentCustomer; return GetProductPrice(product, price, customer, out taxRate); } /// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="price">Price</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetProductPrice(Product product, decimal price, Customer customer, out decimal taxRate) { bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax; return GetProductPrice(product, price, includingTax, customer, out taxRate); } /// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetProductPrice(Product product, decimal price, bool includingTax, Customer customer, out decimal taxRate) { bool priceIncludesTax = _taxSettings.PricesIncludeTax; int taxCategoryId = 0; return GetProductPrice(product, taxCategoryId, price, includingTax, customer, priceIncludesTax, out taxRate); } /// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="taxCategoryId">Tax category identifier</param> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="priceIncludesTax">A value indicating whether price already includes tax</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetProductPrice(Product product, int taxCategoryId, decimal price, bool includingTax, Customer customer, bool priceIncludesTax, out decimal taxRate) { //no need to calculate tax rate if passed "price" is 0 if (price == decimal.Zero) { taxRate = decimal.Zero; return taxRate; } bool isTaxable; GetTaxRate(product, taxCategoryId, customer, price, out taxRate, out isTaxable); if (priceIncludesTax) { //"price" already includes tax if (includingTax) { //we should calculate price WITH tax if (!isTaxable) { //but our request is not taxable //hence we should calculate price WITHOUT tax price = CalculatePrice(price, taxRate, false); } } else { //we should calculate price WITHOUT tax price = CalculatePrice(price, taxRate, false); } } else { //"price" doesn't include tax if (includingTax) { //we should calculate price WITH tax //do it only when price is taxable if (isTaxable) { price = CalculatePrice(price, taxRate, true); } } } if (!isTaxable) { //we return 0% tax rate in case a request is not taxable taxRate = decimal.Zero; } //allowed to support negative price adjustments //if (price < decimal.Zero) // price = decimal.Zero; return price; } #endregion #region Shipping price /// <summary> /// Gets shipping price /// </summary> /// <param name="price">Price</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetShippingPrice(decimal price, Customer customer) { bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax; return GetShippingPrice(price, includingTax, customer); } /// <summary> /// Gets shipping price /// </summary> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetShippingPrice(decimal price, bool includingTax, Customer customer) { decimal taxRate; return GetShippingPrice(price, includingTax, customer, out taxRate); } /// <summary> /// Gets shipping price /// </summary> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetShippingPrice(decimal price, bool includingTax, Customer customer, out decimal taxRate) { taxRate = decimal.Zero; if (!_taxSettings.ShippingIsTaxable) { return price; } int taxClassId = _taxSettings.ShippingTaxClassId; bool priceIncludesTax = _taxSettings.ShippingPriceIncludesTax; return GetProductPrice(null, taxClassId, price, includingTax, customer, priceIncludesTax, out taxRate); } #endregion #region Payment additional fee /// <summary> /// Gets payment method additional handling fee /// </summary> /// <param name="price">Price</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetPaymentMethodAdditionalFee(decimal price, Customer customer) { bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax; return GetPaymentMethodAdditionalFee(price, includingTax, customer); } /// <summary> /// Gets payment method additional handling fee /// </summary> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetPaymentMethodAdditionalFee(decimal price, bool includingTax, Customer customer) { decimal taxRate; return GetPaymentMethodAdditionalFee(price, includingTax, customer, out taxRate); } /// <summary> /// Gets payment method additional handling fee /// </summary> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetPaymentMethodAdditionalFee(decimal price, bool includingTax, Customer customer, out decimal taxRate) { taxRate = decimal.Zero; if (!_taxSettings.PaymentMethodAdditionalFeeIsTaxable) { return price; } int taxClassId = _taxSettings.PaymentMethodAdditionalFeeTaxClassId; bool priceIncludesTax = _taxSettings.PaymentMethodAdditionalFeeIncludesTax; return GetProductPrice(null, taxClassId, price, includingTax, customer, priceIncludesTax, out taxRate); } #endregion #region Checkout attribute price /// <summary> /// Gets checkout attribute value price /// </summary> /// <param name="cav">Checkout attribute value</param> /// <returns>Price</returns> public virtual decimal GetCheckoutAttributePrice(CheckoutAttributeValue cav) { var customer = _workContext.CurrentCustomer; return GetCheckoutAttributePrice(cav, customer); } /// <summary> /// Gets checkout attribute value price /// </summary> /// <param name="cav">Checkout attribute value</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetCheckoutAttributePrice(CheckoutAttributeValue cav, Customer customer) { bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax; return GetCheckoutAttributePrice(cav, includingTax, customer); } /// <summary> /// Gets checkout attribute value price /// </summary> /// <param name="cav">Checkout attribute value</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetCheckoutAttributePrice(CheckoutAttributeValue cav, bool includingTax, Customer customer) { decimal taxRate; return GetCheckoutAttributePrice(cav, includingTax, customer, out taxRate); } /// <summary> /// Gets checkout attribute value price /// </summary> /// <param name="cav">Checkout attribute value</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetCheckoutAttributePrice(CheckoutAttributeValue cav, bool includingTax, Customer customer, out decimal taxRate) { if (cav == null) throw new ArgumentNullException("cav"); taxRate = decimal.Zero; decimal price = cav.PriceAdjustment; if (cav.CheckoutAttribute.IsTaxExempt) { return price; } bool priceIncludesTax = _taxSettings.PricesIncludeTax; int taxClassId = cav.CheckoutAttribute.TaxCategoryId; return GetProductPrice(null, taxClassId, price, includingTax, customer, priceIncludesTax, out taxRate); } #endregion #region VAT /// <summary> /// Gets VAT Number status /// </summary> /// <param name="fullVatNumber">Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111)</param> /// <returns>VAT Number status</returns> public virtual VatNumberStatus GetVatNumberStatus(string fullVatNumber) { string name, address; return GetVatNumberStatus(fullVatNumber, out name, out address); } /// <summary> /// Gets VAT Number status /// </summary> /// <param name="fullVatNumber">Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111)</param> /// <param name="name">Name (if received)</param> /// <param name="address">Address (if received)</param> /// <returns>VAT Number status</returns> public virtual VatNumberStatus GetVatNumberStatus(string fullVatNumber, out string name, out string address) { name = string.Empty; address = string.Empty; if (String.IsNullOrWhiteSpace(fullVatNumber)) return VatNumberStatus.Empty; fullVatNumber = fullVatNumber.Trim(); //GB 111 1111 111 or GB 1111111111 //more advanced regex - http://codeigniter.com/wiki/European_Vat_Checker var r = new Regex(@"^(\w{2})(.*)"); var match = r.Match(fullVatNumber); if (!match.Success) return VatNumberStatus.Invalid; var twoLetterIsoCode = match.Groups[1].Value; var vatNumber = match.Groups[2].Value; return GetVatNumberStatus(twoLetterIsoCode, vatNumber, out name, out address); } /// <summary> /// Gets VAT Number status /// </summary> /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param> /// <param name="vatNumber">VAT number</param> /// <returns>VAT Number status</returns> public virtual VatNumberStatus GetVatNumberStatus(string twoLetterIsoCode, string vatNumber) { string name, address; return GetVatNumberStatus(twoLetterIsoCode, vatNumber, out name, out address); } /// <summary> /// Gets VAT Number status /// </summary> /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param> /// <param name="vatNumber">VAT number</param> /// <param name="name">Name (if received)</param> /// <param name="address">Address (if received)</param> /// <returns>VAT Number status</returns> public virtual VatNumberStatus GetVatNumberStatus(string twoLetterIsoCode, string vatNumber, out string name, out string address) { name = string.Empty; address = string.Empty; if (String.IsNullOrEmpty(twoLetterIsoCode)) return VatNumberStatus.Empty; if (String.IsNullOrEmpty(vatNumber)) return VatNumberStatus.Empty; if (_taxSettings.EuVatAssumeValid) return VatNumberStatus.Valid; if (!_taxSettings.EuVatUseWebService) return VatNumberStatus.Unknown; Exception exception; return DoVatCheck(twoLetterIsoCode, vatNumber, out name, out address, out exception); } /// <summary> /// Performs a basic check of a VAT number for validity /// </summary> /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param> /// <param name="vatNumber">VAT number</param> /// <param name="name">Company name</param> /// <param name="address">Address</param> /// <param name="exception">Exception</param> /// <returns>VAT number status</returns> public virtual VatNumberStatus DoVatCheck(string twoLetterIsoCode, string vatNumber, out string name, out string address, out Exception exception) { name = string.Empty; address = string.Empty; if (vatNumber == null) vatNumber = string.Empty; vatNumber = vatNumber.Trim().Replace(" ", ""); if (twoLetterIsoCode == null) twoLetterIsoCode = string.Empty; if (!String.IsNullOrEmpty(twoLetterIsoCode)) //The service returns INVALID_INPUT for country codes that are not uppercase. twoLetterIsoCode = twoLetterIsoCode.ToUpper(); EuropaCheckVatService.checkVatService s = null; try { bool valid; s = new EuropaCheckVatService.checkVatService(); s.checkVat(ref twoLetterIsoCode, ref vatNumber, out valid, out name, out address); exception = null; return valid ? VatNumberStatus.Valid : VatNumberStatus.Invalid; } catch (Exception ex) { name = address = string.Empty; exception = ex; return VatNumberStatus.Unknown; } finally { if (name == null) name = string.Empty; if (address == null) address = string.Empty; if (s != null) s.Dispose(); } } #endregion #region Exempts /// <summary> /// Gets a value indicating whether a product is tax exempt /// </summary> /// <param name="product">Product</param> /// <param name="customer">Customer</param> /// <returns>A value indicating whether a product is tax exempt</returns> public virtual bool IsTaxExempt(Product product, Customer customer) { if (customer != null) { if (customer.IsTaxExempt) return true; if (customer.CustomerRoles.Where(cr => cr.Active).Any(cr => cr.TaxExempt)) return true; } if (product == null) { return false; } if (product.IsTaxExempt) { return true; } return false; } /// <summary> /// Gets a value indicating whether EU VAT exempt (the European Union Value Added Tax) /// </summary> /// <param name="address">Address</param> /// <param name="customer">Customer</param> /// <returns>Result</returns> public virtual bool IsVatExempt(Address address, Customer customer) { if (!_taxSettings.EuVatEnabled) return false; if (address == null || address.Country == null || customer == null) return false; if (!address.Country.SubjectToVat) // VAT not chargeable if shipping outside VAT zone return true; // VAT not chargeable if address, customer and config meet our VAT exemption requirements: // returns true if this customer is VAT exempt because they are shipping within the EU but outside our shop country, they have supplied a validated VAT number, and the shop is configured to allow VAT exemption var customerVatStatus = (VatNumberStatus) customer.GetAttribute<int>(SystemCustomerAttributeNames.VatNumberStatusId); return address.CountryId != _taxSettings.EuVatShopCountryId && customerVatStatus == VatNumberStatus.Valid && _taxSettings.EuVatAllowVatExemption; } #endregion #endregion } }
using UnityEngine; using System.Collections; [AddComponentMenu("AQUAS/Reflection")] [ExecuteInEditMode] // Make mirror live-update even when not in play mode public class AQUAS_Reflection : MonoBehaviour { public bool m_DisablePixelLights = true; public int m_TextureSize = 256; public float m_ClipPlaneOffset = 0.07f; public LayerMask m_ReflectLayers = -1; private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table private RenderTexture m_ReflectionTexture = null; private int m_OldReflectionTextureSize = 0; private static bool s_InsideRendering = false; public void OnWillRenderObject() { if( !enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled ) return; Camera cam = Camera.current; if( !cam ) return; // Safeguard from recursive reflections. if( s_InsideRendering ) return; s_InsideRendering = true; Camera reflectionCamera; CreateMirrorObjects( cam, out reflectionCamera ); // find out the reflection plane: position and normal in world space Vector3 pos = transform.position; Vector3 normal = transform.up; // Optionally disable pixel lights for reflection int oldPixelLightCount = QualitySettings.pixelLightCount; if( m_DisablePixelLights ) QualitySettings.pixelLightCount = 0; UpdateCameraModes( cam, reflectionCamera ); // Render reflection // Reflect camera around reflection plane float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset; Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d); Matrix4x4 reflection = Matrix4x4.zero; CalculateReflectionMatrix (ref reflection, reflectionPlane); Vector3 oldpos = cam.transform.position; Vector3 newpos = reflection.MultiplyPoint( oldpos ); reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection; // Setup oblique projection matrix so that near plane is our reflection // plane. This way we clip everything below/above it for free. Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f ); Matrix4x4 projection = cam.projectionMatrix; CalculateObliqueMatrix (ref projection, clipPlane); reflectionCamera.projectionMatrix = projection; reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // never render water layer reflectionCamera.targetTexture = m_ReflectionTexture; GL.SetRevertBackfacing (true); reflectionCamera.transform.position = newpos; Vector3 euler = cam.transform.eulerAngles; reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z); reflectionCamera.Render(); reflectionCamera.transform.position = oldpos; GL.SetRevertBackfacing (false); Material[] materials = GetComponent<Renderer>().sharedMaterials; foreach( Material mat in materials ) { if( mat.HasProperty("_ReflectionTex") ) mat.SetTexture( "_ReflectionTex", m_ReflectionTexture ); } // Set matrix on the shader that transforms UVs from object space into screen // space. We want to just project reflection texture on screen. Matrix4x4 scaleOffset = Matrix4x4.TRS( new Vector3(0.5f,0.5f,0.5f), Quaternion.identity, new Vector3(0.5f,0.5f,0.5f) ); Vector3 scale = transform.lossyScale; Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale( new Vector3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z) ); mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx; foreach( Material mat in materials ) { mat.SetMatrix( "_ProjMatrix", mtx ); } // Restore pixel light count if( m_DisablePixelLights ) QualitySettings.pixelLightCount = oldPixelLightCount; s_InsideRendering = false; } // Cleanup all the objects we possibly have created void OnDisable() { if( m_ReflectionTexture ) { DestroyImmediate( m_ReflectionTexture ); m_ReflectionTexture = null; } foreach( DictionaryEntry kvp in m_ReflectionCameras ) DestroyImmediate( ((Camera)kvp.Value).gameObject ); m_ReflectionCameras.Clear(); } private void UpdateCameraModes( Camera src, Camera dest ) { if( dest == null ) return; // set camera to clear the same way as current camera dest.clearFlags = src.clearFlags; dest.backgroundColor = src.backgroundColor; if( src.clearFlags == CameraClearFlags.Skybox ) { Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox; Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox; if( !sky || !sky.material ) { mysky.enabled = false; } else { mysky.enabled = true; mysky.material = sky.material; } } // update other values to match current camera. // even if we are supplying custom camera&projection matrices, // some of values are used elsewhere (e.g. skybox uses far plane) dest.farClipPlane = src.farClipPlane; dest.nearClipPlane = src.nearClipPlane; dest.orthographic = src.orthographic; dest.fieldOfView = src.fieldOfView; dest.aspect = src.aspect; dest.orthographicSize = src.orthographicSize; } // On-demand create any objects we need private void CreateMirrorObjects( Camera currentCamera, out Camera reflectionCamera ) { reflectionCamera = null; // Reflection render texture if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize ) { if( m_ReflectionTexture ) DestroyImmediate( m_ReflectionTexture ); m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 ); m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID(); m_ReflectionTexture.isPowerOfTwo = true; m_ReflectionTexture.hideFlags = HideFlags.DontSave; m_OldReflectionTextureSize = m_TextureSize; } // Camera for reflection reflectionCamera = m_ReflectionCameras[currentCamera] as Camera; if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO { GameObject go = new GameObject( "Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) ); reflectionCamera = go.GetComponent<Camera>(); reflectionCamera.enabled = false; reflectionCamera.transform.position = transform.position; reflectionCamera.transform.rotation = transform.rotation; reflectionCamera.gameObject.AddComponent<FlareLayer>(); go.hideFlags = HideFlags.HideAndDontSave; m_ReflectionCameras[currentCamera] = reflectionCamera; } } // Extended sign: returns -1, 0 or 1 based on sign of a private static float sgn(float a) { if (a > 0.0f) return 1.0f; if (a < 0.0f) return -1.0f; return 0.0f; } // Given position/normal of the plane, calculates plane in camera space. private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign) { Vector3 offsetPos = pos + normal * m_ClipPlaneOffset; Matrix4x4 m = cam.worldToCameraMatrix; Vector3 cpos = m.MultiplyPoint( offsetPos ); Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign; return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) ); } // Adjusts the given projection matrix so that near plane is the given clipPlane // clipPlane is given in camera space. See article in Game Programming Gems 5 and // http://aras-p.info/texts/obliqueortho.html private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane) { Vector4 q = projection.inverse * new Vector4( sgn(clipPlane.x), sgn(clipPlane.y), 1.0f, 1.0f ); Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q))); // third row = clip plane - fourth row projection[2] = c.x - projection[3]; projection[6] = c.y - projection[7]; projection[10] = c.z - projection[11]; projection[14] = c.w - projection[15]; } // Calculates reflection matrix around the given plane private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane) { reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]); reflectionMat.m01 = ( - 2F*plane[0]*plane[1]); reflectionMat.m02 = ( - 2F*plane[0]*plane[2]); reflectionMat.m03 = ( - 2F*plane[3]*plane[0]); reflectionMat.m10 = ( - 2F*plane[1]*plane[0]); reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]); reflectionMat.m12 = ( - 2F*plane[1]*plane[2]); reflectionMat.m13 = ( - 2F*plane[3]*plane[1]); reflectionMat.m20 = ( - 2F*plane[2]*plane[0]); reflectionMat.m21 = ( - 2F*plane[2]*plane[1]); reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]); reflectionMat.m23 = ( - 2F*plane[3]*plane[2]); reflectionMat.m30 = 0F; reflectionMat.m31 = 0F; reflectionMat.m32 = 0F; reflectionMat.m33 = 1F; } }
// 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 Avalonia.Input; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices; using Avalonia.Controls; using System.Reactive.Disposables; using Avalonia.Input.Raw; using Avalonia.Platform; using Avalonia.Win32.Input; using Avalonia.Win32.Interop; using static Avalonia.Win32.Interop.UnmanagedMethods; using Avalonia.Rendering; #if NETSTANDARD using Win32Exception = Avalonia.Win32.NetStandard.AvaloniaWin32Exception; #endif namespace Avalonia.Win32 { class WindowImpl : IWindowImpl { private static readonly List<WindowImpl> s_instances = new List<WindowImpl>(); private static readonly IntPtr DefaultCursor = UnmanagedMethods.LoadCursor( IntPtr.Zero, new IntPtr((int)UnmanagedMethods.Cursor.IDC_ARROW)); private UnmanagedMethods.WndProc _wndProcDelegate; private string _className; private IntPtr _hwnd; private IInputRoot _owner; private bool _trackingMouse; private bool _decorated = true; private double _scaling = 1; private WindowState _showWindowState; private FramebufferManager _framebuffer; public WindowImpl() { CreateWindow(); _framebuffer = new FramebufferManager(_hwnd); s_instances.Add(this); } public Action Activated { get; set; } public Action Closed { get; set; } public Action Deactivated { get; set; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public Action<Point> PositionChanged { get; set; } public Thickness BorderThickness { get { var style = UnmanagedMethods.GetWindowLong(_hwnd, -16); var exStyle = UnmanagedMethods.GetWindowLong(_hwnd, -20); var padding = new UnmanagedMethods.RECT(); if (UnmanagedMethods.AdjustWindowRectEx(ref padding, style, false, exStyle)) { return new Thickness(-padding.left, -padding.top, padding.right, padding.bottom); } else { throw new Win32Exception(); } } } public Size ClientSize { get { UnmanagedMethods.RECT rect; UnmanagedMethods.GetClientRect(_hwnd, out rect); return new Size(rect.right, rect.bottom) / Scaling; } } public IRenderer CreateRenderer(IRenderRoot root) { var loop = AvaloniaLocator.Current.GetService<IRenderLoop>(); return Win32Platform.UseDeferredRendering ? (IRenderer)new DeferredRenderer(root, loop) : new ImmediateRenderer(root); } public void Resize(Size value) { if (value != ClientSize) { value *= Scaling; value += BorderThickness; UnmanagedMethods.SetWindowPos( _hwnd, IntPtr.Zero, 0, 0, (int)value.Width, (int)value.Height, UnmanagedMethods.SetWindowPosFlags.SWP_RESIZE); } } public double Scaling => _scaling; public IPlatformHandle Handle { get; private set; } public bool IsEnabled { get { return UnmanagedMethods.IsWindowEnabled(_hwnd); } set { UnmanagedMethods.EnableWindow(_hwnd, value); } } public Size MaxClientSize { get { return (new Size( UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CXMAXTRACK), UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CYMAXTRACK)) - BorderThickness) / Scaling; } } public IMouseDevice MouseDevice => WindowsMouseDevice.Instance; public WindowState WindowState { get { var placement = default(UnmanagedMethods.WINDOWPLACEMENT); UnmanagedMethods.GetWindowPlacement(_hwnd, ref placement); switch (placement.ShowCmd) { case UnmanagedMethods.ShowWindowCommand.Maximize: return WindowState.Maximized; case UnmanagedMethods.ShowWindowCommand.Minimize: return WindowState.Minimized; default: return WindowState.Normal; } } set { if (UnmanagedMethods.IsWindowVisible(_hwnd)) { ShowWindow(value); } else { _showWindowState = value; } } } public IEnumerable<object> Surfaces => new object[] { Handle, _framebuffer }; public void Activate() { UnmanagedMethods.SetActiveWindow(_hwnd); } public IPopupImpl CreatePopup() { return new PopupImpl(); } public void Dispose() { _framebuffer?.Dispose(); _framebuffer = null; if (_hwnd != IntPtr.Zero) { UnmanagedMethods.DestroyWindow(_hwnd); _hwnd = IntPtr.Zero; } if (_className != null) { UnmanagedMethods.UnregisterClass(_className, UnmanagedMethods.GetModuleHandle(null)); _className = null; } } public void Hide() { UnmanagedMethods.ShowWindow(_hwnd, UnmanagedMethods.ShowWindowCommand.Hide); } public void SetSystemDecorations(bool value) { if (value == _decorated) { return; } var style = (UnmanagedMethods.WindowStyles)UnmanagedMethods.GetWindowLong(_hwnd, -16); style |= UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW; if (!value) { style ^= UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW; } UnmanagedMethods.RECT windowRect; UnmanagedMethods.GetWindowRect(_hwnd, out windowRect); Rect newRect; var oldThickness = BorderThickness; UnmanagedMethods.SetWindowLong(_hwnd, -16, (uint)style); if (value) { var thickness = BorderThickness; newRect = new Rect( windowRect.left - thickness.Left, windowRect.top - thickness.Top, (windowRect.right - windowRect.left) + (thickness.Left + thickness.Right), (windowRect.bottom - windowRect.top) + (thickness.Top + thickness.Bottom)); } else { newRect = new Rect( windowRect.left + oldThickness.Left, windowRect.top + oldThickness.Top, (windowRect.right - windowRect.left) - (oldThickness.Left + oldThickness.Right), (windowRect.bottom - windowRect.top) - (oldThickness.Top + oldThickness.Bottom)); } UnmanagedMethods.SetWindowPos(_hwnd, IntPtr.Zero, (int)newRect.X, (int)newRect.Y, (int)newRect.Width, (int)newRect.Height, UnmanagedMethods.SetWindowPosFlags.SWP_NOZORDER | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); _decorated = value; } public void Invalidate(Rect rect) { var f = Scaling; var r = new UnmanagedMethods.RECT { left = (int)(rect.X * f), top = (int)(rect.Y * f), right = (int)(rect.Right * f), bottom = (int)(rect.Bottom * f), }; UnmanagedMethods.InvalidateRect(_hwnd, ref r, false); } public Point PointToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y) / Scaling; } public Point PointToScreen(Point point) { point *= Scaling; var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ClientToScreen(_hwnd, ref p); return new Point(p.X, p.Y); } public void SetInputRoot(IInputRoot inputRoot) { _owner = inputRoot; } public void SetTitle(string title) { UnmanagedMethods.SetWindowText(_hwnd, title); } public virtual void Show() { ShowWindow(_showWindowState); } public void BeginMoveDrag() { UnmanagedMethods.DefWindowProc(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)UnmanagedMethods.HitTestValues.HTCAPTION), IntPtr.Zero); } static readonly Dictionary<WindowEdge, UnmanagedMethods.HitTestValues> EdgeDic = new Dictionary<WindowEdge, UnmanagedMethods.HitTestValues> { {WindowEdge.East, UnmanagedMethods.HitTestValues.HTRIGHT}, {WindowEdge.North, UnmanagedMethods.HitTestValues.HTTOP }, {WindowEdge.NorthEast, UnmanagedMethods.HitTestValues.HTTOPRIGHT }, {WindowEdge.NorthWest, UnmanagedMethods.HitTestValues.HTTOPLEFT }, {WindowEdge.South, UnmanagedMethods.HitTestValues.HTBOTTOM }, {WindowEdge.SouthEast, UnmanagedMethods.HitTestValues.HTBOTTOMRIGHT }, {WindowEdge.SouthWest, UnmanagedMethods.HitTestValues.HTBOTTOMLEFT }, {WindowEdge.West, UnmanagedMethods.HitTestValues.HTLEFT} }; public void BeginResizeDrag(WindowEdge edge) { UnmanagedMethods.DefWindowProc(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)EdgeDic[edge]), IntPtr.Zero); } public Point Position { get { UnmanagedMethods.RECT rc; UnmanagedMethods.GetWindowRect(_hwnd, out rc); return new Point(rc.left, rc.top); } set { UnmanagedMethods.SetWindowPos( Handle.Handle, IntPtr.Zero, (int)value.X, (int)value.Y, 0, 0, UnmanagedMethods.SetWindowPosFlags.SWP_NOSIZE | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); } } public virtual IDisposable ShowDialog() { Show(); return Disposable.Empty; } public void SetCursor(IPlatformHandle cursor) { UnmanagedMethods.SetClassLong(_hwnd, UnmanagedMethods.ClassLongIndex.GCL_HCURSOR, cursor?.Handle ?? DefaultCursor); } protected virtual IntPtr CreateWindowOverride(ushort atom) { return UnmanagedMethods.CreateWindowEx( 0, atom, null, (int)UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")] protected virtual IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { bool unicode = UnmanagedMethods.IsWindowUnicode(hWnd); const double wheelDelta = 120.0; uint timestamp = unchecked((uint)UnmanagedMethods.GetMessageTime()); RawInputEventArgs e = null; WindowsMouseDevice.Instance.CurrentWindow = this; switch ((UnmanagedMethods.WindowsMessage)msg) { case UnmanagedMethods.WindowsMessage.WM_ACTIVATE: var wa = (UnmanagedMethods.WindowActivate)(ToInt32(wParam) & 0xffff); switch (wa) { case UnmanagedMethods.WindowActivate.WA_ACTIVE: case UnmanagedMethods.WindowActivate.WA_CLICKACTIVE: Activated?.Invoke(); break; case UnmanagedMethods.WindowActivate.WA_INACTIVE: Deactivated?.Invoke(); break; } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_DESTROY: //Window doesn't exist anymore _hwnd = IntPtr.Zero; //Remove root reference to this class, so unmanaged delegate can be collected s_instances.Remove(this); Closed?.Invoke(); //Free other resources Dispose(); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_DPICHANGED: var dpi = ToInt32(wParam) & 0xffff; var newDisplayRect = (UnmanagedMethods.RECT)Marshal.PtrToStructure(lParam, typeof(UnmanagedMethods.RECT)); Position = new Point(newDisplayRect.left, newDisplayRect.top); _scaling = dpi / 96.0; ScalingChanged?.Invoke(_scaling); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_KEYDOWN: case UnmanagedMethods.WindowsMessage.WM_SYSKEYDOWN: e = new RawKeyEventArgs( WindowsKeyboardDevice.Instance, timestamp, RawKeyEventType.KeyDown, KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_KEYUP: case UnmanagedMethods.WindowsMessage.WM_SYSKEYUP: e = new RawKeyEventArgs( WindowsKeyboardDevice.Instance, timestamp, RawKeyEventType.KeyUp, KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_CHAR: // Ignore control chars if (ToInt32(wParam) >= 32) { e = new RawTextInputEventArgs(WindowsKeyboardDevice.Instance, timestamp, new string((char)ToInt32(wParam), 1)); } break; case UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_MBUTTONDOWN: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN ? RawMouseEventType.LeftButtonDown : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_LBUTTONUP: case UnmanagedMethods.WindowsMessage.WM_RBUTTONUP: case UnmanagedMethods.WindowsMessage.WM_MBUTTONUP: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONUP ? RawMouseEventType.LeftButtonUp : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONUP ? RawMouseEventType.RightButtonUp : RawMouseEventType.MiddleButtonUp, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEMOVE: if (!_trackingMouse) { var tm = new UnmanagedMethods.TRACKMOUSEEVENT { cbSize = Marshal.SizeOf(typeof(UnmanagedMethods.TRACKMOUSEEVENT)), dwFlags = 2, hwndTrack = _hwnd, dwHoverTime = 0, }; UnmanagedMethods.TrackMouseEvent(ref tm); } e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, RawMouseEventType.Move, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEWHEEL: e = new RawMouseWheelEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, ScreenToClient(DipFromLParam(lParam)), new Vector(0, (ToInt32(wParam) >> 16) / wheelDelta), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEHWHEEL: e = new RawMouseWheelEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, ScreenToClient(DipFromLParam(lParam)), new Vector(-(ToInt32(wParam) >> 16) / wheelDelta, 0), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSELEAVE: _trackingMouse = false; e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, RawMouseEventType.LeaveWindow, new Point(), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_NCMBUTTONDOWN: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN ? RawMouseEventType.NonClientLeftButtonDown : msg == (int)UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, new Point(0, 0), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_PAINT: UnmanagedMethods.PAINTSTRUCT ps; if (UnmanagedMethods.BeginPaint(_hwnd, out ps) != IntPtr.Zero) { var f = Scaling; var r = ps.rcPaint; Paint?.Invoke(new Rect(r.left / f, r.top / f, (r.right - r.left) / f, (r.bottom - r.top) / f)); UnmanagedMethods.EndPaint(_hwnd, ref ps); } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_SIZE: if (Resized != null && (wParam == (IntPtr)UnmanagedMethods.SizeCommand.Restored || wParam == (IntPtr)UnmanagedMethods.SizeCommand.Maximized)) { var clientSize = new Size(ToInt32(lParam) & 0xffff, ToInt32(lParam) >> 16); Resized(clientSize / Scaling); } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_MOVE: PositionChanged?.Invoke(new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16))); return IntPtr.Zero; } if (e != null && Input != null) { Input(e); if (e.Handled) { return IntPtr.Zero; } } return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam); } static InputModifiers GetMouseModifiers(IntPtr wParam) { var keys = (UnmanagedMethods.ModifierKeys)ToInt32(wParam); var modifiers = WindowsKeyboardDevice.Instance.Modifiers; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_LBUTTON)) modifiers |= InputModifiers.LeftMouseButton; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_RBUTTON)) modifiers |= InputModifiers.RightMouseButton; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_MBUTTON)) modifiers |= InputModifiers.MiddleMouseButton; return modifiers; } private void CreateWindow() { // Ensure that the delegate doesn't get garbage collected by storing it as a field. _wndProcDelegate = new UnmanagedMethods.WndProc(WndProc); _className = Guid.NewGuid().ToString(); UnmanagedMethods.WNDCLASSEX wndClassEx = new UnmanagedMethods.WNDCLASSEX { cbSize = Marshal.SizeOf(typeof(UnmanagedMethods.WNDCLASSEX)), style = 0, lpfnWndProc = _wndProcDelegate, hInstance = UnmanagedMethods.GetModuleHandle(null), hCursor = DefaultCursor, hbrBackground = IntPtr.Zero, lpszClassName = _className }; ushort atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx); if (atom == 0) { throw new Win32Exception(); } _hwnd = CreateWindowOverride(atom); if (_hwnd == IntPtr.Zero) { throw new Win32Exception(); } Handle = new PlatformHandle(_hwnd, PlatformConstants.WindowHandleType); if (UnmanagedMethods.ShCoreAvailable) { uint dpix, dpiy; var monitor = UnmanagedMethods.MonitorFromWindow( _hwnd, UnmanagedMethods.MONITOR.MONITOR_DEFAULTTONEAREST); if (UnmanagedMethods.GetDpiForMonitor( monitor, UnmanagedMethods.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out dpix, out dpiy) == 0) { _scaling = dpix / 96.0; } } } private Point DipFromLParam(IntPtr lParam) { return new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)) / Scaling; } private Point PointFromLParam(IntPtr lParam) { return new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)); } private Point ScreenToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y); } private void ShowWindow(WindowState state) { UnmanagedMethods.ShowWindowCommand command; switch (state) { case WindowState.Minimized: command = ShowWindowCommand.Minimize; break; case WindowState.Maximized: command = ShowWindowCommand.Maximize; break; case WindowState.Normal: command = ShowWindowCommand.Restore; break; default: throw new ArgumentException("Invalid WindowState."); } UnmanagedMethods.ShowWindow(_hwnd, command); if (state == WindowState.Maximized) { MaximizeWithoutCoveringTaskbar(); } if (!Design.IsDesignMode) { SetFocus(_hwnd); } } private void MaximizeWithoutCoveringTaskbar() { IntPtr monitor = MonitorFromWindow(_hwnd, MONITOR.MONITOR_DEFAULTTONEAREST); if (monitor != IntPtr.Zero) { MONITORINFO monitorInfo = new MONITORINFO(); if (GetMonitorInfo(monitor, monitorInfo)) { RECT rcMonitorArea = monitorInfo.rcMonitor; var x = monitorInfo.rcWork.left; var y = monitorInfo.rcWork.top; var cx = Math.Abs(monitorInfo.rcWork.right - x); var cy = Math.Abs(monitorInfo.rcWork.bottom - y); SetWindowPos(_hwnd, new IntPtr(-2), x, y, cx, cy, SetWindowPosFlags.SWP_SHOWWINDOW); } } } public void SetIcon(IWindowIconImpl icon) { var impl = (IconImpl)icon; var hIcon = impl.HIcon; UnmanagedMethods.PostMessage(_hwnd, (int)UnmanagedMethods.WindowsMessage.WM_SETICON, new IntPtr((int)UnmanagedMethods.Icons.ICON_BIG), hIcon); } private static int ToInt32(IntPtr ptr) { if (IntPtr.Size == 4) return ptr.ToInt32(); return (int)(ptr.ToInt64() & 0xffffffff); } } }
using System; using System.Data; using System.Xml; using System.Xml.XPath; using System.Collections; using System.IO; using System.Web.Security; using umbraco.IO; namespace umbraco.cms.businesslogic.web { /// <summary> /// Summary description for Access. /// </summary> public class Access { public Access() { // // TODO: Add constructor logic here // } static private Hashtable _checkedPages = new Hashtable(); //must be volatile for double check lock to work static private volatile XmlDocument _accessXmlContent; static private string _accessXmlSource; private static void clearCheckPages() { _checkedPages.Clear(); } static object _locko = new object(); public static XmlDocument AccessXml { get { if (_accessXmlContent == null) { lock (_locko) { if (_accessXmlContent == null) { if (_accessXmlSource == null) { //if we pop it here it'll make for better stack traces ;) _accessXmlSource = IOHelper.MapPath(SystemFiles.AccessXml, true); } _accessXmlContent = new XmlDocument(); if (!System.IO.File.Exists(_accessXmlSource)) { var file = new FileInfo(_accessXmlSource); if (!Directory.Exists(file.DirectoryName)) { Directory.CreateDirectory(file.Directory.FullName); //ensure the folder exists! } System.IO.FileStream f = System.IO.File.Open(_accessXmlSource, FileMode.Create); System.IO.StreamWriter sw = new StreamWriter(f); sw.WriteLine("<access/>"); sw.Close(); f.Close(); } _accessXmlContent.Load(_accessXmlSource); } } } return _accessXmlContent; } } public static void AddMembershipRoleToDocument(int documentId, string role) { //event AddMemberShipRoleToDocumentEventArgs e = new AddMemberShipRoleToDocumentEventArgs(); new Access().FireBeforeAddMemberShipRoleToDocument(new Document(documentId), role, e); if (!e.Cancel) { XmlElement x = (XmlElement)getPage(documentId); if (x == null) throw new Exception("Document is not protected!"); else { if (x.SelectSingleNode("group [@id = '" + role + "']") == null) { XmlElement groupXml = (XmlElement)AccessXml.CreateNode(XmlNodeType.Element, "group", ""); groupXml.SetAttribute("id", role); x.AppendChild(groupXml); save(); } } new Access().FireAfterAddMemberShipRoleToDocument(new Document(documentId), role, e); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void AddMemberGroupToDocument(int DocumentId, int MemberGroupId) { XmlElement x = (XmlElement) getPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); else { if (x.SelectSingleNode("group [@id = '" + MemberGroupId.ToString() + "']") == null) { XmlElement groupXml = (XmlElement) AccessXml.CreateNode(XmlNodeType.Element, "group", ""); groupXml.SetAttribute("id", MemberGroupId.ToString()); x.AppendChild(groupXml); save(); } } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void AddMemberToDocument(int DocumentId, int MemberId) { XmlElement x = (XmlElement) getPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); else { if (x.Attributes.GetNamedItem("memberId") != null) x.Attributes.GetNamedItem("memberId").Value = MemberId.ToString(); else x.SetAttribute("memberId", MemberId.ToString()); save(); } } public static void AddMembershipUserToDocument(int documentId, string membershipUserName) { //event AddMembershipUserToDocumentEventArgs e = new AddMembershipUserToDocumentEventArgs(); new Access().FireBeforeAddMembershipUserToDocument(new Document(documentId), membershipUserName, e); if (!e.Cancel) { XmlElement x = (XmlElement)getPage(documentId); if (x == null) throw new Exception("Document is not protected!"); else { if (x.Attributes.GetNamedItem("memberId") != null) x.Attributes.GetNamedItem("memberId").Value = membershipUserName; else x.SetAttribute("memberId", membershipUserName); save(); } new Access().FireAfterAddMembershipUserToDocument(new Document(documentId), membershipUserName, e); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void RemoveMemberGroupFromDocument(int DocumentId, int MemberGroupId) { XmlElement x = (XmlElement) getPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); else { XmlNode xGroup = x.SelectSingleNode("group [@id = '" + MemberGroupId.ToString() + "']"); if (xGroup != null) { x.RemoveChild(xGroup); save(); } } } public static void RemoveMembershipRoleFromDocument(int documentId, string role) { RemoveMemberShipRoleFromDocumentEventArgs e = new RemoveMemberShipRoleFromDocumentEventArgs(); new Access().FireBeforeRemoveMemberShipRoleFromDocument(new Document(documentId), role, e); if (!e.Cancel) { XmlElement x = (XmlElement)getPage(documentId); if (x == null) throw new Exception("Document is not protected!"); else { XmlNode xGroup = x.SelectSingleNode("group [@id = '" + role + "']"); if (xGroup != null) { x.RemoveChild(xGroup); save(); } } new Access().FireAfterRemoveMemberShipRoleFromDocument(new Document(documentId), role, e); } } public static bool RenameMemberShipRole(string oldRolename, string newRolename) { bool hasChange = false; if (oldRolename != newRolename) { oldRolename = oldRolename.Replace("'", "&apos;"); foreach (XmlNode x in AccessXml.SelectNodes("//group [@id = '" + oldRolename + "']")) { x.Attributes["id"].Value = newRolename; hasChange = true; } if (hasChange) save(); } return hasChange; } public static void ProtectPage(bool Simple, int DocumentId, int LoginDocumentId, int ErrorDocumentId) { AddProtectionEventArgs e = new AddProtectionEventArgs(); new Access().FireBeforeAddProtection(new Document(DocumentId), e); if (!e.Cancel) { XmlElement x = (XmlElement)getPage(DocumentId); if (x == null) { x = (XmlElement)_accessXmlContent.CreateNode(XmlNodeType.Element, "page", ""); AccessXml.DocumentElement.AppendChild(x); } // if using simple mode, make sure that all existing groups are removed else if (Simple) { x.RemoveAll(); } x.SetAttribute("id", DocumentId.ToString()); x.SetAttribute("loginPage", LoginDocumentId.ToString()); x.SetAttribute("noRightsPage", ErrorDocumentId.ToString()); x.SetAttribute("simple", Simple.ToString()); save(); clearCheckPages(); new Access().FireAfterAddProtection(new Document(DocumentId), e); } } public static void RemoveProtection(int DocumentId) { XmlElement x = (XmlElement) getPage(DocumentId); if (x != null) { //event RemoveProtectionEventArgs e = new RemoveProtectionEventArgs(); new Access().FireBeforeRemoveProtection(new Document(DocumentId), e); if (!e.Cancel) { x.ParentNode.RemoveChild(x); save(); clearCheckPages(); new Access().FireAfterRemoveProtection(new Document(DocumentId), e); } } } private static void save() { SaveEventArgs e = new SaveEventArgs(); new Access().FireBeforeSave(e); if (!e.Cancel) { System.IO.FileStream f = System.IO.File.Open(_accessXmlSource, FileMode.Create); AccessXml.Save(f); f.Close(); new Access().FireAfterSave(e); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static bool IsProtectedByGroup(int DocumentId, int GroupId) { bool isProtected = false; cms.businesslogic.web.Document d = new Document(DocumentId); if (!IsProtected(DocumentId, d.Path)) isProtected = false; else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (currentNode.SelectSingleNode("./group [@id=" + GroupId.ToString() + "]") != null) { isProtected = true; } } return isProtected; } public static bool IsProtectedByMembershipRole(int documentId, string role) { bool isProtected = false; CMSNode d = new CMSNode(documentId); if (!IsProtected(documentId, d.Path)) isProtected = false; else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (currentNode.SelectSingleNode("./group [@id='" + role + "']") != null) { isProtected = true; } } return isProtected; } public static string[] GetAccessingMembershipRoles(int documentId, string path) { ArrayList roles = new ArrayList(); if (!IsProtected(documentId, path)) return null; else { XmlNode currentNode = getPage(getProtectedPage(path)); foreach (XmlNode n in currentNode.SelectNodes("./group")) { roles.Add(n.Attributes.GetNamedItem("id").Value); } return (string[])roles.ToArray(typeof(string)); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static cms.businesslogic.member.MemberGroup[] GetAccessingGroups(int DocumentId) { cms.businesslogic.web.Document d = new Document(DocumentId); if (!IsProtected(DocumentId, d.Path)) return null; else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); cms.businesslogic.member.MemberGroup[] mg = new umbraco.cms.businesslogic.member.MemberGroup[currentNode.SelectNodes("./group").Count]; int count = 0; foreach (XmlNode n in currentNode.SelectNodes("./group")) { mg[count] = new cms.businesslogic.member.MemberGroup(int.Parse(n.Attributes.GetNamedItem("id").Value)); count++; } return mg; } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static cms.businesslogic.member.Member GetAccessingMember(int DocumentId) { cms.businesslogic.web.Document d = new Document(DocumentId); if (!IsProtected(DocumentId, d.Path)) return null; else if (GetProtectionType(DocumentId) != ProtectionType.Simple) throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead"); else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (currentNode.Attributes.GetNamedItem("memberId") != null) return new cms.businesslogic.member.Member(int.Parse( currentNode.Attributes.GetNamedItem("memberId").Value)); else throw new Exception("Document doesn't contain a memberId. This might be caused if document is protected using umbraco RC1 or older."); } } public static MembershipUser GetAccessingMembershipUser(int documentId) { CMSNode d = new CMSNode(documentId); if (!IsProtected(documentId, d.Path)) return null; else if (GetProtectionType(documentId) != ProtectionType.Simple) throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead"); else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (currentNode.Attributes.GetNamedItem("memberId") != null) return Membership.GetUser(currentNode.Attributes.GetNamedItem("memberId").Value); else throw new Exception("Document doesn't contain a memberId. This might be caused if document is protected using umbraco RC1 or older."); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static bool HasAccess(int DocumentId, cms.businesslogic.member.Member Member) { bool hasAccess = false; cms.businesslogic.web.Document d = new Document(DocumentId); if (!IsProtected(DocumentId, d.Path)) hasAccess = true; else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (Member != null) { IDictionaryEnumerator ide = Member.Groups.GetEnumerator(); while(ide.MoveNext()) { cms.businesslogic.member.MemberGroup mg = (cms.businesslogic.member.MemberGroup) ide.Value; if (currentNode.SelectSingleNode("./group [@id=" + mg.Id.ToString() + "]") != null) { hasAccess = true; break; } } } } return hasAccess; } public static bool HasAccces(int documentId, object memberId) { bool hasAccess = false; cms.businesslogic.CMSNode node = new CMSNode(documentId); if (!IsProtected(documentId, node.Path)) return true; else { MembershipUser member = Membership.GetUser(memberId); XmlNode currentNode = getPage(getProtectedPage(node.Path)); if (member != null) { foreach(string role in Roles.GetRolesForUser()) { if (currentNode.SelectSingleNode("./group [@id='" + role + "']") != null) { hasAccess = true; break; } } } } return hasAccess; } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] private static bool HasAccess(int DocumentId, string Path, cms.businesslogic.member.Member Member) { bool hasAccess = false; if (!IsProtected(DocumentId, Path)) hasAccess = true; else { XmlNode currentNode = getPage(getProtectedPage(Path)); if (Member != null) { IDictionaryEnumerator ide = Member.Groups.GetEnumerator(); while(ide.MoveNext()) { cms.businesslogic.member.MemberGroup mg = (cms.businesslogic.member.MemberGroup) ide.Value; if (currentNode.SelectSingleNode("./group [@id=" + mg.Id.ToString() + "]") != null) { hasAccess = true; break; } } } } return hasAccess; } public static bool HasAccess(int documentId, string path, MembershipUser member) { bool hasAccess = false; if (!IsProtected(documentId, path)) hasAccess = true; else { XmlNode currentNode = getPage(getProtectedPage(path)); if (member != null) { string[] roles = Roles.GetRolesForUser(member.UserName); foreach(string role in roles) { if (currentNode.SelectSingleNode("./group [@id='" + role + "']") != null) { hasAccess = true; break; } } } } return hasAccess; } public static ProtectionType GetProtectionType(int DocumentId) { XmlNode x = getPage(DocumentId); try { if (bool.Parse(x.Attributes.GetNamedItem("simple").Value)) return ProtectionType.Simple; else return ProtectionType.Advanced; } catch { return ProtectionType.NotProtected; } } public static bool IsProtected(int DocumentId, string Path) { bool isProtected = false; if (!_checkedPages.ContainsKey(DocumentId)) { foreach(string id in Path.Split(',')) { if (getPage(int.Parse(id)) != null) { isProtected = true; break; } } // Add thread safe updating to the hashtable if (System.Web.HttpContext.Current != null) System.Web.HttpContext.Current.Application.Lock(); if (!_checkedPages.ContainsKey(DocumentId)) _checkedPages.Add(DocumentId, isProtected); if (System.Web.HttpContext.Current != null) System.Web.HttpContext.Current.Application.UnLock(); } else isProtected = (bool) _checkedPages[DocumentId]; return isProtected; } public static int GetErrorPage(string Path) { return int.Parse(getPage(getProtectedPage(Path)).Attributes.GetNamedItem("noRightsPage").Value); } public static int GetLoginPage(string Path) { return int.Parse(getPage(getProtectedPage(Path)).Attributes.GetNamedItem("loginPage").Value); } private static int getProtectedPage(string Path) { int protectedPage = 0; foreach(string id in Path.Split(',')) if (getPage(int.Parse(id)) != null) protectedPage = int.Parse(id); return protectedPage; } private static XmlNode getPage(int documentId) { XmlNode x = AccessXml.SelectSingleNode("/access/page [@id=" + documentId.ToString() + "]"); return x; } //Event delegates public delegate void SaveEventHandler(Access sender, SaveEventArgs e); public delegate void AddProtectionEventHandler(Document sender, AddProtectionEventArgs e); public delegate void RemoveProtectionEventHandler(Document sender, RemoveProtectionEventArgs e); public delegate void AddMemberShipRoleToDocumentEventHandler(Document sender, string role, AddMemberShipRoleToDocumentEventArgs e); public delegate void RemoveMemberShipRoleFromDocumentEventHandler(Document sender, string role, RemoveMemberShipRoleFromDocumentEventArgs e); public delegate void RemoveMemberShipUserFromDocumentEventHandler(Document sender, string MembershipUserName, RemoveMemberShipUserFromDocumentEventArgs e); public delegate void AddMembershipUserToDocumentEventHandler(Document sender, string MembershipUserName, AddMembershipUserToDocumentEventArgs e); //Events public static event SaveEventHandler BeforeSave; protected virtual void FireBeforeSave(SaveEventArgs e) { if (BeforeSave != null) BeforeSave(this, e); } public static event SaveEventHandler AfterSave; protected virtual void FireAfterSave(SaveEventArgs e) { if (AfterSave != null) AfterSave(this, e); } public static event AddProtectionEventHandler BeforeAddProtection; protected virtual void FireBeforeAddProtection(Document doc, AddProtectionEventArgs e) { if (BeforeAddProtection != null) BeforeAddProtection(doc, e); } public static event AddProtectionEventHandler AfterAddProtection; protected virtual void FireAfterAddProtection(Document doc, AddProtectionEventArgs e) { if (AfterAddProtection != null) AfterAddProtection(doc, e); } public static event RemoveProtectionEventHandler BeforeRemoveProtection; protected virtual void FireBeforeRemoveProtection(Document doc, RemoveProtectionEventArgs e) { if (BeforeRemoveProtection != null) BeforeRemoveProtection(doc, e); } public static event RemoveProtectionEventHandler AfterRemoveProtection; protected virtual void FireAfterRemoveProtection(Document doc, RemoveProtectionEventArgs e) { if (AfterRemoveProtection != null) AfterRemoveProtection(doc, e); } public static event AddMemberShipRoleToDocumentEventHandler BeforeAddMemberShipRoleToDocument; protected virtual void FireBeforeAddMemberShipRoleToDocument(Document doc, string role, AddMemberShipRoleToDocumentEventArgs e) { if (BeforeAddMemberShipRoleToDocument != null) BeforeAddMemberShipRoleToDocument(doc, role, e); } public static event AddMemberShipRoleToDocumentEventHandler AfterAddMemberShipRoleToDocument; protected virtual void FireAfterAddMemberShipRoleToDocument(Document doc, string role, AddMemberShipRoleToDocumentEventArgs e) { if (AfterAddMemberShipRoleToDocument != null) AfterAddMemberShipRoleToDocument(doc, role, e); } public static event RemoveMemberShipRoleFromDocumentEventHandler BeforeRemoveMemberShipRoleToDocument; protected virtual void FireBeforeRemoveMemberShipRoleFromDocument(Document doc, string role, RemoveMemberShipRoleFromDocumentEventArgs e) { if (BeforeRemoveMemberShipRoleToDocument != null) BeforeRemoveMemberShipRoleToDocument(doc, role, e); } public static event RemoveMemberShipRoleFromDocumentEventHandler AfterRemoveMemberShipRoleToDocument; protected virtual void FireAfterRemoveMemberShipRoleFromDocument(Document doc, string role, RemoveMemberShipRoleFromDocumentEventArgs e) { if (AfterRemoveMemberShipRoleToDocument != null) AfterRemoveMemberShipRoleToDocument(doc, role, e); } public static event RemoveMemberShipUserFromDocumentEventHandler BeforeRemoveMembershipUserFromDocument; protected virtual void FireBeforeRemoveMembershipUserFromDocument(Document doc, string username, RemoveMemberShipUserFromDocumentEventArgs e) { if (BeforeRemoveMembershipUserFromDocument != null) BeforeRemoveMembershipUserFromDocument(doc, username, e); } public static event RemoveMemberShipUserFromDocumentEventHandler AfterRemoveMembershipUserFromDocument; protected virtual void FireAfterRemoveMembershipUserFromDocument(Document doc, string username, RemoveMemberShipUserFromDocumentEventArgs e) { if (AfterRemoveMembershipUserFromDocument != null) AfterRemoveMembershipUserFromDocument(doc, username, e); } public static event AddMembershipUserToDocumentEventHandler BeforeAddMembershipUserToDocument; protected virtual void FireBeforeAddMembershipUserToDocument(Document doc, string username, AddMembershipUserToDocumentEventArgs e) { if (BeforeAddMembershipUserToDocument != null) BeforeAddMembershipUserToDocument(doc, username, e); } public static event AddMembershipUserToDocumentEventHandler AfterAddMembershipUserToDocument; protected virtual void FireAfterAddMembershipUserToDocument(Document doc, string username, AddMembershipUserToDocumentEventArgs e) { if (AfterAddMembershipUserToDocument != null) AfterAddMembershipUserToDocument(doc, username, e); } } public enum ProtectionType { NotProtected, Simple, Advanced } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace System.Collections.Generic { // The SortedDictionary class implements a generic sorted list of keys // and values. Entries in a sorted list are sorted by their keys and // are accessible both by key and by index. The keys of a sorted dictionary // can be ordered either according to a specific IComparer // implementation given when the sorted dictionary is instantiated, or // according to the IComparable implementation provided by the keys // themselves. In either case, a sorted dictionary does not allow entries // with duplicate or null keys. // // A sorted list internally maintains two arrays that store the keys and // values of the entries. The capacity of a sorted list is the allocated // length of these internal arrays. As elements are added to a sorted list, the // capacity of the sorted list is automatically increased as required by // reallocating the internal arrays. The capacity is never automatically // decreased, but users can call either TrimExcess or // Capacity explicitly. // // The GetKeyList and GetValueList methods of a sorted list // provides access to the keys and values of the sorted list in the form of // List implementations. The List objects returned by these // methods are aliases for the underlying sorted list, so modifications // made to those lists are directly reflected in the sorted list, and vice // versa. // // The SortedList class provides a convenient way to create a sorted // copy of another dictionary, such as a Hashtable. For example: // // Hashtable h = new Hashtable(); // h.Add(...); // h.Add(...); // ... // SortedList s = new SortedList(h); // // The last line above creates a sorted list that contains a copy of the keys // and values stored in the hashtable. In this particular example, the keys // will be ordered according to the IComparable interface, which they // all must implement. To impose a different ordering, SortedList also // has a constructor that allows a specific IComparer implementation to // be specified. // [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, System.Collections.IDictionary, IReadOnlyDictionary<TKey, TValue> { private TKey[] _keys; private TValue[] _values; private int _size; private int _version; private IComparer<TKey> _comparer; private KeyList _keyList; private ValueList _valueList; private Object _syncRoot; private const int DefaultCapacity = 4; // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to DefaultCapacity, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. public SortedList() { _keys = Array.Empty<TKey>(); _values = Array.Empty<TValue>(); _size = 0; _comparer = Comparer<TKey>.Default; } // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to 16, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. // public SortedList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); _keys = new TKey[capacity]; _values = new TValue[capacity]; _comparer = Comparer<TKey>.Default; } // Constructs a new sorted list with a given IComparer // implementation. The sorted list is initially empty and has a capacity of // zero. Upon adding the first element to the sorted list the capacity is // increased to 16, and then increased in multiples of two as required. The // elements of the sorted list are ordered according to the given // IComparer implementation. If comparer is null, the // elements are compared to each other using the IComparable // interface, which in that case must be implemented by the keys of all // entries added to the sorted list. // public SortedList(IComparer<TKey> comparer) : this() { if (comparer != null) { _comparer = comparer; } } // Constructs a new sorted dictionary with a given IComparer // implementation and a given initial capacity. The sorted list is // initially empty, but will have room for the given number of elements // before any reallocations are required. The elements of the sorted list // are ordered according to the given IComparer implementation. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by the keys of all entries added to the sorted list. // public SortedList(int capacity, IComparer<TKey> comparer) : this(comparer) { Capacity = capacity; } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the IComparable interface, which must be implemented by the // keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the given IComparer implementation. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented // by the keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) : this((dictionary != null ? dictionary.Count : 0), comparer) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); int count = dictionary.Count; if (count != 0) { TKey[] keys = _keys; dictionary.Keys.CopyTo(keys, 0); dictionary.Values.CopyTo(_values, 0); Debug.Assert(count == _keys.Length); if (count > 1) { comparer = Comparer; // obtain default if this is null. Array.Sort<TKey, TValue>(keys, _values, comparer); for (int i = 1; i != keys.Length; ++i) { if (comparer.Compare(keys[i - 1], keys[i]) == 0) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, keys[i])); } } } } _size = count; } // Adds an entry with the given key and value to this sorted list. An // ArgumentException is thrown if the key is already present in the sorted list. // public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key)); Insert(~i, key, value); } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int index = IndexOfKey(keyValuePair.Key); if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_values[index], keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int index = IndexOfKey(keyValuePair.Key); if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_values[index], keyValuePair.Value)) { RemoveAt(index); return true; } return false; } // Returns the capacity of this sorted list. The capacity of a sorted list // represents the allocated length of the internal arrays used to store the // keys and values of the list, and thus also indicates the maximum number // of entries the list can contain before a reallocation of the internal // arrays is required. // public int Capacity { get { return _keys.Length; } set { if (value != _keys.Length) { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity); } if (value > 0) { TKey[] newKeys = new TKey[value]; TValue[] newValues = new TValue[value]; if (_size > 0) { Array.Copy(_keys, 0, newKeys, 0, _size); Array.Copy(_values, 0, newValues, 0, _size); } _keys = newKeys; _values = newValues; } else { _keys = Array.Empty<TKey>(); _values = Array.Empty<TValue>(); } } } } public IComparer<TKey> Comparer { get { return _comparer; } } void System.Collections.IDictionary.Add(Object key, Object value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null && !(default(TValue) == null)) // null is an invalid value for Value types throw new ArgumentNullException(nameof(value)); if (!(key is TKey)) throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); if (!(value is TValue) && value != null) // null is a valid value for Reference Types throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); Add((TKey)key, (TValue)value); } // Returns the number of entries in this sorted list. // public int Count { get { return _size; } } // Returns a collection representing the keys of this sorted list. This // method returns the same object as GetKeyList, but typed as an // ICollection instead of an IList. // public IList<TKey> Keys { get { return GetKeyListHelper(); } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return GetKeyListHelper(); } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return GetKeyListHelper(); } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return GetKeyListHelper(); } } // Returns a collection representing the values of this sorted list. This // method returns the same object as GetValueList, but typed as an // ICollection instead of an IList. // public IList<TValue> Values { get { return GetValueListHelper(); } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return GetValueListHelper(); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return GetValueListHelper(); } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return GetValueListHelper(); } } private KeyList GetKeyListHelper() { if (_keyList == null) _keyList = new KeyList(this); return _keyList; } private ValueList GetValueListHelper() { if (_valueList == null) _valueList = new ValueList(this); return _valueList; } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } bool System.Collections.IDictionary.IsReadOnly { get { return false; } } bool System.Collections.IDictionary.IsFixedSize { get { return false; } } bool System.Collections.ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. Object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all entries from this sorted list. public void Clear() { // clear does not change the capacity _version++; // Don't need to doc this but we clear the elements so that the gc can reclaim the references. Array.Clear(_keys, 0, _size); Array.Clear(_values, 0, _size); _size = 0; } bool System.Collections.IDictionary.Contains(Object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } // Checks if this sorted list contains an entry with the given key. // public bool ContainsKey(TKey key) { return IndexOfKey(key) >= 0; } // Checks if this sorted list contains an entry with the given value. The // values of the entries of the sorted list are compared to the given value // using the Object.Equals method. This method performs a linear // search and is substantially slower than the Contains // method. // public bool ContainsValue(TValue value) { return IndexOfValue(value) >= 0; } // Copies the values in this SortedList to an array. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } for (int i = 0; i < Count; i++) { KeyValuePair<TKey, TValue> entry = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]); array[arrayIndex + i] = entry; } } void System.Collections.ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] keyValuePairArray = array as KeyValuePair<TKey, TValue>[]; if (keyValuePairArray != null) { for (int i = 0; i < Count; i++) { keyValuePairArray[i + index] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]); } } else { object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } try { for (int i = 0; i < Count; i++) { objects[i + index] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } } private const int MaxArrayLength = 0X7FEFFFFF; // Ensures that the capacity of this sorted list is at least the given // minimum value. If the current capacity of the list is less than // min, the capacity is increased to twice the current capacity or // to min, whichever is larger. private void EnsureCapacity(int min) { int newCapacity = _keys.Length == 0 ? DefaultCapacity : _keys.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } // Returns the value of the entry at the given index. // private TValue GetByIndex(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); return _values[index]; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } // Returns the key of the entry at the given index. // private TKey GetKey(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); return _keys[index]; } // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. // public TValue this[TKey key] { get { int i = IndexOfKey(key); if (i >= 0) return _values[i]; throw new KeyNotFoundException(); // return default(TValue); } set { if (((Object)key) == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer); if (i >= 0) { _values[i] = value; _version++; return; } Insert(~i, key, value); } } Object System.Collections.IDictionary.this[Object key] { get { if (IsCompatibleKey(key)) { int i = IndexOfKey((TKey)key); if (i >= 0) { return _values[i]; } } return null; } set { if (!IsCompatibleKey(key)) { throw new ArgumentException(SR.Argument_InvalidArgumentForComparison, nameof(key)); } if (value == null && !(default(TValue) == null)) throw new ArgumentNullException(nameof(value)); TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); } } } // Returns the index of the entry with a given key in this sorted list. The // key is located through a binary search, and thus the average execution // time of this method is proportional to Log2(size), where // size is the size of this sorted list. The returned value is -1 if // the given key does not occur in this sorted list. Null is an invalid // key value. // public int IndexOfKey(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); int ret = Array.BinarySearch<TKey>(_keys, 0, _size, key, _comparer); return ret >= 0 ? ret : -1; } // Returns the index of the first occurrence of an entry with a given value // in this sorted list. The entry is located through a linear search, and // thus the average execution time of this method is proportional to the // size of this sorted list. The elements of the list are compared to the // given value using the Object.Equals method. // public int IndexOfValue(TValue value) { return Array.IndexOf(_values, value, 0, _size); } // Inserts an entry with a given key and value at a given index. private void Insert(int index, TKey key, TValue value) { if (_size == _keys.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_keys, index, _keys, index + 1, _size - index); Array.Copy(_values, index, _values, index + 1, _size - index); } _keys[index] = key; _values[index] = value; _size++; _version++; } public bool TryGetValue(TKey key, out TValue value) { int i = IndexOfKey(key); if (i >= 0) { value = _values[i]; return true; } value = default(TValue); return false; } // Removes the entry at the given index. The size of the sorted list is // decreased by one. // public void RemoveAt(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); _size--; if (index < _size) { Array.Copy(_keys, index + 1, _keys, index, _size - index); Array.Copy(_values, index + 1, _values, index, _size - index); } _keys[_size] = default(TKey); _values[_size] = default(TValue); _version++; } // Removes an entry from this sorted list. If an entry with the specified // key exists in the sorted list, it is removed. An ArgumentException is // thrown if the key is null. // public bool Remove(TKey key) { int i = IndexOfKey(key); if (i >= 0) RemoveAt(i); return i >= 0; } void System.Collections.IDictionary.Remove(Object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } // Sets the capacity of this sorted list to the size of the sorted list. // This method can be used to minimize a sorted list's memory overhead once // it is known that no new elements will be added to the sorted list. To // completely clear a sorted list and release all memory referenced by the // sorted list, execute the following statements: // // SortedList.Clear(); // SortedList.TrimExcess(); // public void TrimExcess() { int threshold = (int)(((double)_keys.Length) * 0.9); if (_size < threshold) { Capacity = _size; } } private static bool IsCompatibleKey(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return (key is TKey); } /// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedListEnumerator"]/*' /> private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator { private SortedList<TKey, TValue> _sortedList; private TKey _key; private TValue _value; private int _index; private int _version; private int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int KeyValuePair = 1; internal const int DictEntry = 2; internal Enumerator(SortedList<TKey, TValue> sortedList, int getEnumeratorRetType) { _sortedList = sortedList; _index = 0; _version = _sortedList._version; _getEnumeratorRetType = getEnumeratorRetType; _key = default(TKey); _value = default(TValue); } public void Dispose() { _index = 0; _key = default(TKey); _value = default(TValue); } Object System.Collections.IDictionaryEnumerator.Key { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _key; } } public bool MoveNext() { if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if ((uint)_index < (uint)_sortedList.Count) { _key = _sortedList._keys[_index]; _value = _sortedList._values[_index]; _index++; return true; } _index = _sortedList.Count + 1; _key = default(TKey); _value = default(TValue); return false; } DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_key, _value); } } public KeyValuePair<TKey, TValue> Current { get { return new KeyValuePair<TKey, TValue>(_key, _value); } } Object System.Collections.IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry(_key, _value); } else { return new KeyValuePair<TKey, TValue>(_key, _value); } } } Object System.Collections.IDictionaryEnumerator.Value { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _value; } } void System.Collections.IEnumerator.Reset() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _key = default(TKey); _value = default(TValue); } } private sealed class SortedListKeyEnumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private SortedList<TKey, TValue> _sortedList; private int _index; private int _version; private TKey _currentKey; internal SortedListKeyEnumerator(SortedList<TKey, TValue> sortedList) { _sortedList = sortedList; _version = sortedList._version; } public void Dispose() { _index = 0; _currentKey = default(TKey); } public bool MoveNext() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if ((uint)_index < (uint)_sortedList.Count) { _currentKey = _sortedList._keys[_index]; _index++; return true; } _index = _sortedList.Count + 1; _currentKey = default(TKey); return false; } public TKey Current { get { return _currentKey; } } Object System.Collections.IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentKey; } } void System.Collections.IEnumerator.Reset() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _currentKey = default(TKey); } } private sealed class SortedListValueEnumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private SortedList<TKey, TValue> _sortedList; private int _index; private int _version; private TValue _currentValue; internal SortedListValueEnumerator(SortedList<TKey, TValue> sortedList) { _sortedList = sortedList; _version = sortedList._version; } public void Dispose() { _index = 0; _currentValue = default(TValue); } public bool MoveNext() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if ((uint)_index < (uint)_sortedList.Count) { _currentValue = _sortedList._values[_index]; _index++; return true; } _index = _sortedList.Count + 1; _currentValue = default(TValue); return false; } public TValue Current { get { return _currentValue; } } Object System.Collections.IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentValue; } } void System.Collections.IEnumerator.Reset() { if (_version != _sortedList._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _currentValue = default(TValue); } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] private sealed class KeyList : IList<TKey>, System.Collections.ICollection { private SortedList<TKey, TValue> _dict; internal KeyList(SortedList<TKey, TValue> dictionary) { _dict = dictionary; } public int Count { get { return _dict._size; } } public bool IsReadOnly { get { return true; } } bool System.Collections.ICollection.IsSynchronized { get { return false; } } Object System.Collections.ICollection.SyncRoot { get { return ((ICollection)_dict).SyncRoot; } } public void Add(TKey key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public bool Contains(TKey key) { return _dict.ContainsKey(key); } public void CopyTo(TKey[] array, int arrayIndex) { // defer error checking to Array.Copy Array.Copy(_dict._keys, 0, array, arrayIndex, _dict.Count); } void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try { // defer error checking to Array.Copy Array.Copy(_dict._keys, 0, array, arrayIndex, _dict.Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } public void Insert(int index, TKey value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public TKey this[int index] { get { return _dict.GetKey(index); } set { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } } public IEnumerator<TKey> GetEnumerator() { return new SortedListKeyEnumerator(_dict); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new SortedListKeyEnumerator(_dict); } public int IndexOf(TKey key) { if (((Object)key) == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(_dict._keys, 0, _dict.Count, key, _dict._comparer); if (i >= 0) return i; return -1; } public bool Remove(TKey key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return false; } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] private sealed class ValueList : IList<TValue>, System.Collections.ICollection { private SortedList<TKey, TValue> _dict; internal ValueList(SortedList<TKey, TValue> dictionary) { _dict = dictionary; } public int Count { get { return _dict._size; } } public bool IsReadOnly { get { return true; } } bool System.Collections.ICollection.IsSynchronized { get { return false; } } Object System.Collections.ICollection.SyncRoot { get { return ((ICollection)_dict).SyncRoot; } } public void Add(TValue key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public bool Contains(TValue value) { return _dict.ContainsValue(value); } public void CopyTo(TValue[] array, int arrayIndex) { // defer error checking to Array.Copy Array.Copy(_dict._values, 0, array, arrayIndex, _dict.Count); } void System.Collections.ICollection.CopyTo(Array array, int index) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try { // defer error checking to Array.Copy Array.Copy(_dict._values, 0, array, index, _dict.Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } public void Insert(int index, TValue value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public TValue this[int index] { get { return _dict.GetByIndex(index); } set { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } public IEnumerator<TValue> GetEnumerator() { return new SortedListValueEnumerator(_dict); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new SortedListValueEnumerator(_dict); } public int IndexOf(TValue value) { return Array.IndexOf(_dict._values, value, 0, _dict.Count); } public bool Remove(TValue value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return false; } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void BlendUInt321() { var test = new ImmBinaryOpTest__BlendUInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // 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 ImmBinaryOpTest__BlendUInt321 { private struct TestStruct { public Vector128<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__BlendUInt321 testClass) { var result = Avx2.Blend(_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<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static ImmBinaryOpTest__BlendUInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public ImmBinaryOpTest__BlendUInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[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.Blend( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_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.Blend( Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_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.Blend( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_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.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(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.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(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.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Blend( _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<Vector128<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.Blend(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 = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(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 = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__BlendUInt321(); var result = Avx2.Blend(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.Blend(_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.Blend(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(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((1 & (1 << 0)) == 0) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (((1 & (1 << i)) == 0) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<UInt32>(Vector128<UInt32>.1, Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Threading; namespace System.IO { public partial class FileSystemWatcher { /// <summary>Start monitoring the current directory.</summary> private void StartRaisingEvents() { // If we're already running, don't do anything. if (!IsHandleInvalid(_directoryHandle)) return; // Create handle to directory being monitored var defaultSecAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES); _directoryHandle = Interop.mincore.CreateFile( lpFileName: _directory, dwDesiredAccess: Interop.mincore.FileOperations.FILE_LIST_DIRECTORY, dwShareMode: FileShare.Read | FileShare.Delete | FileShare.Write, securityAttrs: ref defaultSecAttrs, dwCreationDisposition: FileMode.Open, dwFlagsAndAttributes: Interop.mincore.FileOperations.FILE_FLAG_BACKUP_SEMANTICS | Interop.mincore.FileOperations.FILE_FLAG_OVERLAPPED, hTemplateFile: IntPtr.Zero); if (IsHandleInvalid(_directoryHandle)) { _directoryHandle = null; throw new FileNotFoundException(SR.Format(SR.FSW_IOError, _directory)); } // Create the state associated with the operation of monitoring the direction AsyncReadState state; try { // Start ignoring all events that were initiated before this, and // allocate the buffer to be pinned and used for the duration of the operation int session = Interlocked.Increment(ref _currentSession); byte[] buffer = AllocateBuffer(); // Store all state, including a preallocated overlapped, into the state object that'll be // passed from iteration to iteration during the lifetime of the operation. The buffer will be pinned // from now until the end of the operation. state = new AsyncReadState(session, buffer, _directoryHandle, ThreadPoolBoundHandle.BindHandle(_directoryHandle)); unsafe { state.PreAllocatedOverlapped = new PreAllocatedOverlapped(ReadDirectoryChangesCallback, state, buffer); } } catch { // Make sure we don't leave a valid directory handle set if we're not running _directoryHandle.Dispose(); _directoryHandle = null; throw; } // Start monitoring _enabled = true; Monitor(state); } /// <summary>Stop monitoring the current directory.</summary> private void StopRaisingEvents() { _enabled = false; // If we're not running, do nothing. if (IsHandleInvalid(_directoryHandle)) return; // Start ignoring all events occurring after this. Interlocked.Increment(ref _currentSession); // Close the directory handle. This will cause the async operation to stop processing. // This operation doesn't need to be atomic because the API will deal with a closed // handle appropriately. If we get here while asynchronously waiting on a change notification, // closing the directory handle should cause ReadDirectoryChangesCallback be called, // cleaning up the operation. Note that it's critical to also null out the handle. If the // handle is currently in use in a P/Invoke, it will have its reference count temporarily // increased, such that the disposal operation won't take effect and close the handle // until that P/Invoke returns; if during that time the FSW is restarted, the IsHandleInvalid // check will see a valid handle, unless we also null it out. _directoryHandle.Dispose(); _directoryHandle = null; } private void FinalizeDispose() { // We must explicitly dispose the handle to ensure it gets closed before this object is finalized. // Otherwise, it is possible that the GC will decide to finalize the handle after this, // leaving a window of time where our callback could be invoked on a non-existent object. if (!IsHandleInvalid(_directoryHandle)) _directoryHandle.Dispose(); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- // Current "session" ID to ignore old events whenever we stop then restart. private int _currentSession; // Unmanaged handle to monitored directory private SafeFileHandle _directoryHandle; private static bool IsHandleInvalid(SafeFileHandle handle) { return handle == null || handle.IsInvalid || handle.IsClosed; } /// <summary> /// Initiates the next asynchronous read operation if monitoring is still desired. /// If the directory handle has been closed due to an error or due to event monitoring /// being disabled, this cleans up state associated with the operation. /// </summary> private unsafe void Monitor(AsyncReadState state) { // This method should only ever access the directory handle via the state object passed in, and not access it // via _directoryHandle. While this function is executing asynchronously, another thread could set // EnableRaisingEvents to false and then back to true, restarting the FSW and causing a new directory handle // and thread pool binding to be stored. This function could then get into an inconsistent state by doing some // operations against the old handles and some against the new. NativeOverlapped* overlappedPointer = null; bool continueExecuting = false; try { // If shutdown has been requested, exit. The finally block will handle // cleaning up the entire operation, as continueExecuting will remain false. if (!_enabled || IsHandleInvalid(state.DirectoryHandle)) return; // Get the overlapped pointer to use for this iteration. overlappedPointer = state.ThreadPoolBinding.AllocateNativeOverlapped(state.PreAllocatedOverlapped); int size; continueExecuting = Interop.mincore.ReadDirectoryChangesW( state.DirectoryHandle, state.Buffer, // the buffer is kept pinned for the duration of the sync and async operation by the PreAllocatedOverlapped _internalBufferSize, _includeSubdirectories, (int)_notifyFilters, out size, overlappedPointer, IntPtr.Zero); } catch (ObjectDisposedException) { // Ignore. Disposing of the handle is the mechanism by which the FSW communicates // to the asynchronous operation to stop processing. } catch (ArgumentNullException) { //Ignore. The disposed handle could also manifest as an ArgumentNullException. Debug.Assert(IsHandleInvalid(state.DirectoryHandle), "ArgumentNullException from something other than SafeHandle?"); } finally { // At this point the operation has either been initiated and we'll let the callback // handle things from here, or the operation has been stopped or failed, in which case // we need to cleanup because we're no longer executing. if (!continueExecuting) { // Clean up the overlapped pointer created for this iteration if (overlappedPointer != null) { state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer); } // Clean up the thread pool binding created for the entire operation state.PreAllocatedOverlapped.Dispose(); state.ThreadPoolBinding.Dispose(); // Finally, if the handle was for some reason changed or closed during this call, // then don't throw an exception. Otherwise, it's a valid error. if (!IsHandleInvalid(state.DirectoryHandle)) { OnError(new ErrorEventArgs(new Win32Exception())); } } } } /// <summary>Callback invoked when an asynchronous read on the directory handle completes.</summary> private unsafe void ReadDirectoryChangesCallback(uint errorCode, uint numBytes, NativeOverlapped* overlappedPointer) { AsyncReadState state = (AsyncReadState)ThreadPoolBoundHandle.GetNativeOverlappedState(overlappedPointer); try { if (IsHandleInvalid(state.DirectoryHandle)) return; if (errorCode != 0) { // Inside a service the first completion status is false; // need to monitor again. const int ERROR_OPERATION_ABORTED = 995; if (errorCode != ERROR_OPERATION_ABORTED) { OnError(new ErrorEventArgs(new Win32Exception((int)errorCode))); EnableRaisingEvents = false; } return; } // Ignore any events that occurred before this "session", // so we don't get changed or error events after we // told FSW to stop. Even with this check, though, there's a small // race condition, as immediately after we do the check, raising // events could be disabled. if (state.Session != Volatile.Read(ref _currentSession)) return; if (numBytes == 0) { NotifyInternalBufferOverflowEvent(); } else { ParseEventBufferAndNotifyForEach(state.Buffer); } } finally { // Clean up state associated with this one iteration state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer); // Then call Monitor again to either start the next iteration or // clean up the whole operation. Monitor(state); } } private void ParseEventBufferAndNotifyForEach(byte[] buffer) { // Parse each event from the buffer and notify appropriate delegates /****** Format for the buffer is the following C struct: typedef struct _FILE_NOTIFY_INFORMATION { DWORD NextEntryOffset; DWORD Action; DWORD FileNameLength; WCHAR FileName[1]; } FILE_NOTIFY_INFORMATION; NOTE1: FileNameLength is length in bytes. NOTE2: The Filename is a Unicode string that's NOT NULL terminated. NOTE3: A NextEntryOffset of zero means that it's the last entry *******/ // Parse the file notify buffer: int offset = 0; int nextOffset, action, nameLength; string oldName = null; string name = null; do { unsafe { fixed (byte* buffPtr = buffer) { // Get next offset: nextOffset = *((int*)(buffPtr + offset)); // Get change flag: action = *((int*)(buffPtr + offset + 4)); // Get filename length (in bytes): nameLength = *((int*)(buffPtr + offset + 8)); name = new string((char*)(buffPtr + offset + 12), 0, nameLength / 2); } } /* A slightly convoluted piece of code follows. Here's what's happening: We wish to collapse the poorly done rename notifications from the ReadDirectoryChangesW API into a nice rename event. So to do that, it's assumed that a FILE_ACTION_RENAMED_OLD_NAME will be followed immediately by a FILE_ACTION_RENAMED_NEW_NAME in the buffer, which is all that the following code is doing. On a FILE_ACTION_RENAMED_OLD_NAME, it asserts that no previous one existed and saves its name. If there are no more events in the buffer, it'll assert and fire a RenameEventArgs with the Name field null. If a NEW_NAME action comes in with no previous OLD_NAME, we assert and fire a rename event with the OldName field null. If the OLD_NAME and NEW_NAME actions are indeed there one after the other, we'll fire the RenamedEventArgs normally and clear oldName. If the OLD_NAME is followed by another action, we assert and then fire the rename event with the Name field null and then fire the next action. In case it's not a OLD_NAME or NEW_NAME action, we just fire the event normally. (Phew!) */ // If the action is RENAMED_FROM, save the name of the file if (action == Interop.mincore.FileOperations.FILE_ACTION_RENAMED_OLD_NAME) { Debug.Assert(oldName == null, "Two FILE_ACTION_RENAMED_OLD_NAME in a row! [" + oldName + "], [ " + name + "]"); oldName = name; } else if (action == Interop.mincore.FileOperations.FILE_ACTION_RENAMED_NEW_NAME) { if (oldName != null) { NotifyRenameEventArgs(WatcherChangeTypes.Renamed, name, oldName); oldName = null; } else { Debug.Fail("FILE_ACTION_RENAMED_NEW_NAME with no old name! [ " + name + "]"); NotifyRenameEventArgs(WatcherChangeTypes.Renamed, name, oldName); oldName = null; } } else { if (oldName != null) { Debug.Fail("Previous FILE_ACTION_RENAMED_OLD_NAME with no new name! [" + oldName + "]"); NotifyRenameEventArgs(WatcherChangeTypes.Renamed, null, oldName); oldName = null; } switch (action) { case Interop.mincore.FileOperations.FILE_ACTION_ADDED: NotifyFileSystemEventArgs(WatcherChangeTypes.Created, name); break; case Interop.mincore.FileOperations.FILE_ACTION_REMOVED: NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, name); break; case Interop.mincore.FileOperations.FILE_ACTION_MODIFIED: NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, name); break; default: Debug.Fail("Unknown FileSystemEvent action type! Value: " + action); break; } } offset += nextOffset; } while (nextOffset != 0); if (oldName != null) { Debug.Fail("FILE_ACTION_RENAMED_OLD_NAME with no new name! [" + oldName + "]"); NotifyRenameEventArgs(WatcherChangeTypes.Renamed, null, oldName); oldName = null; } } /// <summary> /// State information used by the ReadDirectoryChangesW callback. A single instance of this is used /// for an entire session, getting passed to each iterative call to ReadDirectoryChangesW. /// </summary> private sealed class AsyncReadState { internal AsyncReadState(int session, byte[] buffer, SafeFileHandle handle, ThreadPoolBoundHandle binding) { Debug.Assert(buffer != null); Debug.Assert(handle != null); Debug.Assert(binding != null); Session = session; Buffer = buffer; DirectoryHandle = handle; ThreadPoolBinding = binding; } internal int Session { get; private set; } internal byte[] Buffer { get; private set; } internal SafeFileHandle DirectoryHandle { get; private set; } internal ThreadPoolBoundHandle ThreadPoolBinding { get; private set; } internal PreAllocatedOverlapped PreAllocatedOverlapped { get; set; } } } }
using System; using MGTK.Controls; using MGTK.Enumerators; using Rothko.GUI.MonoGame.Controls; using Rothko.GUI.MonoGame.Interfaces.Dal; using Ninject; using Rothko.UI.Interfaces.Services; using Rothko.UI.Interfaces.Dal; namespace Rothko.GUI.MonoGame.Views { public partial class EditAnimationView { Label _LabelName; TextBox _TextBoxName; Label _LabelListBoxAssets; ListBox _ListBoxAssets; Button _ButtonAddAssetBefore; Button _ButtonAddAssetAfter; Label _LabelListBoxFrames; ListBox _ListBoxFrames; Label _LabelDuration; NumericUpDown _NumericUpDownDuration; Button _ButtonRemoveFrame; Button _ButtonPushFrameUp; Button _ButtonPushFrameDown; Button _ButtonStop; Button _ButtonPlay; Button _ButtonPlayLooped; Button _ButtonOK; Button _ButtonCancel; Label _LabelAnimationControl; InnerAnimationControl _AnimationControl; GroupBox _GroupBoxAnimation; DialogResult DialogResult { get; set; } void InitializeComponent () { int formWidth = 608; int formHeight = 320; Width = formWidth; Height = formHeight; Text = "ANIMATION"; _LabelListBoxAssets = new Label(this) { X = 8, Y = 8, Height = 8, Width = 192, Text = "Assets" }; _ListBoxAssets = new ListBox(this) { X = 8, Y = _LabelListBoxAssets.Y + 16, Height = formHeight - 64 - 24 - 8, Width = 192, SelectedIndex = -1, Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top }; _ButtonAddAssetBefore = new Button(this) { X = 8, Y = _ListBoxAssets.Y + _ListBoxAssets.Height + 8, Width = _ListBoxAssets.Width / 2, Height = 24, Text = "Add Before", Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _ButtonAddAssetAfter = new Button(this) { X = 8 + _ButtonAddAssetBefore.Width, Y = _ListBoxAssets.Y + _ListBoxAssets.Height + 8, Width = _ListBoxAssets.Width / 2, Height = 24, Text = "Add After", Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _LabelListBoxFrames = new Label(this) { X = 8 + 8 + _ListBoxAssets.Width, Y = 8 + 40 + 8, Height = 8, Width = 192, Text = "Frames" }; _ListBoxFrames = new ListBox(this) { X = 8 + 8 + _ListBoxAssets.Width, Y = _LabelListBoxAssets.Y + 16 + 40 + 8, Height = formHeight - 8 - 40 - 64 - 24 - 8 - 32, Width = 192, SelectedIndex = -1, Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top }; _LabelName = new Label(this) { X = _ListBoxAssets.X + _ListBoxAssets.Width + 8, Y = _LabelListBoxAssets.Y, Width = 96, Height = 16, Text = "Name" }; _TextBoxName = new TextBox(this) { X = _LabelName.X, Y = _LabelName.Y + 16, Width = _ListBoxFrames.Width, Height = 24, Text = "" }; _NumericUpDownDuration = new NumericUpDown(this) { X = _LabelListBoxFrames.X, Y = _ListBoxFrames.Y + _ListBoxFrames.Height + 8, Width = _ListBoxFrames.Width - 64 + 16, Height = 24, Maximum = 999999, Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _LabelDuration = new Label(this) { X = _LabelListBoxFrames.X + _NumericUpDownDuration.Width + 8, Y = _NumericUpDownDuration.Y + 4, Width = 48, Height = 24, Text = "msecs", Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _ButtonPushFrameUp = new Button(this) { X = _LabelListBoxFrames.X, Y = _ListBoxFrames.Y + _ListBoxFrames.Height + 8 + 32, Width = _ListBoxFrames.Width / 8, Height = 24, Image = Theme.ArrowUp, Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _ButtonPushFrameDown = new Button(this) { X = _LabelListBoxFrames.X + _ButtonPushFrameUp.Width, Y = _ListBoxFrames.Y + _ListBoxFrames.Height + 8 + 32, Width = _ListBoxFrames.Width / 8, Height = 24, Image = Theme.ArrowDown, Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _ButtonRemoveFrame = new Button(this) { X = _LabelListBoxFrames.X + _ListBoxFrames.Width - (_ListBoxFrames.Width - _ButtonPushFrameDown.Width * 2), Y = _ListBoxFrames.Y + _ListBoxFrames.Height + 8 + 32, Width = _ListBoxFrames.Width - _ButtonPushFrameDown.Width * 2, Height = 24, Text = "Remove", Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _LabelAnimationControl = new Label(this) { X = _ListBoxFrames.X + _ListBoxFrames.Width + 8, Y = 8 + 48, Height = 8, Width = 192, Text = "Animation" }; _GroupBoxAnimation = new GroupBox(this) { X = _LabelAnimationControl.X, Y = _LabelAnimationControl.Y + 8, Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top, Width = 192, Height = formHeight - 64 - 24 - 8 - 32 - 8 }; _AnimationControl = new InnerAnimationControl(this, _Kernel.Get<IAnimationService>(), _Kernel.Get<IContentDatabase>(), _Kernel.Get<IUIRothkoDatabase>()) { X = 8, Y = 16, Width = 192 - 16, Height = formHeight - 64 - 8 - 24 - 24 - 32 - 8, Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top, Parent = _GroupBoxAnimation }; _GroupBoxAnimation.Controls.Add (_AnimationControl); _ButtonStop = new Button(this) { X = _GroupBoxAnimation.X, Y = _GroupBoxAnimation.Y + _GroupBoxAnimation.Height + 8, Width = _GroupBoxAnimation.Width / 4, Height = 24, Text = "Stop", Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _ButtonPlay = new Button(this) { X = _GroupBoxAnimation.X + _GroupBoxAnimation.Width / 4, Y = _GroupBoxAnimation.Y + _GroupBoxAnimation.Height + 8, Width = _GroupBoxAnimation.Width / 4, Height = 24, Text = "Play", Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _ButtonPlayLooped = new Button(this) { X = _GroupBoxAnimation.X + _GroupBoxAnimation.Width / 2, Y = _GroupBoxAnimation.Y + _GroupBoxAnimation.Height + 8, Width = _GroupBoxAnimation.Width / 2, Height = 24, Text = "Play Loop", Anchor = AnchorStyles.Left | AnchorStyles.Bottom }; _ButtonCancel = new Button(this) { X = formWidth - 8 - 64, Y = formHeight - 8 - 24, Width = 64, Height = 24, Text = "Cancel", Anchor = AnchorStyles.Right | AnchorStyles.Bottom }; _ButtonOK = new Button(this) { X = _ButtonCancel.X - 64, Y = _ButtonCancel.Y, Width = 64, Height = 24, Text = "OK", Anchor = AnchorStyles.Right | AnchorStyles.Bottom }; Controls.AddRange( new Control[] { _LabelName, _TextBoxName, _LabelListBoxAssets, _ListBoxAssets, _ButtonAddAssetAfter, _ButtonAddAssetBefore, _LabelListBoxFrames, _ListBoxFrames, _NumericUpDownDuration, _LabelDuration, _ButtonPushFrameDown, _ButtonPushFrameUp, _ButtonRemoveFrame, _LabelAnimationControl, _GroupBoxAnimation, _ButtonStop, _ButtonPlay, _ButtonPlayLooped, _ButtonCancel, _ButtonOK }); } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace RestServerSideWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security.Permissions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudioTools.Project { internal enum tagDVASPECT { DVASPECT_CONTENT = 1, DVASPECT_THUMBNAIL = 2, DVASPECT_ICON = 4, DVASPECT_DOCPRINT = 8 } internal enum tagTYMED { TYMED_HGLOBAL = 1, TYMED_FILE = 2, TYMED_ISTREAM = 4, TYMED_ISTORAGE = 8, TYMED_GDI = 16, TYMED_MFPICT = 32, TYMED_ENHMF = 64, TYMED_NULL = 0 } internal sealed class DataCacheEntry : IDisposable { #region fields /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); private FORMATETC format; private long data; private DATADIR dataDir; private bool isDisposed; #endregion #region properties internal FORMATETC Format { get { return this.format; } } internal long Data { get { return this.data; } } internal DATADIR DataDir { get { return this.dataDir; } } #endregion /// <summary> /// The IntPtr is data allocated that should be removed. It is allocated by the ProcessSelectionData method. /// </summary> internal DataCacheEntry(FORMATETC fmt, IntPtr data, DATADIR dir) { this.format = fmt; this.data = (long)data; this.dataDir = dir; } #region Dispose ~DataCacheEntry() { Dispose(false); } /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing"></param> private void Dispose(bool disposing) { // Everybody can go here. if (!this.isDisposed) { // Synchronize calls to the Dispose simulteniously. lock (Mutex) { if (disposing && this.data != 0) { Marshal.FreeHGlobal((IntPtr)this.data); this.data = 0; } this.isDisposed = true; } } } #endregion } /// <summary> /// Unfortunately System.Windows.Forms.IDataObject and /// Microsoft.VisualStudio.OLE.Interop.IDataObject are different... /// </summary> internal sealed class DataObject : IDataObject { #region fields internal const int DATA_S_SAMEFORMATETC = 0x00040130; EventSinkCollection map; ArrayList entries; #endregion internal DataObject() { this.map = new EventSinkCollection(); this.entries = new ArrayList(); } internal void SetData(FORMATETC format, IntPtr data) { this.entries.Add(new DataCacheEntry(format, data, DATADIR.DATADIR_SET)); } #region IDataObject methods int IDataObject.DAdvise(FORMATETC[] e, uint adv, IAdviseSink sink, out uint cookie) { Utilities.ArgumentNotNull("e", e); STATDATA sdata = new STATDATA(); sdata.ADVF = adv; sdata.FORMATETC = e[0]; sdata.pAdvSink = sink; cookie = this.map.Add(sdata); sdata.dwConnection = cookie; return 0; } void IDataObject.DUnadvise(uint cookie) { this.map.RemoveAt(cookie); } int IDataObject.EnumDAdvise(out IEnumSTATDATA e) { e = new EnumSTATDATA((IEnumerable)this.map); return 0; //?? } int IDataObject.EnumFormatEtc(uint direction, out IEnumFORMATETC penum) { penum = new EnumFORMATETC((DATADIR)direction, (IEnumerable)this.entries); return 0; } int IDataObject.GetCanonicalFormatEtc(FORMATETC[] format, FORMATETC[] fmt) { throw new System.Runtime.InteropServices.COMException("", DATA_S_SAMEFORMATETC); } void IDataObject.GetData(FORMATETC[] fmt, STGMEDIUM[] m) { STGMEDIUM retMedium = new STGMEDIUM(); if (fmt == null || fmt.Length < 1) return; foreach (DataCacheEntry e in this.entries) { if (e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/) { retMedium.tymed = e.Format.tymed; // Caller must delete the memory. retMedium.unionmember = DragDropHelper.CopyHGlobal(new IntPtr(e.Data)); break; } } if (m != null && m.Length > 0) m[0] = retMedium; } void IDataObject.GetDataHere(FORMATETC[] fmt, STGMEDIUM[] m) { } int IDataObject.QueryGetData(FORMATETC[] fmt) { if (fmt == null || fmt.Length < 1) return VSConstants.S_FALSE; foreach (DataCacheEntry e in this.entries) { if (e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/) return VSConstants.S_OK; } return VSConstants.S_FALSE; } void IDataObject.SetData(FORMATETC[] fmt, STGMEDIUM[] m, int fRelease) { } #endregion } [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] internal static class DragDropHelper { #pragma warning disable 414 internal static readonly ushort CF_VSREFPROJECTITEMS; internal static readonly ushort CF_VSSTGPROJECTITEMS; internal static readonly ushort CF_VSPROJECTCLIPDESCRIPTOR; #pragma warning restore 414 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static DragDropHelper() { CF_VSREFPROJECTITEMS = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_VSREFPROJECTITEMS"); CF_VSSTGPROJECTITEMS = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_VSSTGPROJECTITEMS"); CF_VSPROJECTCLIPDESCRIPTOR = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_PROJECTCLIPBOARDDESCRIPTOR"); } public static FORMATETC CreateFormatEtc(ushort iFormat) { FORMATETC fmt = new FORMATETC(); fmt.cfFormat = iFormat; fmt.ptd = IntPtr.Zero; fmt.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT; fmt.lindex = -1; fmt.tymed = (uint)TYMED.TYMED_HGLOBAL; return fmt; } public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) { FORMATETC[] af = new FORMATETC[1]; af[0] = fmtetc; int result = pDataObject.QueryGetData(af); if (result == VSConstants.S_OK) { fmtetc = af[0]; return VSConstants.S_OK; } return result; } public static STGMEDIUM GetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) { FORMATETC[] af = new FORMATETC[1]; af[0] = fmtetc; STGMEDIUM[] sm = new STGMEDIUM[1]; pDataObject.GetData(af, sm); fmtetc = af[0]; return sm[0]; } /// <summary> /// Retrieves data from a VS format. /// </summary> public static List<string> GetDroppedFiles(ushort format, Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject, out DropDataType ddt) { ddt = DropDataType.None; List<string> droppedFiles = new List<string>(); // try HDROP FORMATETC fmtetc = CreateFormatEtc(format); if (QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK) { STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc); if (stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL) { // We are releasing the cloned hglobal here. IntPtr dropInfoHandle = stgmedium.unionmember; if (dropInfoHandle != IntPtr.Zero) { ddt = DropDataType.Shell; try { uint numFiles = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, 0xFFFFFFFF, null, 0); // We are a directory based project thus a projref string is placed on the clipboard. // We assign the maximum length of a projref string. // The format of a projref is : <Proj Guid>|<project rel path>|<file path> uint lenght = (uint)Guid.Empty.ToString().Length + 2 * NativeMethods.MAX_PATH + 2; char[] moniker = new char[lenght + 1]; for (uint fileIndex = 0; fileIndex < numFiles; fileIndex++) { uint queryFileLength = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, fileIndex, moniker, lenght); string filename = new String(moniker, 0, (int)queryFileLength); droppedFiles.Add(filename); } } finally { Marshal.FreeHGlobal(dropInfoHandle); } } } } return droppedFiles; } public static string GetSourceProjectPath(Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject) { string projectPath = null; FORMATETC fmtetc = CreateFormatEtc(CF_VSPROJECTCLIPDESCRIPTOR); if (QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK) { STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc); if (stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL) { // We are releasing the cloned hglobal here. IntPtr dropInfoHandle = stgmedium.unionmember; if (dropInfoHandle != IntPtr.Zero) { try { string path = GetData(dropInfoHandle); // Clone the path that we can release our memory. if (!String.IsNullOrEmpty(path)) { projectPath = String.Copy(path); } } finally { Marshal.FreeHGlobal(dropInfoHandle); } } } } return projectPath; } /// <summary> /// Returns the data packed after the DROPFILES structure. /// </summary> /// <param name="dropHandle"></param> /// <returns></returns> internal static string GetData(IntPtr dropHandle) { IntPtr data = UnsafeNativeMethods.GlobalLock(dropHandle); try { _DROPFILES df = (_DROPFILES)Marshal.PtrToStructure(data, typeof(_DROPFILES)); if (df.fWide != 0) { IntPtr pdata = new IntPtr((long)data + df.pFiles); return Marshal.PtrToStringUni(pdata); } } finally { if (data != IntPtr.Zero) { UnsafeNativeMethods.GlobalUnLock(data); } } return null; } internal static IntPtr CopyHGlobal(IntPtr data) { IntPtr src = UnsafeNativeMethods.GlobalLock(data); var size = UnsafeNativeMethods.GlobalSize(data).ToInt32(); IntPtr ptr = Marshal.AllocHGlobal(size); IntPtr buffer = UnsafeNativeMethods.GlobalLock(ptr); try { for (int i = 0; i < size; i++) { byte val = Marshal.ReadByte(new IntPtr((long)src + i)); Marshal.WriteByte(new IntPtr((long)buffer + i), val); } } finally { if (buffer != IntPtr.Zero) { UnsafeNativeMethods.GlobalUnLock(buffer); } if (src != IntPtr.Zero) { UnsafeNativeMethods.GlobalUnLock(src); } } return ptr; } internal static void CopyStringToHGlobal(string s, IntPtr data, int bufferSize) { Int16 nullTerminator = 0; int dwSize = Marshal.SizeOf(nullTerminator); if ((s.Length + 1) * Marshal.SizeOf(s[0]) > bufferSize) throw new System.IO.InternalBufferOverflowException(); // IntPtr memory already locked... for (int i = 0, len = s.Length; i < len; i++) { Marshal.WriteInt16(data, i * dwSize, s[i]); } // NULL terminate it Marshal.WriteInt16(new IntPtr((long)data + (s.Length * dwSize)), nullTerminator); } } // end of dragdrophelper internal class EnumSTATDATA : IEnumSTATDATA { IEnumerable i; IEnumerator e; public EnumSTATDATA(IEnumerable i) { this.i = i; this.e = i.GetEnumerator(); } void IEnumSTATDATA.Clone(out IEnumSTATDATA clone) { clone = new EnumSTATDATA(i); } int IEnumSTATDATA.Next(uint celt, STATDATA[] d, out uint fetched) { uint rc = 0; //uint size = (fetched != null) ? fetched[0] : 0; for (uint i = 0; i < celt; i++) { if (e.MoveNext()) { STATDATA sdata = (STATDATA)e.Current; rc++; if (d != null && d.Length > i) { d[i] = sdata; } } } fetched = rc; return 0; } int IEnumSTATDATA.Reset() { e.Reset(); return 0; } int IEnumSTATDATA.Skip(uint celt) { for (uint i = 0; i < celt; i++) { e.MoveNext(); } return 0; } } internal class EnumFORMATETC : IEnumFORMATETC { IEnumerable cache; // of DataCacheEntrys. DATADIR dir; IEnumerator e; public EnumFORMATETC(DATADIR dir, IEnumerable cache) { this.cache = cache; this.dir = dir; e = cache.GetEnumerator(); } void IEnumFORMATETC.Clone(out IEnumFORMATETC clone) { clone = new EnumFORMATETC(dir, cache); } int IEnumFORMATETC.Next(uint celt, FORMATETC[] d, uint[] fetched) { uint rc = 0; //uint size = (fetched != null) ? fetched[0] : 0; for (uint i = 0; i < celt; i++) { if (e.MoveNext()) { DataCacheEntry entry = (DataCacheEntry)e.Current; rc++; if (d != null && d.Length > i) { d[i] = entry.Format; } } else { return VSConstants.S_FALSE; } } if (fetched != null && fetched.Length > 0) fetched[0] = rc; return VSConstants.S_OK; } int IEnumFORMATETC.Reset() { e.Reset(); return 0; } int IEnumFORMATETC.Skip(uint celt) { for (uint i = 0; i < celt; i++) { e.MoveNext(); } return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractUInt16() { var test = new SimpleBinaryOpTest__SubtractUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractUInt16 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt16); private const int Op2ElementCount = VectorSize / sizeof(UInt16); private const int RetElementCount = VectorSize / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable; static SimpleBinaryOpTest__SubtractUInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SubtractUInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Subtract( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Subtract( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Subtract( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractUInt16(); var result = Sse2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { if ((ushort)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ushort)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AppendingPackedInt64Buffer = Lucene.Net.Util.Packed.AppendingPackedInt64Buffer; using BytesRef = Lucene.Net.Util.BytesRef; using IBits = Lucene.Net.Util.IBits; using MonotonicAppendingInt64Buffer = Lucene.Net.Util.Packed.MonotonicAppendingInt64Buffer; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using TermsEnumIndex = Lucene.Net.Index.MultiTermsEnum.TermsEnumIndex; using TermsEnumWithSlice = Lucene.Net.Index.MultiTermsEnum.TermsEnumWithSlice; /// <summary> /// A wrapper for <see cref="CompositeReader"/> providing access to <see cref="DocValues"/>. /// /// <para/><b>NOTE</b>: for multi readers, you'll get better /// performance by gathering the sub readers using /// <see cref="IndexReader.Context"/> to get the /// atomic leaves and then operate per-AtomicReader, /// instead of using this class. /// /// <para/><b>NOTE</b>: this is very costly. /// /// <para/> /// @lucene.experimental /// @lucene.internal /// </summary> public class MultiDocValues { /// <summary> /// No instantiation </summary> private MultiDocValues() { } /// <summary> /// Returns a <see cref="NumericDocValues"/> for a reader's norms (potentially merging on-the-fly). /// <para> /// This is a slow way to access normalization values. Instead, access them per-segment /// with <seealso cref="AtomicReader.GetNormValues(string)"/> /// </para> /// </summary> public static NumericDocValues GetNormValues(IndexReader r, string field) { IList<AtomicReaderContext> leaves = r.Leaves; int size = leaves.Count; if (size == 0) { return null; } else if (size == 1) { return leaves[0].AtomicReader.GetNormValues(field); } FieldInfo fi = MultiFields.GetMergedFieldInfos(r).FieldInfo(field); if (fi == null || fi.HasNorms == false) { return null; } bool anyReal = false; NumericDocValues[] values = new NumericDocValues[size]; int[] starts = new int[size + 1]; for (int i = 0; i < size; i++) { AtomicReaderContext context = leaves[i]; NumericDocValues v = context.AtomicReader.GetNormValues(field); if (v == null) { v = DocValues.EMPTY_NUMERIC; } else { anyReal = true; } values[i] = v; starts[i] = context.DocBase; } starts[size] = r.MaxDoc; if (Debugging.AssertsEnabled) Debugging.Assert(anyReal); return new NumericDocValuesAnonymousInnerClassHelper(values, starts); } private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues { private NumericDocValues[] values; private int[] starts; public NumericDocValuesAnonymousInnerClassHelper(NumericDocValues[] values, int[] starts) { this.values = values; this.starts = starts; } public override long Get(int docID) { int subIndex = ReaderUtil.SubIndex(docID, starts); return values[subIndex].Get(docID - starts[subIndex]); } } /// <summary> /// Returns a <see cref="NumericDocValues"/> for a reader's docvalues (potentially merging on-the-fly) /// <para> /// This is a slow way to access numeric values. Instead, access them per-segment /// with <see cref="AtomicReader.GetNumericDocValues(string)"/> /// </para> /// </summary> public static NumericDocValues GetNumericValues(IndexReader r, string field) { IList<AtomicReaderContext> leaves = r.Leaves; int size = leaves.Count; if (size == 0) { return null; } else if (size == 1) { return leaves[0].AtomicReader.GetNumericDocValues(field); } bool anyReal = false; NumericDocValues[] values = new NumericDocValues[size]; int[] starts = new int[size + 1]; for (int i = 0; i < size; i++) { AtomicReaderContext context = leaves[i]; NumericDocValues v = context.AtomicReader.GetNumericDocValues(field); if (v == null) { v = DocValues.EMPTY_NUMERIC; } else { anyReal = true; } values[i] = v; starts[i] = context.DocBase; } starts[size] = r.MaxDoc; if (!anyReal) { return null; } else { return new NumericDocValuesAnonymousInnerClassHelper2(values, starts); } } private class NumericDocValuesAnonymousInnerClassHelper2 : NumericDocValues { private NumericDocValues[] values; private int[] starts; public NumericDocValuesAnonymousInnerClassHelper2(NumericDocValues[] values, int[] starts) { this.values = values; this.starts = starts; } public override long Get(int docID) { int subIndex = ReaderUtil.SubIndex(docID, starts); return values[subIndex].Get(docID - starts[subIndex]); } } /// <summary> /// Returns a <see cref="IBits"/> for a reader's docsWithField (potentially merging on-the-fly) /// <para> /// This is a slow way to access this bitset. Instead, access them per-segment /// with <see cref="AtomicReader.GetDocsWithField(string)"/> /// </para> /// </summary> public static IBits GetDocsWithField(IndexReader r, string field) { IList<AtomicReaderContext> leaves = r.Leaves; int size = leaves.Count; if (size == 0) { return null; } else if (size == 1) { return leaves[0].AtomicReader.GetDocsWithField(field); } bool anyReal = false; bool anyMissing = false; IBits[] values = new IBits[size]; int[] starts = new int[size + 1]; for (int i = 0; i < size; i++) { AtomicReaderContext context = leaves[i]; IBits v = context.AtomicReader.GetDocsWithField(field); if (v == null) { v = new Lucene.Net.Util.Bits.MatchNoBits(context.Reader.MaxDoc); anyMissing = true; } else { anyReal = true; if (v is Lucene.Net.Util.Bits.MatchAllBits == false) { anyMissing = true; } } values[i] = v; starts[i] = context.DocBase; } starts[size] = r.MaxDoc; if (!anyReal) { return null; } else if (!anyMissing) { return new Lucene.Net.Util.Bits.MatchAllBits(r.MaxDoc); } else { return new MultiBits(values, starts, false); } } /// <summary> /// Returns a <see cref="BinaryDocValues"/> for a reader's docvalues (potentially merging on-the-fly) /// <para> /// This is a slow way to access binary values. Instead, access them per-segment /// with <see cref="AtomicReader.GetBinaryDocValues(string)"/> /// </para> /// </summary> public static BinaryDocValues GetBinaryValues(IndexReader r, string field) { IList<AtomicReaderContext> leaves = r.Leaves; int size = leaves.Count; if (size == 0) { return null; } else if (size == 1) { return leaves[0].AtomicReader.GetBinaryDocValues(field); } bool anyReal = false; BinaryDocValues[] values = new BinaryDocValues[size]; int[] starts = new int[size + 1]; for (int i = 0; i < size; i++) { AtomicReaderContext context = leaves[i]; BinaryDocValues v = context.AtomicReader.GetBinaryDocValues(field); if (v == null) { v = DocValues.EMPTY_BINARY; } else { anyReal = true; } values[i] = v; starts[i] = context.DocBase; } starts[size] = r.MaxDoc; if (!anyReal) { return null; } else { return new BinaryDocValuesAnonymousInnerClassHelper(values, starts); } } private class BinaryDocValuesAnonymousInnerClassHelper : BinaryDocValues { private BinaryDocValues[] values; private int[] starts; public BinaryDocValuesAnonymousInnerClassHelper(BinaryDocValues[] values, int[] starts) { this.values = values; this.starts = starts; } public override void Get(int docID, BytesRef result) { int subIndex = ReaderUtil.SubIndex(docID, starts); values[subIndex].Get(docID - starts[subIndex], result); } } /// <summary> /// Returns a <see cref="SortedDocValues"/> for a reader's docvalues (potentially doing extremely slow things). /// <para> /// this is an extremely slow way to access sorted values. Instead, access them per-segment /// with <see cref="AtomicReader.GetSortedDocValues(string)"/> /// </para> /// </summary> public static SortedDocValues GetSortedValues(IndexReader r, string field) { IList<AtomicReaderContext> leaves = r.Leaves; int size = leaves.Count; if (size == 0) { return null; } else if (size == 1) { return leaves[0].AtomicReader.GetSortedDocValues(field); } bool anyReal = false; var values = new SortedDocValues[size]; int[] starts = new int[size + 1]; for (int i = 0; i < size; i++) { AtomicReaderContext context = leaves[i]; SortedDocValues v = context.AtomicReader.GetSortedDocValues(field); if (v == null) { v = DocValues.EMPTY_SORTED; } else { anyReal = true; } values[i] = v; starts[i] = context.DocBase; } starts[size] = r.MaxDoc; if (!anyReal) { return null; } else { TermsEnum[] enums = new TermsEnum[values.Length]; for (int i = 0; i < values.Length; i++) { enums[i] = values[i].GetTermsEnum(); } OrdinalMap mapping = new OrdinalMap(r.CoreCacheKey, enums); return new MultiSortedDocValues(values, starts, mapping); } } /// <summary> /// Returns a <see cref="SortedSetDocValues"/> for a reader's docvalues (potentially doing extremely slow things). /// <para> /// This is an extremely slow way to access sorted values. Instead, access them per-segment /// with <see cref="AtomicReader.GetSortedSetDocValues(string)"/> /// </para> /// </summary> public static SortedSetDocValues GetSortedSetValues(IndexReader r, string field) { IList<AtomicReaderContext> leaves = r.Leaves; int size = leaves.Count; if (size == 0) { return null; } else if (size == 1) { return leaves[0].AtomicReader.GetSortedSetDocValues(field); } bool anyReal = false; SortedSetDocValues[] values = new SortedSetDocValues[size]; int[] starts = new int[size + 1]; for (int i = 0; i < size; i++) { AtomicReaderContext context = leaves[i]; SortedSetDocValues v = context.AtomicReader.GetSortedSetDocValues(field); if (v == null) { v = DocValues.EMPTY_SORTED_SET; } else { anyReal = true; } values[i] = v; starts[i] = context.DocBase; } starts[size] = r.MaxDoc; if (!anyReal) { return null; } else { TermsEnum[] enums = new TermsEnum[values.Length]; for (int i = 0; i < values.Length; i++) { enums[i] = values[i].GetTermsEnum(); } OrdinalMap mapping = new OrdinalMap(r.CoreCacheKey, enums); return new MultiSortedSetDocValues(values, starts, mapping); } } /// <summary> /// maps per-segment ordinals to/from global ordinal space </summary> // TODO: use more efficient packed ints structures? // TODO: pull this out? its pretty generic (maps between N ord()-enabled TermsEnums) public class OrdinalMap { // cache key of whoever asked for this awful thing internal readonly object owner; // globalOrd -> (globalOrd - segmentOrd) where segmentOrd is the the ordinal in the first segment that contains this term internal readonly MonotonicAppendingInt64Buffer globalOrdDeltas; // globalOrd -> first segment container internal readonly AppendingPackedInt64Buffer firstSegments; // for every segment, segmentOrd -> (globalOrd - segmentOrd) internal readonly MonotonicAppendingInt64Buffer[] ordDeltas; /// <summary> /// Creates an ordinal map that allows mapping ords to/from a merged /// space from <c>subs</c>. </summary> /// <param name="owner"> a cache key </param> /// <param name="subs"> <see cref="TermsEnum"/>s that support <see cref="TermsEnum.Ord"/>. They need /// not be dense (e.g. can be FilteredTermsEnums). </param> /// <exception cref="IOException"> if an I/O error occurred. </exception> public OrdinalMap(object owner, TermsEnum[] subs) { // create the ordinal mappings by pulling a termsenum over each sub's // unique terms, and walking a multitermsenum over those this.owner = owner; globalOrdDeltas = new MonotonicAppendingInt64Buffer(PackedInt32s.COMPACT); firstSegments = new AppendingPackedInt64Buffer(PackedInt32s.COMPACT); ordDeltas = new MonotonicAppendingInt64Buffer[subs.Length]; for (int i = 0; i < ordDeltas.Length; i++) { ordDeltas[i] = new MonotonicAppendingInt64Buffer(); } long[] segmentOrds = new long[subs.Length]; ReaderSlice[] slices = new ReaderSlice[subs.Length]; TermsEnumIndex[] indexes = new TermsEnumIndex[slices.Length]; for (int i = 0; i < slices.Length; i++) { slices[i] = new ReaderSlice(0, 0, i); indexes[i] = new TermsEnumIndex(subs[i], i); } MultiTermsEnum mte = new MultiTermsEnum(slices); mte.Reset(indexes); long globalOrd = 0; while (mte.MoveNext()) { TermsEnumWithSlice[] matches = mte.MatchArray; for (int i = 0; i < mte.MatchCount; i++) { int segmentIndex = matches[i].Index; long segmentOrd = matches[i].Terms.Ord; long delta = globalOrd - segmentOrd; // for each unique term, just mark the first segment index/delta where it occurs if (i == 0) { firstSegments.Add(segmentIndex); globalOrdDeltas.Add(delta); } // for each per-segment ord, map it back to the global term. while (segmentOrds[segmentIndex] <= segmentOrd) { ordDeltas[segmentIndex].Add(delta); segmentOrds[segmentIndex]++; } } globalOrd++; } firstSegments.Freeze(); globalOrdDeltas.Freeze(); for (int i = 0; i < ordDeltas.Length; ++i) { ordDeltas[i].Freeze(); } } /// <summary> /// Given a segment number and segment ordinal, returns /// the corresponding global ordinal. /// </summary> public virtual long GetGlobalOrd(int segmentIndex, long segmentOrd) { return segmentOrd + ordDeltas[segmentIndex].Get(segmentOrd); } /// <summary> /// Given global ordinal, returns the ordinal of the first segment which contains /// this ordinal (the corresponding to the segment return <see cref="GetFirstSegmentNumber(long)"/>). /// </summary> public virtual long GetFirstSegmentOrd(long globalOrd) { return globalOrd - globalOrdDeltas.Get(globalOrd); } /// <summary> /// Given a global ordinal, returns the index of the first /// segment that contains this term. /// </summary> public virtual int GetFirstSegmentNumber(long globalOrd) { return (int)firstSegments.Get(globalOrd); } /// <summary> /// Returns the total number of unique terms in global ord space. /// </summary> public virtual long ValueCount => globalOrdDeltas.Count; /// <summary> /// Returns total byte size used by this ordinal map. /// </summary> public virtual long RamBytesUsed() { long size = globalOrdDeltas.RamBytesUsed() + firstSegments.RamBytesUsed(); for (int i = 0; i < ordDeltas.Length; i++) { size += ordDeltas[i].RamBytesUsed(); } return size; } } /// <summary> /// Implements <see cref="SortedDocValues"/> over n subs, using an <see cref="OrdinalMap"/> /// <para/> /// @lucene.internal /// </summary> public class MultiSortedDocValues : SortedDocValues { /// <summary> /// docbase for each leaf: parallel with <see cref="Values"/> </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public int[] DocStarts => docStarts; private readonly int[] docStarts; /// <summary> /// leaf values </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public SortedDocValues[] Values => values; private readonly SortedDocValues[] values; /// <summary> /// ordinal map mapping ords from <c>values</c> to global ord space </summary> public OrdinalMap Mapping => mapping; private readonly OrdinalMap mapping; /// <summary> /// Creates a new <see cref="MultiSortedDocValues"/> over <paramref name="values"/> </summary> internal MultiSortedDocValues(SortedDocValues[] values, int[] docStarts, OrdinalMap mapping) { if (Debugging.AssertsEnabled) { Debugging.Assert(values.Length == mapping.ordDeltas.Length); Debugging.Assert(docStarts.Length == values.Length + 1); } this.values = values; this.docStarts = docStarts; this.mapping = mapping; } public override int GetOrd(int docID) { int subIndex = ReaderUtil.SubIndex(docID, docStarts); int segmentOrd = values[subIndex].GetOrd(docID - docStarts[subIndex]); return segmentOrd == -1 ? segmentOrd : (int)mapping.GetGlobalOrd(subIndex, segmentOrd); } public override void LookupOrd(int ord, BytesRef result) { int subIndex = mapping.GetFirstSegmentNumber(ord); int segmentOrd = (int)mapping.GetFirstSegmentOrd(ord); values[subIndex].LookupOrd(segmentOrd, result); } public override int ValueCount => (int)mapping.ValueCount; } /// <summary> /// Implements <see cref="MultiSortedSetDocValues"/> over n subs, using an <see cref="OrdinalMap"/> /// <para/> /// @lucene.internal /// </summary> public class MultiSortedSetDocValues : SortedSetDocValues { /// <summary> /// docbase for each leaf: parallel with <see cref="Values"/> </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public int[] DocStarts => docStarts; private readonly int[] docStarts; /// <summary> /// leaf values </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public SortedSetDocValues[] Values => values; private readonly SortedSetDocValues[] values; /// <summary> /// ordinal map mapping ords from <c>values</c> to global ord space </summary> public OrdinalMap Mapping => mapping; private readonly OrdinalMap mapping; internal int currentSubIndex; /// <summary> /// Creates a new <see cref="MultiSortedSetDocValues"/> over <paramref name="values"/> </summary> internal MultiSortedSetDocValues(SortedSetDocValues[] values, int[] docStarts, OrdinalMap mapping) { if (Debugging.AssertsEnabled) { Debugging.Assert(values.Length == mapping.ordDeltas.Length); Debugging.Assert(docStarts.Length == values.Length + 1); } this.values = values; this.docStarts = docStarts; this.mapping = mapping; } public override long NextOrd() { long segmentOrd = values[currentSubIndex].NextOrd(); if (segmentOrd == NO_MORE_ORDS) { return segmentOrd; } else { return mapping.GetGlobalOrd(currentSubIndex, segmentOrd); } } public override void SetDocument(int docID) { currentSubIndex = ReaderUtil.SubIndex(docID, docStarts); values[currentSubIndex].SetDocument(docID - docStarts[currentSubIndex]); } public override void LookupOrd(long ord, BytesRef result) { int subIndex = mapping.GetFirstSegmentNumber(ord); long segmentOrd = mapping.GetFirstSegmentOrd(ord); values[subIndex].LookupOrd(segmentOrd, result); } public override long ValueCount => mapping.ValueCount; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Extensions; using Abp.IdentityFramework; using Abp.Localization; using Abp.MultiTenancy; using Abp.Runtime.Caching; using Abp.Runtime.Security; using Abp.Runtime.Session; using Abp.Timing; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNet.Identity; namespace Abp.Authorization.Users { /// <summary> /// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework. /// </summary> public abstract class AbpUserManager<TTenant, TRole, TUser> : UserManager<TUser, long>, ITransientDependency where TTenant : AbpTenant<TTenant, TUser> where TRole : AbpRole<TTenant, TUser>, new() where TUser : AbpUser<TTenant, TUser> { private IUserPermissionStore<TTenant, TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TTenant, TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TTenant, TUser>; } } public ILocalizationManager LocalizationManager { get; set; } public IAbpSession AbpSession { get; set; } protected AbpRoleManager<TTenant, TRole, TUser> RoleManager { get; private set; } protected ISettingManager SettingManager { get; private set; } protected AbpUserStore<TTenant, TRole, TUser> AbpStore { get; private set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly IUserManagementConfig _userManagementConfig; private readonly IIocResolver _iocResolver; private readonly IRepository<TTenant> _tenantRepository; private readonly IMultiTenancyConfig _multiTenancyConfig; private readonly ICacheManager _cacheManager; protected AbpUserManager( AbpUserStore<TTenant, TRole, TUser> userStore, AbpRoleManager<TTenant, TRole, TUser> roleManager, IRepository<TTenant> tenantRepository, IMultiTenancyConfig multiTenancyConfig, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IUserManagementConfig userManagementConfig, IIocResolver iocResolver, ICacheManager cacheManager) : base(userStore) { AbpStore = userStore; RoleManager = roleManager; SettingManager = settingManager; _tenantRepository = tenantRepository; _multiTenancyConfig = multiTenancyConfig; _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _userManagementConfig = userManagementConfig; _iocResolver = iocResolver; _cacheManager = cacheManager; LocalizationManager = NullLocalizationManager.Instance; } public override async Task<IdentityResult> CreateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } if (AbpSession.TenantId.HasValue) { user.TenantId = AbpSession.TenantId.Value; } return await base.CreateAsync(user); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission) { return IsGrantedAsync(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(AbpSession.MultiTenancySide)) { return false; } //Get cached user permissions var cacheItem = await GetUserPermissionCacheItemAsync(userId); //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (await RoleManager.IsGrantedAsync(roleId, permission)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpStore.FindAllAsync(login); } [UnitOfWork] public virtual async Task<AbpLoginResult> LoginAsync(UserLoginInfo login, string tenancyName = null) { if (login == null || login.LoginProvider.IsNullOrEmpty() || login.ProviderKey.IsNullOrEmpty()) { throw new ArgumentException("login"); } //Get and check tenant TTenant tenant = null; if (!_multiTenancyConfig.IsEnabled) { tenant = await GetDefaultTenantAsync(); } else if (!string.IsNullOrWhiteSpace(tenancyName)) { tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName); if (tenant == null) { return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName); } if (!tenant.IsActive) { return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive); } } using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { var user = await AbpStore.FindAsync(tenant == null ? (int?)null : tenant.Id, login); if (user == null) { return new AbpLoginResult(AbpLoginResultType.UnknownExternalLogin); } return await CreateLoginResultAsync(user); } } [UnitOfWork] public virtual async Task<AbpLoginResult> LoginAsync(string userNameOrEmailAddress, string plainPassword, string tenancyName = null) { if (userNameOrEmailAddress.IsNullOrEmpty()) { throw new ArgumentNullException("userNameOrEmailAddress"); } if (plainPassword.IsNullOrEmpty()) { throw new ArgumentNullException("plainPassword"); } //Get and check tenant TTenant tenant = null; if (!_multiTenancyConfig.IsEnabled) { tenant = await GetDefaultTenantAsync(); } else if (!string.IsNullOrWhiteSpace(tenancyName)) { tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName); if (tenant == null) { return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName); } if (!tenant.IsActive) { return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive); } } using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant); var user = await AbpStore.FindByNameOrEmailAsync(tenant == null ? (int?)null : tenant.Id, userNameOrEmailAddress); if (user == null) { return new AbpLoginResult(AbpLoginResultType.InvalidUserNameOrEmailAddress); } if (!loggedInFromExternalSource) { var verificationResult = new PasswordHasher().VerifyHashedPassword(user.Password, plainPassword); if (verificationResult != PasswordVerificationResult.Success) { return new AbpLoginResult(AbpLoginResultType.InvalidPassword); } } return await CreateLoginResultAsync(user); } } private async Task<AbpLoginResult> CreateLoginResultAsync(TUser user) { if (!user.IsActive) { return new AbpLoginResult(AbpLoginResultType.UserIsNotActive); } if (await IsEmailConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsEmailConfirmed) { return new AbpLoginResult(AbpLoginResultType.UserEmailIsNotConfirmed); } user.LastLoginTime = Clock.Now; await Store.UpdateAsync(user); await _unitOfWorkManager.Current.SaveChangesAsync(); return new AbpLoginResult(user, await CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)); } private async Task<bool> TryLoginFromExternalAuthenticationSources(string userNameOrEmailAddress, string plainPassword, TTenant tenant) { if (!_userManagementConfig.ExternalAuthenticationSources.Any()) { return false; } foreach (var sourceType in _userManagementConfig.ExternalAuthenticationSources) { using (var source = _iocResolver.ResolveAsDisposable<IExternalAuthenticationSource<TTenant, TUser>>(sourceType)) { if (await source.Object.TryAuthenticateAsync(userNameOrEmailAddress, plainPassword, tenant)) { var tenantId = tenant == null ? (int?)null : tenant.Id; var user = await AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress); if (user == null) { user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant); user.Tenant = tenant; user.AuthenticationSource = source.Object.Name; user.Password = new PasswordHasher().HashPassword(Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used user.Roles = new List<UserRole>(); foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList()) { user.Roles.Add(new UserRole { RoleId = defaultRole.Id }); } await Store.CreateAsync(user); } else { await source.Object.UpdateUserAsync(user, tenant); user.AuthenticationSource = source.Object.Name; await Store.UpdateAsync(user); } await _unitOfWorkManager.Current.SaveChangesAsync(); return true; } } } return false; } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType) { var identity = await base.CreateIdentityAsync(user, authenticationType); if (user.TenantId.HasValue) { identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture))); } return identity; } public async override Task<IdentityResult> UpdateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var oldUserName = (await GetUserByIdAsync(user.Id)).UserName; if (oldUserName == AbpUser<TTenant, TUser>.AdminUserName && user.UserName != AbpUser<TTenant, TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TTenant, TUser>.AdminUserName)); } return await base.UpdateAsync(user); } public async override Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUser<TTenant, TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TTenant, TUser>.AdminUserName)); } return await base.DeleteAsync(user); } public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var result = await PasswordValidator.ValidateAsync(newPassword); if (!result.Succeeded) { return result; } await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword)); return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames) { //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId); if (roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user.Id, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user.Id, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } private async Task<bool> IsEmailConfirmationRequiredForLoginAsync(int? tenantId) { if (tenantId.HasValue) { return await SettingManager.GetSettingValueForTenantAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, tenantId.Value); } return await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin); } private async Task<TTenant> GetDefaultTenantAsync() { var tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == AbpTenant<TTenant, TUser>.DefaultTenantName); if (tenant == null) { throw new AbpException("There should be a 'Default' tenant if multi-tenancy is disabled!"); } return tenant; } private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId) { return await _cacheManager.GetUserPermissionCache().GetAsync(userId, async () => { var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in await GetRolesAsync(userId)) { newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id); } foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } private string L(string name) { return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name); } public class AbpLoginResult { public AbpLoginResultType Result { get; private set; } public TUser User { get; private set; } public ClaimsIdentity Identity { get; private set; } public AbpLoginResult(AbpLoginResultType result) { Result = result; } public AbpLoginResult(TUser user, ClaimsIdentity identity) : this(AbpLoginResultType.Success) { User = user; Identity = identity; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcdcv = Google.Cloud.Dialogflow.Cx.V3; using sys = System; namespace Google.Cloud.Dialogflow.Cx.V3 { /// <summary>Resource name for the <c>Webhook</c> resource.</summary> public sealed partial class WebhookName : gax::IResourceName, sys::IEquatable<WebhookName> { /// <summary>The possible contents of <see cref="WebhookName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}</c>. /// </summary> ProjectLocationAgentWebhook = 1, } private static gax::PathTemplate s_projectLocationAgentWebhook = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}"); /// <summary>Creates a <see cref="WebhookName"/> 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="WebhookName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static WebhookName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new WebhookName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="WebhookName"/> with the pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="webhookId">The <c>Webhook</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="WebhookName"/> constructed from the provided ids.</returns> public static WebhookName FromProjectLocationAgentWebhook(string projectId, string locationId, string agentId, string webhookId) => new WebhookName(ResourceNameType.ProjectLocationAgentWebhook, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), webhookId: gax::GaxPreconditions.CheckNotNullOrEmpty(webhookId, nameof(webhookId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="WebhookName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="webhookId">The <c>Webhook</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="WebhookName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}</c>. /// </returns> public static string Format(string projectId, string locationId, string agentId, string webhookId) => FormatProjectLocationAgentWebhook(projectId, locationId, agentId, webhookId); /// <summary> /// Formats the IDs into the string representation of this <see cref="WebhookName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="webhookId">The <c>Webhook</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="WebhookName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}</c>. /// </returns> public static string FormatProjectLocationAgentWebhook(string projectId, string locationId, string agentId, string webhookId) => s_projectLocationAgentWebhook.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(webhookId, nameof(webhookId))); /// <summary>Parses the given resource name string into a new <see cref="WebhookName"/> 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}/locations/{location}/agents/{agent}/webhooks/{webhook}</c></description> /// </item> /// </list> /// </remarks> /// <param name="webhookName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="WebhookName"/> if successful.</returns> public static WebhookName Parse(string webhookName) => Parse(webhookName, false); /// <summary> /// Parses the given resource name string into a new <see cref="WebhookName"/> 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}/locations/{location}/agents/{agent}/webhooks/{webhook}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="webhookName">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="WebhookName"/> if successful.</returns> public static WebhookName Parse(string webhookName, bool allowUnparsed) => TryParse(webhookName, allowUnparsed, out WebhookName 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="WebhookName"/> 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}/locations/{location}/agents/{agent}/webhooks/{webhook}</c></description> /// </item> /// </list> /// </remarks> /// <param name="webhookName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="WebhookName"/>, 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 webhookName, out WebhookName result) => TryParse(webhookName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="WebhookName"/> 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}/locations/{location}/agents/{agent}/webhooks/{webhook}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="webhookName">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="WebhookName"/>, 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 webhookName, bool allowUnparsed, out WebhookName result) { gax::GaxPreconditions.CheckNotNull(webhookName, nameof(webhookName)); gax::TemplatedResourceName resourceName; if (s_projectLocationAgentWebhook.TryParseName(webhookName, out resourceName)) { result = FromProjectLocationAgentWebhook(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(webhookName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private WebhookName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string locationId = null, string projectId = null, string webhookId = null) { Type = type; UnparsedResource = unparsedResourceName; AgentId = agentId; LocationId = locationId; ProjectId = projectId; WebhookId = webhookId; } /// <summary> /// Constructs a new instance of a <see cref="WebhookName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="webhookId">The <c>Webhook</c> ID. Must not be <c>null</c> or empty.</param> public WebhookName(string projectId, string locationId, string agentId, string webhookId) : this(ResourceNameType.ProjectLocationAgentWebhook, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), webhookId: gax::GaxPreconditions.CheckNotNullOrEmpty(webhookId, nameof(webhookId))) { } /// <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>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AgentId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { 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>Webhook</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string WebhookId { 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.ProjectLocationAgentWebhook: return s_projectLocationAgentWebhook.Expand(ProjectId, LocationId, AgentId, WebhookId); 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 WebhookName); /// <inheritdoc/> public bool Equals(WebhookName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(WebhookName a, WebhookName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(WebhookName a, WebhookName b) => !(a == b); } /// <summary>Resource name for the <c>Service</c> resource.</summary> public sealed partial class ServiceName : gax::IResourceName, sys::IEquatable<ServiceName> { /// <summary>The possible contents of <see cref="ServiceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>. /// </summary> ProjectLocationNamespaceService = 1, } private static gax::PathTemplate s_projectLocationNamespaceService = new gax::PathTemplate("projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}"); /// <summary>Creates a <see cref="ServiceName"/> 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="ServiceName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ServiceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ServiceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ServiceName"/> with the pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns> public static ServiceName FromProjectLocationNamespaceService(string projectId, string locationId, string namespaceId, string serviceId) => new ServiceName(ResourceNameType.ProjectLocationNamespaceService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>. /// </returns> public static string Format(string projectId, string locationId, string namespaceId, string serviceId) => FormatProjectLocationNamespaceService(projectId, locationId, namespaceId, serviceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>. /// </returns> public static string FormatProjectLocationNamespaceService(string projectId, string locationId, string namespaceId, string serviceId) => s_projectLocationNamespaceService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary>Parses the given resource name string into a new <see cref="ServiceName"/> 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}/locations/{location}/namespaces/{namespace}/services/{service}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ServiceName"/> if successful.</returns> public static ServiceName Parse(string serviceName) => Parse(serviceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ServiceName"/> 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}/locations/{location}/namespaces/{namespace}/services/{service}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceName">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="ServiceName"/> if successful.</returns> public static ServiceName Parse(string serviceName, bool allowUnparsed) => TryParse(serviceName, allowUnparsed, out ServiceName 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="ServiceName"/> 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}/locations/{location}/namespaces/{namespace}/services/{service}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ServiceName"/>, 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 serviceName, out ServiceName result) => TryParse(serviceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ServiceName"/> 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}/locations/{location}/namespaces/{namespace}/services/{service}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceName">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="ServiceName"/>, 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 serviceName, bool allowUnparsed, out ServiceName result) { gax::GaxPreconditions.CheckNotNull(serviceName, nameof(serviceName)); gax::TemplatedResourceName resourceName; if (s_projectLocationNamespaceService.TryParseName(serviceName, out resourceName)) { result = FromProjectLocationNamespaceService(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(serviceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ServiceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string namespaceId = null, string projectId = null, string serviceId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; NamespaceId = namespaceId; ProjectId = projectId; ServiceId = serviceId; } /// <summary> /// Constructs a new instance of a <see cref="ServiceName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> public ServiceName(string projectId, string locationId, string namespaceId, string serviceId) : this(ResourceNameType.ProjectLocationNamespaceService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))) { } /// <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>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Namespace</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string NamespaceId { 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>Service</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ServiceId { 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.ProjectLocationNamespaceService: return s_projectLocationNamespaceService.Expand(ProjectId, LocationId, NamespaceId, ServiceId); 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 ServiceName); /// <inheritdoc/> public bool Equals(ServiceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ServiceName a, ServiceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ServiceName a, ServiceName b) => !(a == b); } public partial class Webhook { /// <summary> /// <see cref="gcdcv::WebhookName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::WebhookName WebhookName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::WebhookName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListWebhooksRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public AgentName ParentAsAgentName { get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetWebhookRequest { /// <summary> /// <see cref="gcdcv::WebhookName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::WebhookName WebhookName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::WebhookName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateWebhookRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public AgentName ParentAsAgentName { get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteWebhookRequest { /// <summary> /// <see cref="gcdcv::WebhookName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::WebhookName WebhookName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::WebhookName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class WebhookRequest { /// <summary> /// <see cref="IntentName"/>-typed view over the <see cref="TriggerIntent"/> resource name property. /// </summary> public IntentName TriggerIntentAsIntentName { get => string.IsNullOrEmpty(TriggerIntent) ? null : IntentName.Parse(TriggerIntent, allowUnparsed: true); set => TriggerIntent = value?.ToString() ?? ""; } } public partial class WebhookResponse { /// <summary> /// <see cref="PageName"/>-typed view over the <see cref="TargetPage"/> resource name property. /// </summary> public PageName TargetPageAsPageName { get => string.IsNullOrEmpty(TargetPage) ? null : PageName.Parse(TargetPage, allowUnparsed: true); set => TargetPage = value?.ToString() ?? ""; } /// <summary> /// <see cref="FlowName"/>-typed view over the <see cref="TargetFlow"/> resource name property. /// </summary> public FlowName TargetFlowAsFlowName { get => string.IsNullOrEmpty(TargetFlow) ? null : FlowName.Parse(TargetFlow, allowUnparsed: true); set => TargetFlow = value?.ToString() ?? ""; } } public partial class PageInfo { /// <summary> /// <see cref="PageName"/>-typed view over the <see cref="CurrentPage"/> resource name property. /// </summary> public PageName CurrentPageAsPageName { get => string.IsNullOrEmpty(CurrentPage) ? null : PageName.Parse(CurrentPage, allowUnparsed: true); set => CurrentPage = value?.ToString() ?? ""; } } public partial class SessionInfo { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get => string.IsNullOrEmpty(Session) ? null : SessionName.Parse(Session, allowUnparsed: true); set => Session = value?.ToString() ?? ""; } } }
//--------------------------------------------------------------------- // This file is part of the CLR Managed Debugger (mdbg) Sample. // // Copyright (C) Microsoft Corporation. All rights reserved. //--------------------------------------------------------------------- using System; using System.Runtime.Serialization; using Microsoft.Samples.Debugging.CorDebug; using Microsoft.Samples.Debugging.CorMetadata; namespace Microsoft.Samples.Debugging.MdbgEngine { /// <summary> /// MDbgException class. Represents errors that occur in mdbg. /// </summary> [Serializable()] public class MDbgException : ApplicationException, ISerializable { /// <summary> /// Initializes a new instance of the MDbgException. /// </summary> public MDbgException() { } /// <summary> /// Initializes a new instance of the MDbgException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public MDbgException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the MDbgException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the MDbgException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected MDbgException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// MDbgSpecialSourcePositionException class. Represents errors that occur because the current source position is special. /// </summary> [Serializable()] public class MDbgSpecialSourcePositionException : MDbgException, ISerializable { /// <summary> /// Initializes a new instance of the MDbgSpecialSourcePositionException. /// </summary> public MDbgSpecialSourcePositionException() : base("Current source position is special") { } /// <summary> /// Initializes a new instance of the MDbgSpecialSourcePositionException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public MDbgSpecialSourcePositionException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the MDbgSpecialSourcePositionException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgSpecialSourcePositionException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the MDbgSpecialSourcePositionException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected MDbgSpecialSourcePositionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// MDbgNoCurrentFrameException class. Represents errors that occur because there is no current frame. /// </summary> [Serializable()] public class MDbgNoCurrentFrameException : MDbgException, ISerializable { /// <summary> /// Initializes a new instance of the MDbgNoCurrentFrameException. /// </summary> public MDbgNoCurrentFrameException() : base("No current frame") { } /// <summary> /// Initializes a new instance of the MDbgNoCurrentFrameException with the specified inner Exception. /// </summary> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgNoCurrentFrameException(Exception innerException) : base("No current frame", innerException) { } /// <summary> /// Initializes a new instance of the MDbgNoCurrentFrameException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public MDbgNoCurrentFrameException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the MDbgNoCurrentFrameException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgNoCurrentFrameException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the MDbgNoCurrentFrameException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected MDbgNoCurrentFrameException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// MDbgNoActiveInstanceException class. Represents errors that occur because there is no active instance. /// </summary> [Serializable()] public class MDbgNoActiveInstanceException : MDbgException, ISerializable { /// <summary> /// Initializes a new instance of the MDbgNoActiveInstanceException. /// </summary> public MDbgNoActiveInstanceException() : base("No active instance") { } /// <summary> /// Initializes a new instance of the MDbgNoActiveInstanceException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public MDbgNoActiveInstanceException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the MDbgNoActiveInstanceException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgNoActiveInstanceException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the MDbgNoActiveInstanceException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected MDbgNoActiveInstanceException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// MDbgValueException class. Represents errors that occur because a value is bad. /// </summary> [Serializable()] public class MDbgValueException : MDbgException, ISerializable { /// <summary> /// Initializes a new instance of the MDbgValueException. /// </summary> public MDbgValueException() { } /// <summary> /// Initializes a new instance of the MDbgValueException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public MDbgValueException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the MDbgValueException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgValueException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the MDbgValueException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected MDbgValueException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// MDbgInvalidArgumentException class. Represents errors that occur because an argument is invalid. /// </summary> [Serializable()] public class MDbgInvalidArgumentException : MDbgException, ISerializable { /// <summary> /// Initializes a new instance of the MDbgInvalidArgumentException. /// </summary> public MDbgInvalidArgumentException() : base("Invalid argument") { } /// <summary> /// Initializes a new instance of the MDbgInvalidArgumentException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public MDbgInvalidArgumentException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the MDbgInvalidArgumentException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgInvalidArgumentException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the MDbgInvalidArgumentException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected MDbgInvalidArgumentException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// MDbgAmbiguousModuleNameException class. Represents errors that occur because a module name is ambiguous. For example if you had mscorlib.exe and mscorlib.dll and asked for mscorlib. /// </summary> [Serializable()] public class MDbgAmbiguousModuleNameException : MDbgException, ISerializable { /// <summary> /// Initializes a new instance of the MDbgAmbiguousModuleNameException. /// </summary> public MDbgAmbiguousModuleNameException() : base("Ambiguous module name") { } /// <summary> /// Initializes a new instance of the MDbgAmbiguousModuleNameException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public MDbgAmbiguousModuleNameException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the MDbgAmbiguousModuleNameException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgAmbiguousModuleNameException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the MDbgAmbiguousModuleNameException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected MDbgAmbiguousModuleNameException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// MDbgValueWrongTypeException class. Represents errors that occur because a value is of the wrong type. /// </summary> [Serializable()] public class MDbgValueWrongTypeException : MDbgException, ISerializable { /// <summary> /// Initializes a new instance of the MDbgValueWrongTypeException. /// </summary> public MDbgValueWrongTypeException() : base("value is of wrong type") { } /// <summary> /// Initializes a new instance of the MDbgValueWrongTypeException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public MDbgValueWrongTypeException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the MDbgValueWrongTypeException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public MDbgValueWrongTypeException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the MDbgValueWrongTypeException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected MDbgValueWrongTypeException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tenancy_config/kaba_encoder_config.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.TenancyConfig { /// <summary>Holder for reflection information generated from tenancy_config/kaba_encoder_config.proto</summary> public static partial class KabaEncoderConfigReflection { #region Descriptor /// <summary>File descriptor for tenancy_config/kaba_encoder_config.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static KabaEncoderConfigReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cih0ZW5hbmN5X2NvbmZpZy9rYWJhX2VuY29kZXJfY29uZmlnLnByb3RvEhpo", "b2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZyKXAQoRS2FiYUVuY29kZXJDb25m", "aWcSIQoZcG9zdF9jaGVja291dF9ncmFjZV9ob3VycxgBIAEoDRIhChlzYWZl", "bG9rX3NlcnZlcl9pcF9hZGRyZXNzGAIgASgJEhsKE3NhZmVsb2tfc2VydmVy", "X3BvcnQYAyABKA0SHwoXc2FmZWxva19zZXJ2ZXJfcGFzc3dvcmQYBCABKAlC", "K1oNdGVuYW5jeWNvbmZpZ6oCGUhPTE1TLlR5cGVzLlRlbmFuY3lDb25maWdi", "BnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.KabaEncoderConfig), global::HOLMS.Types.TenancyConfig.KabaEncoderConfig.Parser, new[]{ "PostCheckoutGraceHours", "SafelokServerIpAddress", "SafelokServerPort", "SafelokServerPassword" }, null, null, null) })); } #endregion } #region Messages public sealed partial class KabaEncoderConfig : pb::IMessage<KabaEncoderConfig> { private static readonly pb::MessageParser<KabaEncoderConfig> _parser = new pb::MessageParser<KabaEncoderConfig>(() => new KabaEncoderConfig()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<KabaEncoderConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.TenancyConfig.KabaEncoderConfigReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KabaEncoderConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KabaEncoderConfig(KabaEncoderConfig other) : this() { postCheckoutGraceHours_ = other.postCheckoutGraceHours_; safelokServerIpAddress_ = other.safelokServerIpAddress_; safelokServerPort_ = other.safelokServerPort_; safelokServerPassword_ = other.safelokServerPassword_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KabaEncoderConfig Clone() { return new KabaEncoderConfig(this); } /// <summary>Field number for the "post_checkout_grace_hours" field.</summary> public const int PostCheckoutGraceHoursFieldNumber = 1; private uint postCheckoutGraceHours_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint PostCheckoutGraceHours { get { return postCheckoutGraceHours_; } set { postCheckoutGraceHours_ = value; } } /// <summary>Field number for the "safelok_server_ip_address" field.</summary> public const int SafelokServerIpAddressFieldNumber = 2; private string safelokServerIpAddress_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SafelokServerIpAddress { get { return safelokServerIpAddress_; } set { safelokServerIpAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "safelok_server_port" field.</summary> public const int SafelokServerPortFieldNumber = 3; private uint safelokServerPort_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint SafelokServerPort { get { return safelokServerPort_; } set { safelokServerPort_ = value; } } /// <summary>Field number for the "safelok_server_password" field.</summary> public const int SafelokServerPasswordFieldNumber = 4; private string safelokServerPassword_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SafelokServerPassword { get { return safelokServerPassword_; } set { safelokServerPassword_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as KabaEncoderConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(KabaEncoderConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (PostCheckoutGraceHours != other.PostCheckoutGraceHours) return false; if (SafelokServerIpAddress != other.SafelokServerIpAddress) return false; if (SafelokServerPort != other.SafelokServerPort) return false; if (SafelokServerPassword != other.SafelokServerPassword) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (PostCheckoutGraceHours != 0) hash ^= PostCheckoutGraceHours.GetHashCode(); if (SafelokServerIpAddress.Length != 0) hash ^= SafelokServerIpAddress.GetHashCode(); if (SafelokServerPort != 0) hash ^= SafelokServerPort.GetHashCode(); if (SafelokServerPassword.Length != 0) hash ^= SafelokServerPassword.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 (PostCheckoutGraceHours != 0) { output.WriteRawTag(8); output.WriteUInt32(PostCheckoutGraceHours); } if (SafelokServerIpAddress.Length != 0) { output.WriteRawTag(18); output.WriteString(SafelokServerIpAddress); } if (SafelokServerPort != 0) { output.WriteRawTag(24); output.WriteUInt32(SafelokServerPort); } if (SafelokServerPassword.Length != 0) { output.WriteRawTag(34); output.WriteString(SafelokServerPassword); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (PostCheckoutGraceHours != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(PostCheckoutGraceHours); } if (SafelokServerIpAddress.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SafelokServerIpAddress); } if (SafelokServerPort != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(SafelokServerPort); } if (SafelokServerPassword.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SafelokServerPassword); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(KabaEncoderConfig other) { if (other == null) { return; } if (other.PostCheckoutGraceHours != 0) { PostCheckoutGraceHours = other.PostCheckoutGraceHours; } if (other.SafelokServerIpAddress.Length != 0) { SafelokServerIpAddress = other.SafelokServerIpAddress; } if (other.SafelokServerPort != 0) { SafelokServerPort = other.SafelokServerPort; } if (other.SafelokServerPassword.Length != 0) { SafelokServerPassword = other.SafelokServerPassword; } } [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: { PostCheckoutGraceHours = input.ReadUInt32(); break; } case 18: { SafelokServerIpAddress = input.ReadString(); break; } case 24: { SafelokServerPort = input.ReadUInt32(); break; } case 34: { SafelokServerPassword = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
// // Copyright (c) Microsoft Corporation. All rights reserved. // // Microsoft Public License (MS-PL) // // This license governs use of the accompanying software. If you use the // software, you accept this license. If you do not accept the license, do not // use the software. // // 1. Definitions // // The terms "reproduce," "reproduction," "derivative works," and // "distribution" have the same meaning here as under U.S. copyright law. A // "contribution" is the original software, or any additions or changes to // the software. A "contributor" is any person that distributes its // contribution under this license. "Licensed patents" are a contributor's // patent claims that read directly on its contribution. // // 2. Grant of Rights // // (A) Copyright Grant- Subject to the terms of this license, including the // license conditions and limitations in section 3, each contributor // grants you a non-exclusive, worldwide, royalty-free copyright license // to reproduce its contribution, prepare derivative works of its // contribution, and distribute its contribution or any derivative works // that you create. // // (B) Patent Grant- Subject to the terms of this license, including the // license conditions and limitations in section 3, each contributor // grants you a non-exclusive, worldwide, royalty-free license under its // licensed patents to make, have made, use, sell, offer for sale, // import, and/or otherwise dispose of its contribution in the software // or derivative works of the contribution in the software. // // 3. Conditions and Limitations // // (A) No Trademark License- This license does not grant you rights to use // any contributors' name, logo, or trademarks. // // (B) If you bring a patent claim against any contributor over patents that // you claim are infringed by the software, your patent license from such // contributor to the software ends automatically. // // (C) If you distribute any portion of the software, you must retain all // copyright, patent, trademark, and attribution notices that are present // in the software. // // (D) If you distribute any portion of the software in source code form, you // may do so only under this license by including a complete copy of this // license with your distribution. If you distribute any portion of the // software in compiled or object code form, you may only do so under a // license that complies with this license. // // (E) The software is licensed "as-is." You bear the risk of using it. The // contributors give no express warranties, guarantees or conditions. You // may have additional consumer rights under your local laws which this // license cannot change. To the extent permitted under your local laws, // the contributors exclude the implied warranties of merchantability, // fitness for a particular purpose and non-infringement. // using System; using System.Diagnostics.CodeAnalysis; namespace Microsoft.ClearScript.Test { public class BaseTestObject : IBaseTestInterface, IExplicitBaseTestInterface { public int[] BaseField; public short BaseScalarField; public TestEnum BaseEnumField; public TimeSpan BaseStructField; public int[] BaseProperty { get; set; } public short BaseScalarProperty { get; set; } public TestEnum BaseEnumProperty { get; set; } public TimeSpan BaseStructProperty { get; set; } public byte BaseReadOnlyProperty { get { return 117; } } public event EventHandler<TestEventArgs<short>> BaseEvent; public void BaseFireEvent(short arg) { if (BaseEvent != null) { BaseEvent(this, new TestEventArgs<short> { Arg = arg }); } } public double BaseMethod(string arg1, int arg2) { return TestUtil.CalcTestValue(new Guid("d5114f53-ca6a-4993-8117-7f8194088c08"), this, arg1.Length, arg2); } public double BaseMethod<T>(string arg1, int arg2, T arg3) where T : struct { return TestUtil.CalcTestValue(new Guid("d18ddd76-a035-44b4-b18b-7c4c7d313c4f"), this, arg1.Length, arg2, arg3.ToString().Length); } public double BaseMethod<T>(int arg) where T : struct { return TestUtil.CalcTestValue(new Guid("53b0fe2a-6b7c-4516-93de-db706b1bf1bb"), this, typeof(T).Name.Length, arg); } public double BaseBindTestMethod<T>(T arg) { return TestUtil.CalcTestValue(new Guid("c0f52143-a775-4b71-b206-a759285a35a5"), this, typeof(T), arg); } #region Implementation of IBaseTestInterface public int[] BaseInterfaceProperty { get; set; } public short BaseInterfaceScalarProperty { get; set; } public TestEnum BaseInterfaceEnumProperty { get; set; } public TimeSpan BaseInterfaceStructProperty { get; set; } public byte BaseInterfaceReadOnlyProperty { get { return 73; } } public event EventHandler<TestEventArgs<short>> BaseInterfaceEvent; public void BaseInterfaceFireEvent(short arg) { if (BaseInterfaceEvent != null) { BaseInterfaceEvent(this, new TestEventArgs<short> { Arg = arg }); } } public double BaseInterfaceMethod(string arg1, int arg2) { return TestUtil.CalcTestValue(new Guid("f58f24cd-1d08-4224-bf78-7dcdb01b733f"), this, arg1.Length, arg2); } public double BaseInterfaceMethod<T>(string arg1, int arg2, T arg3) where T : struct { return TestUtil.CalcTestValue(new Guid("73cd3acf-3c94-4993-8786-70ba0f86f1a7"), this, arg1.Length, arg2, arg3.ToString().Length); } public double BaseInterfaceMethod<T>(int arg) where T : struct { return TestUtil.CalcTestValue(new Guid("28cf53e3-6422-4ac8-82d6-0d3d00e7bc1d"), this, typeof(T).Name.Length, arg); } public double BaseInterfaceBindTestMethod<T>(T arg) { return TestUtil.CalcTestValue(new Guid("302f0d74-7ee8-4e0c-b383-7816d79a889b"), this, typeof(T), arg); } #endregion #region Implementation of IExplicitBaseTestInterface [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] int[] IExplicitBaseTestInterface.ExplicitBaseInterfaceProperty { get; set; } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] short IExplicitBaseTestInterface.ExplicitBaseInterfaceScalarProperty { get; set; } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] TestEnum IExplicitBaseTestInterface.ExplicitBaseInterfaceEnumProperty { get; set; } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] TimeSpan IExplicitBaseTestInterface.ExplicitBaseInterfaceStructProperty { get; set; } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] byte IExplicitBaseTestInterface.ExplicitBaseInterfaceReadOnlyProperty { get { return 17; } } private event EventHandler<TestEventArgs<short>> ExplicitBaseInterfaceEventImpl; [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] event EventHandler<TestEventArgs<short>> IExplicitBaseTestInterface.ExplicitBaseInterfaceEvent { add { ExplicitBaseInterfaceEventImpl += value; } remove { ExplicitBaseInterfaceEventImpl -= value; } } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] void IExplicitBaseTestInterface.ExplicitBaseInterfaceFireEvent(short arg) { if (ExplicitBaseInterfaceEventImpl != null) { ExplicitBaseInterfaceEventImpl(this, new TestEventArgs<short> { Arg = arg }); } } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] double IExplicitBaseTestInterface.ExplicitBaseInterfaceMethod(string arg1, int arg2) { return TestUtil.CalcTestValue(new Guid("354a43bc-7d15-4aeb-b4c9-c6e03893c5f2"), this, arg1.Length, arg2); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] double IExplicitBaseTestInterface.ExplicitBaseInterfaceMethod<T>(string arg1, int arg2, T arg3) { return TestUtil.CalcTestValue(new Guid("b6496578-af16-4424-b16b-808de442d9e3"), this, arg1.Length, arg2, arg3.ToString().Length); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] double IExplicitBaseTestInterface.ExplicitBaseInterfaceMethod<T>(int arg) { return TestUtil.CalcTestValue(new Guid("b9810875-3ccf-400f-b106-d2869905f9bc"), this, typeof(T).Name.Length, arg); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This member requires explicit implementation for testing purposes.")] double IExplicitBaseTestInterface.ExplicitBaseInterfaceBindTestMethod<T>(T arg) { return TestUtil.CalcTestValue(new Guid("5937707d-9158-4d72-986b-8eb13da5c079"), this, typeof(T), arg); } #endregion } public static class BaseTestObjectExtensions { public static double BaseExtensionMethod(this BaseTestObject self, string arg1, int arg2) { return TestUtil.CalcTestValue(new Guid("ffac885b-0e3b-4438-99e1-64f4d2c6f769"), self, arg1.Length, arg2); } public static double BaseExtensionMethod<T>(this BaseTestObject self, string arg1, int arg2, T arg3) where T : struct { return TestUtil.CalcTestValue(new Guid("6ee07aa3-4548-4d59-b7d6-77725bb2c900"), self, arg1.Length, arg2, arg3.ToString().Length); } public static double BaseExtensionMethod<T>(this BaseTestObject self, int arg) where T : struct { return TestUtil.CalcTestValue(new Guid("2db0feaf-8618-4676-a7ba-552a20853fcd"), self, typeof(T).Name.Length, arg); } public static double BaseExtensionBindTestMethod<T>(this BaseTestObject self, T arg) { return TestUtil.CalcTestValue(new Guid("fdef26a4-2155-4be5-a245-4810ae66c491"), self, typeof(T), arg); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.GraphAlgorithms; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Layout.Layered; using Microsoft.Msagl.Core; using Microsoft.Msagl.Core.DataStructures; namespace Microsoft.Msagl.Prototype.Phylo { internal class PhyloTreeLayoutCalclulation : AlgorithmBase{ Anchor[] anchors; ProperLayeredGraph properLayeredGraph; Database dataBase; PhyloTree tree; BasicGraph<Node, IntEdge> intGraph; LayerArrays layerArrays; SortedDictionary<int, double> gridLayerOffsets = new SortedDictionary<int, double>(); double[] layerOffsets; double cellSize; Dictionary<Node, double> nodeOffsets = new Dictionary<Node, double>(); Dictionary<Node, int> nodesToIndices = new Dictionary<Node, int>(); int[] originalNodeToGridLayerIndices; Dictionary<int, int> gridLayerToLayer=new Dictionary<int,int>(); ///// <summary> ///// the layout responsible for the algorithm parameters ///// </summary> internal SugiyamaLayoutSettings LayoutSettings { get; private set; } internal PhyloTreeLayoutCalclulation(PhyloTree phyloTreeP, SugiyamaLayoutSettings settings, BasicGraph<Node, IntEdge> intGraphP, Database dataBase) { this.dataBase = dataBase; this.tree = phyloTreeP; this.LayoutSettings = settings; this.intGraph = intGraphP; originalNodeToGridLayerIndices = new int[intGraph.Nodes.Count]; } protected override void RunInternal() { if (!IsATree()) throw new InvalidDataException("the graph is not a tree"); DefineCellSize(); CalculateOriginalNodeToGridLayerIndices(); CreateLayerArraysAndProperLayeredGraph(); FillDataBase(); RunXCoordinateAssignmentsByBrandes(); CalcTheBoxFromAnchors(); StretchIfNeeded(); ProcessPositionedAnchors(); // SugiyamaLayoutSettings.ShowDataBase(this.dataBase); RouteSplines(); } bool IsATree() { Set<Node> visited = new Set<Node>(); Node root = tree.Nodes.FirstOrDefault(n => !n.InEdges.Any()); if (root == null) return false; return IsATreeUnderNode(root, visited) && visited.Count==tree.Nodes.Count; } static bool IsATreeUnderNode(Node node, Set<Node> visited) { if (visited.Contains(node)) return false; visited.Insert(node); return node.OutEdges.All(outEdge => IsATreeUnderNode(outEdge.Target, visited)); } private void StretchIfNeeded() { if (this.LayoutSettings.AspectRatio != 0) { double aspectRatio = this.tree.Width / this.tree.Height; StretchToDesiredAspectRatio(aspectRatio, LayoutSettings.AspectRatio); } } private void StretchToDesiredAspectRatio(double aspectRatio, double desiredAR) { if (aspectRatio > desiredAR) StretchInYDirection(aspectRatio / desiredAR); else if (aspectRatio < desiredAR) StretchInXDirection(desiredAR / aspectRatio); } private void StretchInYDirection(double scaleFactor) { double center = (this.tree.BoundingBox.Top + this.tree.BoundingBox.Bottom) / 2; foreach (Anchor a in this.dataBase.Anchors) { a.BottomAnchor *= scaleFactor; a.TopAnchor *= scaleFactor; a.Y = center + scaleFactor * (a.Y - center); } double h = this.tree.Height * scaleFactor; this.tree.BoundingBox = new Rectangle(this.tree.BoundingBox.Left, center + h / 2, this.tree.BoundingBox.Right, center - h / 2); } private void StretchInXDirection(double scaleFactor) { double center = (this.tree.BoundingBox.Left + this.tree.BoundingBox.Right) / 2; foreach (Anchor a in this.dataBase.Anchors) { a.LeftAnchor *= scaleFactor; a.RightAnchor *= scaleFactor; a.X = center + scaleFactor * (a.X - center); } double w = this.tree.Width * scaleFactor; this.tree.BoundingBox = new Rectangle(center - w / 2, tree.BoundingBox.Top, center + w / 2, this.tree.BoundingBox.Bottom); } private void DefineCellSize() { double min = double.MaxValue; foreach (PhyloEdge e in this.tree.Edges) min = Math.Min(min, e.Length); this.cellSize=0.3*min; } private void CalculateOriginalNodeToGridLayerIndices() { InitNodesToIndices(); FillNodeOffsets(); foreach (KeyValuePair<Node, double> kv in this.nodeOffsets) { int nodeIndex = this.nodesToIndices[kv.Key]; int gridLayerIndex=originalNodeToGridLayerIndices[nodeIndex] = GetGridLayerIndex(kv.Value); if (!gridLayerOffsets.ContainsKey(gridLayerIndex)) gridLayerOffsets[gridLayerIndex] = kv.Value; } } private int GetGridLayerIndex(double len) { return (int)(len / this.cellSize + 0.5); } private void InitNodesToIndices() { for (int i = 0; i < this.intGraph.Nodes.Count; i++) nodesToIndices[intGraph.Nodes[i]] = i; } private void FillNodeOffsets() { FillNodeOffsets(0.0, tree.Root); } private void FillNodeOffsets(double p, Node node) { nodeOffsets[node] = p; foreach (PhyloEdge e in node.OutEdges) FillNodeOffsets(p+e.Length, e.Target); } private void FillDataBase() { foreach (IntEdge e in intGraph.Edges) dataBase.RegisterOriginalEdgeInMultiedges(e); SizeAnchors(); FigureYCoordinates(); } private void FigureYCoordinates() { double m = GetMultiplier(); int root = nodesToIndices[tree.Root]; CalculateAnchorsY(root,m,0); for (int i = intGraph.NodeCount; i < dataBase.Anchors.Length; i++) dataBase.Anchors[i].Y = -m * layerOffsets[layerArrays.Y[i]]; //fix layer offsets for (int i = 0; i < layerOffsets.Length; i++) layerOffsets[i] *= m; } private double GetMultiplier() { double m = 1; for (int i = layerArrays.Layers.Length - 1; i > 0; i--) { double nm = GetMultiplierBetweenLayers(i); if (nm > m) m = nm; } return m; } private double GetMultiplierBetweenLayers(int i) { int a = FindLowestBottomOnLayer(i); int b = FindHighestTopOnLayer(i - 1); double ay = NodeY(i, a); double by = NodeY(i - 1, b); // we need to have m*(a[y]-b[y])>=anchors[a].BottomAnchor+anchors[b].TopAnchor+layerSeparation; double diff = ay - by; if (diff < 0) throw new InvalidOperationException(); double nm = (dataBase.Anchors[a].BottomAnchor + dataBase.Anchors[b].TopAnchor + LayoutSettings.LayerSeparation) / diff; if (nm > 1) return nm; return 1; } private int FindHighestTopOnLayer(int layerIndex) { int[] layer = layerArrays.Layers[layerIndex]; int ret = layer[0]; double top = NodeY(layerIndex, ret) + dataBase.Anchors[ret].TopAnchor; for (int i = 1; i < layer.Length; i++) { int node=layer[i]; double nt = NodeY(layerIndex, node) + dataBase.Anchors[node].TopAnchor; if (nt > top) { top = nt; ret = node; } } return ret; } private int FindLowestBottomOnLayer(int layerIndex) { int[] layer = layerArrays.Layers[layerIndex]; int ret = layer[0]; double bottom = NodeY(layerIndex, ret) - dataBase.Anchors[ret].BottomAnchor; for (int i = 1; i < layer.Length; i++) { int node = layer[i]; double nb = NodeY(layerIndex, node) - dataBase.Anchors[node].BottomAnchor; if (nb < bottom) { bottom = nb; ret = node; } } return ret; } private double NodeY(int layer, int node) { return - (IsOriginal(node) ? nodeOffsets[intGraph.Nodes[node]] : layerOffsets[layer]); } private bool IsOriginal(int node) { return node < intGraph.NodeCount; } private void CalculateAnchorsY(int node, double m, double y) { //go over original nodes dataBase.Anchors[node].Y = -y; foreach (IntEdge e in intGraph.OutEdges(node)) CalculateAnchorsY(e.Target, m, y + e.Edge.Length * m); } private void SizeAnchors() { dataBase.Anchors = anchors = new Anchor[properLayeredGraph.NodeCount]; for (int i = 0; i < anchors.Length; i++) anchors[i] = new Anchor(LayoutSettings.LabelCornersPreserveCoefficient); //go over the old vertices for (int i = 0; i < intGraph.NodeCount; i++) CalcAnchorsForOriginalNode(i); //go over virtual vertices foreach (IntEdge intEdge in dataBase.AllIntEdges) { if (intEdge.LayerEdges != null) { foreach (LayerEdge layerEdge in intEdge.LayerEdges) { int v = layerEdge.Target; if (v != intEdge.Target) { Anchor anchor = anchors[v]; if (!dataBase.MultipleMiddles.Contains(v)) { anchor.LeftAnchor = anchor.RightAnchor = VirtualNodeWidth / 2.0f; anchor.TopAnchor = anchor.BottomAnchor = VirtualNodeHeight / 2.0f; } else { anchor.LeftAnchor = anchor.RightAnchor = VirtualNodeWidth * 4; anchor.TopAnchor = anchor.BottomAnchor = VirtualNodeHeight / 2.0f; } } } //fix label vertices if (intEdge.Edge.Label!=null) { int lj = intEdge.LayerEdges[intEdge.LayerEdges.Count / 2].Source; Anchor a = anchors[lj]; double w = intEdge.LabelWidth, h = intEdge.LabelHeight; a.RightAnchor = w; a.LeftAnchor = LayoutSettings.NodeSeparation; if (a.TopAnchor < h / 2.0) a.TopAnchor = a.BottomAnchor = h / 2.0; a.LabelToTheRightOfAnchorCenter = true; } } } } /// <summary> /// the width of dummy nodes /// </summary> static double VirtualNodeWidth { get { return 1; } } /// <summary> /// the height of dummy nodes /// </summary> double VirtualNodeHeight { get { return LayoutSettings.MinNodeHeight * 1.5f / 8; } } void CalcAnchorsForOriginalNode(int i) { double leftAnchor = 0; double rightAnchor = leftAnchor; double topAnchor = 0; double bottomAnchor = topAnchor; //that's what we would have without the label and multiedges if (intGraph.Nodes != null) { Node node = intGraph.Nodes[i]; ExtendStandardAnchors(ref leftAnchor, ref rightAnchor, ref topAnchor, ref bottomAnchor, node); } RightAnchorMultiSelfEdges(i, ref rightAnchor, ref topAnchor, ref bottomAnchor); double hw = LayoutSettings.MinNodeWidth / 2; if (leftAnchor < hw) leftAnchor = hw; if (rightAnchor < hw) rightAnchor = hw; double hh = LayoutSettings.MinNodeHeight / 2; if (topAnchor < hh) topAnchor = hh; if (bottomAnchor < hh) bottomAnchor = hh; anchors[i] = new Anchor(leftAnchor, rightAnchor, topAnchor, bottomAnchor, this.intGraph.Nodes[i], LayoutSettings.LabelCornersPreserveCoefficient) {Padding = this.intGraph.Nodes[i].Padding}; #if TEST_MSAGL //anchors[i].Id = this.intGraph.Nodes[i].Id; #endif } private static void ExtendStandardAnchors(ref double leftAnchor, ref double rightAnchor, ref double topAnchor, ref double bottomAnchor, Node node) { double w = node.Width; double h = node.Height; w /= 2.0; h /= 2.0; rightAnchor = leftAnchor = w; topAnchor = bottomAnchor = h; } private void RightAnchorMultiSelfEdges(int i, ref double rightAnchor, ref double topAnchor, ref double bottomAnchor) { double delta = WidthOfSelfeEdge(i, ref rightAnchor, ref topAnchor, ref bottomAnchor); rightAnchor += delta; } private double WidthOfSelfeEdge(int i, ref double rightAnchor, ref double topAnchor, ref double bottomAnchor) { double delta = 0; List<IntEdge> multiedges = dataBase.GetMultiedge(i, i); //it could be a multiple self edge if (multiedges.Count > 0) { foreach (IntEdge e in multiedges) { if (e.Edge.Label != null) { rightAnchor += e.Edge.Label.Width; if (topAnchor < e.Edge.Label.Height / 2.0) topAnchor = bottomAnchor = e.Edge.Label.Height / 2.0f; } } delta += (LayoutSettings.NodeSeparation + LayoutSettings.MinNodeWidth) * multiedges.Count; } return delta; } private void RouteSplines() { Layout.Layered.Routing routing = new Layout.Layered.Routing(LayoutSettings, this.tree, dataBase, this.layerArrays, this.properLayeredGraph, null); routing.Run(); } private void RunXCoordinateAssignmentsByBrandes() { XCoordsWithAlignment.CalculateXCoordinates(this.layerArrays, this.properLayeredGraph, this.tree.Nodes.Count, this.dataBase.Anchors, this.LayoutSettings.NodeSeparation); } private void CreateLayerArraysAndProperLayeredGraph() { int numberOfLayers = this.gridLayerOffsets.Count; this.layerOffsets=new double[numberOfLayers]; int i = numberOfLayers-1; foreach (KeyValuePair<int, double> kv in this.gridLayerOffsets) { layerOffsets[i] = kv.Value; gridLayerToLayer[kv.Key] = i--; } int nOfNodes=CountTotalNodesIncludingVirtual(nodesToIndices[tree.Root]); ////debugging !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //int tt = 0; //foreach (IntEdge ie in this.intGraph.Edges) // tt += this.OriginalNodeLayer(ie.Source) - this.OriginalNodeLayer(ie.Target) - 1; //if (tt + this.intGraph.Nodes.Count != nOfNodes) // throw new Exception(); int[] layering = new int[nOfNodes]; List<int>[] layers = new List<int>[numberOfLayers]; for (i = 0; i < numberOfLayers; i++) layers[i] = new List<int>(); WalkTreeAndInsertLayerEdges(layering, layers); this.layerArrays = new LayerArrays(layering); int[][]ll=layerArrays.Layers=new int[numberOfLayers][]; i = 0; foreach (List<int> layer in layers) { ll[i++] = layer.ToArray(); } this.properLayeredGraph = new ProperLayeredGraph(intGraph); } private int CountTotalNodesIncludingVirtual(int node) { int ret = 1; foreach (IntEdge edge in this.intGraph.OutEdges(node)) ret += NumberOfVirtualNodesOnEdge(edge) + CountTotalNodesIncludingVirtual(edge.Target); return ret; } private int NumberOfVirtualNodesOnEdge(IntEdge edge) { return OriginalNodeLayer(edge.Source) - OriginalNodeLayer(edge.Target) - 1; } private int OriginalNodeLayer(int node) { return gridLayerToLayer[originalNodeToGridLayerIndices[node]]; } private void WalkTreeAndInsertLayerEdges(int[] layering, List<int>[] layers) { int virtualNode = this.intGraph.NodeCount; int root = nodesToIndices[tree.Root]; int l; layering[root] = l = OriginalNodeLayer(root); layers[l].Add(root); WalkTreeAndInsertLayerEdges(layering, layers, root , ref virtualNode); } private void WalkTreeAndInsertLayerEdges(int[] layering, List<int>[] layers, int node, ref int virtualNode) { foreach (IntEdge edge in this.intGraph.OutEdges(node)) InsertLayerEdgesForEdge(edge, layering, ref virtualNode, layers); } private void InsertLayerEdgesForEdge(IntEdge edge, int[] layering, ref int virtualNode, List<int>[] layers) { int span = OriginalNodeLayer(edge.Source) - OriginalNodeLayer(edge.Target); edge.LayerEdges=new LayerEdge[span]; for (int i = 0; i < span; i++) edge.LayerEdges[i] = new LayerEdge(GetSource(i, edge, ref virtualNode), GetTarget(i, span, edge, virtualNode), edge.CrossingWeight); int l = OriginalNodeLayer(edge.Source) - 1; for (int i = 0; i < span; i++) { int node=edge.LayerEdges[i].Target; layering[node] = l; layers[l--].Add(node); } WalkTreeAndInsertLayerEdges(layering, layers, edge.Target, ref virtualNode); } static private int GetTarget(int i, int span, IntEdge edge, int virtualNode) { if (i < span-1) return virtualNode; return edge.Target; } static private int GetSource(int i, IntEdge edge, ref int virtualNode) { if (i > 0) return virtualNode++; return edge.Source; } void ProcessPositionedAnchors() { for (int i = 0; i < this.tree.Nodes.Count; i++) intGraph.Nodes[i].Center=anchors[i].Origin; } private void CalcTheBoxFromAnchors() { if (anchors.Length > 0) { Rectangle box = new Rectangle(anchors[0].Left, anchors[0].Top, anchors[0].Right, anchors[0].Bottom); for (int i = 1; i < anchors.Length; i++) { Anchor a = anchors[i]; box.Add(a.LeftTop); box.Add(a.RightBottom); } double m = Math.Max(box.Width, box.Height); double delta = this.tree.Margins / 100.0 * m; Point del = new Point(-delta, delta); box.Add(box.LeftTop + del); box.Add(box.RightBottom - del); this.tree.BoundingBox = box; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.NetAnalyzers; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { using static MicrosoftNetCoreAnalyzersResources; /// <summary> /// CA1307: Specify StringComparison /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class SpecifyStringComparisonAnalyzer : AbstractGlobalizationDiagnosticAnalyzer { private const string RuleId_CA1307 = "CA1307"; private const string RuleId_CA1310 = "CA1310"; private static readonly ImmutableArray<string> s_CA1310MethodNamesWithFirstStringParameter = ImmutableArray.Create("Compare", "StartsWith", "EndsWith", "IndexOf", "LastIndexOf"); internal static readonly DiagnosticDescriptor Rule_CA1307 = DiagnosticDescriptorHelper.Create( RuleId_CA1307, CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1307Title)), CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1307Message)), DiagnosticCategory.Globalization, RuleLevel.Disabled, description: CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1307Description)), isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor Rule_CA1310 = DiagnosticDescriptorHelper.Create( RuleId_CA1310, CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1310Title)), CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1310Message)), DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: CreateLocalizableResourceString(nameof(SpecifyStringComparisonCA1310Description)), isPortedFxCopRule: false, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule_CA1307, Rule_CA1310); protected override void InitializeWorker(CompilationStartAnalysisContext context) { var stringComparisonType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStringComparison); var stringType = context.Compilation.GetSpecialType(SpecialType.System_String); // Without these symbols the rule cannot run if (stringComparisonType == null) { return; } var overloadMap = GetWellKnownStringOverloads(context.Compilation, stringType, stringComparisonType); var linqExpressionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqExpressionsExpression1); context.RegisterOperationAction(oaContext => { var invocationExpression = (IInvocationOperation)oaContext.Operation; var targetMethod = invocationExpression.TargetMethod; if (targetMethod.IsGenericMethod || targetMethod.ContainingType == null || targetMethod.ContainingType.IsErrorType()) { return; } // Check if we are in a Expression<Func<T...>> context, in which case it is possible // that the underlying call doesn't have the comparison option so we want to bail-out. if (invocationExpression.IsWithinExpressionTree(linqExpressionType)) { return; } // Report correctness issue CA1310 for known string comparison methods that default to culture specific string comparison: // https://docs.microsoft.com/dotnet/standard/base-types/best-practices-strings#string-comparisons-that-use-the-current-culture if (targetMethod.ContainingType.SpecialType == SpecialType.System_String && !overloadMap.IsEmpty && overloadMap.ContainsKey(targetMethod)) { ReportDiagnostic( Rule_CA1310, oaContext, invocationExpression, targetMethod, overloadMap[targetMethod]); return; } // Report maintainability issue CA1307 for any method that has an additional overload with the exact same parameter list, // plus as additional StringComparison parameter. Default StringComparison may or may not match user's intent, // but it is recommended to explicitly specify it for clarity and readability: // https://docs.microsoft.com/dotnet/standard/base-types/best-practices-strings#recommendations-for-string-usage IEnumerable<IMethodSymbol> methodsWithSameNameAsTargetMethod = targetMethod.ContainingType.GetMembers(targetMethod.Name).OfType<IMethodSymbol>(); if (methodsWithSameNameAsTargetMethod.HasMoreThan(1)) { var correctOverload = methodsWithSameNameAsTargetMethod .GetMethodOverloadsWithDesiredParameterAtTrailing(targetMethod, stringComparisonType) .FirstOrDefault(); if (correctOverload != null) { ReportDiagnostic( Rule_CA1307, oaContext, invocationExpression, targetMethod, correctOverload); } } }, OperationKind.Invocation); static ImmutableDictionary<IMethodSymbol, IMethodSymbol> GetWellKnownStringOverloads( Compilation compilation, INamedTypeSymbol stringType, INamedTypeSymbol stringComparisonType) { var objectType = compilation.GetSpecialType(SpecialType.System_Object); var booleanType = compilation.GetSpecialType(SpecialType.System_Boolean); var integerType = compilation.GetSpecialType(SpecialType.System_Int32); var stringCompareToNamedMethods = stringType.GetMembers("CompareTo").OfType<IMethodSymbol>(); var stringCompareToParameterString = stringCompareToNamedMethods.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType)); var stringCompareToParameterObject = stringCompareToNamedMethods.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(objectType)); var stringCompareNamedMethods = stringType.GetMembers("Compare").OfType<IMethodSymbol>(); var stringCompareParameterStringStringBool = stringCompareNamedMethods.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(stringType), GetParameterInfo(booleanType)); var stringCompareParameterStringStringStringComparison = stringCompareNamedMethods.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(stringType), GetParameterInfo(stringComparisonType)); var stringCompareParameterStringIntStringIntIntBool = stringCompareNamedMethods.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(integerType), GetParameterInfo(stringType), GetParameterInfo(integerType), GetParameterInfo(integerType), GetParameterInfo(booleanType)); var stringCompareParameterStringIntStringIntIntComparison = stringCompareNamedMethods.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(integerType), GetParameterInfo(stringType), GetParameterInfo(integerType), GetParameterInfo(integerType), GetParameterInfo(stringComparisonType)); var overloadMapBuilder = ImmutableDictionary.CreateBuilder<IMethodSymbol, IMethodSymbol>(); overloadMapBuilder.AddKeyValueIfNotNull(stringCompareToParameterString, stringCompareParameterStringStringStringComparison); overloadMapBuilder.AddKeyValueIfNotNull(stringCompareToParameterObject, stringCompareParameterStringStringStringComparison); overloadMapBuilder.AddKeyValueIfNotNull(stringCompareParameterStringStringBool, stringCompareParameterStringStringStringComparison); overloadMapBuilder.AddKeyValueIfNotNull(stringCompareParameterStringIntStringIntIntBool, stringCompareParameterStringIntStringIntIntComparison); foreach (var methodName in s_CA1310MethodNamesWithFirstStringParameter) { var methodsWithMethodName = stringType.GetMembers(methodName).OfType<IMethodSymbol>(); foreach (var method in methodsWithMethodName) { if (!method.Parameters.IsEmpty && method.Parameters[0].Type.SpecialType == SpecialType.System_String && !method.Parameters[^1].Type.Equals(stringComparisonType)) { var recommendedMethod = methodsWithMethodName .GetMethodOverloadsWithDesiredParameterAtTrailing(method, stringComparisonType) .FirstOrDefault(); if (recommendedMethod != null) { overloadMapBuilder.AddKeyValueIfNotNull(method, recommendedMethod); } } } } return overloadMapBuilder.ToImmutable(); } } private static void ReportDiagnostic( DiagnosticDescriptor rule, OperationAnalysisContext oaContext, IInvocationOperation invocationExpression, IMethodSymbol targetMethod, IMethodSymbol correctOverload) { oaContext.ReportDiagnostic( invocationExpression.CreateDiagnostic( rule, targetMethod.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), correctOverload.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))); } private static ParameterInfo GetParameterInfo(INamedTypeSymbol type, bool isArray = false, int arrayRank = 0, bool isParams = false) { return ParameterInfo.GetParameterInfo(type, isArray, arrayRank, isParams); } } }
namespace Nancy.ModelBinding { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Nancy.Extensions; using System.Collections; /// <summary> /// Default binder - used as a fallback when a specific modelbinder /// is not available. /// </summary> public class DefaultBinder : IBinder { private readonly IEnumerable<ITypeConverter> typeConverters; private readonly IEnumerable<IBodyDeserializer> bodyDeserializers; private readonly IFieldNameConverter fieldNameConverter; private readonly BindingDefaults defaults; private readonly static MethodInfo toListMethodInfo = typeof(Enumerable).GetMethod("ToList", BindingFlags.Public | BindingFlags.Static); private readonly static MethodInfo toArrayMethodInfo = typeof(Enumerable).GetMethod("ToArray", BindingFlags.Public | BindingFlags.Static); private static readonly Regex bracketRegex = new Regex(@"\[(\d+)\]\z", RegexOptions.Compiled); private static readonly Regex underscoreRegex = new Regex(@"_(\d+)\z", RegexOptions.Compiled); public DefaultBinder(IEnumerable<ITypeConverter> typeConverters, IEnumerable<IBodyDeserializer> bodyDeserializers, IFieldNameConverter fieldNameConverter, BindingDefaults defaults) { if (typeConverters == null) { throw new ArgumentNullException("typeConverters"); } if (bodyDeserializers == null) { throw new ArgumentNullException("bodyDeserializers"); } if (fieldNameConverter == null) { throw new ArgumentNullException("fieldNameConverter"); } if (defaults == null) { throw new ArgumentNullException("defaults"); } this.typeConverters = typeConverters; this.bodyDeserializers = bodyDeserializers; this.fieldNameConverter = fieldNameConverter; this.defaults = defaults; } /// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blackList">Blacklisted binding property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { Type genericType = null; if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure it has a generic type if (modelType.IsGenericType()) { genericType = modelType.GetGenericArguments().FirstOrDefault(); } else { var ienumerable = modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault( i => i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); genericType = ienumerable == null ? null : ienumerable.GetGenericArguments().FirstOrDefault(); } if (genericType == null) { throw new ArgumentException("When modelType is an enumerable it must specify the type.", "modelType"); } } var bindingContext = this.CreateBindingContext(context, modelType, instance, configuration, blackList, genericType); var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext); if (bodyDeserializedModel != null) { UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext); } var bindingExceptions = new List<PropertyBindingException>(); if (!bindingContext.Configuration.BodyOnly) { if (bindingContext.DestinationType.IsCollection() || bindingContext.DestinationType.IsArray() ||bindingContext.DestinationType.IsEnumerable()) { var loopCount = GetBindingListInstanceCount(context); var model = (IList)bindingContext.Model; for (var i = 0; i < loopCount; i++) { object genericinstance; if (model.Count > i) { genericinstance = model[i]; } else { genericinstance = Activator.CreateInstance(bindingContext.GenericType); model.Add(genericinstance); } foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingCollectionValue = modelProperty.GetValue(genericinstance); var collectionStringValue = GetValue(modelProperty.Name, bindingContext, i); if (BindingValueIsValid(collectionStringValue, existingCollectionValue, modelProperty, bindingContext)) { try { BindValue(modelProperty, collectionStringValue, bindingContext, genericinstance); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } } else { foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(bindingContext.Model); var stringValue = GetValue(modelProperty.Name, bindingContext); if (BindingValueIsValid(stringValue, existingValue, modelProperty, bindingContext)) { try { BindValue(modelProperty, stringValue, bindingContext); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } if (bindingExceptions.Any() && !bindingContext.Configuration.IgnoreErrors) { throw new ModelBindingException(modelType, bindingExceptions); } } if (modelType.IsArray()) { var generictoArrayMethod = toArrayMethodInfo.MakeGenericMethod(new[] { genericType }); return generictoArrayMethod.Invoke(null, new[] { bindingContext.Model }); } return bindingContext.Model; } private bool BindingValueIsValid(string bindingValue, object existingValue, BindingMemberInfo modelProperty, BindingContext bindingContext) { return (!String.IsNullOrEmpty(bindingValue) && (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite)); } /// <summary> /// Gets the number of distinct indexes from context: /// /// i.e: /// IntProperty_5 /// StringProperty_5 /// IntProperty_7 /// StringProperty_8 /// You'll end up with a list of 3 matches: 5,7,8 /// /// </summary> /// <param name="context">Current Context </param> /// <returns>An int containing the number of elements</returns> private int GetBindingListInstanceCount(NancyContext context) { var dictionary = context.Request.Form as IDictionary<string, object>; if (dictionary == null) { return 0; } return dictionary.Keys.Select(IsMatch).Where(x => x != -1).Distinct().ToArray().Length; } private static int IsMatch(string item) { var bracketMatch = bracketRegex.Match(item); if (bracketMatch.Success) { return int.Parse(bracketMatch.Groups[1].Value); } var underscoreMatch = underscoreRegex.Match(item); if (underscoreMatch.Success) { return int.Parse(underscoreMatch.Groups[1].Value); } return -1; } private static void UpdateModelWithDeserializedModel(object bodyDeserializedModel, BindingContext bindingContext) { var bodyDeserializedModelType = bodyDeserializedModel.GetType(); if (bodyDeserializedModelType.IsValueType) { bindingContext.Model = bodyDeserializedModel; return; } if (bodyDeserializedModelType.IsCollection() || bodyDeserializedModelType.IsEnumerable() || bodyDeserializedModelType.IsArray()) { var count = 0; foreach (var o in (IEnumerable)bodyDeserializedModel) { var model = (IList)bindingContext.Model; if (o.GetType().IsValueType || o.GetType() == typeof(string)) { HandleValueTypeCollectionElement(model, count, o); } else { HandleReferenceTypeCollectionElement(bindingContext, model, count, o); } count++; } } else { foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(bindingContext.Model); if (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite) { CopyValue(modelProperty, bodyDeserializedModel, bindingContext.Model); } } } } private static void HandleValueTypeCollectionElement(IList model, int count, object o) { // If the instance specified in the binder contains the n-th element use that if (model.Count > count) { return; } model.Add(o); } private static void HandleReferenceTypeCollectionElement(BindingContext bindingContext, IList model, int count, object o) { // If the instance specified in the binder contains the n-th element use that otherwise make a new one. object genericTypeInstance; if (model.Count > count) { genericTypeInstance = model[count]; } else { genericTypeInstance = Activator.CreateInstance(bindingContext.GenericType); model.Add(genericTypeInstance); } foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(genericTypeInstance); if (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite) { CopyValue(modelProperty, o, genericTypeInstance); } } } private static void CopyValue(BindingMemberInfo modelProperty, object source, object destination) { var newValue = modelProperty.GetValue(source); modelProperty.SetValue(destination, newValue); } private static bool IsDefaultValue(object existingValue, Type propertyType) { return propertyType.IsValueType ? Equals(existingValue, Activator.CreateInstance(propertyType)) : existingValue == null; } private BindingContext CreateBindingContext(NancyContext context, Type modelType, object instance, BindingConfig configuration, IEnumerable<string> blackList, Type genericType) { return new BindingContext { Configuration = configuration, Context = context, DestinationType = modelType, Model = CreateModel(modelType, genericType, instance), ValidModelBindingMembers = GetBindingMembers(modelType, genericType, blackList).ToList(), RequestData = this.GetDataFields(context), GenericType = genericType, TypeConverters = this.typeConverters.Concat(this.defaults.DefaultTypeConverters), }; } private IDictionary<string, string> GetDataFields(NancyContext context) { var dictionaries = new IDictionary<string, string>[] { ConvertDynamicDictionary(context.Request.Form), ConvertDynamicDictionary(context.Request.Query), ConvertDynamicDictionary(context.Parameters) }; return dictionaries.Merge(); } private IDictionary<string, string> ConvertDynamicDictionary(DynamicDictionary dictionary) { if (dictionary == null) { return null; } return dictionary.GetDynamicMemberNames().ToDictionary( memberName => this.fieldNameConverter.Convert(memberName), memberName => (string)dictionary[memberName]); } private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context) { BindValue(modelProperty, stringValue, context, context.Model); } private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context, object targetInstance) { var destinationType = modelProperty.PropertyType; var typeConverter = context.TypeConverters.FirstOrDefault(c => c.CanConvertTo(destinationType, context)); if (typeConverter != null) { try { SetBindingMemberValue(modelProperty, targetInstance, typeConverter.Convert(stringValue, destinationType, context)); } catch (Exception e) { throw new PropertyBindingException(modelProperty.Name, stringValue, e); } } else if (destinationType == typeof(string)) { SetBindingMemberValue(modelProperty, targetInstance, stringValue); } } private static void SetBindingMemberValue(BindingMemberInfo modelProperty, object model, object value) { // TODO - catch reflection exceptions? modelProperty.SetValue(model, value); } private static IEnumerable<BindingMemberInfo> GetBindingMembers(Type modelType, Type genericType, IEnumerable<string> blackList) { var blackListHash = new HashSet<string>(blackList, StringComparer.InvariantCulture); return BindingMemberInfo.Collect(genericType ?? modelType) .Where(member => !blackListHash.Contains(member.Name)); } private static object CreateModel(Type modelType, Type genericType, object instance) { if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure instance has a Add method. Otherwise call `.ToList` if (instance != null && modelType.IsInstanceOfType(instance)) { var addMethod = modelType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance); if (addMethod != null) { return instance; } var genericMethod = toListMethodInfo.MakeGenericMethod(genericType); return genericMethod.Invoke(null, new[] { instance }); } //else just make a list var listType = typeof(List<>).MakeGenericType(genericType); return Activator.CreateInstance(listType); } if (instance == null) { return Activator.CreateInstance(modelType, true); } return !modelType.IsInstanceOfType(instance) ? Activator.CreateInstance(modelType, true) : instance; } private static string GetValue(string propertyName, BindingContext context, int index = -1) { if (index != -1) { var indexindexes = context.RequestData.Keys.Select(IsMatch) .Where(i => i != -1) .OrderBy(i => i) .Distinct() .Select((k, i) => new KeyValuePair<int, int>(i, k)) .ToDictionary(k => k.Key, v => v.Value); if (indexindexes.ContainsKey(index)) { var propertyValue = context.RequestData.Where(c => { var indexId = IsMatch(c.Key); return c.Key.StartsWith(propertyName, StringComparison.OrdinalIgnoreCase) && indexId != -1 && indexId == indexindexes[index]; }) .Select(k => k.Value) .FirstOrDefault(); return propertyValue ?? string.Empty; } return string.Empty; } return context.RequestData.ContainsKey(propertyName) ? context.RequestData[propertyName] : string.Empty; } private object DeserializeRequestBody(BindingContext context) { if (context.Context == null || context.Context.Request == null) { return null; } var contentType = GetRequestContentType(context.Context); var bodyDeserializer = this.bodyDeserializers.FirstOrDefault(b => b.CanDeserialize(contentType, context)); if (bodyDeserializer != null) { return bodyDeserializer.Deserialize(contentType, context.Context.Request.Body, context); } bodyDeserializer = this.defaults.DefaultBodyDeserializers.FirstOrDefault(b => b.CanDeserialize(contentType, context)); return bodyDeserializer != null ? bodyDeserializer.Deserialize(contentType, context.Context.Request.Body, context) : null; } private static string GetRequestContentType(NancyContext context) { if (context == null || context.Request == null) { return String.Empty; } var contentType = context.Request.Headers.ContentType; return (string.IsNullOrEmpty(contentType)) ? string.Empty : contentType; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using KaoriStudio.Core.Configuration; using Microsoft.CSharp; using System.CodeDom; using System.CodeDom.Compiler; using KaoriStudio.Core.Text.Parsing; using System.Diagnostics; using KaoriStudio.Core.Helpers; namespace KaoriStudio.CodeGenerator.Generators { /// <summary> /// The lexer DFA generator /// </summary> public class LexerDFA : IGenerator { /// <summary> /// The lexer configuration /// </summary> public struct LexerConfig { /// <summary> /// The namespace /// </summary> public string Namespace { get; set; } /// <summary> /// The class name /// </summary> public string Name { get; set; } /// <summary> /// The method name /// </summary> public string Method { get; set; } /// <summary> /// /// </summary> public bool Partial { get; set; } /// <summary> /// The enum name /// </summary> public string Enum { get; set; } /// <summary> /// The method to use for exceptions /// </summary> public string ExceptionMethod { get; set; } /// <summary> /// The states /// </summary> public State[] States { get; set; } /// <summary> /// Whether a state stack is used /// </summary> public bool StateStack { get; set; } /// <summary> /// The customized error messages. /// </summary> public KeyValuePair<string, string>[] Messages { get; set; } /// <summary> /// Lexer state /// </summary> public struct State { /// <summary> /// The state name /// </summary> public string Name; /// <summary> /// The cases /// </summary> public Case[] Cases { get; set; } /// <summary> /// Lexer state case /// </summary> public struct Case { /// <summary> /// The matching characters /// </summary> public int[] Matches; /// <summary> /// The instructions /// </summary> public Instruction[] Instructions; /// <summary> /// Lexer case instruction /// </summary> public struct Instruction { /// <summary> /// The instruction code /// </summary> public InstructionCode Code { get; set; } /// <summary> /// The arguments /// </summary> public object[] Arguments { get; set; } /// <summary> /// An instruction code /// </summary> public enum InstructionCode { /// <summary> /// Clear buffer /// </summary> Clear, /// <summary> /// Push input to buffer /// </summary> PushInput, /// <summary> /// Push argument to buffer /// </summary> Push, /// <summary> /// Push code to buffer /// </summary> PushCode, /// <summary> /// Set token position to lexer position /// </summary> InPos, /// <summary> /// Set code to lexer character /// </summary> InCode, /// <summary> /// Fused multiply-add /// </summary> FMA, /// <summary> /// Fused shift-or /// </summary> FSO, /// <summary> /// Set code to argument /// </summary> Code, /// <summary> /// Xor code with argument /// </summary> Xor, /// <summary> /// Or code with argument /// </summary> Or, /// <summary> /// And code with argument /// </summary> And, /// <summary> /// Set state to argument /// </summary> State, /// <summary> /// Throw exception /// </summary> Die, /// <summary> /// Yield buffer and token type argument /// </summary> Yield, /// <summary> /// Yield lexer character and token type argument /// </summary> YieldInput, /// <summary> /// Converts the code to lowercase /// </summary> ToLower, /// <summary> /// Converts the code to uppercase /// </summary> ToUpper, /// <summary> /// Pushes the current or specified state /// </summary> PushState, /// <summary> /// Loads the state at the top of the stack /// </summary> PeekState, /// <summary> /// Pops the state /// </summary> PopState, /// <summary> /// Dies if the buffer contains a value. /// </summary> DieIfContains, /// <summary> /// Dies if the buffer contains other characters. /// </summary> DieIfOtherCharacters, } } } } } /// <summary> /// The name of this code generator /// </summary> public string Name { get { return "LexerDFA"; } } /// <summary> /// Generates code /// </summary> /// <param name="data">The data</param> /// <param name="output">The output</param> public void Generate(ConfigurationDictionary data, TextWriter output) { CSharpCodeProvider provider = new CSharpCodeProvider(); LexerConfig config = GenerateConfig(data); GenerateLexer(config, output); } private static void ProcessMatches(object matchValue, SortedSet<int> matches, SortedDictionary<string, LexerConfig.State.Case.Instruction.InstructionCode> ic) { if (matchValue is string) { string matchString = matchValue.ToString(); int prevchr = 0; for (int i = 0; i < matchString.Length; i++) { int cc = (int)matchString[i]; if ((i & 1) == 0) { prevchr = cc; matches.Add(cc); } else { for (int j = prevchr + 1; j <= cc; j++) { matches.Add(j); } } } } else if (matchValue is int) { matches.Add((int)matchValue); } else if (matchValue is ConfigurationDictionary) { foreach (var val in ((ConfigurationDictionary)matchValue).Select(x => x.Value)) ProcessMatches(val, matches, ic); } } private static void ProcessCase(ConfigurationDictionary scase, List<LexerConfig.State.Case> mcases, SortedDictionary<string, LexerConfig.State.Case.Instruction.InstructionCode> ic) { var matches = new SortedSet<int>(); var instructions = new List<LexerConfig.State.Case.Instruction>(); ProcessMatches(scase[0].Value, matches, ic); for (int i = 1; i < scase.Count; i++) { var pair = scase[i]; var key = pair.Key; var value = pair.Value; if (key != null) { if (value == null) value = key; else if (value is string) value = new ConfigurationDictionary(CollectionHelper.CreateEnumerable(key, value)); else if (ObjectHelper.TryAs<ConfigurationDictionary>(value, out var cvalue)) { value = new ConfigurationDictionary(CollectionHelper.CreateEnumerable<object>(key).Concat(cvalue.Values.Cast<object>())); } } if (value is string) { try { instructions.Add(new LexerConfig.State.Case.Instruction() { Code = ic[value.ToString()], Arguments = null }); } catch (Exception) { throw new Exception(value.ToString()); } } else if (value is ConfigurationDictionary) { var insmap = (ConfigurationDictionary)value; var args = new List<object>(); for (int j = 1; j < insmap.Count; j++) args.Add(insmap[j].Value); instructions.Add(new LexerConfig.State.Case.Instruction() { Code = ic[insmap[0].Value.ToString()], Arguments = args.ToArray() }); } } mcases.Add(new LexerConfig.State.Case() { Matches = matches.ToArray(), Instructions = instructions.ToArray() }); } private static void ProcessState(KeyValuePair<string, object> state, List<LexerConfig.State> states, SortedDictionary<string, LexerConfig.State.Case.Instruction.InstructionCode> ic) { var cases = (ConfigurationDictionary)state.Value; //if (state.Key != null) // cases = new ConfigurationDictionary(CollectionHelper.CreateEnumerable<object>(state.Key).Concat((IEnumerable<object>)cases)); var mcases = new List<LexerConfig.State.Case>(); foreach (var scase in cases.Select(x => (ConfigurationDictionary)x.Value)) ProcessCase(scase, mcases, ic); states.Add(new LexerConfig.State() { Name = state.Key, Cases = mcases.ToArray() }); } /// <summary> /// Generates a config from a map /// </summary> /// <param name="data">The map</param> /// <returns>The config</returns> public LexerConfig GenerateConfig(ConfigurationDictionary data) { LexerConfig config = new LexerConfig(); { var stringData = data.Caster<string>(); config.Namespace = stringData["Namespace"]; config.Name = stringData["Name"]; config.Enum = stringData["Enum"]; config.Method = stringData["Method"]; config.ExceptionMethod = stringData["ExceptionMethod"]; config.Partial = data.ValueAs<bool>("Partial", false); config.StateStack = data.ValueAs<bool>("StateStack", false); } var ic = new SortedDictionary<string, LexerConfig.State.Case.Instruction.InstructionCode>(StringComparer.CurrentCultureIgnoreCase); ic["Clear"] = LexerConfig.State.Case.Instruction.InstructionCode.Clear; ic["InPos"] = LexerConfig.State.Case.Instruction.InstructionCode.InPos; ic["PushInput"] = LexerConfig.State.Case.Instruction.InstructionCode.PushInput; ic["Push"] = LexerConfig.State.Case.Instruction.InstructionCode.Push; ic["PushCode"] = LexerConfig.State.Case.Instruction.InstructionCode.PushCode; ic["InPos"] = LexerConfig.State.Case.Instruction.InstructionCode.InPos; ic["InCode"] = LexerConfig.State.Case.Instruction.InstructionCode.InCode; ic["FMA"] = LexerConfig.State.Case.Instruction.InstructionCode.FMA; ic["FSO"] = LexerConfig.State.Case.Instruction.InstructionCode.FSO; ic["Code"] = LexerConfig.State.Case.Instruction.InstructionCode.Code; ic["Xor"] = LexerConfig.State.Case.Instruction.InstructionCode.Xor; ic["Or"] = LexerConfig.State.Case.Instruction.InstructionCode.Or; ic["And"] = LexerConfig.State.Case.Instruction.InstructionCode.And; ic["State"] = LexerConfig.State.Case.Instruction.InstructionCode.State; ic["Die"] = LexerConfig.State.Case.Instruction.InstructionCode.Die; ic["Yield"] = LexerConfig.State.Case.Instruction.InstructionCode.Yield; ic["YieldInput"] = LexerConfig.State.Case.Instruction.InstructionCode.YieldInput; ic["ToLower"] = LexerConfig.State.Case.Instruction.InstructionCode.ToLower; ic["ToUpper"] = LexerConfig.State.Case.Instruction.InstructionCode.ToUpper; ic["PushState"] = LexerConfig.State.Case.Instruction.InstructionCode.PushState; ic["PeekState"] = LexerConfig.State.Case.Instruction.InstructionCode.PeekState; ic["PopState"] = LexerConfig.State.Case.Instruction.InstructionCode.PopState; ic["DieIfContains"] = LexerConfig.State.Case.Instruction.InstructionCode.DieIfContains; ic["DieIfOtherCharacters"] = LexerConfig.State.Case.Instruction.InstructionCode.DieIfOtherCharacters; { var states = new List<LexerConfig.State>(); foreach (var state in data.ValueAs<ConfigurationDictionary>("States")) { ProcessState(state, states, ic); } config.States = states.ToArray(); } if (data.TryGetValueAs<ConfigurationDictionary>("Messages", out var msgs)) config.Messages = msgs.Select(x => new KeyValuePair<string, string>(x.Key, (string)x.Value)).ToArray(); else config.Messages = Array.Empty<KeyValuePair<string, string>>(); return config; } static bool IsPrintable(int chr) { return !(chr < 0x20 || chr > 127); } static string FancyChar(int chr) { switch (chr) { case -1: return "-1"; case '\r': return @"'\r'"; case '\n': return @"'\n'"; case '\t': return @"'\t'"; case '\'': return @"'\''"; case '\\': return @"'\\'"; default: return IsPrintable(chr) ? new string(new char[] { '\'', (char)chr, '\'' }) : ("(char)" + chr.ToString()); } } static string FancyString(int chr) { if (chr >= 0) return FancyString(((char)chr).ToString()); else return "\"\""; } static string FancyString(string str) { StringBuilder sb = new StringBuilder(); sb.Append('"'); foreach (char c in str) { switch (c) { case '\r': sb.Append(@"\r"); break; case '\n': sb.Append(@"\n"); break; case '\t': sb.Append(@"\t"); break; case '\\': sb.Append(@"\\"); break; case '"': sb.Append("\\\""); break; default: if (IsPrintable((int)c)) sb.Append(c); else sb.Append(@"\x").Append(((int)c).ToString("X")); break; } } sb.Append('"'); return sb.ToString(); } /// <summary> /// The default extension for this generator /// </summary> /// <param name="data">The map</param> /// <returns>The default extension for the map</returns> public string DefaultExtension(ConfigurationDictionary data) { return "cs"; } /// <summary> /// Generates code from a configuration /// </summary> /// <param name="data">The configuration</param> /// <param name="output">The output</param> public void GenerateLexer(LexerConfig data, TextWriter output) { IndentedTextWriter itw = new IndentedTextWriter(output); SortedDictionary<string, int> stateIndexes = new SortedDictionary<string, int>(); SortedDictionary<string, int> messageIndexes = new SortedDictionary<string, int>(); itw.Indent = 0; string[] namespaces = new[] { "System", "System.IO", "System.Text", "System.Collections.Generic", "System.Globalization", "KaoriStudio.Core.Text.Parsing", "KaoriStudio.Core.Helpers" }; foreach (var ns in namespaces) { itw.WriteLine("using {0};", ns); } itw.WriteLine("namespace {0}", data.Namespace); itw.WriteLine("{"); itw.Indent++; itw.WriteLine(data.Partial ? "public partial class {0}" : "public class {0}", data.Name); itw.WriteLine("{"); itw.Indent++; itw.WriteLine("public static IEnumerable<Token<{0}>> {1}(TextReader source, TokenPosition inpos)", data.Enum, data.Method); itw.WriteLine("{"); itw.Indent++; if (data.StateStack) itw.WriteLine("var stateStack = new Stack<int>();"); itw.WriteLine("int state = 0;"); itw.WriteLine("StringBuilder buffer = new StringBuilder();"); itw.WriteLine("TokenPosition pos = default(TokenPosition);"); itw.WriteLine("int code = 0;"); itw.WriteLine("int input;"); itw.WriteLine("do"); itw.WriteLine("{"); itw.Indent++; itw.WriteLine("input = source.Read();"); itw.WriteLine("if (input == '\\n')"); itw.WriteLine("{"); itw.Indent++; itw.WriteLine("inpos.Column = 1;"); itw.WriteLine("inpos.Line++;"); itw.Indent--; itw.WriteLine("}"); itw.WriteLine("switch(state)"); itw.WriteLine("{"); itw.Indent++; for (int i = 0; i < data.States.Length; i++) stateIndexes[data.States[i].Name] = i; for (int i = 0; i < data.Messages.Length; i++) { // Console.WriteLine($"{i}: {data.Messages[i].Key}"); messageIndexes[data.Messages[i].Key] = -(i + 2); } for (int i = 0; i < data.States.Length; i++) { LexerConfig.State state = data.States[i]; itw.WriteLine("#region \"{0}({1})\"", state.Name, i); itw.WriteLine("case {0}:", i); itw.Indent++; itw.WriteLine("switch(input)"); itw.WriteLine("{"); itw.Indent++; foreach (LexerConfig.State.Case scase in state.Cases) { if (scase.Matches.Length == 0) { itw.WriteLine("default:"); } else { foreach (int m in scase.Matches) itw.WriteLine("case {0}:", FancyChar(m)); } bool dead = false; itw.Indent++; foreach (var instruction in scase.Instructions) { switch (instruction.Code) { case LexerConfig.State.Case.Instruction.InstructionCode.And: itw.WriteLine("code &= {0};", instruction.Arguments[0]); break; case LexerConfig.State.Case.Instruction.InstructionCode.Clear: itw.WriteLine("buffer.Clear();"); break; case LexerConfig.State.Case.Instruction.InstructionCode.Code: itw.WriteLine("code = {0};", instruction.Arguments[0]); break; case LexerConfig.State.Case.Instruction.InstructionCode.Die: if (instruction.Arguments.Length == 0) itw.WriteLine("throw new TextDeserializationException({0}(state, input), source, inpos);", data.ExceptionMethod); else if (instruction.Arguments[0] is string) itw.WriteLine("throw new TextDeserializationException({0}(state, {1}), source, inpos);", data.ExceptionMethod, messageIndexes[instruction.Arguments[0].ToString()]); dead = true; break; case LexerConfig.State.Case.Instruction.InstructionCode.FMA: itw.WriteLine("code = code * {0} + {1};", instruction.Arguments[0], instruction.Arguments[1]); break; case LexerConfig.State.Case.Instruction.InstructionCode.FSO: itw.WriteLine("code = (code << {0}) | {1};", instruction.Arguments[0], instruction.Arguments[1]); break; case LexerConfig.State.Case.Instruction.InstructionCode.InCode: itw.WriteLine("code = input;"); break; case LexerConfig.State.Case.Instruction.InstructionCode.InPos: itw.WriteLine("pos = inpos;"); break; case LexerConfig.State.Case.Instruction.InstructionCode.Or: itw.WriteLine("code |= {0};", instruction.Arguments[0]); break; case LexerConfig.State.Case.Instruction.InstructionCode.Push: if (instruction.Arguments[0] is string) { var arg = instruction.Arguments[0].ToString(); itw.WriteLine("buffer.Append({0});", arg.Length == 1 ? FancyChar(arg[0]) : FancyString(arg)); } else itw.WriteLine("buffer.Append((char){0});", instruction.Arguments[0]); break; case LexerConfig.State.Case.Instruction.InstructionCode.PushCode: itw.WriteLine("buffer.Append((char)code);"); break; case LexerConfig.State.Case.Instruction.InstructionCode.PushInput: if (scase.Matches.Length == 1) itw.WriteLine("buffer.Append({0});", FancyChar(scase.Matches[0])); else itw.WriteLine("buffer.Append((char)input);"); break; case LexerConfig.State.Case.Instruction.InstructionCode.State: try { itw.WriteLine("state = {0};", (instruction.Arguments[0] is string) ? stateIndexes[instruction.Arguments[0].ToString()] : instruction.Arguments[0]); } catch (KeyNotFoundException) { throw new Exception(string.Format("Unknown state {0}", instruction.Arguments[0])); } break; case LexerConfig.State.Case.Instruction.InstructionCode.Xor: itw.WriteLine("code ^= {0};", instruction.Arguments[0]); break; case LexerConfig.State.Case.Instruction.InstructionCode.Yield: itw.WriteLine("yield return new Token<{0}>({0}.{1}, buffer.ToString(), pos);", data.Enum, instruction.Arguments[0]); break; case LexerConfig.State.Case.Instruction.InstructionCode.YieldInput: if (scase.Matches.Length == 1) itw.WriteLine("yield return new Token<{0}>({0}.{1}, {2}, inpos);", data.Enum, instruction.Arguments[0], FancyString(scase.Matches[0])); else itw.WriteLine("yield return new Token<{0}>({0}.{1}, ((char)input).ToString(), inpos);", data.Enum, instruction.Arguments[0]); break; case LexerConfig.State.Case.Instruction.InstructionCode.ToLower: itw.WriteLine("code = char.ToLowerInvariant((char)code);"); break; case LexerConfig.State.Case.Instruction.InstructionCode.ToUpper: itw.WriteLine("code = char.ToUpperInvariant((char)code);"); break; case LexerConfig.State.Case.Instruction.InstructionCode.PushState: if (instruction.Arguments == null || instruction.Arguments.Length == 0) itw.WriteLine("stateStack.Push({0});", i); else { try { itw.WriteLine("stateStack.Push({0});", (instruction.Arguments[0] is string) ? stateIndexes[instruction.Arguments[0].ToString()] : instruction.Arguments[0]); } catch (KeyNotFoundException) { throw new Exception(string.Format("Unknown state {0}", instruction.Arguments[0])); } } break; case LexerConfig.State.Case.Instruction.InstructionCode.PopState: itw.WriteLine("state = stateStack.Pop();"); break; case LexerConfig.State.Case.Instruction.InstructionCode.PeekState: itw.WriteLine("state = stateStack.Peek();"); break; case LexerConfig.State.Case.Instruction.InstructionCode.DieIfContains: throw new NotImplementedException("DieIfContains"); //break; case LexerConfig.State.Case.Instruction.InstructionCode.DieIfOtherCharacters: itw.WriteLine("foreach(var bufferChar in buffer.ToString())"); itw.WriteLine("{"); itw.Indent++; itw.WriteLine($"if ({FancyString(instruction.Arguments[0].ToString())}.IndexOf(bufferChar) == -1)"); itw.Indent++; //Console.WriteLine(instruction.Arguments[1].GetType().FullName); itw.WriteLine("throw new TextDeserializationException({0}(state, {1}), source, inpos);", data.ExceptionMethod, messageIndexes[instruction.Arguments[1].ToString()]); itw.Indent--; itw.Indent--; itw.WriteLine("}"); break; } } if (!dead) itw.WriteLine("break;"); itw.Indent--; } itw.Indent--; itw.WriteLine("}"); itw.WriteLine("break;"); itw.Indent--; itw.WriteLine("#endregion"); } itw.WriteLine("default:"); itw.Indent++; itw.WriteLine("throw new TextDeserializationException(string.Format(\"Unknown state number {0}\", state), source, inpos);"); itw.Indent--; itw.Indent--; itw.WriteLine("}"); itw.WriteLine("inpos.Index++;"); itw.WriteLine("inpos.Column++;"); itw.Indent--; itw.WriteLine("}"); itw.WriteLine("while(input != -1);"); itw.Indent--; itw.WriteLine("}"); itw.WriteLine("public static IEnumerable<Token<{0}>> {1}(TextReader source)", data.Enum, data.Method); itw.WriteLine("{"); itw.Indent++; itw.WriteLine("return {0}(source, new TokenPosition(0, 1, 1));", data.Method); itw.Indent--; itw.WriteLine("}"); itw.WriteLine("private static string {0}(int state, int input)", data.ExceptionMethod); itw.WriteLine("{"); itw.Indent++; itw.WriteLine("string[] states = {"); itw.Indent++; for (int i = 0; i < data.States.Length; i++) { itw.Write("\"{0}\"", data.States[i].Name); if (i != data.States.Length - 1) itw.Write(","); itw.WriteLine(); } itw.Indent--; itw.WriteLine("};"); itw.WriteLine("string[] messages = {"); itw.Indent++; for (int i = 0; i < data.States.Length; i++) { itw.Write("\"{0}\"", data.States[i].Name); if (i != data.States.Length - 1) itw.Write(","); itw.WriteLine(); } itw.Indent--; itw.WriteLine("};"); itw.WriteLine("if (input == -1)"); itw.Indent++; itw.WriteLine("return string.Format(\"Unexpected EOF in {0}({1})\", states[state], state);"); itw.Indent--; for(int i=0;i<data.Messages.Length;i++) { var message = data.Messages[i]; itw.WriteLine($"else if (input == {-(i + 2)})"); itw.Indent++; itw.WriteLine("return string.Format(" + FancyString(message.Value) + ", states[state], state);"); itw.Indent--; } itw.WriteLine("else"); itw.WriteLine("{"); itw.Indent++; itw.WriteLine("try"); itw.WriteLine("{"); itw.Indent++; itw.WriteLine("return string.Format(\"Unexpected character {0} ({1}) in {2}({3})\", (char)input, input, states[state], state);"); itw.Indent--; itw.WriteLine("}"); itw.WriteLine("catch(InvalidCastException)"); itw.WriteLine("{"); itw.Indent++; itw.WriteLine("return string.Format(\"Unexpected character {0} in {1}({2})\", input, states[state], state);"); itw.Indent--; itw.WriteLine("}"); itw.Indent--; itw.WriteLine("}"); itw.Indent--; itw.WriteLine("}"); itw.Indent--; itw.WriteLine("}"); itw.Indent--; itw.WriteLine("}"); } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class LegacyLowstockContact : IEquatable<LegacyLowstockContact> { /// <summary> /// Initializes a new instance of the <see cref="LegacyLowstockContact" /> class. /// Initializes a new instance of the <see cref="LegacyLowstockContact" />class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="Id">Id (required).</param> /// <param name="Name">Name (required).</param> /// <param name="CustomFields">CustomFields.</param> public LegacyLowstockContact(int? LobId = null, string Id = null, string Name = null, Dictionary<string, Object> CustomFields = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for LegacyLowstockContact and cannot be null"); } else { this.LobId = LobId; } // to ensure "Id" is required (not null) if (Id == null) { throw new InvalidDataException("Id is a required property for LegacyLowstockContact and cannot be null"); } else { this.Id = Id; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for LegacyLowstockContact and cannot be null"); } else { this.Name = Name; } this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets InternalId /// </summary> [DataMember(Name="internalId", EmitDefaultValue=false)] public int? InternalId { get; private set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { 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 LegacyLowstockContact {\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" InternalId: ").Append(InternalId).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LegacyLowstockContact); } /// <summary> /// Returns true if LegacyLowstockContact instances are equal /// </summary> /// <param name="other">Instance of LegacyLowstockContact to be compared</param> /// <returns>Boolean</returns> public bool Equals(LegacyLowstockContact other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.InternalId == other.InternalId || this.InternalId != null && this.InternalId.Equals(other.InternalId) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.InternalId != null) hash = hash * 59 + this.InternalId.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit 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.IO; using System.Net; #if IGNORE_SSL_ERRORS using System.Net.Security; using System.Security.Cryptography.X509Certificates; #endif using System.Text; using MindTouch.Tasking; using MindTouch.Web; using MindTouch.Xml; namespace MindTouch.Dream.Http { using Yield = IEnumerator<IYield>; internal class HttpPlugEndpoint : IPlugEndpoint { //--- Types --- internal class ActivityState { //--- Fields --- private readonly IDreamActivityDescription _activity; private Queue<string> _messages = new Queue<string>(); private readonly IDreamEnvironment _env; private readonly string _verb; private readonly string _uri; //--- Constructors --- internal ActivityState(IDreamEnvironment env, string verb, string uri) { _env = env; _activity = env.CreateActivityDescription(); _verb = verb; _uri = uri; } //--- Messages --- internal void Message(string message) { lock(this) { if(message != null) { if(_messages != null) { _messages.Enqueue(message); if(_messages.Count > 10) { _messages.Dequeue(); } _activity.Description = string.Format("Outgoing: {0} {1} [{2}]", _verb, _uri, string.Join(" -> ", _messages.ToArray())); } } else { _messages = null; _activity.Dispose(); } } } } //--- Class Fields --- private static readonly log4net.ILog _log = LogUtils.CreateLog(); //--- Class Constructor --- static HttpPlugEndpoint() { #if IGNORE_SSL_ERRORS try { ServicePointManager.ServerCertificateValidationCallback = delegate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }; } catch(Exception e) { _log.Error("class ctor", e); } #endif } //--- Methods --- public int GetScoreWithNormalizedUri(XUri uri, out XUri normalized) { normalized = uri; switch(uri.Scheme.ToLowerInvariant()) { case "http": case "https": return 1; case "ext-http": normalized = normalized.WithScheme("http"); return int.MaxValue; case "ext-https": normalized = normalized.WithScheme("https"); return int.MaxValue; default: return 0; } } public Yield Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) { Result<DreamMessage> res; // register activity DreamContext context = DreamContext.CurrentOrNull; Action<string> activity; if(context != null) { activity = new ActivityState(context.Env, verb, uri.ToString()).Message; } else { activity = delegate { }; } activity("pre Invoke"); yield return res = Coroutine.Invoke(HandleInvoke, activity, plug, verb, uri, request, new Result<DreamMessage>(response.Timeout)).Catch(); activity("post Invoke"); // unregister activity activity(null); // return response response.Return(res); } private Yield HandleInvoke(Action<string> activity, Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response) { Result<IAsyncResult> async; // remove internal headers request.Headers.DreamTransport = null; // set request headers request.Headers.Host = uri.Host; if(request.Headers.UserAgent == null) { request.Headers.UserAgent = "Dream/" + DreamUtil.DreamVersion; } // add cookies to request if(request.HasCookies) { request.Headers[DreamHeaders.COOKIE] = DreamCookie.RenderCookieHeader(request.Cookies); } // initialize request activity("pre WebRequest.Create"); var httpRequest = (HttpWebRequest)WebRequest.Create(uri.ToUri()); activity("post WebRequest.Create"); httpRequest.Method = verb; httpRequest.Timeout = System.Threading.Timeout.Infinite; httpRequest.ReadWriteTimeout = System.Threading.Timeout.Infinite; // Note (arnec): httpRequest AutoRedirect is disabled because Plug is responsible for it (this allows redirects to follow // the appropriate handler instead staying stuck in http end point land httpRequest.AllowAutoRedirect = false; // Note from http://support.microsoft.com/kb/904262 // The HTTP request is made up of the following parts: // 1. Sending the request is covered by using the HttpWebRequest.Timeout method. // 2. Getting the response header is covered by using the HttpWebRequest.Timeout method. // 3. Reading the body of the response is not covered by using the HttpWebResponse.Timeout method. In ASP.NET 1.1 and in later versions, reading the body of the response // is covered by using the HttpWebRequest.ReadWriteTimeout method. The HttpWebRequest.ReadWriteTimeout method is used to handle cases where the response headers are // retrieved in a timely manner but where the reading of the response body times out. httpRequest.KeepAlive = false; httpRequest.ProtocolVersion = HttpVersion.Version10; // TODO (steveb): set default proxy //httpRequest.Proxy = WebProxy.GetDefaultProxy(); //httpRequest.Proxy.Credentials = CredentialCache.DefaultCredentials; // set credentials if(plug.Credentials != null) { httpRequest.Credentials = plug.Credentials; httpRequest.PreAuthenticate = true; } else if(!string.IsNullOrEmpty(uri.User) || !string.IsNullOrEmpty(uri.Password)) { httpRequest.Credentials = new NetworkCredential(uri.User ?? string.Empty, uri.Password ?? string.Empty); httpRequest.PreAuthenticate = true; // Note (arnec): this manually adds the basic auth header, so it can authorize // in a single request without requiring challenge var authbytes = Encoding.ASCII.GetBytes(string.Concat(uri.User ?? string.Empty, ":", uri.Password ?? string.Empty)); var base64 = Convert.ToBase64String(authbytes); httpRequest.Headers.Add(DreamHeaders.AUTHORIZATION, "Basic " + base64); } // add request headres foreach(KeyValuePair<string, string> header in request.Headers) { httpRequest.AddHeader(header.Key, header.Value); } // send message stream if((request.ContentLength != 0) || (verb == Verb.POST)) { async = new Result<IAsyncResult>(); try { activity("pre BeginGetRequestStream"); httpRequest.BeginGetRequestStream(async.Return, null); activity("post BeginGetRequestStream"); } catch(Exception e) { activity("pre HandleResponse 1"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@BeginGetRequestStream", verb, uri.ToString(false)); try { httpRequest.Abort(); } catch { } } yield break; } activity("pre yield BeginGetRequestStream"); yield return async.Catch(); activity("post yield BeginGetRequestStream"); // send request Stream outStream; try { activity("pre EndGetRequestStream"); outStream = httpRequest.EndGetRequestStream(async.Value); activity("pre EndGetRequestStream"); } catch(Exception e) { activity("pre HandleResponse 2"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@EndGetRequestStream", verb, uri.ToString(false)); try { httpRequest.Abort(); } catch { } } yield break; } // copy data //(yurig): HttpWebRequest does some internal memory buffering, therefore copying the data syncronously is acceptable. activity("pre CopyStream"); try { request.ToStream().CopyTo(outStream); activity("post CopyStream"); } catch (Exception e) { activity("post CopyStream"); activity("pre HandleResponse 3"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@AsyncUtil.CopyStream", verb, uri.ToString(false)); try { httpRequest.Abort(); } catch { } } yield break; } finally { outStream.Close(); } } request = null; // wait for response async = new Result<IAsyncResult>(response.Timeout); try { activity("pre BeginGetResponse"); httpRequest.BeginGetResponse(async.Return, null); activity("post BeginGetResponse"); } catch(Exception e) { activity("pre HandleResponse 4"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@BeginGetResponse", verb, uri.ToString(false)); try { httpRequest.Abort(); } catch { } } yield break; } activity("pre yield BeginGetResponse"); yield return async.Catch(); activity("post yield BeginGetResponse"); // check if an error occurred if(async.HasException) { activity("pre HandleResponse 5"); if(!HandleResponse(activity, async.Exception, null, response)) { _log.ErrorExceptionMethodCall(async.Exception, "HandleInvoke@BeginGetResponse", verb, uri.ToString(false)); try { httpRequest.Abort(); } catch { } } yield break; } else { // handle response try { HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(async.Value); activity("pre HandleResponse 6"); if(!HandleResponse(activity, null, httpResponse, response)) { try { httpRequest.Abort(); } catch { } } } catch(Exception e) { activity("pre HandleResponse 7"); if(!HandleResponse(activity, e, null, response)) { _log.ErrorExceptionMethodCall(e, "HandleInvoke@EndGetResponse", verb, uri.ToString(false)); try { httpRequest.Abort(); } catch { } } yield break; } } } private bool HandleResponse(Action<string> activity, Exception exception, HttpWebResponse httpResponse, Result<DreamMessage> response) { if(exception != null) { if(exception is WebException) { activity("pre WebException"); httpResponse = (HttpWebResponse)((WebException)exception).Response; activity("post WebException"); } else { activity("pre HttpWebResponse close"); try { httpResponse.Close(); } catch { } activity("HandleResponse exit 1"); response.Return(new DreamMessage(DreamStatus.UnableToConnect, null, new XException(exception))); return false; } } // check if a response was obtained, otherwise fail if(httpResponse == null) { activity("HandleResponse exit 2"); response.Return(new DreamMessage(DreamStatus.UnableToConnect, null, new XException(exception))); return false; } // determine response type MimeType contentType = string.IsNullOrEmpty(httpResponse.ContentType) ? null : new MimeType(httpResponse.ContentType); Stream stream; HttpStatusCode statusCode = httpResponse.StatusCode; WebHeaderCollection headers = httpResponse.Headers; long contentLength = httpResponse.ContentLength; if(contentType != null || contentLength == -1) { activity("pre new BufferedStream"); stream = new BufferedStream(httpResponse.GetResponseStream()); activity("post new BufferedStream"); } else { // TODO (arnec): If we get a response with a stream, but no content-type, we're currently dropping the stream. Might want to revisit that. _log.DebugFormat("response ({0}) has not content-type and content length of {1}", statusCode, contentLength); contentType = null; stream = Stream.Null; httpResponse.Close(); } // encapsulate the response in a dream message activity("HandleResponse exit 3"); response.Return(new DreamMessage((DreamStatus)(int)statusCode, new DreamHeaders(headers), contentType, contentLength, stream)); return true; } } }
using HarmonyLib; using NUnit.Framework; using System.Linq; using System.Reflection; namespace HarmonyLibTests.Patching { [TestFixture] public class PatchSorting : TestLogger { void Patch1() { } void Patch2() { } void Patch3() { } void Patch4() { } void Patch5() { } void Patch6() { } void Patch7() { } void Patch8() { } void Patch9() { } [Test] public void Test_PatchOrder_SamePriorities() { var patches = new MethodInfo[3]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new string[0], new string[0], false), new Patch(patches[1], 1, "owner B", Priority.Normal, new string[0], new string[0], false), new Patch(patches[2], 2, "owner C", Priority.Normal, new string[0], new string[0], false) }; var expectedOrder = new[] { 0, 1, 2 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } [Test] public void Test_PatchOrder_AllPriorities() { var patches = new MethodInfo[9]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Last, new string[0], new string[0], false), new Patch(patches[1], 1, "owner B", Priority.VeryLow, new string[0], new string[0], false), new Patch(patches[2], 2, "owner C", Priority.Low, new string[0], new string[0], false), new Patch(patches[3], 3, "owner D", Priority.LowerThanNormal, new string[0], new string[0], false), new Patch(patches[4], 4, "owner E", Priority.Normal, new string[0], new string[0], false), new Patch(patches[5], 5, "owner F", Priority.HigherThanNormal, new string[0], new string[0], false), new Patch(patches[6], 6, "owner G", Priority.High, new string[0], new string[0], false), new Patch(patches[7], 7, "owner H", Priority.VeryHigh, new string[0], new string[0], false), new Patch(patches[8], 8, "owner I", Priority.First, new string[0], new string[0], false) }; var expectedOrder = new[] { 8, 7, 6, 5, 4, 3, 2, 1, 0 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } [Test] public void Test_PatchOrder_BeforeAndPriorities() { var patches = new MethodInfo[5]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new string[0], new string[0], false), new Patch(patches[1], 1, "owner A", Priority.Normal, new string[0], new string[0], false), new Patch(patches[2], 2, "owner B", Priority.Normal, new[] {"owner A"}, new string[0], false), new Patch(patches[3], 3, "owner C", Priority.First, new string[0], new string[0], false), new Patch(patches[4], 4, "owner D", Priority.Low, new[] {"owner A"}, new string[0], false) }; var expectedOrder = new[] { 3, 2, 4, 0, 1 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } [Test] public void Test_PatchOrder_AfterAndPriorities() { var patches = new MethodInfo[4]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new string[0], new[] {"owner C"}, false), new Patch(patches[1], 1, "owner B", Priority.Normal, new string[0], new string[0], false), new Patch(patches[2], 2, "owner C", Priority.Normal, new string[0], new string[0], false), new Patch(patches[3], 3, "owner D", Priority.First, new string[0], new[] {"owner C"}, false) }; var expectedOrder = new[] { 1, 2, 3, 0 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } [Test] public void Test_PatchOrder_BeforeAndAfterAndPriorities() { var patches = new MethodInfo[5]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.First, new string[0], new string[0], false), new Patch(patches[1], 1, "owner B", Priority.HigherThanNormal, new string[] { "owner E" }, new string[] { "owner C" }, false), new Patch(patches[2], 2, "owner C", Priority.First, new string[0], new string[0], false), new Patch(patches[3], 3, "owner D", Priority.VeryHigh, new string[] { "owner E" }, new string[] { "owner C" }, false), new Patch(patches[4], 4, "owner E", Priority.First, new string[0], new string[0], false) }; var expectedOrder = new[] { 0, 2, 3, 1, 4 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } [Test] public void Test_PatchOrder_TransitiveBefore() { var patches = new MethodInfo[5]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new string[] { "owner B" }, new string[0], false), new Patch(patches[1], 1, "owner B", Priority.HigherThanNormal, new string[] { "owner C" }, new string[0], false), new Patch(patches[2], 2, "owner C", Priority.High, new string[] { "owner D" }, new string[0], false), new Patch(patches[3], 3, "owner D", Priority.VeryHigh, new string[] { "owner E" }, new string[0], false), new Patch(patches[4], 4, "owner E", Priority.First, new string[0], new string[0], false) }; var expectedOrder = new[] { 0, 1, 2, 3, 4 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } [Test] public void Test_PatchOrder_TransitiveAfter() { var patches = new MethodInfo[5]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.First, new string[0], new string[] { "owner B" }, false), new Patch(patches[1], 1, "owner B", Priority.VeryHigh, new string[0], new string[] { "owner C" }, false), new Patch(patches[2], 2, "owner C", Priority.High, new string[0], new string[] { "owner D" }, false), new Patch(patches[3], 3, "owner D", Priority.HigherThanNormal, new string[0], new string[] { "owner E" }, false), new Patch(patches[4], 4, "owner E", Priority.Normal, new string[0], new string[0], false) }; var expectedOrder = new[] { 4, 3, 2, 1, 0 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } // Test simple cyclic dependency breaking. [Test] public void Test_PatchCycle0() { var patches = new MethodInfo[3]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new string[0], new[] {"owner B"}, false), new Patch(patches[1], 1, "owner B", Priority.Normal, new string[0], new[] {"owner C"}, false), new Patch(patches[2], 2, "owner C", Priority.Normal, new string[0], new[] {"owner A"}, false) }; var expectedOrder = new[] { 2, 1, 0 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } // Test simple cyclic dependency declared in reverse breaking. [Test] public void Test_PatchCycle1() { var patches = new MethodInfo[3]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new[] {"owner C"}, new string[0], false), new Patch(patches[1], 1, "owner B", Priority.Normal, new[] {"owner A"}, new string[0], false), new Patch(patches[2], 2, "owner C", Priority.Normal, new[] {"owner B"}, new string[0], false) }; var expectedOrder = new[] { 2, 1, 0 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } // Test with 2 independent cyclic dependencies. [Test] public void Test_PatchCycle2() { var patches = new MethodInfo[8]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new[] {"owner C"}, new string[0], false), new Patch(patches[1], 1, "owner B", Priority.Normal, new[] {"owner A"}, new string[0], false), new Patch(patches[2], 2, "owner C", Priority.Normal, new[] {"owner B"}, new string[0], false), new Patch(patches[3], 3, "owner D", Priority.Normal, new string[0], new string[0], false), new Patch(patches[4], 4, "owner E", Priority.First, new string[0], new string[0], false), new Patch(patches[5], 5, "owner F", Priority.Low, new string[0], new[] {"owner G"}, false), new Patch(patches[6], 6, "owner G", Priority.Normal, new string[0], new[] {"owner H"}, false), new Patch(patches[7], 7, "owner H", Priority.Normal, new string[0], new[] {"owner F"}, false) }; var expectedOrder = new[] { 4, 3, 5, 7, 6, 2, 1, 0 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } // Test with 2 crossdependant cyclic dependencies. Impossible to break any cycle with just 1 cut. [Test] public void Test_PatchCycle3() { var patches = new MethodInfo[8]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new[] {"owner C"}, new string[0], false), new Patch(patches[1], 1, "owner B", Priority.Normal, new[] {"owner A"}, new string[0], false), new Patch(patches[2], 2, "owner C", Priority.Normal, new[] {"owner B"}, new string[0], false), new Patch(patches[3], 3, "owner D", Priority.Normal, new string[0], new string[0], false), new Patch(patches[4], 4, "owner E", Priority.First, new string[0], new string[0], false), new Patch(patches[5], 5, "owner F", Priority.Low, new []{"owner C", "owner H"}, new[] {"owner G", "owner B"}, false), new Patch(patches[6], 6, "owner G", Priority.Normal, new string[0], new[] {"owner H"}, false), new Patch(patches[7], 7, "owner H", Priority.Normal, new string[0], new[] {"owner F"}, false) }; var expectedOrder = new[] { 4, 3, 5, 7, 6, 2, 1, 0 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } // Test with patches that depend on a missing patch. [Test] public void Test_PatchMissing0() { var patches = new MethodInfo[3]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new[] {"ownerB", "missing 1"}, new[] {"owner C"}, false), new Patch(patches[1], 1, "owner B", Priority.Normal, new string[0], new[] {"missing 2"}, false), new Patch(patches[2], 2, "owner C", Priority.Normal, new string[0], new string[0], false) }; var expectedOrder = new[] { 1, 2, 0 }; var methods = PatchFunctions.GetSortedPatchMethods(null, patchInstances, false); for (var i = 0; i < expectedOrder.Length; i++) Assert.AreSame(patches[expectedOrder[i]], methods[i], $"#{i} Expected: {patches[expectedOrder[i]].FullDescription()}, Got: {methods[i].FullDescription()}"); } // Test that sorter patch array compare detects all possible patch changes. [Test] public void Test_PatchSorterCache0() { var patches = new MethodInfo[4]; for (var i = 0; i < patches.Length; i++) patches[i] = GetType().GetMethod("Patch" + (i + 1), AccessTools.all); var patchInstances = new[] { new Patch(patches[0], 0, "owner A", Priority.Normal, new string[0], new string[0], false), new Patch(patches[1], 1, "owner B", Priority.Normal, new[] {"owner A"}, new[] {"owner C"}, false), new Patch(patches[2], 2, "owner C", Priority.Normal, new string[0], new string[0], false), new Patch(patches[3], 3, "owner D", Priority.Normal, new string[0], new string[0], false) }; var sorter = new PatchSorter(patchInstances, false); Assert.True(sorter.ComparePatchLists(patchInstances), "Same array"); Assert.True(sorter.ComparePatchLists(patchInstances.Reverse().ToArray()), "Patch array reversed"); Assert.False(sorter.ComparePatchLists(patchInstances.Take(2).ToArray()), "Sub-array of the original"); patchInstances[1] = new Patch(patches[1], 1, "owner B", Priority.High, new[] { "owner A" }, new[] { "owner C" }, false); Assert.False(sorter.ComparePatchLists(patchInstances), "Priority of patch changed"); patchInstances[1] = new Patch(patches[1], 2, "owner B", Priority.Normal, new[] { "owner A" }, new[] { "owner C" }, false); Assert.False(sorter.ComparePatchLists(patchInstances), "Index of patch changed"); patchInstances[1] = new Patch(patches[1], 1, "owner D", Priority.Normal, new[] { "owner A" }, new[] { "owner C" }, false); Assert.False(sorter.ComparePatchLists(patchInstances), "Owner of patch changed"); patchInstances[1] = new Patch(patches[1], 1, "owner B", Priority.Normal, new[] { "owner D" }, new[] { "owner C" }, false); Assert.False(sorter.ComparePatchLists(patchInstances), "Before of patch changed"); patchInstances[1] = new Patch(patches[1], 1, "owner B", Priority.Normal, new[] { "owner A" }, new[] { "owner D" }, false); Assert.False(sorter.ComparePatchLists(patchInstances), "After of patch changed"); } } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 2.3.1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IMakeEffectiveApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Make Effective /// </summary> /// <remarks> /// The Make Effective endpoint triggers the service to make a deed effective, dating it with the timestamp of when this call is made. The response includes the Title Number, Property information, Borrower(s) information and deed information, as well as the timestamp that is saved onto the deed. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <returns>OperativeDeed</returns> OperativeDeed DeedDeedReferenceMakeEffectivePost (string deedReference); /// <summary> /// Make Effective /// </summary> /// <remarks> /// The Make Effective endpoint triggers the service to make a deed effective, dating it with the timestamp of when this call is made. The response includes the Title Number, Property information, Borrower(s) information and deed information, as well as the timestamp that is saved onto the deed. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <returns>ApiResponse of OperativeDeed</returns> ApiResponse<OperativeDeed> DeedDeedReferenceMakeEffectivePostWithHttpInfo (string deedReference); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Make Effective /// </summary> /// <remarks> /// The Make Effective endpoint triggers the service to make a deed effective, dating it with the timestamp of when this call is made. The response includes the Title Number, Property information, Borrower(s) information and deed information, as well as the timestamp that is saved onto the deed. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <returns>Task of OperativeDeed</returns> System.Threading.Tasks.Task<OperativeDeed> DeedDeedReferenceMakeEffectivePostAsync (string deedReference); /// <summary> /// Make Effective /// </summary> /// <remarks> /// The Make Effective endpoint triggers the service to make a deed effective, dating it with the timestamp of when this call is made. The response includes the Title Number, Property information, Borrower(s) information and deed information, as well as the timestamp that is saved onto the deed. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <returns>Task of ApiResponse (OperativeDeed)</returns> System.Threading.Tasks.Task<ApiResponse<OperativeDeed>> DeedDeedReferenceMakeEffectivePostAsyncWithHttpInfo (string deedReference); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class MakeEffectiveApi : IMakeEffectiveApi { private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="MakeEffectiveApi"/> class. /// </summary> /// <returns></returns> public MakeEffectiveApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="MakeEffectiveApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public MakeEffectiveApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Swagger.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Make Effective The Make Effective endpoint triggers the service to make a deed effective, dating it with the timestamp of when this call is made. The response includes the Title Number, Property information, Borrower(s) information and deed information, as well as the timestamp that is saved onto the deed. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <returns>OperativeDeed</returns> public OperativeDeed DeedDeedReferenceMakeEffectivePost (string deedReference) { ApiResponse<OperativeDeed> localVarResponse = DeedDeedReferenceMakeEffectivePostWithHttpInfo(deedReference); return localVarResponse.Data; } /// <summary> /// Make Effective The Make Effective endpoint triggers the service to make a deed effective, dating it with the timestamp of when this call is made. The response includes the Title Number, Property information, Borrower(s) information and deed information, as well as the timestamp that is saved onto the deed. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <returns>ApiResponse of OperativeDeed</returns> public ApiResponse< OperativeDeed > DeedDeedReferenceMakeEffectivePostWithHttpInfo (string deedReference) { // verify the required parameter 'deedReference' is set if (deedReference == null) throw new ApiException(400, "Missing required parameter 'deedReference' when calling MakeEffectiveApi->DeedDeedReferenceMakeEffectivePost"); var localVarPath = "/deed/{deed_reference}/make-effective"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (deedReference != null) localVarPathParams.Add("deed_reference", Configuration.ApiClient.ParameterToString(deedReference)); // path parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeedDeedReferenceMakeEffectivePost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OperativeDeed>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OperativeDeed) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperativeDeed))); } /// <summary> /// Make Effective The Make Effective endpoint triggers the service to make a deed effective, dating it with the timestamp of when this call is made. The response includes the Title Number, Property information, Borrower(s) information and deed information, as well as the timestamp that is saved onto the deed. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <returns>Task of OperativeDeed</returns> public async System.Threading.Tasks.Task<OperativeDeed> DeedDeedReferenceMakeEffectivePostAsync (string deedReference) { ApiResponse<OperativeDeed> localVarResponse = await DeedDeedReferenceMakeEffectivePostAsyncWithHttpInfo(deedReference); return localVarResponse.Data; } /// <summary> /// Make Effective The Make Effective endpoint triggers the service to make a deed effective, dating it with the timestamp of when this call is made. The response includes the Title Number, Property information, Borrower(s) information and deed information, as well as the timestamp that is saved onto the deed. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <returns>Task of ApiResponse (OperativeDeed)</returns> public async System.Threading.Tasks.Task<ApiResponse<OperativeDeed>> DeedDeedReferenceMakeEffectivePostAsyncWithHttpInfo (string deedReference) { // verify the required parameter 'deedReference' is set if (deedReference == null) throw new ApiException(400, "Missing required parameter 'deedReference' when calling MakeEffectiveApi->DeedDeedReferenceMakeEffectivePost"); var localVarPath = "/deed/{deed_reference}/make-effective"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (deedReference != null) localVarPathParams.Add("deed_reference", Configuration.ApiClient.ParameterToString(deedReference)); // path parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeedDeedReferenceMakeEffectivePost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OperativeDeed>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OperativeDeed) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperativeDeed))); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookFormatProtectionRequest. /// </summary> public partial class WorkbookFormatProtectionRequest : BaseRequest, IWorkbookFormatProtectionRequest { /// <summary> /// Constructs a new WorkbookFormatProtectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookFormatProtectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookFormatProtection using POST. /// </summary> /// <param name="workbookFormatProtectionToCreate">The WorkbookFormatProtection to create.</param> /// <returns>The created WorkbookFormatProtection.</returns> public System.Threading.Tasks.Task<WorkbookFormatProtection> CreateAsync(WorkbookFormatProtection workbookFormatProtectionToCreate) { return this.CreateAsync(workbookFormatProtectionToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookFormatProtection using POST. /// </summary> /// <param name="workbookFormatProtectionToCreate">The WorkbookFormatProtection to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookFormatProtection.</returns> public async System.Threading.Tasks.Task<WorkbookFormatProtection> CreateAsync(WorkbookFormatProtection workbookFormatProtectionToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookFormatProtection>(workbookFormatProtectionToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookFormatProtection. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookFormatProtection. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookFormatProtection>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookFormatProtection. /// </summary> /// <returns>The WorkbookFormatProtection.</returns> public System.Threading.Tasks.Task<WorkbookFormatProtection> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookFormatProtection. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookFormatProtection.</returns> public async System.Threading.Tasks.Task<WorkbookFormatProtection> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookFormatProtection>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookFormatProtection using PATCH. /// </summary> /// <param name="workbookFormatProtectionToUpdate">The WorkbookFormatProtection to update.</param> /// <returns>The updated WorkbookFormatProtection.</returns> public System.Threading.Tasks.Task<WorkbookFormatProtection> UpdateAsync(WorkbookFormatProtection workbookFormatProtectionToUpdate) { return this.UpdateAsync(workbookFormatProtectionToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookFormatProtection using PATCH. /// </summary> /// <param name="workbookFormatProtectionToUpdate">The WorkbookFormatProtection to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookFormatProtection.</returns> public async System.Threading.Tasks.Task<WorkbookFormatProtection> UpdateAsync(WorkbookFormatProtection workbookFormatProtectionToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookFormatProtection>(workbookFormatProtectionToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFormatProtectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFormatProtectionRequest Expand(Expression<Func<WorkbookFormatProtection, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFormatProtectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFormatProtectionRequest Select(Expression<Func<WorkbookFormatProtection, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookFormatProtectionToInitialize">The <see cref="WorkbookFormatProtection"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookFormatProtection workbookFormatProtectionToInitialize) { } } }
// Copyright 2014 Toni Petrina // // 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.ObjectModel; using System.Linq; using FastSharp.Engine.Core; using FastSharpIDE.Common; using GalaSoft.MvvmLight.Command; using ICSharpCode.AvalonEdit.Document; using System; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; using FastSharp.Engine.Roslyn; namespace FastSharpIDE.ViewModel { public class MainViewModel : ViewModelBase { #region Scripting integration private IScriptingEngine _scriptingEngine; private CancellationTokenSource _cancellationToken; public ObservableCollection<CompilerError> BuildErrors { get; set; } public ConsoleOutStream ConsoleOutput { get; set; } #endregion #region Bindable properties public TextDocument Document { get { return Get<TextDocument>(); } set { Set(value); if (value != null) { var textChanges = Observable.FromEvent<EventHandler, string>( h => { EventHandler handler = (sender, e) => h(value.Text); return handler; }, h => value.TextChanged += h, h => value.TextChanged -= h); value.TextChanged += (sender, args) => BuildErrors.Clear(); // update errors textChanges .Throttle(TimeSpan.FromMilliseconds(250)) .Subscribe(SourceChanged); } } } public string Text { get { return Get<string>(); } set { Set(value); } } public ExecutionResultViewModel ExecutionResult { get { return Get<ExecutionResultViewModel>(); } set { Set(value); } } public StatusViewModel Status { get { return Get<StatusViewModel>(); } set { Set(value); } } public bool IsExecuting { get { return Get<bool>(); } set { Set(value); } } #endregion public RelayCommand<string> ExecuteCommand { get; set; } public RelayCommand CancelExecutionCommand { get; set; } public MainViewModel() { BuildErrors = new ObservableCollection<CompilerError>(); Document = new TextDocument(); ExecuteCommand = new RelayCommand<string>(Execute); CancelExecutionCommand = new RelayCommand(CancelExecution); Console.SetOut(ConsoleOutput = new ConsoleOutStream()); } private void CancelExecution() { if (_cancellationToken != null) _cancellationToken.Cancel(true); } private async void Execute(string code) { await ExecuteInternalAsync(code); } private async Task ExecuteInternalAsync(string code) { if (IsExecuting) return; IsExecuting = true; ExecutionResult = new ExecutionResultViewModel(); try { ConsoleOutput.Output.Clear(); if (string.IsNullOrWhiteSpace(code)) { ExecutionResult = new ExecutionResultViewModel { Message = "Nothing to execute", Type = ExecutionResultType.Warning }; Status.SetReady(); return; } Status.SetInfo("Executing..."); _cancellationToken = new CancellationTokenSource(); var result = await _scriptingEngine.ExecuteAsync(code); if (result.CompilerErrors.Any()) { BuildErrors.Clear(); BuildErrors.AddRange(result.CompilerErrors); Status.SetStatus(result.CompilerErrors.First().Text, StatusType.Error); } else { var message = ConsoleOutput.Output.ToString(); message += result.ReturnValue == null ? "** no results from the execution **" : result.ReturnValue.ToString(); Status.SetInfo("Executed"); ExecutionResult = new ExecutionResultViewModel { Message = message, Type = ExecutionResultType.Success }; } } catch (OperationCanceledException) { _cancellationToken = null; ExecutionResult = new ExecutionResultViewModel { Message = "...", Type = ExecutionResultType.Warning }; Status.SetStatus("Execution stopped", StatusType.Error); } catch (Exception e) { _cancellationToken = null; ExecutionResult = new ExecutionResultViewModel { Message = e.ToString(), Type = ExecutionResultType.Error }; Status.SetStatus("Failed", StatusType.Error); } finally { IsExecuting = false; _cancellationToken = null; } } public void Load() { Status = new StatusViewModel(); _scriptingEngine = new RoslynScriptingEngine(); } private void SourceChanged(string code) { var result = _scriptingEngine.Compile(code); BuildErrors.Clear(); if (result.CompilerErrors.Any()) { BuildErrors.AddRange(result.CompilerErrors); Status.SetStatus(result.CompilerErrors.First().Text, StatusType.Error); } else { Status.SetReady(); } } public void Reset() { _scriptingEngine.Reset(); } } }
/* Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser. This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. 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.Drawing; using System.Xml; using System.Globalization; namespace Trizbort { /// <summary> /// Wrapper around an XmlElement for ease of access. /// </summary> public class XmlElementReader { public XmlElementReader() { } public XmlElementReader(XmlElement element) { Element = element; } public XmlElementReader this[string localName] { get { if (Element != null) { foreach (var node in Element.ChildNodes) { if (!(node is XmlElement)) continue; var element = (XmlElement)node; if (element.LocalName == localName) { return new XmlElementReader(element); } } } return new XmlElementReader(); } } public List<XmlElementReader> Children { get { if (m_children == null) { m_children = new List<XmlElementReader>(); if (Element != null) { foreach (var node in Element.ChildNodes) { if (!(node is XmlElement)) continue; var element = (XmlElement)node; m_children.Add(new XmlElementReader(element)); } } } return m_children; } } public string Name { get { if (Element != null) { return Element.LocalName; } return string.Empty; } } public bool HasName(string value) { return StringComparer.InvariantCultureIgnoreCase.Compare(Name, value) == 0; } public string Text { get { if (Element != null) { return Element.InnerText; } return string.Empty; } } public string ToText(string defaultValue) { var text = Text; if (!string.IsNullOrEmpty(text)) { return text; } return defaultValue; } public int ToInt() { return ToInt(0); } public int ToInt(int defaultValue) { int value; if (int.TryParse(Text, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) { return value; } return defaultValue; } public float ToFloat() { return ToFloat(0); } public float ToFloat(float defaultValue) { float value; if (float.TryParse(Text, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) { return value; } return defaultValue; } public bool ToBool() { return ToBool(false); } public bool ToBool(bool defaultValue) { if (StringComparer.InvariantCultureIgnoreCase.Compare(Text, XmlScribe.Yes) == 0) { return true; } else if (StringComparer.InvariantCultureIgnoreCase.Compare(Text, XmlScribe.No) == 0) { return false; } return defaultValue; } public Color ToColor(Color defaultValue) { try { return ColorTranslator.FromHtml(Text); } catch (Exception) { return defaultValue; } } public CompassPoint ToCompassPoint(CompassPoint defaultValue) { CompassPoint point; if (CompassPointHelper.FromName(Text, out point)) { return point; } return defaultValue; } public XmlAttributeReader Attribute(string localName) { if (Element != null) { foreach (XmlAttribute attribute in Element.Attributes) { if (StringComparer.InvariantCultureIgnoreCase.Compare(attribute.LocalName, localName) == 0) { return new XmlAttributeReader(attribute.Value); } } } return new XmlAttributeReader(string.Empty); } public XmlElement Element { get; private set; } private List<XmlElementReader> m_children; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Newtonsoft.Json.Linq; using ReactNative.Bridge; using ReactNative.Modules.Core; using System; using System.Reactive.Subjects; using System.Threading.Tasks; using Windows.System; using static System.FormattableString; namespace ReactNative.Modules.Launch { /// <summary> /// The module responsible for activating URIs and managing the initial launch URL. /// </summary> public class LauncherModule : ReactContextNativeModuleBase, ILifecycleEventListener { private static readonly object s_lock = new object(); // When using these statics, must hold `s_lock`. private static string s_pendingActivatedUrl; private static LauncherModule s_currentInstance; private readonly Subject<string> _urlSubject = new Subject<string>(); private volatile string _activatedUrl; private bool _initialized; private IDisposable _subscription; /// <summary> /// Instantiates the <see cref="LauncherModule"/>. /// </summary> /// <param name="reactContext">The React context.</param> public LauncherModule(ReactContext reactContext) : base(reactContext) { lock (s_lock) { _activatedUrl = s_pendingActivatedUrl; s_pendingActivatedUrl = null; s_currentInstance = this; } } /// <summary> /// The name of the module. /// </summary> public override string Name { get { return "LinkingManager"; } } /// <summary> /// Opens the given URL. /// </summary> /// <param name="url">The URL.</param> /// <param name="promise"> /// The promise that should be resolved after the URL is opened. /// </param> [ReactMethod] public async void openURL(string url, IPromise promise) { if (url == null) { promise.Reject(new ArgumentNullException(nameof(url))); return; } if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { promise.Reject(new ArgumentException(Invariant($"URL argument '{uri}' is not valid."))); return; } try { await Launcher.LaunchUriAsync(uri).AsTask().ConfigureAwait(false); promise.Resolve(true); } catch (Exception ex) { promise.Reject(new InvalidOperationException( Invariant($"Could not open URL '{url}'."), ex)); } } /// <summary> /// Checks if the application can open the given URL. /// </summary> /// <param name="url">The URL.</param> /// <param name="promise"> /// The promise used to return the result of the check. /// </param> [ReactMethod] public async void canOpenURL(string url, IPromise promise) { if (url == null) { promise.Reject(new ArgumentNullException(nameof(url))); return; } if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { promise.Reject(new ArgumentException(Invariant($"URL argument '{uri}' is not valid."))); return; } try { var support = await Launcher.QueryUriSupportAsync(uri, LaunchQuerySupportType.Uri).AsTask().ConfigureAwait(false); promise.Resolve(support == LaunchQuerySupportStatus.Available); } catch (Exception ex) { promise.Reject(new InvalidOperationException( Invariant($"Could not check if URL '{url}' can be opened."), ex)); } } /// <summary> /// Gets the URL the application was launched with, or <code>null</code> /// if the application was started normally. /// </summary> /// <param name="promise"> /// The promise used to return the initial URL. /// </param> [ReactMethod] public void getInitialURL(IPromise promise) { promise.Resolve(_activatedUrl); } /// <summary> /// Called when the app is initialized. /// </summary> public override void Initialize() { _subscription = CreateUrlSubscription(); _initialized = true; } /// <summary> /// Called when the app is being suspended. /// </summary> public void OnSuspend() { _subscription.Dispose(); } /// <summary> /// Called when the app is resumed. /// </summary> public void OnResume() { // Wait for initialization to subscribe to protect against sending // events to a context that has not been fully initialized. if (_initialized) { _subscription = CreateUrlSubscription(); } } /// <summary> /// Called when the app is destroyed. /// </summary> public void OnDestroy() { } /// <summary> /// Called before a <see cref="IReactInstance"/> is disposed. /// </summary> /// <returns> /// A task to await the dispose operation. /// </returns> public override Task OnReactInstanceDisposeAsync() { lock (s_lock) { if (this == s_currentInstance) { s_currentInstance = null; } } return Task.CompletedTask; } /// <summary> /// Called whenever a protocol activation occurs. /// </summary> /// <param name="url">The URL.</param> public void OnActivated(string url) { _urlSubject.OnNext(url); } /// <summary> /// The initial URL used to activate the application. /// </summary> /// <param name="url">The URL.</param> public static void SetActivatedUrl(string url) { // Static state doesn't work well in RNW modules for scenarios that involve creating multiple instances of a // module during the lifetime of the application. Examples: // 1. An app creates multiple RNW bridges in which case each module will have multiple instances living at // the same time. // 2. An app recreates the RNW context in which case each module will have multiple instances but // their lifetimes won't overlap. // // This method is designed to work for (2). The idea is that `url` is intended for 1 module instance. // If the instance is already around, the activated URL will be given to it. Otherwise, the module // instance will *consume* the activated URL during initialization. Once consumed, the URL won't // be around for other instances to consume during their initialization. // // The right behavior for (1) isn't clear. // // Ideally, the app would pass the activated URL directly to the appropriate instance so RNW doesn't // have to guess which module instance the activated URL was intended for. However, there are some // challenges around the right way to plumb this during initialization and some potential races of // getting this to the right place before JavaScript calls `getInitialURL`. lock (s_lock) { if (s_currentInstance != null) { s_currentInstance._activatedUrl = url; } else { s_pendingActivatedUrl = url; } } } private IDisposable CreateUrlSubscription() { return _urlSubject.Subscribe(url => Context.GetJavaScriptModule<RCTDeviceEventEmitter>() .emit("url", new JObject { { "url", url }, })); } } }
using System; using System.Text; using System.IO; using System.Resources; using System.Reflection; using System.Diagnostics; using System.Threading.Tasks; namespace Signum.Utilities { public static class StreamExtensions { const int BufferSize = 32768; public static byte[] ReadAllBytes(this Stream str) { using (MemoryStream ms = new MemoryStream()) { str.CopyTo(ms); return ms.ToArray(); } } public static async Task<byte[]> ReadAllBytesAsync(this Stream str) { using (MemoryStream ms = new MemoryStream()) { await str.CopyToAsync(ms); return ms.ToArray(); } } public static void WriteAllBytes(this Stream str, byte[] data) { str.Write(data, 0, data.Length); } public static string ReadResourceStream(this Assembly assembly, string name, Encoding? encoding = null) { using (Stream? stream = assembly.GetManifestResourceStream(name)) { if (stream == null) throw new MissingManifestResourceException("{0} not found on {1}".FormatWith(name, assembly)); using (StreamReader reader = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding)) return reader.ReadToEnd(); } } static int BytesToRead = sizeof(Int64); public static bool StreamsAreEqual(Stream first, Stream second) { int iterations = (int)Math.Ceiling((double)first.Length / BytesToRead); byte[] one = new byte[BytesToRead]; byte[] two = new byte[BytesToRead]; for (int i = 0; i < iterations; i++) { first.Read(one, 0, BytesToRead); second.Read(two, 0, BytesToRead); if (BitConverter.ToInt64(one, 0) != BitConverter.ToInt64(two, 0)) return false; } return true; } public static bool FilesAreEqual(FileInfo first, FileInfo second) { if (first.Length != second.Length) return false; using (FileStream s1 = first.OpenRead()) using (FileStream s2 = second.OpenRead()) { return StreamsAreEqual(s1, s2); } } [DebuggerStepThrough] public static R Using<T, R>(this T disposable, Func<T, R> function) where T : IDisposable? { //using (disposable) // return function(disposable); try { return function(disposable); } catch (Exception e) { if (disposable is IDisposableException de) de.OnException(e); throw; } finally { if (disposable != null) disposable.Dispose(); } } [DebuggerStepThrough] public static void EndUsing<T>(this T disposable, Action<T> action) where T : IDisposable? { try { action(disposable); } catch (Exception e) { if (disposable is IDisposableException de) de.OnException(e); throw; } finally { if (disposable != null) disposable.Dispose(); } } } public interface IDisposableException : IDisposable { void OnException(Exception ex); } public class ProgressStream : Stream { readonly Stream InnerStream; public event EventHandler? ProgressChanged; public ProgressStream(Stream innerStream) { this.InnerStream = innerStream; } public double GetProgress() { return ((double)Position) / Length; } public override bool CanRead { get { return InnerStream.CanRead; } } public override bool CanSeek { get { return InnerStream.CanSeek; } } public override bool CanWrite { get { return InnerStream.CanWrite; } } public override void Flush() { InnerStream.Flush(); } public override long Length { get { return InnerStream.Length; } } public override long Position { get { return InnerStream.Position; } set { InnerStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { int result = InnerStream.Read(buffer, offset, count); ProgressChanged?.Invoke(this, EventArgs.Empty); return result; } public override long Seek(long offset, SeekOrigin origin) { return InnerStream.Seek(offset, origin); } public override void SetLength(long value) { InnerStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { InnerStream.Write(buffer, offset, count); ProgressChanged?.Invoke(this, EventArgs.Empty); } public override void Close() { InnerStream.Close(); } } }
// Album.cs // // Authors: // Andrzej Wytyczak-Partyka <iapart@gmail.com> // James Willcox <snorp@snorp.net> // // Copyright (C) 2008 Andrzej Wytyczak-Partyka // Copyright (C) 2005 James Willcox <snorp@snorp.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace DPAP { public delegate void AlbumPhotoHandler (object o, int index, Photo track); public class Album { private static int nextid = 1; private int id; private string name = String.Empty; private List<Photo> photos = new List<Photo> (); private List<int> container_ids = new List<int> (); public event AlbumPhotoHandler PhotoAdded; public event AlbumPhotoHandler PhotoRemoved; public event EventHandler NameChanged; public Photo this [int index] { get { if (photos.Count > index) return photos [index]; else return null; } set { photos [index] = value; } } public IList<Photo> Photos { get { return new ReadOnlyCollection<Photo> (photos); } } internal int Id { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; if (NameChanged != null) NameChanged (this, new EventArgs ()); } } internal Album () { id = nextid++; } public Album (string name) : this () { this.name = name; } public void InsertPhoto (int index, Photo photo) { InsertPhoto (index, photo, photos.Count + 1); } internal void InsertPhoto (int index, Photo photo, int id) { photos.Insert (index, photo); container_ids.Insert (index, id); if (PhotoAdded != null) PhotoAdded (this, index, photo); } public void Clear () { photos.Clear (); } public void AddPhoto (Photo photo) { AddPhoto (photo, photos.Count + 1); } internal void AddPhoto (Photo photo, int id) { photos.Add (photo); container_ids.Add (id); if (PhotoAdded != null) PhotoAdded (this, photos.Count - 1, photo); } public void RemoveAt (int index) { Photo photo = (Photo) photos [index]; photos.RemoveAt (index); container_ids.RemoveAt (index); if (PhotoRemoved != null) PhotoRemoved (this, index, photo); } public bool RemovePhoto (Photo photo) { int index; bool ret = false; while ( (index = IndexOf (photo)) >= 0) { ret = true; RemoveAt (index); } return ret; } public int IndexOf (Photo photo) { return photos.IndexOf (photo); } internal int GetContainerId (int index) { return (int) container_ids [index]; } internal ContentNode ToPhotosNode (string [] fields) { ArrayList photo_nodes = new ArrayList (); for (int i = 0; i < photos.Count; i++) { Photo photo = photos [i] as Photo; photo_nodes.Add (photo.ToAlbumNode (fields)); //photo_nodes.Add (photo.ToAlbumsNode ( (int) container_ids [i])); } /*ArrayList deletedNodes = null; if (deletedIds.Length > 0) { deletedNodes = new ArrayList (); foreach (int id in deletedIds) { deletedNodes.Add (new ContentNode ("dmap.itemid", id)); } } */ ArrayList children = new ArrayList (); children.Add (new ContentNode ("dmap.status", 200)); children.Add (new ContentNode ("dmap.updatetype", (byte) 0)); children.Add (new ContentNode ("dmap.specifiedtotalcount", photos.Count)); children.Add (new ContentNode ("dmap.returnedcount", photos.Count)); children.Add (new ContentNode ("dmap.listing", photo_nodes)); // if (deletedNodes != null) // children.Add (new ContentNode ("dmap.deletedidlisting", deletedNodes)); return new ContentNode ("dpap.playlistsongs", children); } internal ContentNode ToNode (bool baseAlbum) { ArrayList nodes = new ArrayList (); nodes.Add (new ContentNode ("dmap.itemid", id)); nodes.Add (new ContentNode ("dmap.persistentid", (long) id)); nodes.Add (new ContentNode ("dmap.itemname", name)); nodes.Add (new ContentNode ("dmap.itemcount", photos.Count)); if (baseAlbum) nodes.Add (new ContentNode ("dpap.baseplaylist", (byte) 1)); return new ContentNode ("dmap.listingitem", nodes); } internal static Album FromNode (ContentNode node) { Album pl = new Album (); foreach (ContentNode child in (ContentNode []) node.Value) { switch (child.Name) { case "dpap.baseplaylist": return null; case "dmap.itemid": pl.Id = (int) child.Value; break; case "dmap.itemname": pl.Name = (string) child.Value; break; default: break; } } return pl; } internal void Update (Album pl) { if (pl.Name == name) return; Name = pl.Name; } internal int LookupIndexByContainerId (int id) { return container_ids.IndexOf (id); } public int getId () { return Id; } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ namespace Microsoft.Live.Operations { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Threading.Tasks; using Microsoft.Live.Serialization; /// <summary> /// Make a call to the oauth token endpoint using a refresh token and parse /// the response to get the new access token. /// </summary> internal class RefreshTokenOperation : WebOperation { #region Class member variables private const string RefreshTokenPostBodyTemplate = AuthConstants.ClientId + "={0}&" + AuthConstants.RefreshToken + "={1}&" + AuthConstants.Scope + "={2}&" + AuthConstants.GrantType + "=" + AuthConstants.RefreshToken; private const string AuthCodePostBodyTemplate = AuthConstants.ClientId + "={0}&" + AuthConstants.Code + "={1}&" + AuthConstants.Callback + "={2}&" + AuthConstants.GrantType + "=" + AuthConstants.AuthorizationCode; private const string ContentTypeFormEncoded = @"application/x-www-form-urlencoded"; #endregion #region Constructors /// <summary> /// Create a new RefreshTokenOperation object. /// </summary> /// <remarks>This constructor is used when exchanging the refresh token for the access token.</remarks> public RefreshTokenOperation( LiveAuthClient authClient, string clientId, string refreshToken, IEnumerable<string> scopes, SynchronizationContextWrapper syncContext) : base(new Uri(authClient.ConsentEndpoint + LiveAuthClient.TokenEndpoint), null, syncContext) { Debug.Assert(authClient != null, "authClient must not be null."); Debug.Assert(!string.IsNullOrEmpty(clientId)); Debug.Assert(!string.IsNullOrEmpty(refreshToken)); this.AuthClient = authClient; this.Body = String.Format( RefreshTokenOperation.RefreshTokenPostBodyTemplate, HttpUtility.UrlEncode(clientId), refreshToken, HttpUtility.UrlEncode(LiveAuthClient.BuildScopeString(scopes))); } /// <summary> /// Create a new RefreshTokenOperation object. /// </summary> /// <remarks>This constructor is used when exchanging the verification code for the access token.</remarks> public RefreshTokenOperation( LiveAuthClient authClient, string clientId, string verificationCode, string redirectUri, SynchronizationContextWrapper syncContext) : base(new Uri(authClient.ConsentEndpoint + LiveAuthClient.TokenEndpoint), null, syncContext) { Debug.Assert(authClient != null, "authClient must not be null."); Debug.Assert(!string.IsNullOrEmpty(clientId)); Debug.Assert(!string.IsNullOrEmpty(verificationCode)); this.AuthClient = authClient; this.Body = String.Format( RefreshTokenOperation.AuthCodePostBodyTemplate, HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(verificationCode), HttpUtility.UrlEncode(redirectUri)); } #endregion #region Properties /// <summary> /// Gets the LiveAuthClient object. /// </summary> public LiveAuthClient AuthClient { get; private set; } /// <summary> /// Gets and sets the operation completed callback delegate. /// </summary> public Action<LiveLoginResult> OperationCompletedCallback { get; set; } #endregion #region Public methods /// <summary> /// We do not support cancel for refresh token. /// </summary> public override void Cancel() { // no-op // We don't support cancel on auth operations. } /// <summary> /// Uses the Task&lt;T&gt; pattern to return a LiveLoginResult. /// NOTE: This method will overwrite and uses its own OperationCompletedCallback. /// </summary> public Task<LiveLoginResult> ExecuteAsync() { var tcs = new TaskCompletionSource<LiveLoginResult>(); this.OperationCompletedCallback = (LiveLoginResult result) => { if (result.Error != null) { tcs.TrySetException(result.Error); } else { tcs.TrySetResult(result); } }; this.Execute(); return tcs.Task; } #endregion #region Protected methods /// <summary> /// We do not support cancel for refresh token. /// </summary> protected override void OnCancel() { // No-op } /// <summary> /// Overrides the base OnExecute method to make a POST request to the oauth token endpoint. /// </summary> protected override void OnExecute() { this.Request = WebRequestFactory.Current.CreateWebRequest(this.Url, "POST"); this.Request.ContentType = ContentTypeFormEncoded; this.Request.BeginGetRequestStream(this.OnGetRequestStreamCompleted, null); } /// <summary> /// Raises the OperationCompletedCallback. /// </summary> protected void OnOperationCompleted(LiveLoginResult opResult) { Action<LiveLoginResult> callback = this.OperationCompletedCallback; if (callback != null) { callback(opResult); } } /// <summary> /// Process the web response from the server. /// </summary> protected override void OnWebResponseReceived(WebResponse response) { LiveLoginResult result; bool nullResponse = (response == null); try { Stream responseStream = (!nullResponse) ? response.GetResponseStream() : null; if (nullResponse || responseStream == null) { result = new LiveLoginResult( new LiveAuthException(AuthErrorCodes.ClientError, ResourceHelper.GetString("ConnectionError"))); } else { result = this.GenerateLoginResultFrom(responseStream); } } finally { if (!nullResponse) { response.Dispose(); } } this.OnOperationCompleted(result); } #endregion #region Private methods private LiveLoginResult GenerateLoginResultFrom(Stream responseStream) { IDictionary<string, object> jsonObj; try { using (var reader = new StreamReader(responseStream)) { var jsReader = new JsonReader(reader.ReadToEnd()); jsonObj = jsReader.ReadValue() as IDictionary<string, object>; } } catch (FormatException fe) { return new LiveLoginResult( new LiveAuthException(AuthErrorCodes.ServerError, fe.Message)); } if (jsonObj == null) { return new LiveLoginResult( new LiveAuthException(AuthErrorCodes.ServerError, ResourceHelper.GetString("ServerError"))); } if (jsonObj.ContainsKey(AuthConstants.Error)) { var errorCode = jsonObj[AuthConstants.Error] as string; if (errorCode.Equals(AuthErrorCodes.InvalidGrant, StringComparison.Ordinal)) { return new LiveLoginResult(LiveConnectSessionStatus.NotConnected, null); } string errorDescription = string.Empty; if (jsonObj.ContainsKey(AuthConstants.ErrorDescription)) { errorDescription = jsonObj[AuthConstants.ErrorDescription] as string; } return new LiveLoginResult(new LiveAuthException(errorCode, errorDescription)); } LiveConnectSession newSession = LiveAuthClient.CreateSession(this.AuthClient, jsonObj); return new LiveLoginResult(LiveConnectSessionStatus.Connected, newSession); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAdGroupAdServiceClientTest { [Category("Autogenerated")][Test] public void GetAdGroupAdRequestObject() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdRequest request = new GetAdGroupAdRequest { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), }; gagvr::AdGroupAd expectedResponse = new gagvr::AdGroupAd { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), Status = gagve::AdGroupAdStatusEnum.Types.AdGroupAdStatus.Removed, Ad = new gagvr::Ad(), PolicySummary = new gagvr::AdGroupAdPolicySummary(), AdStrength = gagve::AdStrengthEnum.Types.AdStrength.Excellent, AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelsAsAdGroupAdLabelNames = { gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }, ActionItems = { "action_items5599cf0c", }, }; mockGrpcClient.Setup(x => x.GetAdGroupAd(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAd response = client.GetAdGroupAd(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupAdRequestObjectAsync() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdRequest request = new GetAdGroupAdRequest { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), }; gagvr::AdGroupAd expectedResponse = new gagvr::AdGroupAd { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), Status = gagve::AdGroupAdStatusEnum.Types.AdGroupAdStatus.Removed, Ad = new gagvr::Ad(), PolicySummary = new gagvr::AdGroupAdPolicySummary(), AdStrength = gagve::AdStrengthEnum.Types.AdStrength.Excellent, AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelsAsAdGroupAdLabelNames = { gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }, ActionItems = { "action_items5599cf0c", }, }; mockGrpcClient.Setup(x => x.GetAdGroupAdAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAd>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAd responseCallSettings = await client.GetAdGroupAdAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupAd responseCancellationToken = await client.GetAdGroupAdAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupAd() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdRequest request = new GetAdGroupAdRequest { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), }; gagvr::AdGroupAd expectedResponse = new gagvr::AdGroupAd { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), Status = gagve::AdGroupAdStatusEnum.Types.AdGroupAdStatus.Removed, Ad = new gagvr::Ad(), PolicySummary = new gagvr::AdGroupAdPolicySummary(), AdStrength = gagve::AdStrengthEnum.Types.AdStrength.Excellent, AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelsAsAdGroupAdLabelNames = { gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }, ActionItems = { "action_items5599cf0c", }, }; mockGrpcClient.Setup(x => x.GetAdGroupAd(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAd response = client.GetAdGroupAd(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupAdAsync() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdRequest request = new GetAdGroupAdRequest { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), }; gagvr::AdGroupAd expectedResponse = new gagvr::AdGroupAd { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), Status = gagve::AdGroupAdStatusEnum.Types.AdGroupAdStatus.Removed, Ad = new gagvr::Ad(), PolicySummary = new gagvr::AdGroupAdPolicySummary(), AdStrength = gagve::AdStrengthEnum.Types.AdStrength.Excellent, AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelsAsAdGroupAdLabelNames = { gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }, ActionItems = { "action_items5599cf0c", }, }; mockGrpcClient.Setup(x => x.GetAdGroupAdAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAd>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAd responseCallSettings = await client.GetAdGroupAdAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupAd responseCancellationToken = await client.GetAdGroupAdAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupAdResourceNames() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdRequest request = new GetAdGroupAdRequest { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), }; gagvr::AdGroupAd expectedResponse = new gagvr::AdGroupAd { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), Status = gagve::AdGroupAdStatusEnum.Types.AdGroupAdStatus.Removed, Ad = new gagvr::Ad(), PolicySummary = new gagvr::AdGroupAdPolicySummary(), AdStrength = gagve::AdStrengthEnum.Types.AdStrength.Excellent, AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelsAsAdGroupAdLabelNames = { gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }, ActionItems = { "action_items5599cf0c", }, }; mockGrpcClient.Setup(x => x.GetAdGroupAd(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAd response = client.GetAdGroupAd(request.ResourceNameAsAdGroupAdName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupAdResourceNamesAsync() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdRequest request = new GetAdGroupAdRequest { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), }; gagvr::AdGroupAd expectedResponse = new gagvr::AdGroupAd { ResourceNameAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), Status = gagve::AdGroupAdStatusEnum.Types.AdGroupAdStatus.Removed, Ad = new gagvr::Ad(), PolicySummary = new gagvr::AdGroupAdPolicySummary(), AdStrength = gagve::AdStrengthEnum.Types.AdStrength.Excellent, AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelsAsAdGroupAdLabelNames = { gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }, ActionItems = { "action_items5599cf0c", }, }; mockGrpcClient.Setup(x => x.GetAdGroupAdAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAd>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAd responseCallSettings = await client.GetAdGroupAdAsync(request.ResourceNameAsAdGroupAdName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupAd responseCancellationToken = await client.GetAdGroupAdAsync(request.ResourceNameAsAdGroupAdName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupAdsRequestObject() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); MutateAdGroupAdsRequest request = new MutateAdGroupAdsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupAdOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateAdGroupAdsResponse expectedResponse = new MutateAdGroupAdsResponse { Results = { new MutateAdGroupAdResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupAds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupAdsResponse response = client.MutateAdGroupAds(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupAdsRequestObjectAsync() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); MutateAdGroupAdsRequest request = new MutateAdGroupAdsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupAdOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateAdGroupAdsResponse expectedResponse = new MutateAdGroupAdsResponse { Results = { new MutateAdGroupAdResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupAdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupAdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupAdsResponse responseCallSettings = await client.MutateAdGroupAdsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupAdsResponse responseCancellationToken = await client.MutateAdGroupAdsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupAds() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); MutateAdGroupAdsRequest request = new MutateAdGroupAdsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupAdOperation(), }, }; MutateAdGroupAdsResponse expectedResponse = new MutateAdGroupAdsResponse { Results = { new MutateAdGroupAdResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupAds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupAdsResponse response = client.MutateAdGroupAds(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupAdsAsync() { moq::Mock<AdGroupAdService.AdGroupAdServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdService.AdGroupAdServiceClient>(moq::MockBehavior.Strict); MutateAdGroupAdsRequest request = new MutateAdGroupAdsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupAdOperation(), }, }; MutateAdGroupAdsResponse expectedResponse = new MutateAdGroupAdsResponse { Results = { new MutateAdGroupAdResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupAdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupAdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdServiceClient client = new AdGroupAdServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupAdsResponse responseCallSettings = await client.MutateAdGroupAdsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupAdsResponse responseCancellationToken = await client.MutateAdGroupAdsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Xunit; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; using Microsoft.VisualStudio.Services.Agent.Worker; using Microsoft.VisualStudio.Services.Agent.Util; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker { public sealed class ExecutionContextL0 { [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void InitializeJob_LogsWarningsFromVariables() { using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); environment.Variables["v1"] = "v1-$(v2)"; environment.Variables["v2"] = "v2-$(v1)"; List<TaskInstance> tasks = new List<TaskInstance>(); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks)); // Arrange: Setup the paging logger. var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); ec.Initialize(hc); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); // Assert. pagingLogger.Verify(x => x.Write(It.Is<string>(y => y.IndexOf("##[warning]") >= 0)), Times.Exactly(2)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void AddIssue_CountWarningsErrors() { using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<TaskInstance> tasks = new List<TaskInstance>(); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks)); // Arrange: Setup the paging logger. var pagingLogger = new Mock<IPagingLogger>(); var jobServerQueue = new Mock<IJobServerQueue>(); jobServerQueue.Setup(x => x.QueueTimelineRecordUpdate(It.IsAny<Guid>(), It.IsAny<TimelineRecord>())); hc.EnqueueInstance(pagingLogger.Object); hc.SetSingleton(jobServerQueue.Object); ec.Initialize(hc); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Error, Message = "error" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.AddIssue(new Issue() { Type = IssueType.Warning, Message = "warning" }); ec.Complete(); // Assert. jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny<Guid>(), It.Is<TimelineRecord>(t => t.ErrorCount == 15)), Times.AtLeastOnce); jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny<Guid>(), It.Is<TimelineRecord>(t => t.WarningCount == 14)), Times.AtLeastOnce); jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny<Guid>(), It.Is<TimelineRecord>(t => t.Issues.Where(i => i.Type == IssueType.Error).Count() == 10)), Times.AtLeastOnce); jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny<Guid>(), It.Is<TimelineRecord>(t => t.Issues.Where(i => i.Type == IssueType.Warning).Count() == 10)), Times.AtLeastOnce); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void StepTarget_VerifySet() { using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { ec.Initialize(hc); var pipeContainer = new Pipelines.ContainerResource { Alias = "container" }; pipeContainer.Properties.Set<string>("image", "someimage"); // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<Pipelines.JobStep> steps = new List<Pipelines.JobStep>(); steps.Add(new Pipelines.TaskStep { Target = new Pipelines.StepTarget { Target = "container" }, Reference = new Pipelines.TaskStepDefinitionReference() }); var resources = new Pipelines.JobResources(); resources.Containers.Add(pipeContainer); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, null, new Dictionary<string, string>(), new Dictionary<string, VariableValue>(), new List<MaskHint>(), resources, new Pipelines.WorkspaceOptions(), steps); // Arrange var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); ec.SetStepTarget(steps[0].Target); // Assert. Assert.IsType<ContainerInfo>(ec.StepTarget()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void StepTarget_RestrictedCommands_Host() { using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { ec.Initialize(hc); var pipeContainer = new Pipelines.ContainerResource { Alias = "container" }; pipeContainer.Properties.Set<string>("image", "someimage"); // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<Pipelines.JobStep> steps = new List<Pipelines.JobStep>(); steps.Add(new Pipelines.TaskStep { Target = new Pipelines.StepTarget { Target = "host", Commands = "restricted" }, Reference = new Pipelines.TaskStepDefinitionReference() }); var resources = new Pipelines.JobResources(); resources.Containers.Add(pipeContainer); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, null, new Dictionary<string, string>(), new Dictionary<string, VariableValue>(), new List<MaskHint>(), resources, new Pipelines.WorkspaceOptions(), steps); // Arrange var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); ec.SetStepTarget(steps[0].Target); // Assert. Assert.IsType<HostInfo>(ec.StepTarget()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void StepTarget_LoadStepContainersWithoutJobContainer() { using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { ec.Initialize(hc); var pipeContainer = new Pipelines.ContainerResource { Alias = "container" }; pipeContainer.Properties.Set<string>("image", "someimage"); // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<Pipelines.JobStep> steps = new List<Pipelines.JobStep>(); steps.Add(new Pipelines.TaskStep { Target = new Pipelines.StepTarget { Target = "container" }, Reference = new Pipelines.TaskStepDefinitionReference() }); var resources = new Pipelines.JobResources(); resources.Containers.Add(pipeContainer); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, null, new Dictionary<string, string>(), new Dictionary<string, VariableValue>(), new List<MaskHint>(), resources, new Pipelines.WorkspaceOptions(), steps); // Arrange: Setup command manager var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); // Assert. Assert.Equal(1, ec.Containers.Count()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void SidecarContainers_VerifyNotJobContainers() { using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { ec.Initialize(hc); var pipeContainer = new Pipelines.ContainerResource { Alias = "container" }; var pipeContainerSidecar = new Pipelines.ContainerResource { Alias = "sidecar" }; var pipeContainerExtra = new Pipelines.ContainerResource { Alias = "extra" }; pipeContainer.Properties.Set<string>("image", "someimage"); pipeContainerSidecar.Properties.Set<string>("image", "someimage"); pipeContainerExtra.Properties.Set<string>("image", "someimage"); // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<Pipelines.JobStep> steps = new List<Pipelines.JobStep>(); steps.Add(new Pipelines.TaskStep { Reference = new Pipelines.TaskStepDefinitionReference() }); var resources = new Pipelines.JobResources(); resources.Containers.Add(pipeContainer); resources.Containers.Add(pipeContainerSidecar); resources.Containers.Add(pipeContainerExtra); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var sidecarContainers = new Dictionary<string, string>(); sidecarContainers.Add("sidecar", "sidecar"); var jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, null, sidecarContainers, new Dictionary<string, VariableValue>(), new List<MaskHint>(), resources, new Pipelines.WorkspaceOptions(), steps); // Arrange: Setup command manager var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); // Assert. Assert.Equal(2, ec.Containers.Count()); Assert.Equal(1, ec.SidecarContainers.Count()); Assert.False(ec.SidecarContainers.First().IsJobContainer); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void InitializeJob_should_set_JobSettings() { using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<TaskInstance> tasks = new List<TaskInstance>(); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks)); // Arrange: Setup the paging logger. var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); ec.Initialize(hc); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); // Assert. Assert.NotNull(ec.JobSettings); Assert.Equal(Boolean.FalseString, ec.JobSettings[WellKnownJobSettings.HasMultipleCheckouts]); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void InitializeJob_should_set_JobSettings_multicheckout() { using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<TaskInstance> tasks = new List<TaskInstance>(); tasks.Add(new TaskInstance() { Id = Pipelines.PipelineConstants.CheckoutTask.Id, Version = Pipelines.PipelineConstants.CheckoutTask.Version }); tasks.Add(new TaskInstance() { Id = Pipelines.PipelineConstants.CheckoutTask.Id, Version = Pipelines.PipelineConstants.CheckoutTask.Version }); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks)); // Arrange: Setup the paging logger. var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); ec.Initialize(hc); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); // Assert. Assert.NotNull(ec.JobSettings); Assert.Equal(Boolean.TrueString, ec.JobSettings[WellKnownJobSettings.HasMultipleCheckouts]); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void InitializeJob_should_mark_primary_repository() { // Note: the primary repository is defined as the first repository that is checked out in the job using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<TaskInstance> tasks = new List<TaskInstance>(); tasks.Add(new TaskInstance() { Id = Pipelines.PipelineConstants.CheckoutTask.Id, Version = Pipelines.PipelineConstants.CheckoutTask.Version, Inputs = { { Pipelines.PipelineConstants.CheckoutTaskInputs.Repository, "repo1" } } }); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks)); var repo1 = new Pipelines.RepositoryResource() { Alias = "repo1" }; jobRequest.Resources.Repositories.Add(repo1); // Arrange: Setup the paging logger. var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); ec.Initialize(hc); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); // Assert. Assert.NotNull(ec.JobSettings); Assert.Equal(Boolean.FalseString, ec.JobSettings[WellKnownJobSettings.HasMultipleCheckouts]); Assert.Equal("repo1", ec.JobSettings[WellKnownJobSettings.FirstRepositoryCheckedOut]); Assert.Equal(Boolean.TrueString, repo1.Properties.Get<string>(RepositoryUtil.IsPrimaryRepository)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void InitializeJob_should_mark_primary_repository_in_multicheckout() { // Note: the primary repository is defined as the first repository that is checked out in the job using (TestHostContext hc = CreateTestContext()) using (var ec = new Agent.Worker.ExecutionContext()) { // Arrange: Create a job request message. TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); List<TaskInstance> tasks = new List<TaskInstance>(); tasks.Add(new TaskInstance() { Id = Pipelines.PipelineConstants.CheckoutTask.Id, Version = Pipelines.PipelineConstants.CheckoutTask.Version, Inputs = { { Pipelines.PipelineConstants.CheckoutTaskInputs.Repository, "repo2" } } }); tasks.Add(new TaskInstance() { Id = Pipelines.PipelineConstants.CheckoutTask.Id, Version = Pipelines.PipelineConstants.CheckoutTask.Version, Inputs = { { Pipelines.PipelineConstants.CheckoutTaskInputs.Repository, "repo3" } } }); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; var jobRequest = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks)); var repo1 = new Pipelines.RepositoryResource() { Alias = "self" }; var repo2 = new Pipelines.RepositoryResource() { Alias = "repo2" }; var repo3 = new Pipelines.RepositoryResource() { Alias = "repo3" }; jobRequest.Resources.Repositories.Add(repo1); jobRequest.Resources.Repositories.Add(repo2); jobRequest.Resources.Repositories.Add(repo3); // Arrange: Setup the paging logger. var pagingLogger = new Mock<IPagingLogger>(); hc.EnqueueInstance(pagingLogger.Object); ec.Initialize(hc); // Act. ec.InitializeJob(jobRequest, CancellationToken.None); // Assert. Assert.NotNull(ec.JobSettings); Assert.Equal(Boolean.TrueString, ec.JobSettings[WellKnownJobSettings.HasMultipleCheckouts]); Assert.Equal("repo2", ec.JobSettings[WellKnownJobSettings.FirstRepositoryCheckedOut]); Assert.Equal(Boolean.FalseString, repo1.Properties.Get<string>(RepositoryUtil.IsPrimaryRepository, Boolean.FalseString)); Assert.Equal(Boolean.TrueString, repo2.Properties.Get<string>(RepositoryUtil.IsPrimaryRepository, Boolean.FalseString)); Assert.Equal(Boolean.FalseString, repo3.Properties.Get<string>(RepositoryUtil.IsPrimaryRepository, Boolean.FalseString)); } } private TestHostContext CreateTestContext([CallerMemberName] String testName = "") { var hc = new TestHostContext(this, testName); // Arrange: Setup the configation store. var configurationStore = new Mock<IConfigurationStore>(); configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings()); hc.SetSingleton(configurationStore.Object); // Arrange: Setup the proxy configation. var proxy = new Mock<IVstsAgentWebProxy>(); hc.SetSingleton(proxy.Object); // Arrange: Setup the cert configation. var cert = new Mock<IAgentCertificateManager>(); hc.SetSingleton(cert.Object); // Arrange: Create the execution context. hc.SetSingleton(new Mock<IJobServerQueue>().Object); return hc; } private JobRequestMessage CreateJobRequestMessage() { TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new TimelineReference(); JobEnvironment environment = new JobEnvironment(); environment.SystemConnection = new ServiceEndpoint(); environment.Variables["v1"] = "v1"; List<TaskInstance> tasks = new List<TaskInstance>(); Guid JobId = Guid.NewGuid(); string jobName = "some job name"; return new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks); } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS; namespace LoadMapControl { public class frmMain : System.Windows.Forms.Form { public System.Windows.Forms.TextBox txtPath; private System.Windows.Forms.Button cmdLoadDoc; private System.Windows.Forms.OpenFileDialog openFileDialog1; private ESRI.ArcGIS.Controls.AxPageLayoutControl axPageLayoutControl1; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; public System.ComponentModel.Container components = null; public frmMain() { InitializeComponent(); } protected override void Dispose( bool disposing ) { ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain)); this.txtPath = new System.Windows.Forms.TextBox(); this.cmdLoadDoc = new System.Windows.Forms.Button(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.axPageLayoutControl1 = new ESRI.ArcGIS.Controls.AxPageLayoutControl(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); ((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.SuspendLayout(); // // txtPath // this.txtPath.Enabled = false; this.txtPath.Location = new System.Drawing.Point(8, 40); this.txtPath.Name = "txtPath"; this.txtPath.Size = new System.Drawing.Size(352, 20); this.txtPath.TabIndex = 1; // // cmdLoadDoc // this.cmdLoadDoc.Location = new System.Drawing.Point(232, 8); this.cmdLoadDoc.Name = "cmdLoadDoc"; this.cmdLoadDoc.Size = new System.Drawing.Size(128, 24); this.cmdLoadDoc.TabIndex = 2; this.cmdLoadDoc.Text = "Load Map Document"; this.cmdLoadDoc.Click += new System.EventHandler(this.cmdLoadDoc_Click); // // axPageLayoutControl1 // this.axPageLayoutControl1.Location = new System.Drawing.Point(8, 64); this.axPageLayoutControl1.Name = "axPageLayoutControl1"; this.axPageLayoutControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axPageLayoutControl1.OcxState"))); this.axPageLayoutControl1.Size = new System.Drawing.Size(352, 368); this.axPageLayoutControl1.TabIndex = 3; // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(8, 2); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(32, 32); this.axLicenseControl1.TabIndex = 4; // // frmMain // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(368, 438); this.Controls.Add(this.axLicenseControl1); this.Controls.Add(this.axPageLayoutControl1); this.Controls.Add(this.cmdLoadDoc); this.Controls.Add(this.txtPath); this.Name = "frmMain"; this.Text = "Load Map Document"; ((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (!RuntimeManager.Bind(ProductCode.Engine)) { if (!RuntimeManager.Bind(ProductCode.Desktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run( new frmMain()); } private void cmdLoadDoc_Click(object sender, System.EventArgs e) { //Open a file dialog for selecting map documents openFileDialog1.Title = "Browse Map Document"; openFileDialog1.Filter = "Map Documents (*.mxd, *.mxt, *.pmf)|*.pmf; *.mxt; *.mxd"; openFileDialog1.ShowDialog(); //Exit if no map document is selected string sFilePath = openFileDialog1.FileName; if (sFilePath == "") return; bool bPass, bIsMapDoc; IMapDocument ipMapDoc; ipMapDoc = new MapDocumentClass(); //Check if the map document is password protected bPass = ipMapDoc.get_IsPasswordProtected(sFilePath); if(bPass) { //Disable the main form this.Enabled = false; //Show the password dialog frmPassword Form2 = new frmPassword(); Form2.ShowDialog (this); int check = Form2.Check; //OK button pressed if (check == 1) { try { //Set a waiting cursor Cursor.Current = Cursors.WaitCursor; //Load the password protected map axPageLayoutControl1.LoadMxFile(sFilePath, Form2.Password); txtPath.Text = sFilePath; this.Enabled = true; //Set a default cursor Cursor.Current = Cursors.Default; } catch { this.Enabled = true; MessageBox.Show("The Password was incorrect!"); } } else { this.Enabled = true; } } else { //Check whether the file is a map document bIsMapDoc = axPageLayoutControl1.CheckMxFile(sFilePath); if(bIsMapDoc) { Cursor.Current = Cursors.WaitCursor; //Load the Mx document axPageLayoutControl1.LoadMxFile(sFilePath, Type.Missing); txtPath.Text = sFilePath; //Set a default cursor Cursor.Current = Cursors.Default; } else { MessageBox.Show(sFilePath + " is not a valid ArcMap document"); sFilePath = ""; } } } } }
// 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.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using 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> /// NetworkSecurityGroupsOperations operations. /// </summary> internal partial class NetworkSecurityGroupsOperations : IServiceOperations<NetworkManagementClient>, INetworkSecurityGroupsOperations { /// <summary> /// Initializes a new instance of the NetworkSecurityGroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NetworkSecurityGroupsOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </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<NetworkSecurityGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // 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("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", 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.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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 (Newtonsoft.Json.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<NetworkSecurityGroup>(); _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<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Creates or updates a network security group in the specified resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network security group /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<NetworkSecurityGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<NetworkSecurityGroup> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all network security groups in a subscription. /// </summary> /// <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<NetworkSecurityGroup>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/networkSecurityGroups").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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 (Newtonsoft.Json.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<NetworkSecurityGroup>>(); _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<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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 network security groups in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </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<NetworkSecurityGroup>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // 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("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", 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.Network/networkSecurityGroups").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 (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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 (Newtonsoft.Json.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<NetworkSecurityGroup>>(); _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<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Deletes the specified network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </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="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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // 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("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", 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.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _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 != 202 && (int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } 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(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a network security group in the specified resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network security group /// 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<NetworkSecurityGroup>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // 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("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", 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.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _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; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (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 != 201 && (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 (Newtonsoft.Json.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<NetworkSecurityGroup>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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 network security groups in a subscription. /// </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<NetworkSecurityGroup>>> ListAllNextWithHttpMessagesAsync(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, "ListAllNext", 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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 (Newtonsoft.Json.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<NetworkSecurityGroup>>(); _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<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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 network security groups in 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<NetworkSecurityGroup>>> ListNextWithHttpMessagesAsync(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, "ListNext", 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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 (Newtonsoft.Json.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<NetworkSecurityGroup>>(); _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<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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; } } }
/* * 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 Mono.Data.SqliteClient; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace OpenSim.Region.UserStatistics { public struct stats_default_page_values { public Scene[] all_scenes; public float avg_client_fps; public float avg_client_mem_use; public float avg_client_resends; public float avg_ping; public float avg_sim_fps; public Dictionary<UUID, USimStatsData> sim_stat_data; public Dictionary<string, IStatsController> stats_reports; public float total_kb_in; public float total_kb_out; public int total_num_sessions; public int total_num_users; } public class Default_Report : IStatsController { public string ReportName { get { return "Home"; } } #region IStatsController Members public Hashtable ProcessModel(Hashtable pParams) { SqliteConnection conn = (SqliteConnection)pParams["DatabaseConnection"]; List<Scene> m_scene = (List<Scene>)pParams["Scenes"]; stats_default_page_values mData = rep_DefaultReport_data(conn, m_scene); mData.sim_stat_data = (Dictionary<UUID, USimStatsData>)pParams["SimStats"]; mData.stats_reports = (Dictionary<string, IStatsController>)pParams["Reports"]; Hashtable nh = new Hashtable(); nh.Add("hdata", mData); nh.Add("Reports", pParams["Reports"]); return nh; } public string RenderView(Hashtable pModelResult) { stats_default_page_values mData = (stats_default_page_values)pModelResult["hdata"]; return rep_Default_report_view(mData); } #endregion IStatsController Members /// <summary> /// Return summar information in the form: /// <pre> /// {"totalUsers": "34", /// "totalSessions": "233", /// ... /// } /// </pre> /// </summary> /// <param name="pModelResult"></param> /// <returns></returns> public string RenderJson(Hashtable pModelResult) { stats_default_page_values values = (stats_default_page_values)pModelResult["hdata"]; OSDMap summaryInfo = new OSDMap(); summaryInfo.Add("totalUsers", new OSDString(values.total_num_users.ToString())); summaryInfo.Add("totalSessions", new OSDString(values.total_num_sessions.ToString())); summaryInfo.Add("averageClientFPS", new OSDString(values.avg_client_fps.ToString())); summaryInfo.Add("averageClientMem", new OSDString(values.avg_client_mem_use.ToString())); summaryInfo.Add("averageSimFPS", new OSDString(values.avg_sim_fps.ToString())); summaryInfo.Add("averagePingTime", new OSDString(values.avg_ping.ToString())); summaryInfo.Add("totalKBOut", new OSDString(values.total_kb_out.ToString())); summaryInfo.Add("totalKBIn", new OSDString(values.total_kb_in.ToString())); return summaryInfo.ToString(); } public string rep_Default_report_view(stats_default_page_values values) { StringBuilder output = new StringBuilder(); const string TableClass = "defaultr"; const string TRClass = "defaultr"; const string TDHeaderClass = "header"; const string TDDataClass = "content"; //const string TDDataClassRight = "contentright"; const string TDDataClassCenter = "contentcenter"; const string STYLESHEET = @" <STYLE> body { font-size:15px; font-family:Helvetica, Verdana; color:Black; } TABLE.defaultr { } TR.defaultr { padding: 5px; } TD.header { font-weight:bold; padding:5px; } TD.content {} TD.contentright { text-align: right; } TD.contentcenter { text-align: center; } TD.align_top { vertical-align: top; } </STYLE> "; HTMLUtil.HtmlHeaders_O(ref output); HTMLUtil.InsertProtoTypeAJAX(ref output); string[] ajaxUpdaterDivs = new string[3]; int[] ajaxUpdaterSeconds = new int[3]; string[] ajaxUpdaterReportFragments = new string[3]; ajaxUpdaterDivs[0] = "activeconnections"; ajaxUpdaterSeconds[0] = 10; ajaxUpdaterReportFragments[0] = "activeconnectionsajax.html"; ajaxUpdaterDivs[1] = "activesimstats"; ajaxUpdaterSeconds[1] = 20; ajaxUpdaterReportFragments[1] = "simstatsajax.html"; ajaxUpdaterDivs[2] = "activelog"; ajaxUpdaterSeconds[2] = 5; ajaxUpdaterReportFragments[2] = "activelogajax.html"; HTMLUtil.InsertPeriodicUpdaters(ref output, ajaxUpdaterDivs, ajaxUpdaterSeconds, ajaxUpdaterReportFragments); output.Append(STYLESHEET); HTMLUtil.HtmlHeaders_C(ref output); HTMLUtil.AddReportLinks(ref output, values.stats_reports, ""); HTMLUtil.TABLE_O(ref output, TableClass); HTMLUtil.TR_O(ref output, TRClass); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("# Users Total"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("# Sessions Total"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Avg Client FPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Avg Client Mem Use"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Avg Sim FPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Avg Ping"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("KB Out Total"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("KB In Total"); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TR_O(ref output, TRClass); HTMLUtil.TD_O(ref output, TDDataClass); output.Append(values.total_num_users); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClass); output.Append(values.total_num_sessions); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.avg_client_fps); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.avg_client_mem_use); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.avg_sim_fps); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.avg_ping); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.total_kb_out); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(values.total_kb_in); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TABLE_C(ref output); HTMLUtil.HR(ref output, ""); HTMLUtil.TABLE_O(ref output, ""); HTMLUtil.TR_O(ref output, ""); HTMLUtil.TD_O(ref output, "align_top"); output.Append("<DIV id=\"activeconnections\">Active Connections loading...</DIV>"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, "align_top"); output.Append("<DIV id=\"activesimstats\">SimStats loading...</DIV>"); output.Append("<DIV id=\"activelog\">ActiveLog loading...</DIV>"); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TABLE_C(ref output); output.Append("</BODY></HTML>"); // TODO: FIXME: template return output.ToString(); } public stats_default_page_values rep_DefaultReport_data(SqliteConnection db, List<Scene> m_scene) { stats_default_page_values returnstruct = new stats_default_page_values(); returnstruct.all_scenes = m_scene.ToArray(); lock (db) { string SQL = @"SELECT COUNT(DISTINCT agent_id) as agents, COUNT(*) as sessions, AVG(avg_fps) as client_fps, AVG(avg_sim_fps) as savg_sim_fps, AVG(avg_ping) as sav_ping, SUM(n_out_kb) as num_in_kb, SUM(n_out_pk) as num_in_packets, SUM(n_in_kb) as num_out_kb, SUM(n_in_pk) as num_out_packets, AVG(mem_use) as sav_mem_use FROM stats_session_data;"; SqliteCommand cmd = new SqliteCommand(SQL, db); SqliteDataReader sdr = cmd.ExecuteReader(); if (sdr.HasRows) { sdr.Read(); returnstruct.total_num_users = Convert.ToInt32(sdr["agents"]); returnstruct.total_num_sessions = Convert.ToInt32(sdr["sessions"]); returnstruct.avg_client_fps = Convert.ToSingle(sdr["client_fps"]); returnstruct.avg_sim_fps = Convert.ToSingle(sdr["savg_sim_fps"]); returnstruct.avg_ping = Convert.ToSingle(sdr["sav_ping"]); returnstruct.total_kb_out = Convert.ToSingle(sdr["num_out_kb"]); returnstruct.total_kb_in = Convert.ToSingle(sdr["num_in_kb"]); returnstruct.avg_client_mem_use = Convert.ToSingle(sdr["sav_mem_use"]); } } return returnstruct; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnCurriculumReferencium class. /// </summary> [Serializable] public partial class PnCurriculumReferenciumCollection : ActiveList<PnCurriculumReferencium, PnCurriculumReferenciumCollection> { public PnCurriculumReferenciumCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnCurriculumReferenciumCollection</returns> public PnCurriculumReferenciumCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnCurriculumReferencium o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_curriculum_referencia table. /// </summary> [Serializable] public partial class PnCurriculumReferencium : ActiveRecord<PnCurriculumReferencium>, IActiveRecord { #region .ctors and Default Settings public PnCurriculumReferencium() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnCurriculumReferencium(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnCurriculumReferencium(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnCurriculumReferencium(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_curriculum_referencia", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdCurriculumReferencia = new TableSchema.TableColumn(schema); colvarIdCurriculumReferencia.ColumnName = "id_curriculum_referencia"; colvarIdCurriculumReferencia.DataType = DbType.Int32; colvarIdCurriculumReferencia.MaxLength = 0; colvarIdCurriculumReferencia.AutoIncrement = true; colvarIdCurriculumReferencia.IsNullable = false; colvarIdCurriculumReferencia.IsPrimaryKey = true; colvarIdCurriculumReferencia.IsForeignKey = false; colvarIdCurriculumReferencia.IsReadOnly = false; colvarIdCurriculumReferencia.DefaultSetting = @""; colvarIdCurriculumReferencia.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdCurriculumReferencia); TableSchema.TableColumn colvarIdLegajo = new TableSchema.TableColumn(schema); colvarIdLegajo.ColumnName = "id_legajo"; colvarIdLegajo.DataType = DbType.Int32; colvarIdLegajo.MaxLength = 0; colvarIdLegajo.AutoIncrement = false; colvarIdLegajo.IsNullable = false; colvarIdLegajo.IsPrimaryKey = false; colvarIdLegajo.IsForeignKey = false; colvarIdLegajo.IsReadOnly = false; colvarIdLegajo.DefaultSetting = @""; colvarIdLegajo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdLegajo); TableSchema.TableColumn colvarEmpleador = new TableSchema.TableColumn(schema); colvarEmpleador.ColumnName = "empleador"; colvarEmpleador.DataType = DbType.AnsiString; colvarEmpleador.MaxLength = -1; colvarEmpleador.AutoIncrement = false; colvarEmpleador.IsNullable = false; colvarEmpleador.IsPrimaryKey = false; colvarEmpleador.IsForeignKey = false; colvarEmpleador.IsReadOnly = false; colvarEmpleador.DefaultSetting = @""; colvarEmpleador.ForeignKeyTableName = ""; schema.Columns.Add(colvarEmpleador); TableSchema.TableColumn colvarDomicilioEmpresa = new TableSchema.TableColumn(schema); colvarDomicilioEmpresa.ColumnName = "domicilio_empresa"; colvarDomicilioEmpresa.DataType = DbType.AnsiString; colvarDomicilioEmpresa.MaxLength = -1; colvarDomicilioEmpresa.AutoIncrement = false; colvarDomicilioEmpresa.IsNullable = true; colvarDomicilioEmpresa.IsPrimaryKey = false; colvarDomicilioEmpresa.IsForeignKey = false; colvarDomicilioEmpresa.IsReadOnly = false; colvarDomicilioEmpresa.DefaultSetting = @""; colvarDomicilioEmpresa.ForeignKeyTableName = ""; schema.Columns.Add(colvarDomicilioEmpresa); TableSchema.TableColumn colvarDesde = new TableSchema.TableColumn(schema); colvarDesde.ColumnName = "desde"; colvarDesde.DataType = DbType.DateTime; colvarDesde.MaxLength = 0; colvarDesde.AutoIncrement = false; colvarDesde.IsNullable = true; colvarDesde.IsPrimaryKey = false; colvarDesde.IsForeignKey = false; colvarDesde.IsReadOnly = false; colvarDesde.DefaultSetting = @""; colvarDesde.ForeignKeyTableName = ""; schema.Columns.Add(colvarDesde); TableSchema.TableColumn colvarHasta = new TableSchema.TableColumn(schema); colvarHasta.ColumnName = "hasta"; colvarHasta.DataType = DbType.DateTime; colvarHasta.MaxLength = 0; colvarHasta.AutoIncrement = false; colvarHasta.IsNullable = true; colvarHasta.IsPrimaryKey = false; colvarHasta.IsForeignKey = false; colvarHasta.IsReadOnly = false; colvarHasta.DefaultSetting = @""; colvarHasta.ForeignKeyTableName = ""; schema.Columns.Add(colvarHasta); TableSchema.TableColumn colvarTareas = new TableSchema.TableColumn(schema); colvarTareas.ColumnName = "tareas"; colvarTareas.DataType = DbType.AnsiString; colvarTareas.MaxLength = -1; colvarTareas.AutoIncrement = false; colvarTareas.IsNullable = false; colvarTareas.IsPrimaryKey = false; colvarTareas.IsForeignKey = false; colvarTareas.IsReadOnly = false; colvarTareas.DefaultSetting = @""; colvarTareas.ForeignKeyTableName = ""; schema.Columns.Add(colvarTareas); TableSchema.TableColumn colvarCertificado = new TableSchema.TableColumn(schema); colvarCertificado.ColumnName = "certificado"; colvarCertificado.DataType = DbType.AnsiStringFixedLength; colvarCertificado.MaxLength = 1; colvarCertificado.AutoIncrement = false; colvarCertificado.IsNullable = false; colvarCertificado.IsPrimaryKey = false; colvarCertificado.IsForeignKey = false; colvarCertificado.IsReadOnly = false; colvarCertificado.DefaultSetting = @""; colvarCertificado.ForeignKeyTableName = ""; schema.Columns.Add(colvarCertificado); TableSchema.TableColumn colvarReferencias = new TableSchema.TableColumn(schema); colvarReferencias.ColumnName = "referencias"; colvarReferencias.DataType = DbType.AnsiString; colvarReferencias.MaxLength = -1; colvarReferencias.AutoIncrement = false; colvarReferencias.IsNullable = true; colvarReferencias.IsPrimaryKey = false; colvarReferencias.IsForeignKey = false; colvarReferencias.IsReadOnly = false; colvarReferencias.DefaultSetting = @""; colvarReferencias.ForeignKeyTableName = ""; schema.Columns.Add(colvarReferencias); TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema); colvarDomicilio.ColumnName = "domicilio"; colvarDomicilio.DataType = DbType.AnsiString; colvarDomicilio.MaxLength = -1; colvarDomicilio.AutoIncrement = false; colvarDomicilio.IsNullable = true; colvarDomicilio.IsPrimaryKey = false; colvarDomicilio.IsForeignKey = false; colvarDomicilio.IsReadOnly = false; colvarDomicilio.DefaultSetting = @""; colvarDomicilio.ForeignKeyTableName = ""; schema.Columns.Add(colvarDomicilio); TableSchema.TableColumn colvarTelefono = new TableSchema.TableColumn(schema); colvarTelefono.ColumnName = "telefono"; colvarTelefono.DataType = DbType.AnsiString; colvarTelefono.MaxLength = -1; colvarTelefono.AutoIncrement = false; colvarTelefono.IsNullable = true; colvarTelefono.IsPrimaryKey = false; colvarTelefono.IsForeignKey = false; colvarTelefono.IsReadOnly = false; colvarTelefono.DefaultSetting = @""; colvarTelefono.ForeignKeyTableName = ""; schema.Columns.Add(colvarTelefono); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_curriculum_referencia",schema); } } #endregion #region Props [XmlAttribute("IdCurriculumReferencia")] [Bindable(true)] public int IdCurriculumReferencia { get { return GetColumnValue<int>(Columns.IdCurriculumReferencia); } set { SetColumnValue(Columns.IdCurriculumReferencia, value); } } [XmlAttribute("IdLegajo")] [Bindable(true)] public int IdLegajo { get { return GetColumnValue<int>(Columns.IdLegajo); } set { SetColumnValue(Columns.IdLegajo, value); } } [XmlAttribute("Empleador")] [Bindable(true)] public string Empleador { get { return GetColumnValue<string>(Columns.Empleador); } set { SetColumnValue(Columns.Empleador, value); } } [XmlAttribute("DomicilioEmpresa")] [Bindable(true)] public string DomicilioEmpresa { get { return GetColumnValue<string>(Columns.DomicilioEmpresa); } set { SetColumnValue(Columns.DomicilioEmpresa, value); } } [XmlAttribute("Desde")] [Bindable(true)] public DateTime? Desde { get { return GetColumnValue<DateTime?>(Columns.Desde); } set { SetColumnValue(Columns.Desde, value); } } [XmlAttribute("Hasta")] [Bindable(true)] public DateTime? Hasta { get { return GetColumnValue<DateTime?>(Columns.Hasta); } set { SetColumnValue(Columns.Hasta, value); } } [XmlAttribute("Tareas")] [Bindable(true)] public string Tareas { get { return GetColumnValue<string>(Columns.Tareas); } set { SetColumnValue(Columns.Tareas, value); } } [XmlAttribute("Certificado")] [Bindable(true)] public string Certificado { get { return GetColumnValue<string>(Columns.Certificado); } set { SetColumnValue(Columns.Certificado, value); } } [XmlAttribute("Referencias")] [Bindable(true)] public string Referencias { get { return GetColumnValue<string>(Columns.Referencias); } set { SetColumnValue(Columns.Referencias, value); } } [XmlAttribute("Domicilio")] [Bindable(true)] public string Domicilio { get { return GetColumnValue<string>(Columns.Domicilio); } set { SetColumnValue(Columns.Domicilio, value); } } [XmlAttribute("Telefono")] [Bindable(true)] public string Telefono { get { return GetColumnValue<string>(Columns.Telefono); } set { SetColumnValue(Columns.Telefono, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdLegajo,string varEmpleador,string varDomicilioEmpresa,DateTime? varDesde,DateTime? varHasta,string varTareas,string varCertificado,string varReferencias,string varDomicilio,string varTelefono) { PnCurriculumReferencium item = new PnCurriculumReferencium(); item.IdLegajo = varIdLegajo; item.Empleador = varEmpleador; item.DomicilioEmpresa = varDomicilioEmpresa; item.Desde = varDesde; item.Hasta = varHasta; item.Tareas = varTareas; item.Certificado = varCertificado; item.Referencias = varReferencias; item.Domicilio = varDomicilio; item.Telefono = varTelefono; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdCurriculumReferencia,int varIdLegajo,string varEmpleador,string varDomicilioEmpresa,DateTime? varDesde,DateTime? varHasta,string varTareas,string varCertificado,string varReferencias,string varDomicilio,string varTelefono) { PnCurriculumReferencium item = new PnCurriculumReferencium(); item.IdCurriculumReferencia = varIdCurriculumReferencia; item.IdLegajo = varIdLegajo; item.Empleador = varEmpleador; item.DomicilioEmpresa = varDomicilioEmpresa; item.Desde = varDesde; item.Hasta = varHasta; item.Tareas = varTareas; item.Certificado = varCertificado; item.Referencias = varReferencias; item.Domicilio = varDomicilio; item.Telefono = varTelefono; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdCurriculumReferenciaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdLegajoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn EmpleadorColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn DomicilioEmpresaColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn DesdeColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn HastaColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn TareasColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn CertificadoColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn ReferenciasColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn DomicilioColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn TelefonoColumn { get { return Schema.Columns[10]; } } #endregion #region Columns Struct public struct Columns { public static string IdCurriculumReferencia = @"id_curriculum_referencia"; public static string IdLegajo = @"id_legajo"; public static string Empleador = @"empleador"; public static string DomicilioEmpresa = @"domicilio_empresa"; public static string Desde = @"desde"; public static string Hasta = @"hasta"; public static string Tareas = @"tareas"; public static string Certificado = @"certificado"; public static string Referencias = @"referencias"; public static string Domicilio = @"domicilio"; public static string Telefono = @"telefono"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
namespace Nancy.Testing.Tests { using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Linq; using Nancy.Extensions; using Nancy.Tests; using Nancy.Helpers; using Nancy.Session; using Xunit; using FakeItEasy; using Nancy.Authentication.Forms; using Xunit.Extensions; public class BrowserFixture { private readonly Browser browser; public BrowserFixture() { var bootstrapper = new ConfigurableBootstrapper(config => config.Modules(typeof(EchoModule))); CookieBasedSessions.Enable(bootstrapper); browser = new Browser(bootstrapper); } [Fact] public void Should_be_able_to_send_string_in_body() { // Given const string thisIsMyRequestBody = "This is my request body"; // When var result = browser.Post("/", with => { with.HttpRequest(); with.Body(thisIsMyRequestBody); }); // Then result.Body.AsString().ShouldEqual(thisIsMyRequestBody); } [Fact] public void Should_be_able_to_set_user_host_address() { // Given const string userHostAddress = "127.0.0.1"; // When var result = browser.Get("/userHostAddress", with => { with.HttpRequest(); with.UserHostAddress(userHostAddress); }); // Then result.Body.AsString().ShouldEqual(userHostAddress); } [Fact] public void Should_be_able_check_is_local_ipV4() { // Given const string userHostAddress = "127.0.0.1"; // When var result = browser.Get("/isLocal", with => { with.HttpRequest(); with.HostName("localhost"); with.UserHostAddress(userHostAddress); }); // Then result.Body.AsString().ShouldEqual("local"); } [Fact] public void Should_be_able_check_is_local_ipV6() { // Given const string userHostAddress = "::1"; // When var result = browser.Get("/isLocal", with => { with.HttpRequest(); with.HostName("localhost"); with.UserHostAddress(userHostAddress); }); // Then result.Body.AsString().ShouldEqual("local"); } [Fact] public void Should_be_able_check_is_not_local() { // Given const string userHostAddress = "84.12.65.72"; // When var result = browser.Get("/isLocal", with => { with.HttpRequest(); with.HostName("anotherhost"); with.UserHostAddress(userHostAddress); }); // Then result.Body.AsString().ShouldEqual("not-local"); } [Fact] public void Should_be_able_to_send_stream_in_body() { // Given const string thisIsMyRequestBody = "This is my request body"; var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(thisIsMyRequestBody); writer.Flush(); // When var result = browser.Post("/", with => { with.HttpRequest(); with.Body(stream, "text/plain"); }); // Then result.Body.AsString().ShouldEqual(thisIsMyRequestBody); } [Fact] public void Should_be_able_to_send_json_in_body() { // Given var model = new EchoModel { SomeString = "Some String", SomeInt = 29, SomeBoolean = true }; // When var result = browser.Post("/", with => { with.JsonBody(model); }); // Then var actualModel = result.Body.DeserializeJson<EchoModel>(); actualModel.ShouldNotBeNull(); actualModel.SomeString.ShouldEqual(model.SomeString); actualModel.SomeInt.ShouldEqual(model.SomeInt); actualModel.SomeBoolean.ShouldEqual(model.SomeBoolean); } [Fact] public void Should_be_able_to_send_xml_in_body() { // Given var model = new EchoModel { SomeString = "Some String", SomeInt = 29, SomeBoolean = true }; // When var result = browser.Post("/", with => { with.XMLBody(model); }); // Then var actualModel = result.Body.DeserializeXml<EchoModel>(); actualModel.ShouldNotBeNull(); actualModel.SomeString.ShouldEqual(model.SomeString); actualModel.SomeInt.ShouldEqual(model.SomeInt); actualModel.SomeBoolean.ShouldEqual(model.SomeBoolean); } [Fact] public void Should_add_basic_authentication_credentials_to_the_headers_of_the_request() { // Given var context = new BrowserContext(); // When context.BasicAuth("username", "password"); // Then IBrowserContextValues values = context; var credentials = string.Format("{0}:{1}", "username", "password"); var encodedCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)); values.Headers["Authorization"].ShouldHaveCount(1); values.Headers["Authorization"].First().ShouldEqual("Basic " + encodedCredentials); } [Fact] public void Should_add_cookies_to_the_request() { // Given var context = new BrowserContext(); var cookies = new Dictionary<string, string> { {"CookieName", "CookieValue"}, {"SomeCookieName", "SomeCookieValue"} }; // When context.Cookie(cookies); // Then IBrowserContextValues values = context; var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); values.Headers["Cookie"].ShouldHaveCount(1); values.Headers["Cookie"].First().ShouldEqual(cookieString); } [Fact] public void Should_add_cookie_to_the_request() { // Given var context = new BrowserContext(); var cookies = new Dictionary<string, string> { {"CookieName", "CookieValue"}, {"SomeCookieName", "SomeCookieValue"} }; // When foreach (var cookie in cookies) { context.Cookie(cookie.Key, cookie.Value); } // Then IBrowserContextValues values = context; var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); values.Headers["Cookie"].ShouldHaveCount(1); values.Headers["Cookie"].First().ShouldEqual(cookieString); } [Fact] public void Should_add_cookies_to_the_request_and_get_cookies_in_response() { // Given var cookies = new Dictionary<string, string> { {"CookieName", "CookieValue"}, {"SomeCookieName", "SomeCookieValue"} }; // When var result = browser.Get("/cookie", with => { with.Cookie(cookies); }); // Then result.Cookies.Single(x => x.Name == "CookieName").Value.ShouldEqual("CookieValue"); result.Cookies.Single(x => x.Name == "SomeCookieName").Value.ShouldEqual("SomeCookieValue"); } [Fact] public void Should_add_a_cookie_to_the_request_and_get_a_cookie_in_response() { // Given, When var result = browser.Get("/cookie", with => with.Cookie("CookieName", "CookieValue")); // Then result.Cookies.Single(x => x.Name == "CookieName").Value.ShouldEqual("CookieValue"); } [Fact] public void Should_be_able_to_continue_with_another_request() { // Given const string FirstRequestBody = "This is my first request body"; const string SecondRequestBody = "This is my second request body"; var firstRequestStream = new MemoryStream(); var firstRequestWriter = new StreamWriter(firstRequestStream); firstRequestWriter.Write(FirstRequestBody); firstRequestWriter.Flush(); var secondRequestStream = new MemoryStream(); var secondRequestWriter = new StreamWriter(secondRequestStream); secondRequestWriter.Write(SecondRequestBody); secondRequestWriter.Flush(); // When var result = browser.Post("/", with => { with.HttpRequest(); with.Body(firstRequestStream, "text/plain"); }).Then.Post("/", with => { with.HttpRequest(); with.Body(secondRequestStream, "text/plain"); }); // Then result.Body.AsString().ShouldEqual(SecondRequestBody); } [Fact] public void Should_maintain_cookies_when_chaining_requests() { // Given // When var result = browser.Get( "/session", with => with.HttpRequest()) .Then .Get( "/session", with => with.HttpRequest()); result.Body.AsString().ShouldEqual("Current session value is: I've created a session!"); } [Fact] public void Should_maintain_cookies_even_if_not_set_on_directly_preceding_request() { // Given // When var result = browser.Get( "/session", with => with.HttpRequest()) .Then .Get( "/nothing", with => with.HttpRequest()) .Then .Get( "/session", with => with.HttpRequest()); //Then result.Body.AsString().ShouldEqual("Current session value is: I've created a session!"); } [Fact] public void Should_be_able_to_not_specify_delegate_for_basic_http_request() { //Given, When var result = browser.Get("/type"); //Then result.Body.AsString().ShouldEqual("http"); } [Fact] public void Should_add_ajax_header() { //Given, When var result = browser.Get("/ajax", with => with.AjaxRequest()); //Then result.Body.AsString().ShouldEqual("ajax"); } [Fact] public void Should_throw_an_exception_when_the_cert_couldnt_be_found() { //Given, When var exception = Record.Exception(() => { var result = browser.Get("/ajax", with => with.Certificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, "aa aa aa")); }); //Then exception.ShouldBeOfType<InvalidOperationException>(); } [Fact] public void Should_add_certificate() { //Given, When var result = browser.Get("/cert", with => with.Certificate()); //Then result.Context.Request.ClientCertificate.ShouldNotBeNull(); } [Fact] public void Should_change_scheme_to_https_when_HttpsRequest_is_called_on_the_context() { //Given, When var result = browser.Get("/", with => with.HttpsRequest()); //Then result.Context.Request.Url.Scheme.ShouldEqual("https"); } [Fact] public void Should_add_forms_authentication_cookie_to_the_request() { //Given var userId = A.Dummy<Guid>(); var formsAuthConfig = new FormsAuthenticationConfiguration() { RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), }; var encryptedId = formsAuthConfig.CryptographyConfiguration.EncryptionProvider.Encrypt(userId.ToString()); var hmacBytes = formsAuthConfig.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedId); var hmacString = Convert.ToBase64String(hmacBytes); var cookieContents = String.Format("{1}{0}", encryptedId, hmacString); //When var response = browser.Get("/cookie", (with) => { with.HttpRequest(); with.FormsAuth(userId, formsAuthConfig); }); var cookie = response.Cookies.Single(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName); var cookieValue = HttpUtility.UrlDecode(cookie.Value); //Then cookieValue.ShouldEqual(cookieContents); } [Fact] public void Should_return_JSON_serialized_form() { var response = browser.Post("/serializedform", (with) => { with.HttpRequest(); with.Accept("application/json"); with.FormValue("SomeString", "Hi"); with.FormValue("SomeInt", "1"); with.FormValue("SomeBoolean", "true"); }); var actualModel = response.Body.DeserializeJson<EchoModel>(); Assert.Equal("Hi", actualModel.SomeString); Assert.Equal(1, actualModel.SomeInt); Assert.Equal(true, actualModel.SomeBoolean); } [Fact] public void Should_return_JSON_serialized_querystring() { var response = browser.Get("/serializedquerystring", (with) => { with.HttpRequest(); with.Accept("application/json"); with.Query("SomeString", "Hi"); with.Query("SomeInt", "1"); with.Query("SomeBoolean", "true"); }); var actualModel = response.Body.DeserializeJson<EchoModel>(); Assert.Equal("Hi", actualModel.SomeString); Assert.Equal(1, actualModel.SomeInt); Assert.Equal(true, actualModel.SomeBoolean); } [Fact] public void Should_encode_form() { //Given, When var result = browser.Post("/encoded", with => { with.HttpRequest(); with.FormValue("name", "john++"); }); //Then result.Body.AsString().ShouldEqual("john++"); } [Fact] public void Should_encode_querystring() { //Given, When var result = browser.Post("/encodedquerystring", with => { with.HttpRequest(); with.Query("name", "john++"); }); //Then result.Body.AsString().ShouldEqual("john++"); } public class EchoModel { public string SomeString { get; set; } public int SomeInt { get; set; } public bool SomeBoolean { get; set; } } public class EchoModule : NancyModule { public EchoModule() { Post["/"] = ctx => { var body = new StreamReader(this.Context.Request.Body).ReadToEnd(); return new Response { Contents = stream => { var writer = new StreamWriter(stream); writer.Write(body); writer.Flush(); } }; }; Get["/cookie"] = ctx => { var response = (Response)"Cookies"; foreach (var cookie in this.Request.Cookies) { response.AddCookie(cookie.Key, cookie.Value); } return response; }; Get["/nothing"] = ctx => string.Empty; Get["/userHostAddress"] = ctx => this.Request.UserHostAddress; Get["/isLocal"] = _ => this.Request.IsLocal() ? "local" : "not-local"; Get["/session"] = ctx => { var value = Session["moo"] ?? ""; var output = "Current session value is: " + value; if (string.IsNullOrEmpty(value.ToString())) { Session["moo"] = "I've created a session!"; } var response = (Response)output; return response; }; Get["/type"] = _ => this.Request.Url.Scheme.ToLower(); Get["/ajax"] = _ => this.Request.IsAjaxRequest() ? "ajax" : "not-ajax"; Post["/encoded"] = parameters => (string)this.Request.Form.name; Post["/encodedquerystring"] = parameters => (string)this.Request.Query.name; Post["/serializedform"] = _ => { var data = Request.Form.ToDictionary(); return data; }; Get["/serializedquerystring"] = _ => { var data = Request.Query.ToDictionary(); return data; }; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Globalization; namespace System.Xml.Xsl.Runtime { /// <summary> /// Base internal class for all sort keys. /// Inherits from IComparable, so that Array.Sort can perform comparison. /// </summary> internal abstract class XmlSortKey : IComparable { private int _priority; // Original input ordering used to ensure that sort is stable private XmlSortKey _nextKey; // Next sort key if there are multiple keys (null otherwise) /// <summary> /// Get or set this key's index, relative to other keys involved in a sort. This priority will /// break ties. If the priority is not set, then the sort will not be stable. /// </summary> public int Priority { //get { return this.priority; } set { // All linked keys have same priority XmlSortKey key = this; while (key != null) { key._priority = value; key = key._nextKey; } } } /// <summary> /// Sometimes a key is composed of multiple parts. For example: (LastName, FirstName). Multi-part /// keys are linked together in a list. This method recursively adds a new key part to the end of the list. /// Returns the first (primary) key in the list. /// </summary> public XmlSortKey AddSortKey(XmlSortKey sortKey) { if (_nextKey != null) { // Add to end of list--this is not it _nextKey.AddSortKey(sortKey); } else { // This is the end of the list _nextKey = sortKey; } return this; } /// <summary> /// When two keys are compared and found to be equal, the tie must be broken. If there is a secondary key, /// then use that to break the tie. Otherwise, use the input ordering to break the tie. Since every key /// has a unique index, this is guaranteed to always break the tie. /// </summary> protected int BreakSortingTie(XmlSortKey that) { if (_nextKey != null) { // There are multiple keys, so break tie using next key Debug.Assert(_nextKey != null && that._nextKey != null); return _nextKey.CompareTo(that._nextKey); } Debug.Assert(_priority != that._priority); return (_priority < that._priority) ? -1 : 1; } /// <summary> /// Compare a non-empty key (this) to an empty key (obj). The empty sequence always sorts either before all /// other values, or after all other values. /// </summary> protected int CompareToEmpty(object obj) { XmlEmptySortKey that = obj as XmlEmptySortKey; Debug.Assert(that != null && !(this is XmlEmptySortKey)); return that.IsEmptyGreatest ? -1 : 1; } /// <summary> /// Base internal class is abstract and doesn't actually implement CompareTo; derived classes must do this. /// </summary> public abstract int CompareTo(object that); } /// <summary> /// Sort key for the empty sequence. Empty sequence always compares sorts either before all other values, /// or after all other values. /// </summary> internal class XmlEmptySortKey : XmlSortKey { private bool _isEmptyGreatest; public XmlEmptySortKey(XmlCollation collation) { // Greatest, Ascending: isEmptyGreatest = true // Greatest, Descending: isEmptyGreatest = false // Least, Ascending: isEmptyGreatest = false // Least, Descending: isEmptyGreatest = true _isEmptyGreatest = collation.EmptyGreatest != collation.DescendingOrder; } public bool IsEmptyGreatest { get { return _isEmptyGreatest; } } public override int CompareTo(object obj) { XmlEmptySortKey that = obj as XmlEmptySortKey; if (that == null) { // Empty compared to non-empty Debug.Assert(obj is XmlSortKey); return -(obj as XmlSortKey).CompareTo(this); } // Empty compared to empty return BreakSortingTie(that); } } /// <summary> /// Sort key for xs:decimal values. /// </summary> internal class XmlDecimalSortKey : XmlSortKey { private decimal _decVal; public XmlDecimalSortKey(decimal value, XmlCollation collation) { // Invert decimal if sorting in descending order _decVal = collation.DescendingOrder ? -value : value; } public override int CompareTo(object obj) { XmlDecimalSortKey that = obj as XmlDecimalSortKey; int cmp; if (that == null) return CompareToEmpty(obj); cmp = decimal.Compare(_decVal, that._decVal); if (cmp == 0) return BreakSortingTie(that); return cmp; } } /// <summary> /// Sort key for xs:integer values. /// </summary> internal class XmlIntegerSortKey : XmlSortKey { private long _longVal; public XmlIntegerSortKey(long value, XmlCollation collation) { // Invert long if sorting in descending order _longVal = collation.DescendingOrder ? ~value : value; } public override int CompareTo(object obj) { XmlIntegerSortKey that = obj as XmlIntegerSortKey; if (that == null) return CompareToEmpty(obj); if (_longVal == that._longVal) return BreakSortingTie(that); return (_longVal < that._longVal) ? -1 : 1; } } /// <summary> /// Sort key for xs:int values. /// </summary> internal class XmlIntSortKey : XmlSortKey { private int _intVal; public XmlIntSortKey(int value, XmlCollation collation) { // Invert integer if sorting in descending order _intVal = collation.DescendingOrder ? ~value : value; } public override int CompareTo(object obj) { XmlIntSortKey that = obj as XmlIntSortKey; if (that == null) return CompareToEmpty(obj); if (_intVal == that._intVal) return BreakSortingTie(that); return (_intVal < that._intVal) ? -1 : 1; } } /// <summary> /// Sort key for xs:string values. Strings are sorted according to a byte-wise sort key calculated by caller. /// </summary> internal class XmlStringSortKey : XmlSortKey { private readonly SortKey _sortKey; private readonly byte[] _sortKeyBytes; private readonly bool _descendingOrder; public XmlStringSortKey(SortKey sortKey, bool descendingOrder) { _sortKey = sortKey; _descendingOrder = descendingOrder; } public XmlStringSortKey(byte[] sortKey, bool descendingOrder) { _sortKeyBytes = sortKey; _descendingOrder = descendingOrder; } public override int CompareTo(object obj) { XmlStringSortKey that = obj as XmlStringSortKey; int idx, cntCmp, result; if (that == null) return CompareToEmpty(obj); // Compare either using SortKey.Compare or byte arrays if (_sortKey != null) { Debug.Assert(that._sortKey != null, "Both keys must have non-null sortKey field"); result = SortKey.Compare(_sortKey, that._sortKey); } else { Debug.Assert(_sortKeyBytes != null && that._sortKeyBytes != null, "Both keys must have non-null sortKeyBytes field"); cntCmp = (_sortKeyBytes.Length < that._sortKeyBytes.Length) ? _sortKeyBytes.Length : that._sortKeyBytes.Length; for (idx = 0; idx < cntCmp; idx++) { if (_sortKeyBytes[idx] < that._sortKeyBytes[idx]) { result = -1; goto Done; } if (_sortKeyBytes[idx] > that._sortKeyBytes[idx]) { result = 1; goto Done; } } // So far, keys are equal, so now test length of each key if (_sortKeyBytes.Length < that._sortKeyBytes.Length) result = -1; else if (_sortKeyBytes.Length > that._sortKeyBytes.Length) result = 1; else result = 0; } Done: // Use document order to break sorting tie if (result == 0) return BreakSortingTie(that); return _descendingOrder ? -result : result; } } /// <summary> /// Sort key for Double values. /// </summary> internal class XmlDoubleSortKey : XmlSortKey { private double _dblVal; private bool _isNaN; public XmlDoubleSortKey(double value, XmlCollation collation) { if (double.IsNaN(value)) { // Treat NaN as if it were the empty sequence _isNaN = true; // Greatest, Ascending: isEmptyGreatest = true // Greatest, Descending: isEmptyGreatest = false // Least, Ascending: isEmptyGreatest = false // Least, Descending: isEmptyGreatest = true _dblVal = (collation.EmptyGreatest != collation.DescendingOrder) ? double.PositiveInfinity : double.NegativeInfinity; } else { _dblVal = collation.DescendingOrder ? -value : value; } } public override int CompareTo(object obj) { XmlDoubleSortKey that = obj as XmlDoubleSortKey; if (that == null) { // Compare to empty sequence if (_isNaN) return BreakSortingTie(obj as XmlSortKey); return CompareToEmpty(obj); } if (_dblVal == that._dblVal) { if (_isNaN) { // NaN sorts equal to NaN if (that._isNaN) return BreakSortingTie(that); // NaN sorts before or after all non-NaN values Debug.Assert(_dblVal == double.NegativeInfinity || _dblVal == double.PositiveInfinity); return (_dblVal == double.NegativeInfinity) ? -1 : 1; } else if (that._isNaN) { // NaN sorts before or after all non-NaN values Debug.Assert(that._dblVal == double.NegativeInfinity || that._dblVal == double.PositiveInfinity); return (that._dblVal == double.NegativeInfinity) ? 1 : -1; } return BreakSortingTie(that); } return (_dblVal < that._dblVal) ? -1 : 1; } } /// <summary> /// Sort key for DateTime values (just convert DateTime to ticks and use Long sort key). /// </summary> internal class XmlDateTimeSortKey : XmlIntegerSortKey { public XmlDateTimeSortKey(DateTime value, XmlCollation collation) : base(value.Ticks, collation) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using Internal.Reflection.Extensions.NonPortable; using Internal.LowLevelLinq; namespace System.Reflection { //============================================================================================================== // This api set retrieves the "effective" set of custom attributes associated with a given Reflection element. // The effective set not only includes attributes declared directly on the element but attributes inherited // from the element's "parents." // // Api conventions: // // - "T or "attributeType" arguments must be non-null, non-interface type that derives from System.Attribute. // // - The default for the "inherited" parameter is "true". For Assemblies, Modules and FieldInfos, // the api ignores the value of "inherited." // // // Definition of "effective" set of custom attributes: // // The following element types can inherit custom attributes from its "parents". Inheritance is transitive, // so this also includes grandparents, etc. // // - TypeInfos inherit from base classes (but not interfaces.) // // - MethodInfos that override a virtual in a base class (but not an interface) inherit // from the method it overrode. // // - PropertyInfos that override a virtual in a base class (but not an interface) inherit // from the property it override. // // - EventInfos that override a virtual in a base class (but not an interface) inherit // from the event it override. // // - ParameterInfos whose declaring method overrides a virtual in a base class (but not an interface) // inherit from the matching parameter in the method that was overridden. // // Custom attributes only flow down this chain if they are marked inheritable. Note that the // AttributeUsageAttribute attribute it itself inheritable, and custom attributes can derive from other custom attributes: // if a custom attribute and its base class(s) both define AttributeUsages, the most derived AttributeUsage wins. // // If an element and one of its parents both include a custom attribute of the *exact same type* (even // if calling different overloads of the constructor), and that attribute types does *not* declare AllowMultiple=true, // these apis will only return the one attached to the most derived parent.) // // Dependency note: // This class must depend only on the CustomAttribute properties that return IEnumerable<CustomAttributeData>. // All of the other custom attribute api route back here so calls to them will cause an infinite recursion. // //============================================================================================================== public static class CustomAttributeExtensions { //============================================================================================================== // This group returns the single custom attribute whose type matches or is a subclass of "attributeType". // // Returns null if no matching custom attribute found. // // Throws AmbiguousMatchException if multple matches found. //============================================================================================================== public static Attribute GetCustomAttribute(this Assembly element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType); return matches.OneOrNull<Attribute>(); } public static Attribute GetCustomAttribute(this Module element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType); return matches.OneOrNull<Attribute>(); } public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit: true); return matches.OneOrNull<Attribute>(); } public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType, bool inherit) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit); return matches.OneOrNull<Attribute>(); } public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit: true); return matches.OneOrNull<Attribute>(); } public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType, bool inherit) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit); return matches.OneOrNull<Attribute>(); } //============================================================================================================== // This group returns the single custom attribute whose type matches or is a subclass of "T". // // Returns null if no matching custom attribute found. // // Throws AmbiguousMatchException if multple matches found. //============================================================================================================== public static T GetCustomAttribute<T>(this Assembly element) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), skipTypeValidation: true); return matches.OneOrNull<T>(); } public static T GetCustomAttribute<T>(this Module element) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), skipTypeValidation: true); return matches.OneOrNull<T>(); } public static T GetCustomAttribute<T>(this MemberInfo element) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), inherit: true, skipTypeValidation: true); return matches.OneOrNull<T>(); } public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), inherit, skipTypeValidation: true); return matches.OneOrNull<T>(); } public static T GetCustomAttribute<T>(this ParameterInfo element) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), inherit: true, skipTypeValidation: true); return matches.OneOrNull<T>(); } public static T GetCustomAttribute<T>(this ParameterInfo element, bool inherit) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), inherit, skipTypeValidation: true); return matches.OneOrNull<T>(); } //============================================================================================================== // This group retrieves all custom attributes that applies to a given element. //============================================================================================================== public static IEnumerable<Attribute> GetCustomAttributes(this Assembly element) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(null, skipTypeValidation: true); return matches.Select(m => m.Instantiate()); } public static IEnumerable<Attribute> GetCustomAttributes(this Module element) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(null, skipTypeValidation: true); return matches.Select(m => m.Instantiate()); } public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(null, inherit: true, skipTypeValidation: true); return matches.Select(m => m.Instantiate()); } public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, bool inherit) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(null, inherit, skipTypeValidation: true); return matches.Select(m => m.Instantiate()); } public static IEnumerable<Attribute> GetCustomAttributes(this ParameterInfo element) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(null, inherit: true, skipTypeValidation: true); return matches.Select(m => m.Instantiate()); } public static IEnumerable<Attribute> GetCustomAttributes(this ParameterInfo element, bool inherit) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(null, inherit, skipTypeValidation: true); return matches.Select(m => m.Instantiate()); } //============================================================================================================== // This group retrieves all custom attributes associated with a given element whose attribute type matches or // is a subclass of "attributeType". //============================================================================================================== public static IEnumerable<Attribute> GetCustomAttributes(this Assembly element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType); return matches.Instantiate(attributeType); } public static IEnumerable<Attribute> GetCustomAttributes(this Module element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType); return matches.Instantiate(attributeType); } public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit: true); return matches.Instantiate(attributeType); } public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit); return matches.Instantiate(attributeType); } public static IEnumerable<Attribute> GetCustomAttributes(this ParameterInfo element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit: true); return matches.Instantiate(attributeType); } public static IEnumerable<Attribute> GetCustomAttributes(this ParameterInfo element, Type attributeType, bool inherit) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit); return matches.Instantiate(attributeType); } //============================================================================================================== // This group retrieves all custom attributes associated with a given element whose attribute type matches or // is a subclass of "T". //============================================================================================================== public static IEnumerable<T> GetCustomAttributes<T>(this Assembly element) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), skipTypeValidation: true); return matches.Select(m => (T)(m.Instantiate())); } public static IEnumerable<T> GetCustomAttributes<T>(this Module element) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), skipTypeValidation: true); return matches.Select(m => (T)(m.Instantiate())); } public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo element) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), inherit: true, skipTypeValidation: true); return matches.Select(m => (T)(m.Instantiate())); } public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo element, bool inherit) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), inherit, skipTypeValidation: true); return matches.Select(m => (T)(m.Instantiate())); } public static IEnumerable<T> GetCustomAttributes<T>(this ParameterInfo element) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), inherit: true, skipTypeValidation: true); return matches.Select(m => (T)(m.Instantiate())); } public static IEnumerable<T> GetCustomAttributes<T>(this ParameterInfo element, bool inherit) where T : Attribute { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(typeof(T), inherit, skipTypeValidation: true); return matches.Select(m => (T)(m.Instantiate())); } //============================================================================================================== // This group determines whether the element has an associated custom attribute whose type matches or is a subclass // of "attributeType". //============================================================================================================== public static bool IsDefined(this Assembly element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType); return matches.Any(); } public static bool IsDefined(this Module element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType); return matches.Any(); } public static bool IsDefined(this MemberInfo element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit: true); return matches.Any(); } public static bool IsDefined(this MemberInfo element, Type attributeType, bool inherit) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit); return matches.Any(); } public static bool IsDefined(this ParameterInfo element, Type attributeType) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit: true); return matches.Any(); } public static bool IsDefined(this ParameterInfo element, Type attributeType, bool inherit) { IEnumerable<CustomAttributeData> matches = element.GetMatchingCustomAttributes(attributeType, inherit); return matches.Any(); } //============================================================================================================================== // Helper for the GetCustomAttribute() family. //============================================================================================================================== private static T OneOrNull<T>(this IEnumerable<CustomAttributeData> results) where T : Attribute { IEnumerator<CustomAttributeData> enumerator = results.GetEnumerator(); if (!enumerator.MoveNext()) return null; CustomAttributeData result = enumerator.Current; if (enumerator.MoveNext()) throw new AmbiguousMatchException(); return (T)(result.Instantiate()); } //============================================================================================================================== // Helper for the GetCustomAttributes() methods that take a specific attribute type. For desktop compatibility, // we return a freshly allocated array of the specific attribute type even though the api's return type promises only an IEnumerable<Attribute>. // There are known store apps that cast the results of apis and expect the cast to work. The implementation of Attribute.GetCustomAttribute() // also relies on this (it performs an unsafe cast to Attribute[] and does not re-copy the array.) //============================================================================================================================== private static IEnumerable<Attribute> Instantiate(this IEnumerable<CustomAttributeData> cads, Type actualElementType) { LowLevelList<Attribute> attributes = new LowLevelList<Attribute>(); foreach (CustomAttributeData cad in cads) { Attribute instantiatedAttribute = cad.Instantiate(); attributes.Add(instantiatedAttribute); } int count = attributes.Count; Attribute[] result; try { result = (Attribute[])Array.CreateInstance(actualElementType, count); } catch (NotSupportedException) when (actualElementType.ContainsGenericParameters) { // This is here for desktop compatibility (using try-catch as control flow to avoid slowing down the mainline case.) // CustomAttributeExtensions.GetCustomAttributes() normally returns an array of the exact attribute type requested except when // the reqested type is an open type. Its ICustomAttributeProvider counterpart would return an Object[] array but that's // not possible with this api's return type so it returns null instead. return null; } attributes.CopyTo(result, 0); return result; } //============================================================================================================================== // This is used to "convert" the output of CustomAttributeExtensions.GetCustomAttributes() from IEnumerable<Attribute> to Attribute[] // as required by the Attribute.GetCustomAttributes() members. // // This relies on the fact that CustomAttributeExtensions.GetCustomAttribute()'s actual return type is an array whose element type is that // of the specific attributeType searched on. (Though this isn't explicitly promised, real world code does in fact rely on this so // this is a compat thing we're stuck with now.) //============================================================================================================================== [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Attribute[] AsAttributeArray(this IEnumerable<Attribute> attributes) => (Attribute[])attributes; } }
/* * 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 cloudfront-2015-07-27.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.CloudFront.Model { /// <summary> /// A summary of the information for an Amazon CloudFront streaming distribution. /// </summary> public partial class StreamingDistributionSummary { private Aliases _aliases; private string _comment; private string _domainName; private bool? _enabled; private string _id; private DateTime? _lastModifiedTime; private PriceClass _priceClass; private S3Origin _s3Origin; private string _status; private TrustedSigners _trustedSigners; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public StreamingDistributionSummary() { } /// <summary> /// Gets and sets the property Aliases. A complex type that contains information about /// CNAMEs (alternate domain names), if any, for this streaming distribution. /// </summary> public Aliases Aliases { get { return this._aliases; } set { this._aliases = value; } } // Check to see if Aliases property is set internal bool IsSetAliases() { return this._aliases != null; } /// <summary> /// Gets and sets the property Comment. The comment originally specified when this distribution /// was created. /// </summary> public string Comment { get { return this._comment; } set { this._comment = value; } } // Check to see if Comment property is set internal bool IsSetComment() { return this._comment != null; } /// <summary> /// Gets and sets the property DomainName. The domain name corresponding to the distribution. /// For example: d604721fxaaqy9.cloudfront.net. /// </summary> public string DomainName { get { return this._domainName; } set { this._domainName = value; } } // Check to see if DomainName property is set internal bool IsSetDomainName() { return this._domainName != null; } /// <summary> /// Gets and sets the property Enabled. Whether the distribution is enabled to accept /// end user requests for content. /// </summary> public bool Enabled { get { return this._enabled.GetValueOrDefault(); } set { this._enabled = value; } } // Check to see if Enabled property is set internal bool IsSetEnabled() { return this._enabled.HasValue; } /// <summary> /// Gets and sets the property Id. The identifier for the distribution. For example: EDFDVBD632BHDS5. /// </summary> public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property LastModifiedTime. The date and time the distribution was /// last modified. /// </summary> public DateTime LastModifiedTime { get { return this._lastModifiedTime.GetValueOrDefault(); } set { this._lastModifiedTime = value; } } // Check to see if LastModifiedTime property is set internal bool IsSetLastModifiedTime() { return this._lastModifiedTime.HasValue; } /// <summary> /// Gets and sets the property PriceClass. /// </summary> public PriceClass PriceClass { get { return this._priceClass; } set { this._priceClass = value; } } // Check to see if PriceClass property is set internal bool IsSetPriceClass() { return this._priceClass != null; } /// <summary> /// Gets and sets the property S3Origin. A complex type that contains information about /// the Amazon S3 bucket from which you want CloudFront to get your media files for distribution. /// </summary> public S3Origin S3Origin { get { return this._s3Origin; } set { this._s3Origin = value; } } // Check to see if S3Origin property is set internal bool IsSetS3Origin() { return this._s3Origin != null; } /// <summary> /// Gets and sets the property Status. Indicates the current status of the distribution. /// When the status is Deployed, the distribution's information is fully propagated throughout /// the Amazon CloudFront system. /// </summary> public string Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property TrustedSigners. A complex type that specifies the AWS accounts, /// if any, that you want to allow to create signed URLs for private content. If you want /// to require signed URLs in requests for objects in the target origin that match the /// PathPattern for this cache behavior, specify true for Enabled, and specify the applicable /// values for Quantity and Items. For more information, go to Using a Signed URL to Serve /// Private Content in the Amazon CloudFront Developer Guide. If you don't want to require /// signed URLs in requests for objects that match PathPattern, specify false for Enabled /// and 0 for Quantity. Omit Items. To add, change, or remove one or more trusted signers, /// change Enabled to true (if it's currently false), change Quantity as applicable, and /// specify all of the trusted signers that you want to include in the updated distribution. /// </summary> public TrustedSigners TrustedSigners { get { return this._trustedSigners; } set { this._trustedSigners = value; } } // Check to see if TrustedSigners property is set internal bool IsSetTrustedSigners() { return this._trustedSigners != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Culture-specific collection of resources. ** ** ===========================================================*/ namespace System.Resources { using System; using System.Collections; using System.IO; using System.Globalization; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // A ResourceSet stores all the resources defined in one particular CultureInfo. // // The method used to load resources is straightforward - this class // enumerates over an IResourceReader, loading every name and value, and // stores them in a hash table. Custom IResourceReaders can be used. // [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class ResourceSet : IDisposable, IEnumerable { [NonSerialized] protected IResourceReader Reader; #if FEATURE_CORECLR internal Hashtable Table; #else protected Hashtable Table; #endif private Hashtable _caseInsensitiveTable; // For case-insensitive lookups. #if LOOSELY_LINKED_RESOURCE_REFERENCE [OptionalField] private Assembly _assembly; // For LooselyLinkedResourceReferences #endif // LOOSELY_LINKED_RESOURCE_REFERENCE protected ResourceSet() { // To not inconvenience people subclassing us, we should allocate a new // hashtable here just so that Table is set to something. CommonInit(); } // For RuntimeResourceSet, ignore the Table parameter - it's a wasted // allocation. internal ResourceSet(bool junk) { } // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to open & read from a file // on disk. // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public ResourceSet(String fileName) { Reader = new ResourceReader(fileName); CommonInit(); ReadResources(); } #if LOOSELY_LINKED_RESOURCE_REFERENCE public ResourceSet(String fileName, Assembly assembly) { Reader = new ResourceReader(fileName); CommonInit(); _assembly = assembly; ReadResources(); } #endif // LOOSELY_LINKED_RESOURCE_REFERENCE // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to read from an open stream // of data. // [System.Security.SecurityCritical] // auto-generated_required public ResourceSet(Stream stream) { Reader = new ResourceReader(stream); CommonInit(); ReadResources(); } #if LOOSELY_LINKED_RESOURCE_REFERENCE [System.Security.SecurityCritical] // auto_generated_required public ResourceSet(Stream stream, Assembly assembly) { Reader = new ResourceReader(stream); CommonInit(); _assembly = assembly; ReadResources(); } #endif // LOOSELY_LINKED_RESOURCE_REFERENCE public ResourceSet(IResourceReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); Reader = reader; CommonInit(); ReadResources(); } #if LOOSELY_LINKED_RESOURCE_REFERENCE public ResourceSet(IResourceReader reader, Assembly assembly) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); Reader = reader; CommonInit(); _assembly = assembly; ReadResources(); } #endif // LOOSELY_LINKED_RESOURCE_REFERENCE private void CommonInit() { Table = new Hashtable(); } // Closes and releases any resources used by this ResourceSet, if any. // All calls to methods on the ResourceSet after a call to close may // fail. Close is guaranteed to be safely callable multiple times on a // particular ResourceSet, and all subclasses must support these semantics. public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { // Close the Reader in a thread-safe way. IResourceReader copyOfReader = Reader; Reader = null; if (copyOfReader != null) copyOfReader.Close(); } Reader = null; _caseInsensitiveTable = null; Table = null; } public void Dispose() { Dispose(true); } #if LOOSELY_LINKED_RESOURCE_REFERENCE // Optional - used for resolving assembly manifest resource references. // This can safely be null. [ComVisible(false)] public Assembly Assembly { get { return _assembly; } /*protected*/ set { _assembly = value; } } #endif // LOOSELY_LINKED_RESOURCE_REFERENCE // Returns the preferred IResourceReader class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultReader() { return typeof(ResourceReader); } // Returns the preferred IResourceWriter class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultWriter() { #if FEATURE_CORECLR return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true); #else return typeof(ResourceWriter); #endif } [ComVisible(false)] public virtual IDictionaryEnumerator GetEnumerator() { return GetEnumeratorHelper(); } /// <internalonly/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorHelper(); } private IDictionaryEnumerator GetEnumeratorHelper() { Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet")); return copyOfTable.GetEnumerator(); } // Look up a string value for a resource given its name. // public virtual String GetString(String name) { Object obj = GetObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name)); } } public virtual String GetString(String name, bool ignoreCase) { Object obj; String s; // Case-sensitive lookup obj = GetObjectInternal(name); try { s = (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name)); } // case-sensitive lookup succeeded if (s != null || !ignoreCase) { return s; } // Try doing a case-insensitive lookup obj = GetCaseInsensitiveObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name)); } } // Look up an object value for a resource given its name. // public virtual Object GetObject(String name) { return GetObjectInternal(name); } public virtual Object GetObject(String name, bool ignoreCase) { Object obj = GetObjectInternal(name); if (obj != null || !ignoreCase) return obj; return GetCaseInsensitiveObjectInternal(name); } protected virtual void ReadResources() { IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { Object value = en.Value; #if LOOSELY_LINKED_RESOURCE_REFERENCE if (Assembly != null && value is LooselyLinkedResourceReference) { LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value; value = assRef.Resolve(Assembly); } #endif //LOOSELYLINKEDRESOURCEREFERENCE Table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it // to help with some WinRes lifetime issues. } private Object GetObjectInternal(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet")); return copyOfTable[name]; } private Object GetCaseInsensitiveObjectInternal(String name) { Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet")); Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close if (caseTable == null) { caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase); #if _DEBUG //Console.WriteLine("ResourceSet::GetObject loading up case-insensitive data"); BCLDebug.Perf(false, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing "+name+" correctly in your source"); #endif IDictionaryEnumerator en = copyOfTable.GetEnumerator(); while (en.MoveNext()) { caseTable.Add(en.Key, en.Value); } _caseInsensitiveTable = caseTable; } return caseTable[name]; } } }
/** * CUETools.Flake: pure managed FLAC audio encoder * Copyright (c) 2009 Grigory Chudov * Based on Flake encoder, http://flake-enc.sourceforge.net/ * Copyright (c) 2006-2009 Justin Ruggles * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.Text; using System.IO; namespace CUETools.Codecs.FLAKE { [AudioDecoderClass("cuetools", "flac", 2)] public class FlakeReader: IAudioSource { int[] samplesBuffer; int[] residualBuffer; byte[] _framesBuffer; int _framesBufferLength = 0, _framesBufferOffset = 0; long first_frame_offset; SeekPoint[] seek_table; Crc8 crc8; FlacFrame frame; BitReader framereader; AudioPCMConfig pcm; uint min_block_size = 0; uint max_block_size = 0; uint min_frame_size = 0; uint max_frame_size = 0; int _samplesInBuffer, _samplesBufferOffset; long _sampleCount = 0, _sampleOffset = 0; bool do_crc = true; string _path; Stream _IO; public bool DoCRC { get { return do_crc; } set { do_crc = value; } } public int[] Samples { get { return samplesBuffer; } } public FlakeReader(string path, Stream IO) { _path = path; _IO = IO != null ? IO : new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x10000); crc8 = new Crc8(); _framesBuffer = new byte[0x20000]; decode_metadata(); frame = new FlacFrame(PCM.ChannelCount); framereader = new BitReader(); //max_frame_size = 16 + ((Flake.MAX_BLOCKSIZE * PCM.BitsPerSample * PCM.ChannelCount + 1) + 7) >> 3); if (((int)max_frame_size * PCM.BitsPerSample * PCM.ChannelCount * 2 >> 3) > _framesBuffer.Length) { byte[] temp = _framesBuffer; _framesBuffer = new byte[((int)max_frame_size * PCM.BitsPerSample * PCM.ChannelCount * 2 >> 3)]; if (_framesBufferLength > 0) Array.Copy(temp, _framesBufferOffset, _framesBuffer, 0, _framesBufferLength); _framesBufferOffset = 0; } _samplesInBuffer = 0; if (PCM.BitsPerSample != 16 && PCM.BitsPerSample != 24) throw new Exception("invalid flac file"); samplesBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; residualBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; } public FlakeReader(AudioPCMConfig _pcm) { pcm = _pcm; crc8 = new Crc8(); samplesBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; residualBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; frame = new FlacFrame(PCM.ChannelCount); framereader = new BitReader(); } public void Close() { _IO.Close(); } public long Length { get { return _sampleCount; } } public long Remaining { get { return Length - Position; } } public long Position { get { return _sampleOffset - _samplesInBuffer; } set { if (value > _sampleCount) throw new Exception("seeking past end of stream"); if (value < Position || value > _sampleOffset) { if (seek_table != null && _IO.CanSeek) { int best_st = -1; for (int st = 0; st < seek_table.Length; st++) { if (seek_table[st].number <= value && (best_st == -1 || seek_table[st].number > seek_table[best_st].number)) best_st = st; } if (best_st != -1) { _framesBufferLength = 0; _samplesInBuffer = 0; _samplesBufferOffset = 0; _IO.Position = (long)seek_table[best_st].offset + first_frame_offset; _sampleOffset = seek_table[best_st].number; } } if (value < Position) throw new Exception("cannot seek backwards without seek table"); } while (value > _sampleOffset) { _samplesInBuffer = 0; _samplesBufferOffset = 0; fill_frames_buffer(); if (_framesBufferLength == 0) throw new Exception("seek failed"); int bytesDecoded = DecodeFrame(_framesBuffer, _framesBufferOffset, _framesBufferLength); _framesBufferLength -= bytesDecoded; _framesBufferOffset += bytesDecoded; _sampleOffset += _samplesInBuffer; }; int diff = _samplesInBuffer - (int)(_sampleOffset - value); _samplesInBuffer -= diff; _samplesBufferOffset += diff; } } public AudioPCMConfig PCM { get { return pcm; } } public string Path { get { return _path; } } unsafe void interlace(AudioBuffer buff, int offset, int count) { if (PCM.ChannelCount == 2) { fixed (int* src = &samplesBuffer[_samplesBufferOffset]) buff.Interlace(offset, src, src + Flake.MAX_BLOCKSIZE, count); } else { for (int ch = 0; ch < PCM.ChannelCount; ch++) fixed (int* res = &buff.Samples[offset, ch], src = &samplesBuffer[_samplesBufferOffset + ch * Flake.MAX_BLOCKSIZE]) { int* psrc = src; for (int i = 0; i < count; i++) res[i * PCM.ChannelCount] = *(psrc++); } } } public int Read(AudioBuffer buff, int maxLength) { buff.Prepare(this, maxLength); int offset = 0; int sampleCount = buff.Length; while (_samplesInBuffer < sampleCount) { if (_samplesInBuffer > 0) { interlace(buff, offset, _samplesInBuffer); sampleCount -= _samplesInBuffer; offset += _samplesInBuffer; _samplesInBuffer = 0; _samplesBufferOffset = 0; } fill_frames_buffer(); if (_framesBufferLength == 0) return buff.Length = offset; int bytesDecoded = DecodeFrame(_framesBuffer, _framesBufferOffset, _framesBufferLength); _framesBufferLength -= bytesDecoded; _framesBufferOffset += bytesDecoded; _samplesInBuffer -= _samplesBufferOffset; // can be set by Seek, otherwise zero _sampleOffset += _samplesInBuffer; } interlace(buff, offset, sampleCount); _samplesInBuffer -= sampleCount; _samplesBufferOffset += sampleCount; if (_samplesInBuffer == 0) _samplesBufferOffset = 0; return buff.Length = offset + sampleCount; } unsafe void fill_frames_buffer() { if (_framesBufferLength == 0) _framesBufferOffset = 0; else if (_framesBufferLength < _framesBuffer.Length / 2 && _framesBufferOffset >= _framesBuffer.Length / 2) { fixed (byte* buff = _framesBuffer) AudioSamples.MemCpy(buff, buff + _framesBufferOffset, _framesBufferLength); _framesBufferOffset = 0; } while (_framesBufferLength < _framesBuffer.Length / 2) { int read = _IO.Read(_framesBuffer, _framesBufferOffset + _framesBufferLength, _framesBuffer.Length - _framesBufferOffset - _framesBufferLength); _framesBufferLength += read; if (read == 0) break; } } unsafe void decode_frame_header(BitReader bitreader, FlacFrame frame) { int header_start = bitreader.Position; if (bitreader.readbits(15) != 0x7FFC) throw new Exception("invalid frame"); uint vbs = bitreader.readbit(); frame.bs_code0 = (int) bitreader.readbits(4); uint sr_code0 = bitreader.readbits(4); frame.ch_mode = (ChannelMode)bitreader.readbits(4); uint bps_code = bitreader.readbits(3); if (Flake.flac_bitdepths[bps_code] != PCM.BitsPerSample) throw new Exception("unsupported bps coding"); uint t1 = bitreader.readbit(); // == 0????? if (t1 != 0) throw new Exception("unsupported frame coding"); frame.frame_number = (int)bitreader.read_utf8(); // custom block size if (frame.bs_code0 == 6) { frame.bs_code1 = (int)bitreader.readbits(8); frame.blocksize = frame.bs_code1 + 1; } else if (frame.bs_code0 == 7) { frame.bs_code1 = (int)bitreader.readbits(16); frame.blocksize = frame.bs_code1 + 1; } else frame.blocksize = Flake.flac_blocksizes[frame.bs_code0]; // custom sample rate if (sr_code0 < 1 || sr_code0 > 11) { // sr_code0 == 12 -> sr == bitreader.readbits(8) * 1000; // sr_code0 == 13 -> sr == bitreader.readbits(16); // sr_code0 == 14 -> sr == bitreader.readbits(16) * 10; throw new Exception("invalid sample rate mode"); } int frame_channels = (int)frame.ch_mode + 1; if (frame_channels > 11) throw new Exception("invalid channel mode"); if (frame_channels == 2 || frame_channels > 8) // Mid/Left/Right Side Stereo frame_channels = 2; else frame.ch_mode = ChannelMode.NotStereo; if (frame_channels != PCM.ChannelCount) throw new Exception("invalid channel mode"); // CRC-8 of frame header byte crc = do_crc ? crc8.ComputeChecksum(bitreader.Buffer, header_start, bitreader.Position - header_start) : (byte)0; frame.crc8 = (byte)bitreader.readbits(8); if (do_crc && frame.crc8 != crc) throw new Exception("header crc mismatch"); } unsafe void decode_subframe_constant(BitReader bitreader, FlacFrame frame, int ch) { int obits = frame.subframes[ch].obits; frame.subframes[ch].best.residual[0] = bitreader.readbits_signed(obits); } unsafe void decode_subframe_verbatim(BitReader bitreader, FlacFrame frame, int ch) { int obits = frame.subframes[ch].obits; for (int i = 0; i < frame.blocksize; i++) frame.subframes[ch].best.residual[i] = bitreader.readbits_signed(obits); } unsafe void decode_residual(BitReader bitreader, FlacFrame frame, int ch) { // rice-encoded block // coding method frame.subframes[ch].best.rc.coding_method = (int)bitreader.readbits(2); // ????? == 0 if (frame.subframes[ch].best.rc.coding_method != 0 && frame.subframes[ch].best.rc.coding_method != 1) throw new Exception("unsupported residual coding"); // partition order frame.subframes[ch].best.rc.porder = (int)bitreader.readbits(4); if (frame.subframes[ch].best.rc.porder > 8) throw new Exception("invalid partition order"); int psize = frame.blocksize >> frame.subframes[ch].best.rc.porder; int res_cnt = psize - frame.subframes[ch].best.order; int rice_len = 4 + frame.subframes[ch].best.rc.coding_method; // residual int j = frame.subframes[ch].best.order; int* r = frame.subframes[ch].best.residual + j; for (int p = 0; p < (1 << frame.subframes[ch].best.rc.porder); p++) { if (p == 1) res_cnt = psize; int n = Math.Min(res_cnt, frame.blocksize - j); int k = frame.subframes[ch].best.rc.rparams[p] = (int)bitreader.readbits(rice_len); if (k == (1 << rice_len) - 1) { k = frame.subframes[ch].best.rc.esc_bps[p] = (int)bitreader.readbits(5); for (int i = n; i > 0; i--) *(r++) = bitreader.readbits_signed((int)k); } else { bitreader.read_rice_block(n, (int)k, r); r += n; } j += n; } } unsafe void decode_subframe_fixed(BitReader bitreader, FlacFrame frame, int ch) { // warm-up samples int obits = frame.subframes[ch].obits; for (int i = 0; i < frame.subframes[ch].best.order; i++) frame.subframes[ch].best.residual[i] = bitreader.readbits_signed(obits); // residual decode_residual(bitreader, frame, ch); } unsafe void decode_subframe_lpc(BitReader bitreader, FlacFrame frame, int ch) { // warm-up samples int obits = frame.subframes[ch].obits; for (int i = 0; i < frame.subframes[ch].best.order; i++) frame.subframes[ch].best.residual[i] = bitreader.readbits_signed(obits); // LPC coefficients frame.subframes[ch].best.cbits = (int)bitreader.readbits(4) + 1; // lpc_precision if (frame.subframes[ch].best.cbits >= 16) throw new Exception("cbits >= 16"); frame.subframes[ch].best.shift = bitreader.readbits_signed(5); if (frame.subframes[ch].best.shift < 0) throw new Exception("negative shift"); for (int i = 0; i < frame.subframes[ch].best.order; i++) frame.subframes[ch].best.coefs[i] = bitreader.readbits_signed(frame.subframes[ch].best.cbits); // residual decode_residual(bitreader, frame, ch); } unsafe void decode_subframes(BitReader bitreader, FlacFrame frame) { fixed (int *r = residualBuffer, s = samplesBuffer) for (int ch = 0; ch < PCM.ChannelCount; ch++) { // subframe header uint t1 = bitreader.readbit(); // ?????? == 0 if (t1 != 0) throw new Exception("unsupported subframe coding (ch == " + ch.ToString() + ")"); int type_code = (int)bitreader.readbits(6); frame.subframes[ch].wbits = (int)bitreader.readbit(); if (frame.subframes[ch].wbits != 0) frame.subframes[ch].wbits += (int)bitreader.read_unary(); frame.subframes[ch].obits = PCM.BitsPerSample - frame.subframes[ch].wbits; switch (frame.ch_mode) { case ChannelMode.MidSide: frame.subframes[ch].obits += ch; break; case ChannelMode.LeftSide: frame.subframes[ch].obits += ch; break; case ChannelMode.RightSide: frame.subframes[ch].obits += 1 - ch; break; } frame.subframes[ch].best.type = (SubframeType)type_code; frame.subframes[ch].best.order = 0; if ((type_code & (uint)SubframeType.LPC) != 0) { frame.subframes[ch].best.order = (type_code - (int)SubframeType.LPC) + 1; frame.subframes[ch].best.type = SubframeType.LPC; } else if ((type_code & (uint)SubframeType.Fixed) != 0) { frame.subframes[ch].best.order = (type_code - (int)SubframeType.Fixed); frame.subframes[ch].best.type = SubframeType.Fixed; } frame.subframes[ch].best.residual = r + ch * Flake.MAX_BLOCKSIZE; frame.subframes[ch].samples = s + ch * Flake.MAX_BLOCKSIZE; // subframe switch (frame.subframes[ch].best.type) { case SubframeType.Constant: decode_subframe_constant(bitreader, frame, ch); break; case SubframeType.Verbatim: decode_subframe_verbatim(bitreader, frame, ch); break; case SubframeType.Fixed: decode_subframe_fixed(bitreader, frame, ch); break; case SubframeType.LPC: decode_subframe_lpc(bitreader, frame, ch); break; default: throw new Exception("invalid subframe type"); } } } unsafe void restore_samples_fixed(FlacFrame frame, int ch) { FlacSubframeInfo sub = frame.subframes[ch]; AudioSamples.MemCpy(sub.samples, sub.best.residual, sub.best.order); int* data = sub.samples + sub.best.order; int* residual = sub.best.residual + sub.best.order; int data_len = frame.blocksize - sub.best.order; int s0, s1, s2; switch (sub.best.order) { case 0: AudioSamples.MemCpy(data, residual, data_len); break; case 1: s1 = data[-1]; for (int i = data_len; i > 0; i--) { s1 += *(residual++); *(data++) = s1; } //data[i] = residual[i] + data[i - 1]; break; case 2: s2 = data[-2]; s1 = data[-1]; for (int i = data_len; i > 0; i--) { s0 = *(residual++) + (s1 << 1) - s2; *(data++) = s0; s2 = s1; s1 = s0; } //data[i] = residual[i] + data[i - 1] * 2 - data[i - 2]; break; case 3: for (int i = 0; i < data_len; i++) data[i] = residual[i] + (((data[i - 1] - data[i - 2]) << 1) + (data[i - 1] - data[i - 2])) + data[i - 3]; break; case 4: for (int i = 0; i < data_len; i++) data[i] = residual[i] + ((data[i - 1] + data[i - 3]) << 2) - ((data[i - 2] << 2) + (data[i - 2] << 1)) - data[i - 4]; break; } } unsafe void restore_samples_lpc(FlacFrame frame, int ch) { FlacSubframeInfo sub = frame.subframes[ch]; ulong csum = 0; fixed (int* coefs = sub.best.coefs) { for (int i = sub.best.order; i > 0; i--) csum += (ulong)Math.Abs(coefs[i - 1]); if ((csum << sub.obits) >= 1UL << 32) lpc.decode_residual_long(sub.best.residual, sub.samples, frame.blocksize, sub.best.order, coefs, sub.best.shift); else lpc.decode_residual(sub.best.residual, sub.samples, frame.blocksize, sub.best.order, coefs, sub.best.shift); } } unsafe void restore_samples(FlacFrame frame) { for (int ch = 0; ch < PCM.ChannelCount; ch++) { switch (frame.subframes[ch].best.type) { case SubframeType.Constant: AudioSamples.MemSet(frame.subframes[ch].samples, frame.subframes[ch].best.residual[0], frame.blocksize); break; case SubframeType.Verbatim: AudioSamples.MemCpy(frame.subframes[ch].samples, frame.subframes[ch].best.residual, frame.blocksize); break; case SubframeType.Fixed: restore_samples_fixed(frame, ch); break; case SubframeType.LPC: restore_samples_lpc(frame, ch); break; } if (frame.subframes[ch].wbits != 0) { int* s = frame.subframes[ch].samples; int x = (int) frame.subframes[ch].wbits; for (int i = frame.blocksize; i > 0; i--) *(s++) <<= x; } } if (frame.ch_mode != ChannelMode.NotStereo) { int* l = frame.subframes[0].samples; int* r = frame.subframes[1].samples; switch (frame.ch_mode) { case ChannelMode.LeftRight: break; case ChannelMode.MidSide: for (int i = frame.blocksize; i > 0; i--) { int mid = *l; int side = *r; mid <<= 1; mid |= (side & 1); /* i.e. if 'side' is odd... */ *(l++) = (mid + side) >> 1; *(r++) = (mid - side) >> 1; } break; case ChannelMode.LeftSide: for (int i = frame.blocksize; i > 0; i--) { int _l = *(l++), _r = *r; *(r++) = _l - _r; } break; case ChannelMode.RightSide: for (int i = frame.blocksize; i > 0; i--) *(l++) += *(r++); break; } } } public unsafe int DecodeFrame(byte[] buffer, int pos, int len) { fixed (byte* buf = buffer) { framereader.Reset(buf, pos, len); decode_frame_header(framereader, frame); decode_subframes(framereader, frame); framereader.flush(); ushort crc_1 = framereader.get_crc16(); ushort crc_2 = framereader.read_ushort(); if (do_crc && crc_1 != crc_2) throw new Exception("frame crc mismatch"); restore_samples(frame); _samplesInBuffer = frame.blocksize; return framereader.Position - pos; } } bool skip_bytes(int bytes) { for (int j = 0; j < bytes; j++) if (0 == _IO.Read(_framesBuffer, 0, 1)) return false; return true; } unsafe void decode_metadata() { byte x; int i, id; //bool first = true; byte[] FLAC__STREAM_SYNC_STRING = new byte[] { (byte)'f', (byte)'L', (byte)'a', (byte)'C' }; byte[] ID3V2_TAG_ = new byte[] { (byte)'I', (byte)'D', (byte)'3' }; for (i = id = 0; i < 4; ) { if (_IO.Read(_framesBuffer, 0, 1) == 0) throw new Exception("FLAC stream not found"); x = _framesBuffer[0]; if (x == FLAC__STREAM_SYNC_STRING[i]) { //first = true; i++; id = 0; continue; } if (id < 3 && x == ID3V2_TAG_[id]) { id++; i = 0; if (id == 3) { if (!skip_bytes(3)) throw new Exception("FLAC stream not found"); int skip = 0; for (int j = 0; j < 4; j++) { if (0 == _IO.Read(_framesBuffer, 0, 1)) throw new Exception("FLAC stream not found"); skip <<= 7; skip |= ((int)_framesBuffer[0] & 0x7f); } if (!skip_bytes(skip)) throw new Exception("FLAC stream not found"); } continue; } id = 0; if (x == 0xff) /* MAGIC NUMBER for the first 8 frame sync bits */ { do { if (_IO.Read(_framesBuffer, 0, 1) == 0) throw new Exception("FLAC stream not found"); x = _framesBuffer[0]; } while (x == 0xff); if (x >> 2 == 0x3e) /* MAGIC NUMBER for the last 6 sync bits */ { //_IO.Position -= 2; // state = frame throw new Exception("headerless file unsupported"); } } throw new Exception("FLAC stream not found"); } do { fill_frames_buffer(); fixed (byte* buf = _framesBuffer) { BitReader bitreader = new BitReader(buf, _framesBufferOffset, _framesBufferLength - _framesBufferOffset); bool is_last = bitreader.readbit() != 0; MetadataType type = (MetadataType)bitreader.readbits(7); int len = (int)bitreader.readbits(24); if (type == MetadataType.StreamInfo) { const int FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */ const int FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */ min_block_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN); max_block_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN); min_frame_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN); max_frame_size = bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN); int sample_rate = (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN); int channels = 1 + (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN); int bits_per_sample = 1 + (int)bitreader.readbits(FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN); pcm = new AudioPCMConfig(bits_per_sample, channels, sample_rate); _sampleCount = (long)bitreader.readbits64(FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN); bitreader.skipbits(FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN); } else if (type == MetadataType.Seektable) { int num_entries = len / 18; seek_table = new SeekPoint[num_entries]; for (int e = 0; e < num_entries; e++) { seek_table[e].number = bitreader.read_long(); seek_table[e].offset = bitreader.read_long(); seek_table[e].framesize = (int)bitreader.read_ushort(); } } if (_framesBufferLength < 4 + len) { _IO.Position += 4 + len - _framesBufferLength; _framesBufferLength = 0; } else { _framesBufferLength -= 4 + len; _framesBufferOffset += 4 + len; } if (is_last) break; } } while (true); first_frame_offset = _IO.Position - _framesBufferLength; } } }
using Signum.Entities.Authorization; using Signum.React.Facades; using Signum.React.Json; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Signum.Entities; using Signum.Utilities.Reflection; using Signum.Services; using Signum.Engine.Authorization; using Signum.React.Maps; using Microsoft.AspNetCore.Builder; using Signum.React.ApiControllers; using Signum.Engine; using Signum.Engine.Maps; namespace Signum.React.Authorization { public static class AuthServer { public static bool MergeInvalidUsernameAndPasswordMessages = false; public static Action<ActionContext, UserEntity> UserPreLogin; public static Action<ActionContext, UserEntity> UserLogged; public static Action<ActionContext, UserEntity> UserLoggingOut; public static void Start(IApplicationBuilder app, Func<AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey) { SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod()); AuthTokenServer.Start(tokenConfig, hashableEncryptionKey); ReflectionServer.GetContext = () => new { Culture = ReflectionServer.GetCurrentValidCulture(), Role = UserEntity.Current == null ? null : RoleEntity.Current, }; AuthLogic.OnRulesChanged += () => ReflectionServer.cache.Clear(); if (TypeAuthLogic.IsStarted) { ReflectionServer.TypeExtension += (ti, t) => { if (typeof(Entity).IsAssignableFrom(t)) { if (UserEntity.Current == null) return null; var ta = TypeAuthLogic.GetAllowed(t); if (ta.MaxUI() == TypeAllowedBasic.None) return null; ti.Extension.Add("maxTypeAllowed", ta.MaxUI()); ti.Extension.Add("minTypeAllowed", ta.MinUI()); ti.RequiresEntityPack |= ta.Conditions.Any(); return ti; } else { if (t.HasAttribute<AllowUnathenticatedAttribute>()) return ti; if (UserEntity.Current == null) return null; if (!AuthServer.IsNamespaceAllowed(t)) return null; return ti; } }; EntityPackTS.AddExtension += ep => { var typeAllowed = UserEntity.Current == null ? TypeAllowedBasic.None : ep.entity.IsNew ? TypeAuthLogic.GetAllowed(ep.entity.GetType()).MaxUI() : TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Write, true) ? TypeAllowedBasic.Write : TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Read, true) ? TypeAllowedBasic.Read : TypeAllowedBasic.None; ep.extension.Add("typeAllowed", typeAllowed); }; OperationController.AnyReadonly += (Lite<Entity>[] lites) => { return lites.GroupBy(ap => ap.EntityType).Any(gr => { var ta = TypeAuthLogic.GetAllowed(gr.Key); if (ta.Min(inUserInterface: true) == TypeAllowedBasic.Write) return false; if (ta.Max(inUserInterface: true) <= TypeAllowedBasic.Read) return true; return giCountReadonly.GetInvoker(gr.Key)() > 0; }); }; } if (QueryAuthLogic.IsStarted) { ReflectionServer.TypeExtension += (ti, t) => { if (ti.QueryDefined) { var allowed = UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(t); if (allowed == QueryAllowed.None) ti.QueryDefined = false; ti.Extension.Add("queryAllowed", allowed); } return ti; }; ReflectionServer.FieldInfoExtension += (mi, fi) => { if (fi.DeclaringType!.Name.EndsWith("Query")) { var allowed = UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(fi.GetValue(null)!); if (allowed == QueryAllowed.None) return null; mi.Extension.Add("queryAllowed", allowed); } return mi; }; } if (PropertyAuthLogic.IsStarted) { ReflectionServer.PropertyRouteExtension += (mi, pr) => { var allowed = UserEntity.Current == null ? pr.GetAllowUnathenticated() : pr.GetPropertyAllowed(); if (allowed == PropertyAllowed.None) return null; mi.Extension.Add("propertyAllowed", allowed); return mi; }; EntityJsonConverter.CanReadPropertyRoute += (pr, mod) => { var allowed = UserEntity.Current == null ? pr.GetAllowUnathenticated() : pr.GetPropertyAllowed(); return allowed == PropertyAllowed.None ? "Not allowed" : null; }; EntityJsonConverter.CanWritePropertyRoute += (pr, mod) => { var allowed = UserEntity.Current == null ? pr.GetAllowUnathenticated() : pr.GetPropertyAllowed(); return allowed == PropertyAllowed.Write ? null : "Not allowed to write property: " + pr.ToString(); }; } if (OperationAuthLogic.IsStarted) { ReflectionServer.OperationExtension += (oits, oi, type) => { var allowed = UserEntity.Current == null ? false : OperationAuthLogic.GetOperationAllowed(oi.OperationSymbol, type, inUserInterface: true); if (!allowed) return null; return oits; }; } if (PermissionAuthLogic.IsStarted) { ReflectionServer.FieldInfoExtension += (mi, fi) => { if (fi.FieldType == typeof(PermissionSymbol)) { var allowed = UserEntity.Current == null ? false : PermissionAuthLogic.IsAuthorized((PermissionSymbol)fi.GetValue(null)!); if (allowed == false) return null; } return mi; }; } var piPasswordHash = ReflectionTools.GetPropertyInfo((UserEntity e) => e.PasswordHash); var pcs = PropertyConverter.GetPropertyConverters(typeof(UserEntity)); pcs.GetOrThrow("passwordHash").CustomWriteJsonProperty = ctx => { }; pcs.Add("newPassword", new PropertyConverter { AvoidValidate = true, CustomWriteJsonProperty = ctx => { }, CustomReadJsonProperty = ctx => { EntityJsonConverter.AssertCanWrite(ctx.ParentPropertyRoute.Add(piPasswordHash), ctx.Entity); var password = (string)ctx.JsonReader.Value!; var error = UserEntity.OnValidatePassword(password); if (error != null) throw new ApplicationException(error); ((UserEntity)ctx.Entity).PasswordHash = Security.EncodePassword(password); } }); if (TypeAuthLogic.IsStarted) Omnibox.OmniboxServer.IsNavigable += type => TypeAuthLogic.GetAllowed(type).MaxUI() >= TypeAllowedBasic.Read; if (SessionLogLogic.IsStarted) AuthServer.UserLogged += (ActionContext ac, UserEntity user) => { Microsoft.AspNetCore.Http.HttpRequest re = ac.HttpContext.Request; SessionLogLogic.SessionStart( re.Host.ToString(), re.Headers["User-Agent"].FirstOrDefault()); }; SchemaMap.GetColorProviders += GetMapColors; } public static ResetLazy<Dictionary<string, List<Type>>> entitiesByNamespace = new ResetLazy<Dictionary<string, List<Type>>>(() => Schema.Current.Tables.Keys.Where(t => !EnumEntity.IsEnumEntity(t)).GroupToDictionary(t => t.Namespace!)); public static bool IsNamespaceAllowed(Type type) { var func = ReflectionServer.OverrideIsNamespaceAllowed.TryGetC(type.Namespace!); if (func != null) return func(); var typesInNamespace = entitiesByNamespace.Value.TryGetC(type.Namespace!); if (typesInNamespace != null) return typesInNamespace.Any(t => TypeAuthLogic.GetAllowed(t).MaxUI() > TypeAllowedBasic.None); throw new InvalidOperationException(@$"Unable to determine whether the metadata for '{type.FullName}' should be delivered to the client for role '{RoleEntity.Current}' because there are no entities in the namespace '{type.Namespace!}'."); } static GenericInvoker<Func<int>> giCountReadonly = new GenericInvoker<Func<int>>(() => CountReadonly<Entity>()); public static int CountReadonly<T>() where T : Entity { return Database.Query<T>().Count(a => !a.IsAllowedFor(TypeAllowedBasic.Write, true)); } public static void OnUserPreLogin(ActionContext ac, UserEntity user) { AuthServer.UserPreLogin?.Invoke(ac, user); } public static void AddUserSession(ActionContext ac, UserEntity user) { UserEntity.Current = user; AuthServer.UserLogged?.Invoke(ac, user); } static MapColorProvider[] GetMapColors() { if (!BasicPermission.AdminRules.IsAuthorized()) return new MapColorProvider[0]; var roleRules = AuthLogic.RolesInOrder().ToDictionary(r => r, r => TypeAuthLogic.GetTypeRules(r).Rules.ToDictionary(a => a.Resource.CleanName, a => a.Allowed)); return roleRules.Keys.Select((r, i) => new MapColorProvider { Name = "role-" + r.Key(), NiceName = "Role - " + r.ToString(), AddExtra = t => { TypeAllowedAndConditions? tac = roleRules[r].TryGetC(t.typeName); if (tac == null) return; t.extra["role-" + r.Key() + "-ui"] = GetName(ToStringList(tac, userInterface: true)); t.extra["role-" + r.Key() + "-db"] = GetName(ToStringList(tac, userInterface: false)); t.extra["role-" + r.Key() + "-tooltip"] = ToString(tac.Fallback) + "\n" + (tac.Conditions.IsNullOrEmpty() ? null : tac.Conditions.ToString(a => a.TypeCondition.NiceToString() + ": " + ToString(a.Allowed), "\n") + "\n"); }, Order = 10, }).ToArray(); } static string GetName(List<TypeAllowedBasic?> list) { return "auth-" + list.ToString(a => a == null ? "Error" : a.ToString(), "-"); } static List<TypeAllowedBasic?> ToStringList(TypeAllowedAndConditions tac, bool userInterface) { List<TypeAllowedBasic?> result = new List<TypeAllowedBasic?>(); result.Add(tac.Fallback == null ? (TypeAllowedBasic?)null : tac.Fallback.Value.Get(userInterface)); foreach (var c in tac.Conditions) result.Add(c.Allowed.Get(userInterface)); return result; } private static string ToString(TypeAllowed? typeAllowed) { if (typeAllowed == null) return "MERGE ERROR!"; if (typeAllowed.Value.GetDB() == typeAllowed.Value.GetUI()) return typeAllowed.Value.GetDB().NiceToString(); return "DB {0} / UI {1}".FormatWith(typeAllowed.Value.GetDB().NiceToString(), typeAllowed.Value.GetUI().NiceToString()); } } }
using OpenTK; using SageCS.Core.Loaders; using SageCS.INI; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace SageCS.Core { public class INIParser : StreamReader { public static Dictionary<string, string> macros = new Dictionary<string, string>(); private string[] data; private string line; private int index = 0; private int lineNumber = 0; public INIParser(Stream str) : base(str) { long filesize = str.Length; while (str.Position < filesize) { ParseLine(); string s = getString(); string name; switch (s) { case "#include": PrintError("include"); break; case "#define": macros.Add(getString().ToUpper(), getStrings()); break; case "GameData": //GameData data = new GameData(); //ParseObject(data); //INIManager.SetGameData(data); break; case "Object": //INI.Object.Parse(this, getString()); break; case "MappedImage": //MappedImage.Parse(this, getString()); break; case "Upgrade": //Upgrade.Parse(this, getString()); break; case "Weapon": //Weapon.Parse(this, getString()); break; case "ModifierList": ModifierList ml = new ModifierList(); name = getString(); ParseObject(ml); INIManager.AddModifierList(name, ml); break; case "Armor": Armor ar = new Armor(); name = getString(); ParseObject(ar); INIManager.AddArmor(name, ar); break; case "AmbientStream": AmbientStream ast = new AmbientStream(); name = getString(); ParseObject(ast); INIManager.AddAmbientStream(name, ast); break; case "CommandButton": CommandButton cb = new CommandButton(); name = getString(); ParseObject(cb); INIManager.AddCommandButton(name, cb); break; default: //PrintError("unhandled entry: " + data[0]); break; } } } private void ParseObject(object o) { string s; Dictionary<string, FieldInfo> fields = new Dictionary<string, FieldInfo>(); //get all class variables foreach (var prop in o.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { fields.Add(prop.Name, prop); } do { ParseLine(); s = getString(); if (s.Equals("Armor")) { ((Armor)o).AddType(getString(), getFloat()); } else if (s.Equals("Modifier")) { ((ModifierList)o).AddModifier(getString(), getFloat()); } else if (fields.ContainsKey(s)) { Type type = fields[s].FieldType; if (type == typeof(string)) fields[s].SetValue(o, getString()); else if (type == typeof(int)) fields[s].SetValue(o, getInt()); else if (type == typeof(float)) fields[s].SetValue(o, getFloat()); else if (type == typeof(float[])) fields[s].SetValue(o, getFloats()); else if (type == typeof(bool)) fields[s].SetValue(o, getBool()); else if (type == typeof(OpenTK.Vector2)) fields[s].SetValue(o, getVec2()); else if (type == typeof(OpenTK.Vector3)) fields[s].SetValue(o, getVec3()); else PrintError(" invalid type: " + type); } else { if (!s.Equals("End") && !s.Equals("END")) PrintError("invalid parameter in " + o.GetType() + " class: " + s); } } while (!s.Equals("End") && !s.Equals("END")); } public string[] ParseLine() { char[] separators = new char[] { ' ', '\t' }; line = base.ReadLine().Trim(); if (line.Contains(";")) line = line.Remove(line.IndexOf(";")); if (line.Contains("//")) line = line.Remove(line.IndexOf("//")); lineNumber++; data = line.Replace("=", "").Split(separators, StringSplitOptions.RemoveEmptyEntries); index = 0; //insert the values from the macros for (int i = 0; i < data.Length; i++) { //if the string contains a '_' it should be a macro -> cast to upper case if (macros.ContainsKey(data[i].ToUpper())) data[i] = macros[data[i].ToUpper()]; } for (int i = 0; i < data.Length; i++) { if (data[i].Equals("#MULTIPLY(")) data[i] = data[i + 1] + "*" + data[i + 2]; } if (data.Length != 0 && !data[0].StartsWith(";") && !data[0].StartsWith("//")) return data; return ParseLine(); } private bool HasNext() { return (index < data.Length); } public string getString() { if (!HasNext()) { PrintError("insufficient amount of values!!"); throw new IndexOutOfRangeException(); } return data[index++]; } public string getStrings() { string result = ""; while(HasNext()) { result += getString() + " "; } return result; } public int getInt() { int result; string s = getString(); s = s.Replace("%", ""); s = s.Replace("Left:", ""); s = s.Replace("Top:", ""); s = s.Replace("Right:", ""); s = s.Replace("Bottom:", ""); s = s.Replace("Min:", ""); s = s.Replace("Max:", ""); if (int.TryParse(s, out result)) return result; else { PrintError(s + " could not be parsed as integer value!!"); throw new FormatException(); } } public float getFloat() { float result; string s = getString(); s = s.Replace("%", ""); s = s.Replace("f", ""); s = s.Replace("X:", "").Replace("Y:", "").Replace("Z:", ""); s = s.Replace("R:", "").Replace("G:", "").Replace("B:", ""); s = s.Replace("MP1:", "").Replace("MP2:", "").Replace("MP3:", "").Replace("MP4:", "").Replace("MP5:", "").Replace("MP6:", "").Replace("MP7:", "").Replace("MP8:", ""); if (s.Contains("*")) { string[] vals = s.Split('*'); float one, two; if (float.TryParse(vals[0], out one) && float.TryParse(vals[1], out two)) return one * two; else PrintError(s + " could not be parsed as float value!!"); throw new FormatException(); } else if (float.TryParse(s, out result)) return result; else { PrintError(s + " could not be parsed as float value!!"); throw new FormatException(); } } public float[] getFloats() { List<float> f = new List<float>(); while(HasNext()) { f.Add(getFloat()); } return f.ToArray<float>(); } public bool getBool() { bool result; string s = getString(); s = s.Replace("Yes", "True"); s = s.Replace("No", "False"); if (bool.TryParse(s, out result)) return result; else { PrintError(s + " could not be parsed as boolean value!!"); throw new FormatException(); } } public Vector2 getVec2() { return new Vector2(getFloat(), getFloat()); } public Vector3 getVec3() { return new Vector3(getFloat(), getFloat(), getFloat()); } public void PrintError(string message) { Console.WriteLine("### INI ERROR ###"); Console.WriteLine("# in file: " + ((BigStream)this.BaseStream).Name); Console.WriteLine("# at line: " + lineNumber + " " + line); Console.WriteLine("# " + message); Console.WriteLine("#################"); Console.WriteLine(" "); } } }
// Lucene version compatibility level 4.8.1 using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Diagnostics; using Lucene.Net.Util; using System.Diagnostics; using System.Text.RegularExpressions; namespace Lucene.Net.Analysis.Pattern { /* * 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> /// CaptureGroup uses .NET regexes to emit multiple tokens - one for each capture /// group in one or more patterns. /// /// <para> /// For example, a pattern like: /// </para> /// /// <para> /// <c>"(https?://([a-zA-Z\-_0-9.]+))"</c> /// </para> /// /// <para> /// when matched against the string "http://www.foo.com/index" would return the /// tokens "https://www.foo.com" and "www.foo.com". /// </para> /// /// <para> /// If none of the patterns match, or if preserveOriginal is true, the original /// token will be preserved. /// </para> /// <para> /// Each pattern is matched as often as it can be, so the pattern /// <c> "(...)"</c>, when matched against <c>"abcdefghi"</c> would /// produce <c>["abc","def","ghi"]</c> /// </para> /// <para> /// A camelCaseFilter could be written as: /// </para> /// <para> /// <code> /// "([A-Z]{2,})", /// "(?&lt;![A-Z])([A-Z][a-z]+)", /// "(?:^|\\b|(?&lt;=[0-9_])|(?&lt;=[A-Z]{2}))([a-z]+)", /// "([0-9]+)" /// </code> /// </para> /// <para> /// plus if <see cref="preserveOriginal"/> is true, it would also return /// <c>camelCaseFilter</c> /// </para> /// </summary> public sealed class PatternCaptureGroupTokenFilter : TokenFilter { private readonly ICharTermAttribute charTermAttr; private readonly IPositionIncrementAttribute posAttr; private State state; private readonly Match[] matchers; private readonly Regex[] patterns; private readonly CharsRef spare = new CharsRef(); private readonly int[] groupCounts; private readonly bool preserveOriginal; private int[] currentGroup; private int currentMatcher; /// <summary> /// Creates a new <see cref="PatternCaptureGroupTokenFilter"/> /// </summary> /// <param name="input"> /// the input <see cref="TokenStream"/> </param> /// <param name="preserveOriginal"> /// set to true to return the original token even if one of the /// patterns matches </param> /// <param name="patterns"> /// an array of <see cref="Pattern"/> objects to match against each token </param> public PatternCaptureGroupTokenFilter(TokenStream input, bool preserveOriginal, params Regex[] patterns) : base(input) { this.preserveOriginal = preserveOriginal; this.matchers = new Match[patterns.Length]; this.groupCounts = new int[patterns.Length]; this.currentGroup = new int[patterns.Length]; this.patterns = patterns; for (int i = 0; i < patterns.Length; i++) { this.groupCounts[i] = patterns[i].GetGroupNumbers().Length; this.currentGroup[i] = -1; this.matchers[i] = null; // Reset to null so we can tell we are at the head of the chain } this.charTermAttr = AddAttribute<ICharTermAttribute>(); this.posAttr = AddAttribute<IPositionIncrementAttribute>(); } private bool NextCapture() { int min_offset = int.MaxValue; currentMatcher = -1; Match matcher; for (int i = 0; i < matchers.Length; i++) { if (currentGroup[i] == -1) { if (matchers[i] is null) matchers[i] = patterns[i].Match(new string(spare.Chars, spare.Offset, spare.Length)); else matchers[i] = matchers[i].NextMatch(); currentGroup[i] = matchers[i].Success ? 1 : 0; } matcher = matchers[i]; if (currentGroup[i] != 0) { while (currentGroup[i] < groupCounts[i] + 1) { int start = matcher.Groups[currentGroup[i]].Index; int end = matcher.Groups[currentGroup[i]].Index + matcher.Groups[currentGroup[i]].Length; if (start == end || preserveOriginal && start == 0 && spare.Length == end) { currentGroup[i]++; continue; } if (start < min_offset) { min_offset = start; currentMatcher = i; } break; } if (currentGroup[i] == groupCounts[i] + 1) { currentGroup[i] = -1; i--; } } } return currentMatcher != -1; } public override bool IncrementToken() { if (currentMatcher != -1 && NextCapture()) { if (Debugging.AssertsEnabled) Debugging.Assert(state != null); ClearAttributes(); RestoreState(state); int start = matchers[currentMatcher].Groups[currentGroup[currentMatcher]].Index; int end = matchers[currentMatcher].Groups[currentGroup[currentMatcher]].Index + matchers[currentMatcher].Groups[currentGroup[currentMatcher]].Length; posAttr.PositionIncrement = 0; charTermAttr.CopyBuffer(spare.Chars, start, end - start); currentGroup[currentMatcher]++; return true; } if (!m_input.IncrementToken()) { return false; } char[] buffer = charTermAttr.Buffer; int length = charTermAttr.Length; spare.CopyChars(buffer, 0, length); state = CaptureState(); for (int i = 0; i < matchers.Length; i++) { matchers[i] = null; currentGroup[i] = -1; } if (preserveOriginal) { currentMatcher = 0; } else if (NextCapture()) { int start = matchers[currentMatcher].Groups[currentGroup[currentMatcher]].Index; int end = matchers[currentMatcher].Groups[currentGroup[currentMatcher]].Index + matchers[currentMatcher].Groups[currentGroup[currentMatcher]].Length; // if we start at 0 we can simply set the length and save the copy if (start == 0) { charTermAttr.Length = end; } else { charTermAttr.CopyBuffer(spare.Chars, start, end - start); } currentGroup[currentMatcher]++; } return true; } public override void Reset() { base.Reset(); state = null; currentMatcher = -1; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime; using System.Xml; using System.Threading.Tasks; using System.Threading; namespace System.ServiceModel.Description { internal static class NamingHelper { internal const string DefaultNamespace = "http://tempuri.org/"; internal const string DefaultServiceName = "service"; internal const string MSNamespace = "http://schemas.microsoft.com/2005/07/ServiceModel"; // simplified rules for appending paths to base URIs. note that this differs from new Uri(baseUri, string) // 1) CombineUriStrings("http://foo/bar/z", "baz") ==> "http://foo/bar/z/baz" // 2) CombineUriStrings("http://foo/bar/z/", "baz") ==> "http://foo/bar/z/baz" // 3) CombineUriStrings("http://foo/bar/z", "/baz") ==> "http://foo/bar/z/baz" // 4) CombineUriStrings("http://foo/bar/z", "http://baz/q") ==> "http://baz/q" // 5) CombineUriStrings("http://foo/bar/z", "") ==> "" internal static string CombineUriStrings(string baseUri, string path) { if (Uri.IsWellFormedUriString(path, UriKind.Absolute) || path == String.Empty) { return path; } else { // combine if (baseUri.EndsWith("/", StringComparison.Ordinal)) { return baseUri + (path.StartsWith("/", StringComparison.Ordinal) ? path.Substring(1) : path); } else { return baseUri + (path.StartsWith("/", StringComparison.Ordinal) ? path : "/" + path); } } } internal static string TypeName(Type t) { Type[] args = null; if (t.GetTypeInfo().IsGenericType) { args = t.GetTypeInfo().GenericTypeArguments; } else if (t.GetTypeInfo().ContainsGenericParameters) { args = t.GetTypeInfo().GenericTypeParameters; } if (args != null) { int nameEnd = t.Name.IndexOf('`'); string result = nameEnd > 0 ? t.Name.Substring(0, nameEnd) : t.Name; result += "Of"; for (int i = 0; i < args.Length; ++i) { result = result + "_" + TypeName(args[i]); } return result; } else if (t.IsArray) { return "ArrayOf" + TypeName(t.GetElementType()); } else { return t.Name; } } // name, ns could have any combination of nulls internal static XmlQualifiedName GetContractName(Type contractType, string name, string ns) { XmlName xmlName = new XmlName(name ?? TypeName(contractType)); // ns can be empty if (ns == null) { ns = DefaultNamespace; } return new XmlQualifiedName(xmlName.EncodedName, ns); } // name could be null // logicalMethodName is MethodInfo.Name with Begin removed for async pattern // return encoded version to be used in OperationDescription internal static XmlName GetOperationName(string logicalMethodName, string name) { return new XmlName(String.IsNullOrEmpty(name) ? logicalMethodName : name); } internal static string GetMessageAction(OperationDescription operation, bool isResponse) { ContractDescription contract = operation.DeclaringContract; XmlQualifiedName contractQname = new XmlQualifiedName(contract.Name, contract.Namespace); return GetMessageAction(contractQname, operation.CodeName, null, isResponse); } // name could be null // logicalMethodName is MethodInfo.Name with Begin removed for async pattern internal static string GetMessageAction(XmlQualifiedName contractName, string opname, string action, bool isResponse) { if (action != null) { return action; } System.Text.StringBuilder actionBuilder = new System.Text.StringBuilder(64); if (String.IsNullOrEmpty(contractName.Namespace)) { actionBuilder.Append("urn:"); } else { actionBuilder.Append(contractName.Namespace); if (!contractName.Namespace.EndsWith("/", StringComparison.Ordinal)) { actionBuilder.Append('/'); } } actionBuilder.Append(contractName.Name); actionBuilder.Append('/'); action = isResponse ? opname + "Response" : opname; return CombineUriStrings(actionBuilder.ToString(), action); } internal delegate bool DoesNameExist(string name, object nameCollection); internal static string GetUniqueName(string baseName, DoesNameExist doesNameExist, object nameCollection) { for (int i = 0; i < Int32.MaxValue; i++) { string name = i > 0 ? baseName + i : baseName; if (!doesNameExist(name, nameCollection)) { return name; } } Fx.Assert("Too Many Names"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Cannot generate unique name for name {0}", baseName))); } internal static void CheckUriProperty(string ns, string propName) { Uri uri; if (!Uri.TryCreate(ns, UriKind.RelativeOrAbsolute, out uri)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.SFXUnvalidNamespaceValue, ns, propName)); } internal static void CheckUriParameter(string ns, string paramName) { Uri uri; if (!Uri.TryCreate(ns, UriKind.RelativeOrAbsolute, out uri)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(paramName, SR.Format(SR.SFXUnvalidNamespaceParam, ns)); } // Converts names that contain characters that are not permitted in XML names to valid names. internal static string XmlName(string name) { if (string.IsNullOrEmpty(name)) return name; if (IsAsciiLocalName(name)) return name; if (IsValidNCName(name)) return name; return XmlConvert.EncodeLocalName(name); } // Transforms an XML name into an object name. internal static string CodeName(string name) { return XmlConvert.DecodeName(name); } private static bool IsAlpha(char ch) { return (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z'); } private static bool IsDigit(char ch) { return (ch >= '0' && ch <= '9'); } private static bool IsAsciiLocalName(string localName) { Fx.Assert(null != localName, ""); if (!IsAlpha(localName[0])) return false; for (int i = 1; i < localName.Length; i++) { char ch = localName[i]; if (!IsAlpha(ch) && !IsDigit(ch)) return false; } return true; } internal static bool IsValidNCName(string name) { try { XmlConvert.VerifyNCName(name); return true; } catch (XmlException) { return false; } } } internal class XmlName { private string _decoded; private string _encoded; internal XmlName(string name) : this(name, false) { } internal XmlName(string name, bool isEncoded) { if (isEncoded) { ValidateEncodedName(name, true /*allowNull*/); _encoded = name; } else { _decoded = name; } } internal string EncodedName { get { if (_encoded == null) _encoded = NamingHelper.XmlName(_decoded); return _encoded; } } internal string DecodedName { get { if (_decoded == null) _decoded = NamingHelper.CodeName(_encoded); return _decoded; } } private static void ValidateEncodedName(string name, bool allowNull) { if (allowNull && name == null) return; try { XmlConvert.VerifyNCName(name); } catch (XmlException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(e.Message, "name")); } } private bool IsEmpty { get { return string.IsNullOrEmpty(_encoded) && string.IsNullOrEmpty(_decoded); } } internal static bool IsNullOrEmpty(XmlName xmlName) { return xmlName == null || xmlName.IsEmpty; } private bool Matches(XmlName xmlName) { return string.Equals(this.EncodedName, xmlName.EncodedName, StringComparison.Ordinal); } public override bool Equals(object obj) { if (object.ReferenceEquals(obj, this)) { return true; } if (object.ReferenceEquals(obj, null)) { return false; } XmlName xmlName = obj as XmlName; if (xmlName == null) { return false; } return Matches(xmlName); } public override int GetHashCode() { if (string.IsNullOrEmpty(EncodedName)) return 0; return EncodedName.GetHashCode(); } public override string ToString() { if (_encoded == null && _decoded == null) return null; if (_encoded != null) return _encoded; return _decoded; } public static bool operator ==(XmlName a, XmlName b) { if (object.ReferenceEquals(a, null)) { return object.ReferenceEquals(b, null); } return (a.Equals(b)); } public static bool operator !=(XmlName a, XmlName b) { return !(a == b); } } static internal class ServiceReflector { internal const string BeginMethodNamePrefix = "Begin"; internal const string EndMethodNamePrefix = "End"; internal static readonly Type VoidType = typeof(void); internal const string AsyncMethodNameSuffix = "Async"; internal static readonly Type taskType = typeof(Task); internal static readonly Type taskTResultType = typeof(Task<>); internal static readonly Type CancellationTokenType = typeof(CancellationToken); internal static readonly Type IProgressType = typeof(IProgress<>); private static readonly Type s_asyncCallbackType = typeof(AsyncCallback); private static readonly Type s_asyncResultType = typeof(IAsyncResult); private static readonly Type s_objectType = typeof(object); private static readonly Type s_OperationContractAttributeType = typeof(OperationContractAttribute); static internal Type GetOperationContractProviderType(MethodInfo method) { if (GetSingleAttribute<OperationContractAttribute>(method) != null) { return s_OperationContractAttributeType; } IOperationContractAttributeProvider provider = GetFirstAttribute<IOperationContractAttributeProvider>(method); if (provider != null) { return provider.GetType(); } return null; } // returns the set of root interfaces for the service class (meaning doesn't include callback ifaces) static internal List<Type> GetInterfaces(Type service) { List<Type> types = new List<Type>(); bool implicitContract = false; if (service.IsDefined(typeof(ServiceContractAttribute), false)) { implicitContract = true; types.Add(service); } if (!implicitContract) { Type t = GetAncestorImplicitContractClass(service); if (t != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxContractInheritanceRequiresInterfaces2, service, t))); } foreach (MethodInfo method in GetMethodsInternal(service)) { Type operationContractProviderType = GetOperationContractProviderType(method); if (operationContractProviderType == s_OperationContractAttributeType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ServicesWithoutAServiceContractAttributeCan2, operationContractProviderType.Name, method.Name, service.FullName))); } } } foreach (Type t in service.GetInterfaces()) { if (t.IsDefined(typeof(ServiceContractAttribute), false)) { if (implicitContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxContractInheritanceRequiresInterfaces, service, t))); } types.Add(t); } } return types; } private static Type GetAncestorImplicitContractClass(Type service) { for (service = service.BaseType(); service != null; service = service.BaseType()) { if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(service) != null) { return service; } } return null; } static internal List<Type> GetInheritedContractTypes(Type service) { List<Type> types = new List<Type>(); foreach (Type t in service.GetInterfaces()) { if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(t) != null) { types.Add(t); } } for (service = service.BaseType(); service != null; service = service.BaseType()) { if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(service) != null) { types.Add(service); } } return types; } static internal object[] GetCustomAttributes(CustomAttributeProvider attrProvider, Type attrType) { return GetCustomAttributes(attrProvider, attrType, false); } static internal object[] GetCustomAttributes(CustomAttributeProvider attrProvider, Type attrType, bool inherit) { try { if (typeof(Attribute).IsAssignableFrom(attrType)) { return attrProvider.GetCustomAttributes(attrType, inherit); } else { List<object> attrTypeAttributes = new List<object>(); object[] allCustomAttributes = attrProvider.GetCustomAttributes(inherit); foreach (object customAttribute in allCustomAttributes) { if (attrType.IsAssignableFrom(customAttribute.GetType())) { attrTypeAttributes.Add(customAttribute); } } return attrTypeAttributes.ToArray(); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } Type type = attrProvider.Type; MethodInfo method = attrProvider.MethodInfo; ParameterInfo param = attrProvider.ParameterInfo; // there is no good way to know if this is a return type attribute if (type != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxErrorReflectingOnType2, attrType.Name, type.Name), e)); } else if (method != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxErrorReflectingOnMethod3, attrType.Name, method.Name, method.DeclaringType.Name), e)); } else if (param != null) { method = param.Member as MethodInfo; if (method != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxErrorReflectingOnParameter4, attrType.Name, param.Name, method.Name, method.DeclaringType.Name), e)); } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxErrorReflectionOnUnknown1, attrType.Name), e)); } } static internal T GetFirstAttribute<T>(CustomAttributeProvider attrProvider) where T : class { Type attrType = typeof(T); object[] attrs = GetCustomAttributes(attrProvider, attrType); if (attrs.Length == 0) { return null; } else { return attrs[0] as T; } } static internal T GetSingleAttribute<T>(CustomAttributeProvider attrProvider) where T : class { Type attrType = typeof(T); object[] attrs = GetCustomAttributes(attrProvider, attrType); if (attrs.Length == 0) { return null; } else if (attrs.Length > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.tooManyAttributesOfTypeOn2, attrType, attrProvider.ToString()))); } else { return attrs[0] as T; } } static internal T GetRequiredSingleAttribute<T>(CustomAttributeProvider attrProvider) where T : class { T result = GetSingleAttribute<T>(attrProvider); if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.couldnTFindRequiredAttributeOfTypeOn2, typeof(T), attrProvider.ToString()))); } return result; } static internal T GetSingleAttribute<T>(CustomAttributeProvider attrProvider, Type[] attrTypeGroup) where T : class { T result = GetSingleAttribute<T>(attrProvider); if (result != null) { Type attrType = typeof(T); foreach (Type otherType in attrTypeGroup) { if (otherType == attrType) { continue; } object[] attrs = GetCustomAttributes(attrProvider, otherType); if (attrs != null && attrs.Length > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxDisallowedAttributeCombination, attrProvider, attrType.FullName, otherType.FullName))); } } } return result; } static internal T GetRequiredSingleAttribute<T>(CustomAttributeProvider attrProvider, Type[] attrTypeGroup) where T : class { T result = GetSingleAttribute<T>(attrProvider, attrTypeGroup); if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.couldnTFindRequiredAttributeOfTypeOn2, typeof(T), attrProvider.ToString()))); } return result; } static internal Type GetContractType(Type interfaceType) { ServiceContractAttribute contractAttribute; return GetContractTypeAndAttribute(interfaceType, out contractAttribute); } static internal Type GetContractTypeAndAttribute(Type interfaceType, out ServiceContractAttribute contractAttribute) { contractAttribute = GetSingleAttribute<ServiceContractAttribute>(interfaceType); if (contractAttribute != null) { return interfaceType; } List<Type> types = new List<Type>(GetInheritedContractTypes(interfaceType)); if (types.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.AttemptedToGetContractTypeForButThatTypeIs1, interfaceType.Name))); } foreach (Type potentialContractRoot in types) { bool mayBeTheRoot = true; foreach (Type t in types) { if (!t.IsAssignableFrom(potentialContractRoot)) { mayBeTheRoot = false; } } if (mayBeTheRoot) { contractAttribute = GetSingleAttribute<ServiceContractAttribute>(potentialContractRoot); return potentialContractRoot; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxNoMostDerivedContract, interfaceType.Name))); } private static List<MethodInfo> GetMethodsInternal(Type interfaceType) { List<MethodInfo> methods = new List<MethodInfo>(); foreach (MethodInfo mi in interfaceType.GetRuntimeMethods().Where(m => !m.IsStatic)) { if (GetSingleAttribute<OperationContractAttribute>(mi) != null) { methods.Add(mi); } else if (GetFirstAttribute<IOperationContractAttributeProvider>(mi) != null) { methods.Add(mi); } } return methods; } // The metadata for "in" versus "out" seems to be inconsistent, depending upon what compiler generates it. // The following code assumes this is the truth table that all compilers will obey: // // True Parameter Type .IsIn .IsOut .ParameterType.IsByRef // // in F F F ...OR... // in T F F // // in/out T T T ...OR... // in/out F F T // // out F T T static internal void ValidateParameterMetadata(MethodInfo methodInfo) { ParameterInfo[] parameters = methodInfo.GetParameters(); foreach (ParameterInfo parameter in parameters) { if (!parameter.ParameterType.IsByRef) { if (parameter.IsOut) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.Format(SR.SFxBadByValueParameterMetadata, methodInfo.Name, methodInfo.DeclaringType.Name))); } } else { if (parameter.IsIn && !parameter.IsOut) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.Format(SR.SFxBadByReferenceParameterMetadata, methodInfo.Name, methodInfo.DeclaringType.Name))); } } } } static internal bool FlowsIn(ParameterInfo paramInfo) // conceptually both "in" and "in/out" params return true { return !paramInfo.IsOut || paramInfo.IsIn; } static internal bool FlowsOut(ParameterInfo paramInfo) // conceptually both "out" and "in/out" params return true { return paramInfo.ParameterType.IsByRef; } // for async method is the begin method static internal ParameterInfo[] GetInputParameters(MethodInfo method, bool asyncPattern) { int count = 0; ParameterInfo[] parameters = method.GetParameters(); // length of parameters we care about (-2 for async) int len = parameters.Length; if (asyncPattern) { len -= 2; } // count the ins for (int i = 0; i < len; i++) { if (FlowsIn(parameters[i])) { count++; } } // grab the ins ParameterInfo[] result = new ParameterInfo[count]; int pos = 0; for (int i = 0; i < len; i++) { ParameterInfo param = parameters[i]; if (FlowsIn(param)) { result[pos++] = param; } } return result; } // for async method is the end method static internal ParameterInfo[] GetOutputParameters(MethodInfo method, bool asyncPattern) { int count = 0; ParameterInfo[] parameters = method.GetParameters(); // length of parameters we care about (-1 for async) int len = parameters.Length; if (asyncPattern) { len -= 1; } // count the outs for (int i = 0; i < len; i++) { if (FlowsOut(parameters[i])) { count++; } } // grab the outs ParameterInfo[] result = new ParameterInfo[count]; int pos = 0; for (int i = 0; i < len; i++) { ParameterInfo param = parameters[i]; if (FlowsOut(param)) { result[pos++] = param; } } return result; } static internal bool HasOutputParameters(MethodInfo method, bool asyncPattern) { ParameterInfo[] parameters = method.GetParameters(); // length of parameters we care about (-1 for async) int len = parameters.Length; if (asyncPattern) { len -= 1; } // count the outs for (int i = 0; i < len; i++) { if (FlowsOut(parameters[i])) { return true; } } return false; } private static MethodInfo GetEndMethodInternal(MethodInfo beginMethod) { string logicalName = GetLogicalName(beginMethod); string endMethodName = EndMethodNamePrefix + logicalName; MethodInfo[] endMethods = beginMethod.DeclaringType.GetTypeInfo().GetDeclaredMethods(endMethodName).ToArray(); if (endMethods.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.NoEndMethodFoundForAsyncBeginMethod3, beginMethod.Name, beginMethod.DeclaringType.FullName, endMethodName))); } if (endMethods.Length > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.MoreThanOneEndMethodFoundForAsyncBeginMethod3, beginMethod.Name, beginMethod.DeclaringType.FullName, endMethodName))); } return (MethodInfo)endMethods[0]; } static internal MethodInfo GetEndMethod(MethodInfo beginMethod) { MethodInfo endMethod = GetEndMethodInternal(beginMethod); if (!HasEndMethodShape(endMethod)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidAsyncEndMethodSignatureForMethod2, endMethod.Name, endMethod.DeclaringType.FullName))); } return endMethod; } static internal XmlName GetOperationName(MethodInfo method) { OperationContractAttribute operationAttribute = GetOperationContractAttribute(method); return NamingHelper.GetOperationName(GetLogicalName(method), operationAttribute.Name); } static internal bool HasBeginMethodShape(MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); if (!method.Name.StartsWith(BeginMethodNamePrefix, StringComparison.Ordinal) || parameters.Length < 2 || parameters[parameters.Length - 2].ParameterType != s_asyncCallbackType || parameters[parameters.Length - 1].ParameterType != s_objectType || method.ReturnType != s_asyncResultType) { return false; } return true; } static internal bool IsBegin(OperationContractAttribute opSettings, MethodInfo method) { if (opSettings.AsyncPattern) { if (!HasBeginMethodShape(method)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidAsyncBeginMethodSignatureForMethod2, method.Name, method.DeclaringType.FullName))); } return true; } return false; } static internal bool IsTask(MethodInfo method) { if (method.ReturnType == taskType) { return true; } if (method.ReturnType.IsGenericType() && method.ReturnType.GetGenericTypeDefinition() == taskTResultType) { return true; } return false; } static internal bool IsTask(MethodInfo method, out Type taskTResult) { taskTResult = null; Type methodReturnType = method.ReturnType; if (methodReturnType == taskType) { taskTResult = VoidType; return true; } if (methodReturnType.IsGenericType() && methodReturnType.GetGenericTypeDefinition() == taskTResultType) { taskTResult = methodReturnType.GetGenericArguments()[0]; return true; } return false; } static internal bool HasEndMethodShape(MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); if (!method.Name.StartsWith(EndMethodNamePrefix, StringComparison.Ordinal) || parameters.Length < 1 || parameters[parameters.Length - 1].ParameterType != s_asyncResultType) { return false; } return true; } internal static OperationContractAttribute GetOperationContractAttribute(MethodInfo method) { OperationContractAttribute operationContractAttribute = GetSingleAttribute<OperationContractAttribute>(method); if (operationContractAttribute != null) { return operationContractAttribute; } IOperationContractAttributeProvider operationContractProvider = GetFirstAttribute<IOperationContractAttributeProvider>(method); if (operationContractProvider != null) { return operationContractProvider.GetOperationContractAttribute(); } return null; } static internal bool IsBegin(MethodInfo method) { OperationContractAttribute opSettings = GetOperationContractAttribute(method); if (opSettings == null) return false; return IsBegin(opSettings, method); } static internal string GetLogicalName(MethodInfo method) { bool isAsync = IsBegin(method); bool isTask = isAsync ? false : IsTask(method); return GetLogicalName(method, isAsync, isTask); } static internal string GetLogicalName(MethodInfo method, bool isAsync, bool isTask) { if (isAsync) { return method.Name.Substring(BeginMethodNamePrefix.Length); } else if (isTask && method.Name.EndsWith(AsyncMethodNameSuffix, StringComparison.Ordinal)) { return method.Name.Substring(0, method.Name.Length - AsyncMethodNameSuffix.Length); } else { return method.Name; } } static internal bool HasNoDisposableParameters(MethodInfo methodInfo) { foreach (ParameterInfo inputInfo in methodInfo.GetParameters()) { if (IsParameterDisposable(inputInfo.ParameterType)) { return false; } } if (methodInfo.ReturnParameter != null) { return (!IsParameterDisposable(methodInfo.ReturnParameter.ParameterType)); } return true; } static internal bool IsParameterDisposable(Type type) { return ((!type.IsSealed()) || typeof(IDisposable).IsAssignableFrom(type)); } } }
// 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.Collections.Generic; using System.Text; using Microsoft.Build.Tasks; using Microsoft.Build.Shared; using Microsoft.Build.UnitTests; using System.IO; using Microsoft.Build.Utilities; using FrameworkNameVersioning = System.Runtime.Versioning.FrameworkName; using Xunit; #if !RUNTIME_TYPE_NETCORE namespace Microsoft.Build.UnitTests { /// <summary> /// Tests for the task which gets the reference assembly paths for a given target framework version / moniker /// </summary> sealed public class GetReferenceAssmeblyPath_Tests { /// <summary> /// Test the case where there is a good target framework moniker passed in. /// </summary> [Fact] public void TestGeneralFrameworkMonikerGood() { string targetFrameworkMoniker = ".NetFramework, Version=v4.5"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Equal(ToolLocationHelper.GetPathToReferenceAssemblies(new FrameworkNameVersioning(targetFrameworkMoniker)).Count, returnedPaths.Length); Assert.Equal(0, engine.Errors); // "Expected the log to contain no errors" } /// <summary> /// Test the case where there is a good target framework moniker passed in. /// </summary> [Fact] public void TestGeneralFrameworkMonikerGoodWithRoot() { string tempDirectory = Path.Combine(Path.GetTempPath(), "TestGeneralFrameworkMonikerGoodWithRoot"); string framework41Directory = Path.Combine(tempDirectory, Path.Combine("MyFramework", "v4.1") + Path.DirectorySeparatorChar); string redistListDirectory = Path.Combine(framework41Directory, "RedistList"); string redistListFile = Path.Combine(redistListDirectory, "FrameworkList.xml"); try { Directory.CreateDirectory(framework41Directory); Directory.CreateDirectory(redistListDirectory); string redistListContents = "<FileList Redist='Microsoft-Windows-CLRCoreComp' Name='.NET Framework 4.1'>" + "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "</FileList >"; File.WriteAllText(redistListFile, redistListContents); string targetFrameworkMoniker = "MyFramework, Version=v4.1"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.RootPath = tempDirectory; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Single(returnedPaths); Assert.Equal(framework41Directory, returnedPaths[0]); Assert.Equal(0, engine.Log.Length); // "Expected the log to contain nothing" Assert.Equal(".NET Framework 4.1", displayName); } finally { if (Directory.Exists(framework41Directory)) { FileUtilities.DeleteWithoutTrailingBackslash(framework41Directory, true); } } } /// <summary> /// Test the case where there is a good target framework moniker passed in. /// </summary> [Fact] public void TestGeneralFrameworkMonikerGoodWithRootWithProfile() { string tempDirectory = Path.Combine(Path.GetTempPath(), "TestGeneralFrameworkMonikerGoodWithRootWithProfile"); string framework41Directory = Path.Combine(tempDirectory, Path.Combine("MyFramework", "v4.1", "Profile", "Client")); string redistListDirectory = Path.Combine(framework41Directory, "RedistList"); string redistListFile = Path.Combine(redistListDirectory, "FrameworkList.xml"); try { Directory.CreateDirectory(framework41Directory); Directory.CreateDirectory(redistListDirectory); string redistListContents = "<FileList Redist='Microsoft-Windows-CLRCoreComp' Name='.NET Framework 4.1 Client'>" + "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "</FileList >"; File.WriteAllText(redistListFile, redistListContents); FrameworkNameVersioning name = new FrameworkNameVersioning("MyFramework", new Version("4.1"), "Client"); string targetFrameworkMoniker = name.FullName; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.RootPath = tempDirectory; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Single(returnedPaths); Assert.Equal(framework41Directory + Path.DirectorySeparatorChar, returnedPaths[0]); Assert.Equal(".NET Framework 4.1 Client", displayName); } finally { if (Directory.Exists(framework41Directory)) { FileUtilities.DeleteWithoutTrailingBackslash(framework41Directory, true); } } } /// <summary> /// Test the case where the target framework moniker is null. Expect there to be an error logged. /// </summary> [Fact] public void TestGeneralFrameworkMonikerNull() { MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = null; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Null(getReferencePaths.TargetFrameworkMonikerDisplayName); Assert.Empty(returnedPaths); Assert.Equal(1, engine.Errors); } /// <summary> /// Test the case where the target framework moniker is empty. Expect there to be an error logged. /// </summary> [Fact] public void TestGeneralFrameworkMonikerNonExistent() { MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; // Make a framework which does not exist, intentional misspelling of framework getReferencePaths.TargetFrameworkMoniker = ".NetFramewok, Version=v99.0"; bool success = getReferencePaths.Execute(); Assert.False(success); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Empty(returnedPaths); string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Null(displayName); FrameworkNameVersioning frameworkMoniker = new FrameworkNameVersioning(getReferencePaths.TargetFrameworkMoniker); string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("GetReferenceAssemblyPaths.NoReferenceAssemblyDirectoryFound", frameworkMoniker.ToString()); engine.AssertLogContains("ERROR MSB3644: " + message); } [Fact] public void TestSuppressNotFoundError() { MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; // Make a framework which does not exist, intentional misspelling of framework getReferencePaths.TargetFrameworkMoniker = ".NetFramewok, Version=v99.0"; getReferencePaths.SuppressNotFoundError = true; bool success = getReferencePaths.Execute(); Assert.True(success); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Empty(returnedPaths); string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Null(displayName); Assert.Equal(0, engine.Errors); } /// <summary> /// Test the case where there is a good target framework moniker passed in. /// </summary> [Fact] public void TestGeneralFrameworkMonikerGoodWithInvalidIncludePath() { string tempDirectory = Path.Combine(Path.GetTempPath(), "TestGeneralFrameworkMonikerGoodWithInvalidIncludePath"); string framework41Directory = Path.Combine(tempDirectory, Path.Combine("MyFramework", "v4.1") + Path.DirectorySeparatorChar); string redistListDirectory = Path.Combine(framework41Directory, "RedistList"); string redistListFile = Path.Combine(redistListDirectory, "FrameworkList.xml"); try { Directory.CreateDirectory(framework41Directory); Directory.CreateDirectory(redistListDirectory); string redistListContents = "<FileList Redist='Microsoft-Windows-CLRCoreComp' IncludeFramework='..\\Mooses' Name='Chained oh noes'>" + "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "</FileList >"; File.WriteAllText(redistListFile, redistListContents); string targetFrameworkMoniker = "MyFramework, Version=v4.1"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.RootPath = tempDirectory; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Empty(returnedPaths); string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Null(displayName); FrameworkNameVersioning frameworkMoniker = new FrameworkNameVersioning(getReferencePaths.TargetFrameworkMoniker); string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("GetReferenceAssemblyPaths.NoReferenceAssemblyDirectoryFound", frameworkMoniker.ToString()); engine.AssertLogContains(message); } finally { if (Directory.Exists(framework41Directory)) { FileUtilities.DeleteWithoutTrailingBackslash(framework41Directory, true); } } } /// <summary> /// Test the case where there is a good target framework moniker passed in but there is a problem with the RedistList. /// </summary> [Fact] public void TestGeneralFrameworkMonikerGoodWithInvalidCharInIncludePath() { string tempDirectory = Path.Combine(Path.GetTempPath(), "TestGeneralFrameworkMonikerGoodWithInvalidCharInIncludePath"); string framework41Directory = Path.Combine(tempDirectory, Path.Combine("MyFramework", "v4.1") + Path.DirectorySeparatorChar); string redistListDirectory = Path.Combine(framework41Directory, "RedistList"); string redistListFile = Path.Combine(redistListDirectory, "FrameworkList.xml"); try { Directory.CreateDirectory(framework41Directory); Directory.CreateDirectory(redistListDirectory); string redistListContents = "<FileList Redist='Microsoft-Windows-CLRCoreComp' IncludeFramework='v4.*' Name='Chained oh noes'>" + "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "</FileList >"; File.WriteAllText(redistListFile, redistListContents); string targetFrameworkMoniker = "MyFramework, Version=v4.1"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.RootPath = tempDirectory; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Empty(returnedPaths); string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Null(displayName); FrameworkNameVersioning frameworkMoniker = new FrameworkNameVersioning(getReferencePaths.TargetFrameworkMoniker); if (NativeMethodsShared.IsWindows) { engine.AssertLogContains("MSB3643"); } else { // Since under Unix there are no invalid characters, we don't fail in the incorrect path // and go through to actually looking for the directory string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword( "GetReferenceAssemblyPaths.NoReferenceAssemblyDirectoryFound", frameworkMoniker.ToString()); engine.AssertLogContains(message); } } finally { if (Directory.Exists(framework41Directory)) { FileUtilities.DeleteWithoutTrailingBackslash(framework41Directory, true); } } } /// <summary> /// Test the case where there is a good target framework moniker passed in. /// </summary> [Fact] public void TestGeneralFrameworkMonikerGoodWithFrameworkInFallbackPaths() { using (var env = TestEnvironment.Create()) { string frameworkRootDir = Path.Combine(env.DefaultTestDirectory.Path, "framework-root"); var framework41Directory = env.CreateFolder(Path.Combine(frameworkRootDir, Path.Combine("MyFramework", "v4.1") + Path.DirectorySeparatorChar)); var redistListDirectory = env.CreateFolder(Path.Combine(framework41Directory.Path, "RedistList")); string redistListContents = "<FileList Redist='Microsoft-Windows-CLRCoreComp' Name='.NET Framework 4.1'>" + "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "</FileList >"; env.CreateFile(redistListDirectory, "FrameworkList.xml", redistListContents); string targetFrameworkMoniker = "MyFramework, Version=v4.1"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.RootPath = env.CreateFolder().Path; getReferencePaths.RootPath = frameworkRootDir; getReferencePaths.TargetFrameworkFallbackSearchPaths = $"/foo/bar;{frameworkRootDir}"; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Single(returnedPaths); Assert.Equal(framework41Directory.Path, returnedPaths[0]); Assert.Equal(0, engine.Log.Length); // "Expected the log to contain nothing" Assert.Equal(".NET Framework 4.1", displayName); } } } } #endif
#region File Description //----------------------------------------------------------------------------- // Projectile.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; #endregion namespace Spacewar { /// <summary> /// Represents a projectile in SpacewarGame - retro or evolved /// </summary> public class Projectile : SpacewarSceneItem { private static int[] projectileCount = new int[3]; /// <summary> /// Which player this projectile came from /// </summary> private PlayerIndex player; /// <summary> /// The damage that this bullet does /// </summary> private int damage; private double endTime; private int projectileType; private bool exploded = false; private Particles particles; private bool projectileArmed; private Vector3 thrust; #region Properties public static int[] ProjectileCount { get { return projectileCount; } } public int Damage { get { return damage; } } #endregion /// <summary> /// Cretes a new projectile /// </summary> /// <param name="game">Instance of the game</param> /// <param name="player">Which player it came from</param> /// <param name="position">The start position</param> /// <param name="velocity">The start velocity</param> /// <param name="angle">The direction its facing</param> /// <param name="time">The time the projectile was fired</param> public Projectile(Game game, PlayerIndex player, Vector3 position, Vector3 velocity, float angle, TimeSpan time, Particles particles) : base(game) { this.player = player; this.velocity = velocity; this.position = position; projectileCount[(int)player]++; if (SpacewarGame.GameState == GameState.PlayEvolved) { projectileType = (int)SpacewarGame.Players[(int)player].ProjectileType; this.particles = particles; endTime = time.TotalSeconds + SpacewarGame.Settings.Weapons[projectileType].Lifetime; thrust = Vector3.Multiply(Vector3.Normalize(velocity), SpacewarGame.Settings.Weapons[projectileType].Acceleration); radius = 2; damage = SpacewarGame.Settings.Weapons[projectileType].Damage; if (SpacewarGame.GameState == GameState.PlayEvolved) { shape = new BasicEffectShape(GameInstance, BasicEffectShapes.Projectile, projectileType, LightingType.InGame); //Evolved needs scaling scale.X = scale.Y = scale.Z = SpacewarGame.Settings.BulletScale; rotation.X = MathHelper.ToRadians(90); rotation.Y = 0; rotation.Z = (float)angle; } } else { //Build up a retro weapon damage = 5; //One shot kill projectileType = (int)ProjectileType.Peashooter; radius = 1; endTime = time.TotalSeconds + 2.0; acceleration = Vector3.Zero; } //Play 'shoot' sound switch (projectileType) { case (int)ProjectileType.Peashooter: Sound.PlayCue(Sounds.PeashooterFire); break; case (int)ProjectileType.MachineGun: Sound.PlayCue(Sounds.MachineGunFire); break; case (int)ProjectileType.DoubleMachineGun: Sound.PlayCue(Sounds.DoubleMachineGunFire); break; case (int)ProjectileType.Rocket: Sound.PlayCue(Sounds.RocketExplode); break; case (int)ProjectileType.BFG: Sound.PlayCue(Sounds.BFGFire); break; } } /// <summary> /// Updates the bullet. Removes it from scene when item is timed out /// </summary> /// <param name="time">Current game time</param> /// <param name="elapsedTime">Elapsed time since last update</param> public override void Update(TimeSpan time, TimeSpan elapsedTime) { //See if this bullets lifespan has expired if (time.TotalSeconds > endTime) { //BFG explodes and has a blast radius if (SpacewarGame.GameState == GameState.PlayEvolved && projectileType == 4 && !exploded) { Sound.PlayCue(Sounds.Explosion); particles.AddExplosion(Position); //We don't delete it this frame but we change the radius and the damage exploded = true; radius = 30; damage = 3; } else { DeleteProjectile(); } } acceleration = thrust; //For the rocket we need particles if (projectileType == 3) { particles.AddRocketTrail(shape.World, new Vector2(acceleration.X, -acceleration.Y)); } base.Update(time, elapsedTime); } public void DeleteProjectile() { if (!delete) projectileCount[(int)player]--; delete = true; } /// <summary> /// Checks if there is a collision between the this and the passed in item /// </summary> /// <param name="item">A scene item to check</param> /// <returns>True if there is a collision</returns> public override bool Collide(SceneItem item) { // Until we get collision meshes sorted just do a simple sphere (well circle!) check float currentDistance = (Position - item.Position).Length(); bool colliding = base.Collide(item); // For projectiles, do not allow them to destroy the ship that just fired them! Ship shipItem = item as Ship; if ((shipItem != null) && (shipItem.Player == player)) { if (colliding && !projectileArmed) { colliding = false; } else if (!colliding && !projectileArmed) { // Once projectile is at least 2 ship radii away, it can arm! // This is becuase the bolt launches with your velocity at the time // and the ship can "catch up" to the bolt pretty easily if you are // thrusting in the direction you are firing. if (currentDistance > item.Radius * 2.0f) projectileArmed = true; } } return colliding; } } }
// 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.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Data.SqlClient { sealed internal class SqlSequentialTextReader : System.IO.TextReader { private SqlDataReader _reader; // The SqlDataReader that we are reading data from private int _columnIndex; // The index of out column in the table private Encoding _encoding; // Encoding for this character stream private Decoder _decoder; // Decoder based on the encoding (NOTE: Decoders are stateful as they are designed to process streams of data) private byte[] _leftOverBytes; // Bytes leftover from the last Read() operation - this can be null if there were no bytes leftover (Possible optimization: re-use the same array?) private int _peekedChar; // The last character that we peeked at (or -1 if we haven't peeked at anything) private Task _currentTask; // The current async task private CancellationTokenSource _disposalTokenSource; // Used to indicate that a cancellation is requested due to disposal internal SqlSequentialTextReader(SqlDataReader reader, int columnIndex, Encoding encoding) { Debug.Assert(reader != null, "Null reader when creating sequential textreader"); Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential textreader"); Debug.Assert(encoding != null, "Null encoding when creating sequential textreader"); _reader = reader; _columnIndex = columnIndex; _encoding = encoding; _decoder = encoding.GetDecoder(); _leftOverBytes = null; _peekedChar = -1; _currentTask = null; _disposalTokenSource = new CancellationTokenSource(); } internal int ColumnIndex { get { return _columnIndex; } } public override int Peek() { if (_currentTask != null) { throw ADP.AsyncOperationPending(); } if (IsClosed) { throw ADP.ObjectDisposed(this); } if (!HasPeekedChar) { _peekedChar = Read(); } Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), string.Format("Bad peeked character: {0}", _peekedChar)); return _peekedChar; } public override int Read() { if (_currentTask != null) { throw ADP.AsyncOperationPending(); } if (IsClosed) { throw ADP.ObjectDisposed(this); } int readChar = -1; // If there is already a peeked char, then return it if (HasPeekedChar) { readChar = _peekedChar; _peekedChar = -1; } // If there is data available try to read a char else { char[] tempBuffer = new char[1]; int charsRead = InternalRead(tempBuffer, 0, 1); if (charsRead == 1) { readChar = tempBuffer[0]; } } Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), string.Format("Bad read character: {0}", readChar)); return readChar; } public override int Read(char[] buffer, int index, int count) { ValidateReadParameters(buffer, index, count); if (IsClosed) { throw ADP.ObjectDisposed(this); } if (_currentTask != null) { throw ADP.AsyncOperationPending(); } int charsRead = 0; int charsNeeded = count; // Load in peeked char if ((charsNeeded > 0) && (HasPeekedChar)) { Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar)); buffer[index + charsRead] = (char)_peekedChar; charsRead++; charsNeeded--; _peekedChar = -1; } // If we need more data and there is data available, read charsRead += InternalRead(buffer, index + charsRead, charsNeeded); return charsRead; } public override Task<int> ReadAsync(char[] buffer, int index, int count) { ValidateReadParameters(buffer, index, count); TaskCompletionSource<int> completion = new TaskCompletionSource<int>(); if (IsClosed) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } else { try { Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null); if (original != null) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending())); } else { bool completedSynchronously = true; int charsRead = 0; int adjustedIndex = index; int charsNeeded = count; // Load in peeked char if ((HasPeekedChar) && (charsNeeded > 0)) { // Take a copy of _peekedChar in case it is cleared during close int peekedChar = _peekedChar; if (peekedChar >= char.MinValue) { Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar)); buffer[adjustedIndex] = (char)peekedChar; adjustedIndex++; charsRead++; charsNeeded--; _peekedChar = -1; } } int byteBufferUsed; byte[] byteBuffer = PrepareByteBuffer(charsNeeded, out byteBufferUsed); // Permit a 0 byte read in order to advance the reader to the correct column if ((byteBufferUsed < byteBuffer.Length) || (byteBuffer.Length == 0)) { int bytesRead; var reader = _reader; if (reader != null) { Task<int> getBytesTask = reader.GetBytesAsync(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed, Timeout.Infinite, _disposalTokenSource.Token, out bytesRead); if (getBytesTask == null) { byteBufferUsed += bytesRead; } else { // We need more data - setup the callback, and mark this as not completed sync completedSynchronously = false; getBytesTask.ContinueWith((t) => { _currentTask = null; // If we completed but the textreader is closed, then report cancellation if ((t.Status == TaskStatus.RanToCompletion) && (!IsClosed)) { try { int bytesReadFromStream = t.Result; byteBufferUsed += bytesReadFromStream; if (byteBufferUsed > 0) { charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded); } completion.SetResult(charsRead); } catch (Exception ex) { completion.SetException(ex); } } else if (IsClosed) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } else if (t.Status == TaskStatus.Faulted) { if (t.Exception.InnerException is SqlException) { // ReadAsync can't throw a SqlException, so wrap it in an IOException completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException))); } else { completion.SetException(t.Exception.InnerException); } } else { completion.SetCanceled(); } }, TaskScheduler.Default); } if ((completedSynchronously) && (byteBufferUsed > 0)) { // No more data needed, decode what we have charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded); } } else { // Reader is null, close must of happened in the middle of this read completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } } if (completedSynchronously) { _currentTask = null; if (IsClosed) { completion.SetCanceled(); } else { completion.SetResult(charsRead); } } } } catch (Exception ex) { // In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it completion.TrySetException(ex); Interlocked.CompareExchange(ref _currentTask, null, completion.Task); throw; } } return completion.Task; } protected override void Dispose(bool disposing) { if (disposing) { // Set the textreader as closed SetClosed(); } base.Dispose(disposing); } /// <summary> /// Forces the TextReader to act as if it was closed /// This does not actually close the stream, read off the rest of the data or dispose this /// </summary> internal void SetClosed() { _disposalTokenSource.Cancel(); _reader = null; _peekedChar = -1; // Wait for pending task var currentTask = _currentTask; if (currentTask != null) { ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne(); } } /// <summary> /// Performs the actual reading and converting /// NOTE: This assumes that buffer, index and count are all valid, we're not closed (!IsClosed) and that there is data left (IsDataLeft()) /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> /// <returns></returns> private int InternalRead(char[] buffer, int index, int count) { Debug.Assert(buffer != null, "Null output buffer"); Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), string.Format("Bad count: {0} or index: {1}", count, index)); Debug.Assert(!IsClosed, "Can't read while textreader is closed"); try { int byteBufferUsed; byte[] byteBuffer = PrepareByteBuffer(count, out byteBufferUsed); byteBufferUsed += _reader.GetBytesInternalSequential(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed); if (byteBufferUsed > 0) { return DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, index, count); } else { // Nothing to read, or nothing read return 0; } } catch (SqlException ex) { // Read can't throw a SqlException - so wrap it in an IOException throw ADP.ErrorReadingFromStream(ex); } } /// <summary> /// Creates a byte array large enough to store all bytes for the characters in the current encoding, then fills it with any leftover bytes /// </summary> /// <param name="numberOfChars">Number of characters that are to be read</param> /// <param name="byteBufferUsed">Number of bytes pre-filled by the leftover bytes</param> /// <returns>A byte array of the correct size, pre-filled with leftover bytes</returns> private byte[] PrepareByteBuffer(int numberOfChars, out int byteBufferUsed) { Debug.Assert(numberOfChars >= 0, "Can't prepare a byte buffer for negative characters"); byte[] byteBuffer; if (numberOfChars == 0) { byteBuffer = new byte[0]; byteBufferUsed = 0; } else { int byteBufferSize = _encoding.GetMaxByteCount(numberOfChars); if (_leftOverBytes != null) { // If we have more leftover bytes than we need for this conversion, then just re-use the leftover buffer if (_leftOverBytes.Length > byteBufferSize) { byteBuffer = _leftOverBytes; byteBufferUsed = byteBuffer.Length; } else { // Otherwise, copy over the leftover buffer byteBuffer = new byte[byteBufferSize]; Buffer.BlockCopy(_leftOverBytes, 0, byteBuffer, 0, _leftOverBytes.Length); byteBufferUsed = _leftOverBytes.Length; } } else { byteBuffer = new byte[byteBufferSize]; byteBufferUsed = 0; } } return byteBuffer; } /// <summary> /// Decodes the given bytes into characters, and stores the leftover bytes for later use /// </summary> /// <param name="inBuffer">Buffer of bytes to decode</param> /// <param name="inBufferCount">Number of bytes to decode from the inBuffer</param> /// <param name="outBuffer">Buffer to write the characters to</param> /// <param name="outBufferOffset">Offset to start writing to outBuffer at</param> /// <param name="outBufferCount">Maximum number of characters to decode</param> /// <returns>The actual number of characters decoded</returns> private int DecodeBytesToChars(byte[] inBuffer, int inBufferCount, char[] outBuffer, int outBufferOffset, int outBufferCount) { Debug.Assert(inBuffer != null, "Null input buffer"); Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), string.Format("Bad inBufferCount: {0}", inBufferCount)); Debug.Assert(outBuffer != null, "Null output buffer"); Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), string.Format("Bad outBufferCount: {0} or outBufferOffset: {1}", outBufferCount, outBufferOffset)); int charsRead; int bytesUsed; bool completed; _decoder.Convert(inBuffer, 0, inBufferCount, outBuffer, outBufferOffset, outBufferCount, false, out bytesUsed, out charsRead, out completed); // completed may be false and there is no spare bytes if the Decoder has stored bytes to use later if ((!completed) && (bytesUsed < inBufferCount)) { _leftOverBytes = new byte[inBufferCount - bytesUsed]; Buffer.BlockCopy(inBuffer, bytesUsed, _leftOverBytes, 0, _leftOverBytes.Length); } else { // If Convert() sets completed to true, then it must have used all of the bytes we gave it Debug.Assert(bytesUsed >= inBufferCount, "Converted completed, but not all bytes were used"); _leftOverBytes = null; } Debug.Assert(((_reader == null) || (_reader.ColumnDataBytesRemaining() > 0) || (!completed) || (_leftOverBytes == null)), "Stream has run out of data and the decoder finished, but there are leftover bytes"); Debug.Assert(charsRead > 0, "Converted no chars. Bad encoding?"); return charsRead; } /// <summary> /// True if this TextReader is supposed to be closed /// </summary> private bool IsClosed { get { return (_reader == null); } } /// <summary> /// True if there is a peeked character available /// </summary> private bool HasPeekedChar { get { return (_peekedChar >= char.MinValue); } } /// <summary> /// Checks the parameters passed into a Read() method are valid /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> internal static void ValidateReadParameters(char[] buffer, int index, int count) { if (buffer == null) { throw ADP.ArgumentNull(nameof(buffer)); } if (index < 0) { throw ADP.ArgumentOutOfRange(nameof(index)); } if (count < 0) { throw ADP.ArgumentOutOfRange(nameof(count)); } try { if (checked(index + count) > buffer.Length) { throw ExceptionBuilder.InvalidOffsetLength(); } } catch (OverflowException) { // If we've overflowed when adding index and count, then they never would have fit into buffer anyway throw ExceptionBuilder.InvalidOffsetLength(); } } } sealed internal class SqlUnicodeEncoding : UnicodeEncoding { private static SqlUnicodeEncoding s_singletonEncoding = new SqlUnicodeEncoding(); private SqlUnicodeEncoding() : base(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false) { } public override Decoder GetDecoder() { return new SqlUnicodeDecoder(); } public override int GetMaxByteCount(int charCount) { // SQL Server never sends a BOM, so we can assume that its 2 bytes per char return charCount * 2; } public static Encoding SqlUnicodeEncodingInstance { get { return s_singletonEncoding; } } sealed private class SqlUnicodeDecoder : Decoder { public override int GetCharCount(byte[] bytes, int index, int count) { // SQL Server never sends a BOM, so we can assume that its 2 bytes per char return count / 2; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // This method is required - simply call Convert() int bytesUsed; int charsUsed; bool completed; Convert(bytes, byteIndex, byteCount, chars, charIndex, chars.Length - charIndex, true, out bytesUsed, out charsUsed, out completed); return charsUsed; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Assume 2 bytes per char and no BOM charsUsed = Math.Min(charCount, byteCount / 2); bytesUsed = charsUsed * 2; completed = (bytesUsed == byteCount); // BlockCopy uses offsets\length measured in bytes, not the actual array index Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * 2, bytesUsed); } } } }
using System; using HelperSharp; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; namespace GeneticSharp.Extensions.Checkers { #region Enums /// <summary> /// The checkers player. /// </summary> public enum CheckersPlayer { /// <summary> /// The player one. /// </summary> PlayerOne, /// <summary> /// The player two. /// </summary> PlayerTwo } #endregion /// <summary> /// Checkers board. /// </summary> public class CheckersBoard { #region Fields private CheckersSquare[,] m_squares; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GeneticSharp.Extensions.Checkers.CheckersBoard"/> class. /// </summary> /// <param name="size">The board size in number of squares of each side.</param> public CheckersBoard(int size) { if (size < 8) { throw new ArgumentException("The minimum valid size is 8."); } Size = size; m_squares = new CheckersSquare[size, size]; Reset(); } #endregion #region Properties /// <summary> /// Gets the size. /// </summary> public int Size { get; private set; } /// <summary> /// Gets the player one's pieces. /// </summary> public List<CheckersPiece> PlayerOnePieces { get; private set; } /// <summary> /// Gets the player two's pieces. /// </summary> public List<CheckersPiece> PlayerTwoPieces { get; private set; } #endregion #region Methods /// <summary> /// Reset the board to initial state (player one and two with pieces in start positions). /// </summary> public void Reset() { PlayerOnePieces = new List<CheckersPiece> (); PlayerTwoPieces = new List<CheckersPiece> (); for (int c = 0; c < Size; c++) { for (int r = 0; r < Size; r++) { var square = new CheckersSquare(c, r); if (square.State == CheckersSquareState.Free) { if (r < 3) { var piece = new CheckersPiece (CheckersPlayer.PlayerOne); PlayerOnePieces.Add (piece); square.PutPiece (piece); } else if (r >= Size - 3) { var piece = new CheckersPiece (CheckersPlayer.PlayerTwo); PlayerTwoPieces.Add (piece); square.PutPiece (piece); } } m_squares[c, r] = square; } } } /// <summary> /// Gets the square from column index and row index specified. /// </summary> /// <returns>The square.</returns> /// <param name="columnIndex">Column index.</param> /// <param name="rowIndex">Row index.</param> public CheckersSquare GetSquare(int columnIndex, int rowIndex) { if (!IsValidIndex(columnIndex)) { throw new ArgumentOutOfRangeException("columnIndex"); } if (!IsValidIndex(rowIndex)) { throw new ArgumentOutOfRangeException("rowIndex"); } return m_squares [columnIndex, rowIndex]; } /// <summary> /// Move a piece using the specified move. /// </summary> /// <param name="move">The move to perform.</param> /// <returns>True if move was performed, otherwise false.</returns> public bool MovePiece(CheckersMove move) { ExceptionHelper.ThrowIfNull ("move", move); bool moved = false; var from = GetSquare(move.Piece.CurrentSquare.ColumnIndex, move.Piece.CurrentSquare.RowIndex); var moveKind = GetMoveKind(move); if (moveKind != CheckersMoveKind.Invalid) { var to = GetSquare(move.ToSquare.ColumnIndex, move.ToSquare.RowIndex); to.PutPiece (from.CurrentPiece); var indexModifier = to.State == CheckersSquareState.OccupiedByPlayerOne ? 1 : -1; from.RemovePiece (); // if (!to.PutPiece (from.CurrentPiece)) { // throw new InvalidOperationException ("Trying to put a piece on a square that already have a piece."); // } // var indexModifier = to.State == CheckersSquareState.OccupiedByPlayerOne ? 1 : -1; // if (!from.RemovePiece ()) { // throw new InvalidOperationException ("Trying to remove a piece on a square that have no piece."); // } moved = true; if (moveKind == CheckersMoveKind.Capture) // Capture move. { if (to.ColumnIndex == from.ColumnIndex + (2 * indexModifier)) { GetSquare (from.ColumnIndex + (1 * indexModifier), from.RowIndex + (1 * indexModifier)).RemovePiece (); } else if (to.ColumnIndex == from.ColumnIndex - (2 * indexModifier)) { GetSquare (from.ColumnIndex - (1 * indexModifier), from.RowIndex + (1 * indexModifier)).RemovePiece (); } // else { // throw new InvalidOperationException ("Houston, we have a problem! Capture move without capture any piece."); // } moved = true; } } return moved; } /// <summary> /// Gets the kind of the move. /// </summary> /// <returns>The move kind.</returns> /// <param name="move">The move.</param> public CheckersMoveKind GetMoveKind(CheckersMove move) { var kind = CheckersMoveKind.Invalid; var player = move.Piece.Player; var currentSquareState = move.Piece.CurrentSquare.State; if (currentSquareState == CheckersSquareState.OccupiedByPlayerOne || currentSquareState == CheckersSquareState.OccupiedByPlayerTwo) { var from = GetSquare(move.Piece.CurrentSquare.ColumnIndex, move.Piece.CurrentSquare.RowIndex); var to = GetSquare(move.ToSquare.ColumnIndex, move.ToSquare.RowIndex); // From is square of the AI player and To is a free square. if (from.State == currentSquareState && to.State == CheckersSquareState.Free) { int indexModifier = GetIndexModifier(player); CheckersSquareState opponentState; if (from.State == CheckersSquareState.OccupiedByPlayerOne) { opponentState = CheckersSquareState.OccupiedByPlayerTwo; } else { opponentState = CheckersSquareState.OccupiedByPlayerOne; } // Forward move. if (to.RowIndex == from.RowIndex + (1 * indexModifier) && (to.ColumnIndex == from.ColumnIndex - (1 * indexModifier) || to.ColumnIndex == from.ColumnIndex + (1 * indexModifier))) { kind = CheckersMoveKind.Forward; } else if (to.RowIndex == from.RowIndex + (2 * indexModifier)) // Capture move. { if (to.ColumnIndex == from.ColumnIndex + (2 * indexModifier) && GetSquare(from.ColumnIndex + (1 * indexModifier), from.RowIndex + (1 * indexModifier)).State == opponentState) // To right. { kind = CheckersMoveKind.Capture; } else if (to.ColumnIndex == from.ColumnIndex - (2 * indexModifier) && GetSquare(from.ColumnIndex - (1 * indexModifier), from.RowIndex + (1 * indexModifier)).State == opponentState) // To left. { kind = CheckersMoveKind.Capture; } } } } return kind; } /// <summary> /// Counts the number of pieces capturable by specified piece. /// </summary> /// <param name="piece">The piece which can capture another ones.</param> /// <returns>The number of capturable pieces.</returns> public int CountCapturableByPiece(CheckersPiece piece) { ExceptionHelper.ThrowIfNull("piece", piece); var capturableCount = 0; var square = piece.CurrentSquare; var newRowIndex = square.RowIndex + 2 * GetIndexModifier(piece.Player); if (IsValidIndex(newRowIndex)) { var columnIndex = square.ColumnIndex; var newColumnToLeftIndex = columnIndex - 2; var newColumnToRightIndex = columnIndex + 2; if(IsValidIndex(newColumnToLeftIndex)) { capturableCount += GetMoveKind(new CheckersMove(piece, GetSquare(newColumnToLeftIndex, newRowIndex))) == CheckersMoveKind.Capture ? 1 : 0; } if(IsValidIndex(newColumnToRightIndex)) { capturableCount += GetMoveKind(new CheckersMove(piece, GetSquare(newColumnToRightIndex, newRowIndex))) == CheckersMoveKind.Capture ? 1 : 0; } } return capturableCount; } /// <summary> /// Counts the number of chances the specified piece to be captured. /// </summary> /// <param name="piece">The piece which can be captured.</param> /// <returns>The number of changes of piece be captured.</returns> public int CountPieceChancesToBeCaptured(CheckersPiece piece) { ExceptionHelper.ThrowIfNull("piece", piece); var capturedCount = 0; var square = piece.CurrentSquare; var indexModifier = GetIndexModifier(piece.Player); var enemyPieceRowIndex = square.RowIndex + 1 * indexModifier; var enemyToSquareRowIndex = square.RowIndex - 1 * indexModifier; if (IsValidIndex(enemyPieceRowIndex) && IsValidIndex(enemyToSquareRowIndex)) { var columnIndex = square.ColumnIndex; var enemyLeftColumnIndex = columnIndex - 1; var enemyRightColumnIndex = columnIndex + 1; if (IsValidIndex(enemyLeftColumnIndex) && IsValidIndex(enemyRightColumnIndex)) { var enemyPiece = GetSquare(enemyLeftColumnIndex, enemyPieceRowIndex).CurrentPiece; if(enemyPiece != null) { capturedCount += GetMoveKind(new CheckersMove(enemyPiece, GetSquare(enemyRightColumnIndex, enemyToSquareRowIndex))) == CheckersMoveKind.Capture ? 1 : 0; } enemyPiece = GetSquare(enemyRightColumnIndex, enemyPieceRowIndex).CurrentPiece; if (enemyPiece != null) { capturedCount += GetMoveKind(new CheckersMove(enemyPiece, GetSquare(enemyLeftColumnIndex, enemyToSquareRowIndex))) == CheckersMoveKind.Capture ? 1 : 0; } } } return capturedCount; } #endregion #region Helpers private bool IsValidIndex(int index) { return index >= 0 && index < Size; } private static int GetIndexModifier(CheckersPlayer player) { int indexModifier; if (player == CheckersPlayer.PlayerOne) { indexModifier = 1; } else { indexModifier = -1; } return indexModifier; } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using Epi.Analysis; using Epi; using Epi.Windows; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Printout command /// </summary> public partial class ReportDialog : CommandDesignDialog { #region Constructor /// <summary> /// Constructor for the Printout dialog /// </summary> /// <param name="frm"></param> public ReportDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); radioButtonDisplay.Checked = true; textBoxFileSavePath.Text = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Reports"); foreach (String printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) { comboBoxSelectPrinter.Items.Add(printer.ToString()); } System.Drawing.Printing.PrintDocument prtdoc = new System.Drawing.Printing.PrintDocument(); string defaultPrinter = prtdoc.PrinterSettings.PrinterName; comboBoxSelectPrinter.Text = defaultPrinter; GenerateCommand(); } #endregion Constructors #region Event Handlers /// <summary> /// Clear button clears the text /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnClear_Click(object sender, System.EventArgs e) { textBoxReportName.Text = string.Empty; textBoxFileSavePath.Text = string.Empty; } #endregion //Event Handlers #region Protected Methods /// <summary> /// Generate command text /// </summary> protected override void GenerateCommand() { if (textBoxReportName.Text.Trim().Length > 0) { StringBuilder sb = new StringBuilder(); sb.Append(CommandNames.REPORT).Append(StringLiterals.SPACE); if (textBoxReportName.Text.Trim().Length != 0) { sb.Append(Util.InsertInSingleQuotes(textBoxReportName.Text.Trim())); } sb.Append(StringLiterals.SPACE); if (radioButtonPrinter.Checked) { sb.Append(Util.InsertInSingleQuotes(comboBoxSelectPrinter.Text.Trim())); } else if (radioButtonFile.Checked) { sb.Append("TO").Append(StringLiterals.SPACE); sb.Append(Util.InsertInSingleQuotes(textBoxFileSavePath.Text.Trim())); } else { sb.Append("DISPLAY"); } CommandText = sb.ToString(); textBoxCommandPreview.Text = CommandText; btnOK.Enabled = true; } else { btnOK.Enabled = false; } } #endregion //Protected Methods #region Private Methods private void Construct() { if (!this.DesignMode) { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); } } #endregion Private Methods private void btnEditReport_Click(object sender, EventArgs e) { string epiReportExecutablePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); epiReportExecutablePath = System.IO.Path.Combine(epiReportExecutablePath, "EpiReport.exe"); String commandText = epiReportExecutablePath; string commandlineString = string.Empty; commandlineString = commandText + " " + string.Format("/template:\"{0}\"", textBoxReportName.Text.Trim()); Process process = null; STARTUPINFO startupInfo = new STARTUPINFO(); PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION(); bool created = CreateProcess( null, commandlineString, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startupInfo, out processInfo); if (created) { process = Process.GetProcessById((int)processInfo.dwProcessId); } else { throw new GeneralException("Could not execute the command: '" + commandlineString + "'"); } } public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } public struct STARTUPINFO { public uint cb; public string lpReserved; public string lpDesktop; public string lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public uint dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } public struct SECURITY_ATTRIBUTES { public int length; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } // Using interop call here since this will allow us to execute the entire command line string. // The System.Diagnostics.Process.Start() method will not allow this. [DllImport("kernel32.dll")] public static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); private void buttonEllipsisReportName_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Report Files(*.ept)|" + "*.ept|All files (*.*)|*.*"; dialog.Title = "Select Report Template"; if (dialog.ShowDialog() == DialogResult.OK) { textBoxReportName.Text = dialog.FileName; } GenerateCommand(); } private void buttonEllipsisSaveFileOutputPath_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "Select the directory that the report will be placed in."; dialog.ShowNewFolderButton = false; dialog.SelectedPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); dialog.SelectedPath = System.IO.Path.Combine(dialog.SelectedPath, "Reports"); if (dialog.ShowDialog() == DialogResult.OK) { textBoxFileSavePath.Text = dialog.SelectedPath; } GenerateCommand(); } private void radioButtonDisplay_CheckedChanged(object sender, EventArgs e) { textBoxFileSavePath.Enabled = !radioButtonDisplay.Checked; buttonEllipsisSaveFileOutputPath.Enabled = !radioButtonDisplay.Checked; comboBoxSelectPrinter.Enabled = !radioButtonDisplay.Checked; GenerateCommand(); } private void radioButtonFile_CheckedChanged(object sender, EventArgs e) { textBoxFileSavePath.Enabled = !radioButtonDisplay.Checked; buttonEllipsisSaveFileOutputPath.Enabled = !radioButtonDisplay.Checked; comboBoxSelectPrinter.Enabled = radioButtonDisplay.Checked; GenerateCommand(); } private void radioButtonPrinter_CheckedChanged(object sender, EventArgs e) { textBoxFileSavePath.Enabled = radioButtonDisplay.Checked; buttonEllipsisSaveFileOutputPath.Enabled = radioButtonDisplay.Checked; comboBoxSelectPrinter.Enabled = !radioButtonDisplay.Checked; GenerateCommand(); } private void comboBoxSelectPrinter_SelectedIndexChanged(object sender, EventArgs e) { GenerateCommand(); } private void textBoxReportName_TextChanged(object sender, EventArgs e) { if (System.IO.File.Exists(textBoxReportName.Text.Trim())) { btnEditReport.Enabled = true; } else { btnEditReport.Enabled = false; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Index { using ByteRunAutomaton = Lucene.Net.Util.Automaton.ByteRunAutomaton; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton; using IntsRef = Lucene.Net.Util.IntsRef; using StringHelper = Lucene.Net.Util.StringHelper; using Transition = Lucene.Net.Util.Automaton.Transition; /// <summary> /// A FilteredTermsEnum that enumerates terms based upon what is accepted by a /// DFA. /// <p> /// The algorithm is such: /// <ol> /// <li>As long as matches are successful, keep reading sequentially. /// <li>When a match fails, skip to the next string in lexicographic order that /// does not enter a reject state. /// </ol> /// <p> /// The algorithm does not attempt to actually skip to the next string that is /// completely accepted. this is not possible when the language accepted by the /// FSM is not finite (i.e. * operator). /// </p> /// @lucene.experimental /// </summary> internal class AutomatonTermsEnum : FilteredTermsEnum { // a tableized array-based form of the DFA private readonly ByteRunAutomaton RunAutomaton; // common suffix of the automaton private readonly BytesRef CommonSuffixRef; // true if the automaton accepts a finite language private readonly bool? Finite; // array of sorted transitions for each state, indexed by state number private readonly Transition[][] AllTransitions; // for path tracking: each long records gen when we last // visited the state; we use gens to avoid having to clear private readonly long[] Visited; private long CurGen; // the reference used for seeking forwards through the term dictionary private readonly BytesRef SeekBytesRef = new BytesRef(10); // true if we are enumerating an infinite portion of the DFA. // in this case it is faster to drive the query based on the terms dictionary. // when this is true, linearUpperBound indicate the end of range // of terms where we should simply do sequential reads instead. private bool Linear_Renamed = false; private readonly BytesRef LinearUpperBound = new BytesRef(10); private readonly IComparer<BytesRef> TermComp; /// <summary> /// Construct an enumerator based upon an automaton, enumerating the specified /// field, working on a supplied TermsEnum /// <p> /// @lucene.experimental /// <p> </summary> /// <param name="compiled"> CompiledAutomaton </param> public AutomatonTermsEnum(TermsEnum tenum, CompiledAutomaton compiled) : base(tenum) { this.Finite = compiled.Finite; this.RunAutomaton = compiled.RunAutomaton; Debug.Assert(this.RunAutomaton != null); this.CommonSuffixRef = compiled.CommonSuffixRef; this.AllTransitions = compiled.SortedTransitions; // used for path tracking, where each bit is a numbered state. Visited = new long[RunAutomaton.Size]; TermComp = Comparator; } /// <summary> /// Returns true if the term matches the automaton. Also stashes away the term /// to assist with smart enumeration. /// </summary> protected internal override AcceptStatus Accept(BytesRef term) { if (CommonSuffixRef == null || StringHelper.EndsWith(term, CommonSuffixRef)) { if (RunAutomaton.Run(term.Bytes, term.Offset, term.Length)) { return Linear_Renamed ? AcceptStatus.YES : AcceptStatus.YES_AND_SEEK; } else { return (Linear_Renamed && TermComp.Compare(term, LinearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK; } } else { return (Linear_Renamed && TermComp.Compare(term, LinearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK; } } protected internal override BytesRef NextSeekTerm(BytesRef term) { //System.out.println("ATE.nextSeekTerm term=" + term); if (term == null) { Debug.Assert(SeekBytesRef.Length == 0); // return the empty term, as its valid if (RunAutomaton.IsAccept(RunAutomaton.InitialState)) { return SeekBytesRef; } } else { SeekBytesRef.CopyBytes(term); } // seek to the next possible string; if (NextString()) { return SeekBytesRef; // reposition } else { return null; // no more possible strings can match } } /// <summary> /// Sets the enum to operate in linear fashion, as we have found /// a looping transition at position: we set an upper bound and /// act like a TermRangeQuery for this portion of the term space. /// </summary> private int Linear { set { Debug.Assert(Linear_Renamed == false); int state = RunAutomaton.InitialState; int maxInterval = 0xff; for (int i = 0; i < value; i++) { state = RunAutomaton.Step(state, SeekBytesRef.Bytes[i] & 0xff); Debug.Assert(state >= 0, "state=" + state); } for (int i = 0; i < AllTransitions[state].Length; i++) { Transition t = AllTransitions[state][i]; if (t.Min <= (SeekBytesRef.Bytes[value] & 0xff) && (SeekBytesRef.Bytes[value] & 0xff) <= t.Max) { maxInterval = t.Max; break; } } // 0xff terms don't get the optimization... not worth the trouble. if (maxInterval != 0xff) { maxInterval++; } int length = value + 1; // value + maxTransition if (LinearUpperBound.Bytes.Length < length) { LinearUpperBound.Bytes = new byte[length]; } Array.Copy(SeekBytesRef.Bytes, 0, LinearUpperBound.Bytes, 0, value); LinearUpperBound.Bytes[value] = (byte)maxInterval; LinearUpperBound.Length = length; Linear_Renamed = true; } } private readonly IntsRef SavedStates = new IntsRef(10); /// <summary> /// Increments the byte buffer to the next String in binary order after s that will not put /// the machine into a reject state. If such a string does not exist, returns /// false. /// /// The correctness of this method depends upon the automaton being deterministic, /// and having no transitions to dead states. /// </summary> /// <returns> true if more possible solutions exist for the DFA </returns> private bool NextString() { int state; int pos = 0; SavedStates.Grow(SeekBytesRef.Length + 1); int[] states = SavedStates.Ints; states[0] = RunAutomaton.InitialState; while (true) { CurGen++; Linear_Renamed = false; // walk the automaton until a character is rejected. for (state = states[pos]; pos < SeekBytesRef.Length; pos++) { Visited[state] = CurGen; int nextState = RunAutomaton.Step(state, SeekBytesRef.Bytes[pos] & 0xff); if (nextState == -1) { break; } states[pos + 1] = nextState; // we found a loop, record it for faster enumeration if ((Finite == false) && !Linear_Renamed && Visited[nextState] == CurGen) { Linear = pos; } state = nextState; } // take the useful portion, and the last non-reject state, and attempt to // append characters that will match. if (NextString(state, pos)) { return true; } // no more solutions exist from this useful portion, backtrack else { if ((pos = Backtrack(pos)) < 0) // no more solutions at all { return false; } int newState = RunAutomaton.Step(states[pos], SeekBytesRef.Bytes[pos] & 0xff); if (newState >= 0 && RunAutomaton.IsAccept(newState)) /* String is good to go as-is */ { return true; } /* else advance further */ // TODO: paranoia? if we backtrack thru an infinite DFA, the loop detection is important! // for now, restart from scratch for all infinite DFAs if (Finite == false) { pos = 0; } } } } /// <summary> /// Returns the next String in lexicographic order that will not put /// the machine into a reject state. /// /// this method traverses the DFA from the given position in the String, /// starting at the given state. /// /// If this cannot satisfy the machine, returns false. this method will /// walk the minimal path, in lexicographic order, as long as possible. /// /// If this method returns false, then there might still be more solutions, /// it is necessary to backtrack to find out. /// </summary> /// <param name="state"> current non-reject state </param> /// <param name="position"> useful portion of the string </param> /// <returns> true if more possible solutions exist for the DFA from this /// position </returns> private bool NextString(int state, int position) { /* * the next lexicographic character must be greater than the existing * character, if it exists. */ int c = 0; if (position < SeekBytesRef.Length) { c = SeekBytesRef.Bytes[position] & 0xff; // if the next byte is 0xff and is not part of the useful portion, // then by definition it puts us in a reject state, and therefore this // path is dead. there cannot be any higher transitions. backtrack. if (c++ == 0xff) { return false; } } SeekBytesRef.Length = position; Visited[state] = CurGen; Transition[] transitions = AllTransitions[state]; // find the minimal path (lexicographic order) that is >= c for (int i = 0; i < transitions.Length; i++) { Transition transition = transitions[i]; if (transition.Max >= c) { int nextChar = Math.Max(c, transition.Min); // append either the next sequential char, or the minimum transition SeekBytesRef.Grow(SeekBytesRef.Length + 1); SeekBytesRef.Length++; SeekBytesRef.Bytes[SeekBytesRef.Length - 1] = (byte)nextChar; state = transition.Dest.Number; /* * as long as is possible, continue down the minimal path in * lexicographic order. if a loop or accept state is encountered, stop. */ while (Visited[state] != CurGen && !RunAutomaton.IsAccept(state)) { Visited[state] = CurGen; /* * Note: we work with a DFA with no transitions to dead states. * so the below is ok, if it is not an accept state, * then there MUST be at least one transition. */ transition = AllTransitions[state][0]; state = transition.Dest.Number; // append the minimum transition SeekBytesRef.Grow(SeekBytesRef.Length + 1); SeekBytesRef.Length++; SeekBytesRef.Bytes[SeekBytesRef.Length - 1] = (byte)transition.Min; // we found a loop, record it for faster enumeration if ((Finite == false) && !Linear_Renamed && Visited[state] == CurGen) { Linear = SeekBytesRef.Length - 1; } } return true; } } return false; } /// <summary> /// Attempts to backtrack thru the string after encountering a dead end /// at some given position. Returns false if no more possible strings /// can match. /// </summary> /// <param name="position"> current position in the input String </param> /// <returns> position >=0 if more possible solutions exist for the DFA </returns> private int Backtrack(int position) { while (position-- > 0) { int nextChar = SeekBytesRef.Bytes[position] & 0xff; // if a character is 0xff its a dead-end too, // because there is no higher character in binary sort order. if (nextChar++ != 0xff) { SeekBytesRef.Bytes[position] = (byte)nextChar; SeekBytesRef.Length = position + 1; return position; } } return -1; // all solutions exhausted } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic{ /// <summary> /// Strongly-typed collection for the VwAspnetApplication class. /// </summary> [Serializable] public partial class VwAspnetApplicationCollection : ReadOnlyList<VwAspnetApplication, VwAspnetApplicationCollection> { public VwAspnetApplicationCollection() {} } /// <summary> /// This is Read-only wrapper class for the vw_aspnet_Applications view. /// </summary> [Serializable] public partial class VwAspnetApplication : ReadOnlyRecord<VwAspnetApplication>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("vw_aspnet_Applications", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarApplicationName = new TableSchema.TableColumn(schema); colvarApplicationName.ColumnName = "ApplicationName"; colvarApplicationName.DataType = DbType.String; colvarApplicationName.MaxLength = 256; colvarApplicationName.AutoIncrement = false; colvarApplicationName.IsNullable = false; colvarApplicationName.IsPrimaryKey = false; colvarApplicationName.IsForeignKey = false; colvarApplicationName.IsReadOnly = false; schema.Columns.Add(colvarApplicationName); TableSchema.TableColumn colvarLoweredApplicationName = new TableSchema.TableColumn(schema); colvarLoweredApplicationName.ColumnName = "LoweredApplicationName"; colvarLoweredApplicationName.DataType = DbType.String; colvarLoweredApplicationName.MaxLength = 256; colvarLoweredApplicationName.AutoIncrement = false; colvarLoweredApplicationName.IsNullable = false; colvarLoweredApplicationName.IsPrimaryKey = false; colvarLoweredApplicationName.IsForeignKey = false; colvarLoweredApplicationName.IsReadOnly = false; schema.Columns.Add(colvarLoweredApplicationName); TableSchema.TableColumn colvarApplicationId = new TableSchema.TableColumn(schema); colvarApplicationId.ColumnName = "ApplicationId"; colvarApplicationId.DataType = DbType.Guid; colvarApplicationId.MaxLength = 0; colvarApplicationId.AutoIncrement = false; colvarApplicationId.IsNullable = false; colvarApplicationId.IsPrimaryKey = false; colvarApplicationId.IsForeignKey = false; colvarApplicationId.IsReadOnly = false; schema.Columns.Add(colvarApplicationId); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.String; colvarDescription.MaxLength = 256; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = true; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; schema.Columns.Add(colvarDescription); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("vw_aspnet_Applications",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public VwAspnetApplication() { SetSQLProps(); SetDefaults(); MarkNew(); } public VwAspnetApplication(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public VwAspnetApplication(object keyID) { SetSQLProps(); LoadByKey(keyID); } public VwAspnetApplication(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("ApplicationName")] [Bindable(true)] public string ApplicationName { get { return GetColumnValue<string>("ApplicationName"); } set { SetColumnValue("ApplicationName", value); } } [XmlAttribute("LoweredApplicationName")] [Bindable(true)] public string LoweredApplicationName { get { return GetColumnValue<string>("LoweredApplicationName"); } set { SetColumnValue("LoweredApplicationName", value); } } [XmlAttribute("ApplicationId")] [Bindable(true)] public Guid ApplicationId { get { return GetColumnValue<Guid>("ApplicationId"); } set { SetColumnValue("ApplicationId", value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>("Description"); } set { SetColumnValue("Description", value); } } #endregion #region Columns Struct public struct Columns { public static string ApplicationName = @"ApplicationName"; public static string LoweredApplicationName = @"LoweredApplicationName"; public static string ApplicationId = @"ApplicationId"; public static string Description = @"Description"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// (c) Copyright 2012 Hewlett-Packard Development Company, L.P. // 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.IO; using System.Reflection; using HpToolsLauncher.Properties; namespace HpToolsLauncher { public class ApiTestRunner : IFileSysTestRunner { public const string STRunnerName = "ServiceTestExecuter.exe"; public const string STRunnerTestArg = @"-test"; public const string STRunnerReportArg = @"-report"; public const string STRunnerInputParamsArg = @"-inParams"; private const int PollingTimeMs = 500; private bool _stCanRun; private string _stExecuterPath = Directory.GetCurrentDirectory(); private readonly IAssetRunner _runner; private TimeSpan _timeout = TimeSpan.MaxValue; private Stopwatch _stopwatch = null; private RunCancelledDelegate _runCancelled; /// <summary> /// constructor /// </summary> /// <param name="runner">parent runner</param> /// <param name="timeout">the global timout</param> public ApiTestRunner(IAssetRunner runner, TimeSpan timeout) { _stopwatch = Stopwatch.StartNew(); _timeout = timeout; _stCanRun = TrySetSTRunner(); _runner = runner; } /// <summary> /// Search ServiceTestExecuter.exe in the current running process directory, /// and if not found, in the installation folder (taken from registry) /// </summary> /// <returns></returns> public bool TrySetSTRunner() { if (File.Exists(STRunnerName)) return true; _stExecuterPath = Helper.GetSTInstallPath(); if ((!String.IsNullOrEmpty(_stExecuterPath))) { _stExecuterPath += "bin"; return true; } _stCanRun = false; return false; } /// <summary> /// runs the given test /// </summary> /// <param name="testinf"></param> /// <param name="errorReason"></param> /// <param name="runCancelled">cancellation delegate, holds the function that checks cancellation</param> /// <returns></returns> public TestRunResults RunTest(TestInfo testinf, ref string errorReason, RunCancelledDelegate runCancelled) { TestRunResults runDesc = new TestRunResults(); ConsoleWriter.ActiveTestRun = runDesc; ConsoleWriter.WriteLine(DateTime.Now.ToString(Launcher.DateFormat) + " Running: " + testinf.TestPath); runDesc.ReportLocation = testinf.TestPath; runDesc.ErrorDesc = errorReason; runDesc.TestPath = testinf.TestPath; runDesc.TestState = TestState.Unknown; if (!Helper.IsServiceTestInstalled()) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = string.Format(Resources.LauncherStNotInstalled, System.Environment.MachineName); ConsoleWriter.WriteErrLine(runDesc.ErrorDesc); Environment.ExitCode = (int)Launcher.ExitCodeEnum.Failed; return runDesc; } _runCancelled = runCancelled; if (!_stCanRun) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = Resources.STExecuterNotFound; return runDesc; } string fileName = Path.Combine(_stExecuterPath, STRunnerName); if (!File.Exists(fileName)) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = Resources.STExecuterNotFound; ConsoleWriter.WriteErrLine(Resources.STExecuterNotFound); return runDesc; } //write the input parameter xml file for the API test string paramFileName = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 10); string tempPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestParams"); Directory.CreateDirectory(tempPath); string paramsFilePath = Path.Combine(tempPath, "params" + paramFileName + ".xml"); string paramFileContent = testinf.GenerateAPITestXmlForTest(); string argumentString = ""; if (!string.IsNullOrWhiteSpace(paramFileContent)) { File.WriteAllText(paramsFilePath, paramFileContent); argumentString = String.Format("{0} \"{1}\" {2} \"{3}\" {4} \"{5}\"", STRunnerTestArg, testinf.TestPath, STRunnerReportArg, runDesc.ReportLocation, STRunnerInputParamsArg, paramsFilePath); } else { argumentString = String.Format("{0} \"{1}\" {2} \"{3}\"", STRunnerTestArg, testinf.TestPath, STRunnerReportArg, runDesc.ReportLocation); } Stopwatch s = Stopwatch.StartNew(); runDesc.TestState = TestState.Running; if (!ExecuteProcess(fileName, argumentString, ref errorReason)) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = errorReason; } else { runDesc.ReportLocation = Path.Combine(runDesc.ReportLocation, "Report"); if (!File.Exists(Path.Combine(runDesc.ReportLocation, "Results.xml"))) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = "No Results.xml file found"; } } //File.Delete(paramsFilePath); runDesc.Runtime = s.Elapsed; return runDesc; } /// <summary> /// performs global cleanup code for this type of runner /// </summary> public void CleanUp() { } #region Process /// <summary> /// executes the run of the test by using the Init and RunProcss routines /// </summary> /// <param name="proc"></param> /// <param name="fileName"></param> /// <param name="arguments"></param> /// <param name="enableRedirection"></param> private bool ExecuteProcess(string fileName, string arguments, ref string failureReason) { Process proc = null; try { using (proc = new Process()) { InitProcess(proc, fileName, arguments, true); RunProcess(proc, true); //it could be that the process already existed //before we could handle the cancel request if (_runCancelled()) { failureReason = "Process was stopped since job has timed out!"; ConsoleWriter.WriteLine(failureReason); if (!proc.HasExited) { proc.OutputDataReceived -= OnOutputDataReceived; proc.ErrorDataReceived -= OnErrorDataReceived; proc.Kill(); return false; } } if (proc.ExitCode != 0) { failureReason = "The Api test runner's exit code was: " + proc.ExitCode; ConsoleWriter.WriteLine(failureReason); return false; } } } catch (Exception e) { failureReason = e.Message; return false; } finally { if (proc != null) { proc.Close(); } } return true; } /// <summary> /// initializes the ServiceTestExecuter process /// </summary> /// <param name="proc"></param> /// <param name="fileName"></param> /// <param name="arguments"></param> /// <param name="enableRedirection"></param> private void InitProcess(Process proc, string fileName, string arguments, bool enableRedirection) { var processStartInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, WorkingDirectory = Directory.GetCurrentDirectory() }; if (!enableRedirection) return; processStartInfo.ErrorDialog = false; processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; proc.StartInfo = processStartInfo; proc.EnableRaisingEvents = true; proc.StartInfo.CreateNoWindow = true; proc.OutputDataReceived += OnOutputDataReceived; proc.ErrorDataReceived += OnErrorDataReceived; } /// <summary> /// runs the ServiceTestExecuter process after initialization /// </summary> /// <param name="proc"></param> /// <param name="enableRedirection"></param> private void RunProcess(Process proc, bool enableRedirection) { proc.Start(); if (enableRedirection) { proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); } proc.WaitForExit(PollingTimeMs); while (!_runCancelled() && !proc.HasExited) { proc.WaitForExit(PollingTimeMs); } } /// <summary> /// callback function for spawnd process errors /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnErrorDataReceived(object sender, DataReceivedEventArgs e) { var p = sender as Process; if (p == null) return; try { if (!p.HasExited || p.ExitCode == 0) return; } catch { return; } string format = String.Format("{0} {1}: ", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()); string errorData = e.Data; if (String.IsNullOrEmpty(errorData)) { errorData = String.Format("External process has exited with code {0}", p.ExitCode); } ConsoleWriter.WriteErrLine(errorData); } /// <summary> /// callback function for spawnd process output /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { if (!String.IsNullOrEmpty(e.Data)) { string data = e.Data; ConsoleWriter.WriteLine(data); } } #endregion } }
// // System.Web.Security.FormsAuthentication // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2002,2003 Ximian, Inc (http://www.ximian.com) // Copyright (c) 2005 Novell, Inc (http://www.novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Util; namespace System.Web.Security { public sealed class FormsAuthentication { const int MD5_hash_size = 16; const int SHA1_hash_size = 20; static string authConfigPath = "system.web/authentication"; static bool initialized; static string cookieName; static string cookiePath; static int timeout; static FormsProtectionEnum protection; static object locker = new object (); static byte [] init_vector; // initialization vector used for 3DES #if NET_1_1 static bool requireSSL; static bool slidingExpiration; #endif // same names and order used in xsp static string [] indexFiles = { "index.aspx", "Default.aspx", "default.aspx", "index.html", "index.htm" }; public static bool Authenticate (string name, string password) { if (name == null || password == null) return false; Initialize (); HttpContext context = HttpContext.Current; if (context == null) throw new HttpException ("Context is null!"); AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig; Hashtable users = config.CredentialUsers; string stored = users [name] as string; if (stored == null) return false; switch (config.PasswordFormat) { case FormsAuthPasswordFormat.Clear: /* Do nothing */ break; case FormsAuthPasswordFormat.MD5: password = HashPasswordForStoringInConfigFile (password, "MD5"); break; case FormsAuthPasswordFormat.SHA1: password = HashPasswordForStoringInConfigFile (password, "SHA1"); break; } return (password == stored); } static FormsAuthenticationTicket Decrypt2 (byte [] bytes) { if (protection == FormsProtectionEnum.None) return FormsAuthenticationTicket.FromByteArray (bytes); MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig; bool all = (protection == FormsProtectionEnum.All); byte [] result = bytes; if (all || protection == FormsProtectionEnum.Encryption) { ICryptoTransform decryptor; decryptor = new TripleDESCryptoServiceProvider().CreateDecryptor (config.DecryptionKey192Bits, init_vector); result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length); bytes = null; } if (all || protection == FormsProtectionEnum.Validation) { int count; if (config.ValidationType == MachineKeyValidation.MD5) count = MD5_hash_size; else count = SHA1_hash_size; // 3DES and SHA1 byte [] vk = config.ValidationKey; byte [] mix = new byte [result.Length - count + vk.Length]; Buffer.BlockCopy (result, 0, mix, 0, result.Length - count); Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length); byte [] hash = null; switch (config.ValidationType) { case MachineKeyValidation.MD5: hash = MD5.Create ().ComputeHash (mix); break; // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1" case MachineKeyValidation.TripleDES: case MachineKeyValidation.SHA1: hash = SHA1.Create ().ComputeHash (mix); break; } if (result.Length < count) throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket"); int i, k; for (i = result.Length - count, k = 0; k < count; i++, k++) { if (result [i] != hash [k]) throw new ArgumentException ("Error validating ticket.", "encryptedTicket"); } } return FormsAuthenticationTicket.FromByteArray (result); } public static FormsAuthenticationTicket Decrypt (string encryptedTicket) { if (encryptedTicket == null || encryptedTicket == String.Empty) throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket"); Initialize (); FormsAuthenticationTicket ticket; byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length); try { ticket = Decrypt2 (bytes); } catch (Exception) { ticket = null; } return ticket; } public static string Encrypt (FormsAuthenticationTicket ticket) { if (ticket == null) throw new ArgumentNullException ("ticket"); Initialize (); byte [] ticket_bytes = ticket.ToByteArray (); if (protection == FormsProtectionEnum.None) return GetHexString (ticket_bytes); byte [] result = ticket_bytes; MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig; bool all = (protection == FormsProtectionEnum.All); if (all || protection == FormsProtectionEnum.Validation) { byte [] valid_bytes = null; byte [] vk = config.ValidationKey; byte [] mix = new byte [ticket_bytes.Length + vk.Length]; Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length); Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length); switch (config.ValidationType) { case MachineKeyValidation.MD5: valid_bytes = MD5.Create ().ComputeHash (mix); break; // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1" case MachineKeyValidation.TripleDES: case MachineKeyValidation.SHA1: valid_bytes = SHA1.Create ().ComputeHash (mix); break; } int tlen = ticket_bytes.Length; int vlen = valid_bytes.Length; result = new byte [tlen + vlen]; Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen); Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen); } if (all || protection == FormsProtectionEnum.Encryption) { ICryptoTransform encryptor; encryptor = new TripleDESCryptoServiceProvider().CreateEncryptor (config.DecryptionKey192Bits, init_vector); result = encryptor.TransformFinalBlock (result, 0, result.Length); } return GetHexString (result); } public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie) { return GetAuthCookie (userName, createPersistentCookie, null); } public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath) { Initialize (); if (userName == null) userName = String.Empty; if (strCookiePath == null || strCookiePath.Length == 0) strCookiePath = cookiePath; DateTime now = DateTime.Now; DateTime then; if (createPersistentCookie) then = now.AddYears (50); else then = now.AddMinutes (timeout); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, userName, now, then, createPersistentCookie, String.Empty, cookiePath); if (!createPersistentCookie) then = DateTime.MinValue; return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then); } public static string GetRedirectUrl (string userName, bool createPersistentCookie) { if (userName == null) return null; Initialize (); HttpRequest request = HttpContext.Current.Request; string returnUrl = request ["RETURNURL"]; if (returnUrl != null) return returnUrl; returnUrl = request.ApplicationPath; string apppath = request.PhysicalApplicationPath; bool found = false; foreach (string indexFile in indexFiles) { string filePath = Path.Combine (apppath, indexFile); if (File.Exists (filePath)) { returnUrl = UrlUtils.Combine (returnUrl, indexFile); found = true; break; } } if (!found) returnUrl = UrlUtils.Combine (returnUrl, "index.aspx"); return returnUrl; } static string GetHexString (string str) { return GetHexString (Encoding.UTF8.GetBytes (str)); } static string GetHexString (byte [] bytes) { StringBuilder result = new StringBuilder (bytes.Length * 2); foreach (byte b in bytes) result.AppendFormat ("{0:X2}", (int) b); return result.ToString (); } public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat) { if (password == null) throw new ArgumentNullException ("password"); if (passwordFormat == null) throw new ArgumentNullException ("passwordFormat"); byte [] bytes; if (String.Compare (passwordFormat, "MD5", true) == 0) { bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password)); } else if (String.Compare (passwordFormat, "SHA1", true) == 0) { bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password)); } else { throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat"); } return GetHexString (bytes); } public static void Initialize () { if (initialized) return; lock (locker) { if (initialized) return; HttpContext context = HttpContext.Current; if (context == null) throw new HttpException ("Context is null!"); AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig; if (authConfig != null) { cookieName = authConfig.CookieName; timeout = authConfig.Timeout; cookiePath = authConfig.CookiePath; protection = authConfig.Protection; #if NET_1_1 requireSSL = authConfig.RequireSSL; slidingExpiration = authConfig.SlidingExpiration; #endif } else { cookieName = ".MONOAUTH"; timeout = 30; cookiePath = "/"; protection = FormsProtectionEnum.All; #if NET_1_1 slidingExpiration = true; #endif } // IV is 8 bytes long for 3DES init_vector = new byte [8]; int len = cookieName.Length; for (int i = 0; i < 8; i++) { if (i >= len) break; init_vector [i] = (byte) cookieName [i]; } initialized = true; } } public static void RedirectFromLoginPage (string userName, bool createPersistentCookie) { RedirectFromLoginPage (userName, createPersistentCookie, null); } public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath) { if (userName == null) return; Initialize (); SetAuthCookie (userName, createPersistentCookie, strCookiePath); HttpResponse resp = HttpContext.Current.Response; resp.Redirect (GetRedirectUrl (userName, createPersistentCookie), false); } public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld) { if (tOld == null) return null; DateTime now = DateTime.Now; TimeSpan toIssue = now - tOld.IssueDate; TimeSpan toExpiration = tOld.Expiration - now; if (toExpiration > toIssue) return tOld; FormsAuthenticationTicket tNew = tOld.Clone (); tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate)); return tNew; } public static void SetAuthCookie (string userName, bool createPersistentCookie) { Initialize (); SetAuthCookie (userName, createPersistentCookie, cookiePath); } public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath) { HttpContext context = HttpContext.Current; if (context == null) throw new HttpException ("Context is null!"); HttpResponse response = context.Response; if (response == null) throw new HttpException ("Response is null!"); response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath)); } public static void SignOut () { Initialize (); HttpContext context = HttpContext.Current; if (context == null) throw new HttpException ("Context is null!"); HttpResponse response = context.Response; if (response == null) throw new HttpException ("Response is null!"); response.Cookies.MakeCookieExpire (cookieName, cookiePath); } public static string FormsCookieName { get { Initialize (); return cookieName; } } public static string FormsCookiePath { get { Initialize (); return cookiePath; } } #if NET_1_1 public static bool RequireSSL { get { Initialize (); return requireSSL; } } public static bool SlidingExpiration { get { Initialize (); return slidingExpiration; } } #endif } }
using System; using System.Collections; using System.Data; using System.Data.OleDb; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComUtils.Framework.ReportFrame.DS { public class sys_ReportHistoryParaDS { public sys_ReportHistoryParaDS() { } private const string THIS = "PCSComUtils.Framework.ReportFrame.DS.DS.sys_ReportHistoryParaDS"; //************************************************************************** /// <Description> /// This method uses to add data to sys_ReportHistoryPara /// </Description> /// <Inputs> /// sys_ReportHistoryParaVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { sys_ReportHistoryParaVO objObject = (sys_ReportHistoryParaVO) pobjObjectVO; string strSql = String.Empty; strSql = "INSERT INTO " + sys_ReportHistoryParaTable.TABLE_NAME + "(" + sys_ReportHistoryParaTable.HISTORYID_FLD + "," + sys_ReportHistoryParaTable.PARANAME_FLD + "," + sys_ReportHistoryParaTable.PARAVALUE_FLD + "," + sys_ReportHistoryParaTable.TAGVALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD + ")" + " VALUES(?,?,?,?,?,?)"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.HISTORYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.HISTORYID_FLD].Value = objObject.HistoryID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.PARANAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.PARANAME_FLD].Value = objObject.ParaName; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.PARAVALUE_FLD, OleDbType.VarWChar)); if (objObject.ParaValue != string.Empty) ocmdPCS.Parameters[sys_ReportHistoryParaTable.PARAVALUE_FLD].Value = objObject.ParaValue; else ocmdPCS.Parameters[sys_ReportHistoryParaTable.PARAVALUE_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.TAGVALUE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.TAGVALUE_FLD].Value = objObject.TagValue; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD].Value = objObject.FilterField1Value; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD].Value = objObject.FilterField2Value; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_ReportHistoryPara /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + sys_ReportHistoryParaTable.TABLE_NAME + " WHERE " + sys_ReportHistoryParaTable.HISTORYID_FLD + "=" + pintID.ToString().Trim(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from sys_ReportHistoryPara /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// sys_ReportHistoryParaVO /// </Outputs> /// <Returns> /// sys_ReportHistoryParaVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportHistoryParaTable.HISTORYID_FLD + "," + sys_ReportHistoryParaTable.PARANAME_FLD + "," + sys_ReportHistoryParaTable.PARAVALUE_FLD + "," + sys_ReportHistoryParaTable.TAGVALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD + " FROM " + sys_ReportHistoryParaTable.TABLE_NAME + " WHERE " + sys_ReportHistoryParaTable.HISTORYID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); sys_ReportHistoryParaVO objObject = new sys_ReportHistoryParaVO(); while (odrPCS.Read()) { objObject.HistoryID = int.Parse(odrPCS[sys_ReportHistoryParaTable.HISTORYID_FLD].ToString().Trim()); objObject.ParaName = odrPCS[sys_ReportHistoryParaTable.PARANAME_FLD].ToString().Trim(); objObject.ParaValue = odrPCS[sys_ReportHistoryParaTable.PARAVALUE_FLD].ToString().Trim(); objObject.TagValue = odrPCS[sys_ReportHistoryParaTable.TAGVALUE_FLD].ToString().Trim(); objObject.FilterField1Value = odrPCS[sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD].ToString().Trim(); objObject.FilterField2Value = odrPCS[sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD].ToString().Trim(); } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to sys_ReportHistoryPara /// </Description> /// <Inputs> /// sys_ReportHistoryParaVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; sys_ReportHistoryParaVO objObject = (sys_ReportHistoryParaVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE " + sys_ReportHistoryParaTable.TABLE_NAME + " SET " + sys_ReportHistoryParaTable.PARANAME_FLD + "= ?" + "," + sys_ReportHistoryParaTable.PARAVALUE_FLD + "= ?" + "," + sys_ReportHistoryParaTable.TAGVALUE_FLD + "= ?" + "," + sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD + "= ?" + "," + sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD + "= ?" + " WHERE " + sys_ReportHistoryParaTable.HISTORYID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.PARANAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.PARANAME_FLD].Value = objObject.ParaName; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.PARAVALUE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.PARAVALUE_FLD].Value = objObject.ParaValue; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.TAGVALUE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.TAGVALUE_FLD].Value = objObject.TagValue; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD].Value = objObject.FilterField1Value; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD].Value = objObject.FilterField2Value; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryParaTable.HISTORYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_ReportHistoryParaTable.HISTORYID_FLD].Value = objObject.HistoryID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from sys_ReportHistoryPara /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportHistoryParaTable.HISTORYID_FLD + "," + sys_ReportHistoryParaTable.PARANAME_FLD + "," + sys_ReportHistoryParaTable.PARAVALUE_FLD + "," + sys_ReportHistoryParaTable.TAGVALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD + " FROM " + sys_ReportHistoryParaTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, sys_ReportHistoryParaTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from sys_ReportHistoryPara of specified History /// </Description> /// <Inputs> /// HistoryID /// </Inputs> /// <Outputs> /// ArrayList /// </Outputs> /// <Returns> /// ArrayList /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 21-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList ListByHistory(string pstrHistoryID) { const string METHOD_NAME = THIS + ".ListByHistory()"; ArrayList arrObjects = new ArrayList(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; OleDbDataReader odrPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportHistoryParaTable.HISTORYID_FLD + "," + sys_ReportHistoryParaTable.PARANAME_FLD + "," + sys_ReportHistoryParaTable.PARAVALUE_FLD + "," + sys_ReportHistoryParaTable.TAGVALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD + " FROM " + sys_ReportHistoryParaTable.TABLE_NAME + " WHERE " + sys_ReportHistoryParaTable.HISTORYID_FLD + "= ? ";// + pstrHistoryID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter( sys_ReportHistoryParaTable.HISTORYID_FLD , OleDbType.VarWChar)); ocmdPCS.Parameters[ sys_ReportHistoryParaTable.HISTORYID_FLD ].Value = pstrHistoryID ; ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); while (odrPCS.Read()) { sys_ReportHistoryParaVO voHistoryPara = new sys_ReportHistoryParaVO(); voHistoryPara.HistoryID = int.Parse(odrPCS[sys_ReportHistoryParaTable.HISTORYID_FLD].ToString().Trim()); voHistoryPara.ParaName = odrPCS[sys_ReportHistoryParaTable.PARANAME_FLD].ToString().Trim(); voHistoryPara.ParaValue = odrPCS[sys_ReportHistoryParaTable.PARAVALUE_FLD].ToString().Trim(); voHistoryPara.TagValue = odrPCS[sys_ReportHistoryParaTable.TAGVALUE_FLD].ToString().Trim(); voHistoryPara.FilterField1Value = odrPCS[sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD].ToString().Trim(); voHistoryPara.FilterField2Value = odrPCS[sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD].ToString().Trim(); arrObjects.Add(voHistoryPara); } arrObjects.TrimToSize(); return arrObjects; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + sys_ReportHistoryParaTable.HISTORYID_FLD + "," + sys_ReportHistoryParaTable.PARANAME_FLD + "," + sys_ReportHistoryParaTable.PARAVALUE_FLD + "," + sys_ReportHistoryParaTable.TAGVALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD1VALUE_FLD + "," + sys_ReportHistoryParaTable.FILTERFIELD2VALUE_FLD + " FROM " + sys_ReportHistoryParaTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData, sys_ReportHistoryParaTable.TABLE_NAME); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_ReportHistoryPara /// but keep 10 last report /// </Description> /// <Inputs> /// HistoryID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 09-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public void DeleteButKeep10Last(int pintMaxID, string pstrUserName) { const string METHOD_NAME = THIS + ".DeleteButKeep10Last()"; string strSql = String.Empty; strSql = "DELETE " + sys_ReportHistoryParaTable.TABLE_NAME + " WHERE " + sys_ReportHistoryParaTable.HISTORYID_FLD + "<=" + (pintMaxID - 9).ToString().Trim() + " AND " + sys_ReportHistoryParaTable.HISTORYID_FLD + " IN (" + " SELECT " + sys_ReportHistoryTable.TABLE_NAME + "." + sys_ReportHistoryTable.HISTORYID_FLD + " FROM " + sys_ReportHistoryTable.TABLE_NAME + " WHERE " + sys_ReportHistoryTable.TABLE_NAME + "." + sys_ReportHistoryTable.USERID_FLD + "= ? )"; //"= '" + pstrUserName + "')"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter( sys_ReportHistoryTable.USERID_FLD , OleDbType.VarWChar)); ocmdPCS.Parameters[ sys_ReportHistoryTable.USERID_FLD ].Value = pstrUserName ; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
// MIT License - Copyright (C) The Mono.Xna Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.Runtime.Serialization; using System.Diagnostics; namespace TriangleDemo { /// <summary> /// Describes a 4D-vector. /// </summary> [DebuggerDisplay("{DebugDisplayString,nq}")] public struct Vector4 : IEquatable<Vector4> { #region Private Fields private static readonly Vector4 zero = new Vector4(); private static readonly Vector4 one = new Vector4(1f, 1f, 1f, 1f); private static readonly Vector4 unitX = new Vector4(1f, 0f, 0f, 0f); private static readonly Vector4 unitY = new Vector4(0f, 1f, 0f, 0f); private static readonly Vector4 unitZ = new Vector4(0f, 0f, 1f, 0f); private static readonly Vector4 unitW = new Vector4(0f, 0f, 0f, 1f); #endregion #region Public Fields /// <summary> /// The x coordinate of this <see cref="Vector4"/>. /// </summary> public float X; /// <summary> /// The y coordinate of this <see cref="Vector4"/>. /// </summary> public float Y; /// <summary> /// The z coordinate of this <see cref="Vector4"/>. /// </summary> public float Z; /// <summary> /// The w coordinate of this <see cref="Vector4"/>. /// </summary> public float W; #endregion #region Public Properties /// <summary> /// Returns a <see cref="Vector4"/> with components 0, 0, 0, 0. /// </summary> public static Vector4 Zero { get { return zero; } } /// <summary> /// Returns a <see cref="Vector4"/> with components 1, 1, 1, 1. /// </summary> public static Vector4 One { get { return one; } } /// <summary> /// Returns a <see cref="Vector4"/> with components 1, 0, 0, 0. /// </summary> public static Vector4 UnitX { get { return unitX; } } /// <summary> /// Returns a <see cref="Vector4"/> with components 0, 1, 0, 0. /// </summary> public static Vector4 UnitY { get { return unitY; } } /// <summary> /// Returns a <see cref="Vector4"/> with components 0, 0, 1, 0. /// </summary> public static Vector4 UnitZ { get { return unitZ; } } /// <summary> /// Returns a <see cref="Vector4"/> with components 0, 0, 0, 1. /// </summary> public static Vector4 UnitW { get { return unitW; } } #endregion #region Internal Properties internal string DebugDisplayString { get { return string.Concat( this.X.ToString(), " ", this.Y.ToString(), " ", this.Z.ToString(), " ", this.W.ToString() ); } } #endregion #region Constructors /// <summary> /// Constructs a 3d vector with X, Y, Z and W from four values. /// </summary> /// <param name="x">The x coordinate in 4d-space.</param> /// <param name="y">The y coordinate in 4d-space.</param> /// <param name="z">The z coordinate in 4d-space.</param> /// <param name="w">The w coordinate in 4d-space.</param> public Vector4(float x, float y, float z, float w) { this.X = x; this.Y = y; this.Z = z; this.W = w; } /// <summary> /// Constructs a 3d vector with X, Y, Z from <see cref="Vector3"/> and W from a scalar. /// </summary> /// <param name="value">The x, y and z coordinates in 4d-space.</param> /// <param name="w">The w coordinate in 4d-space.</param> public Vector4(Vector3 value, float w) { this.X = value.X; this.Y = value.Y; this.Z = value.Z; this.W = w; } /// <summary> /// Constructs a 4d vector with X, Y, Z and W set to the same value. /// </summary> /// <param name="value">The x, y, z and w coordinates in 4d-space.</param> public Vector4(float value) { this.X = value; this.Y = value; this.Z = value; this.W = value; } #endregion #region Public Methods /// <summary> /// Performs vector addition on <paramref name="value1"/> and <paramref name="value2"/>. /// </summary> /// <param name="value1">The first vector to add.</param> /// <param name="value2">The second vector to add.</param> /// <returns>The result of the vector addition.</returns> public static Vector4 Add(Vector4 value1, Vector4 value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; value1.W += value2.W; return value1; } /// <summary> /// Performs vector addition on <paramref name="value1"/> and /// <paramref name="value2"/>, storing the result of the /// addition in <paramref name="result"/>. /// </summary> /// <param name="value1">The first vector to add.</param> /// <param name="value2">The second vector to add.</param> /// <param name="result">The result of the vector addition.</param> public static void Add(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; result.Z = value1.Z + value2.Z; result.W = value1.W + value2.W; } /// <summary> /// Returns the distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The distance between two vectors.</returns> public static float Distance(Vector4 value1, Vector4 value2) { return (float)Math.Sqrt(DistanceSquared(value1, value2)); } /// <summary> /// Returns the distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="result">The distance between two vectors as an output parameter.</param> public static void Distance(ref Vector4 value1, ref Vector4 value2, out float result) { result = (float)Math.Sqrt(DistanceSquared(value1, value2)); } /// <summary> /// Returns the squared distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The squared distance between two vectors.</returns> public static float DistanceSquared(Vector4 value1, Vector4 value2) { return (value1.W - value2.W) * (value1.W - value2.W) + (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } /// <summary> /// Returns the squared distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="result">The squared distance between two vectors as an output parameter.</param> public static void DistanceSquared(ref Vector4 value1, ref Vector4 value2, out float result) { result = (value1.W - value2.W) * (value1.W - value2.W) + (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } /// <summary> /// Divides the components of a <see cref="Vector4"/> by the components of another <see cref="Vector4"/>. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="value2">Divisor <see cref="Vector4"/>.</param> /// <returns>The result of dividing the vectors.</returns> public static Vector4 Divide(Vector4 value1, Vector4 value2) { value1.W /= value2.W; value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } /// <summary> /// Divides the components of a <see cref="Vector4"/> by a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="divider">Divisor scalar.</param> /// <returns>The result of dividing a vector by a scalar.</returns> public static Vector4 Divide(Vector4 value1, float divider) { float factor = 1f / divider; value1.W *= factor; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } /// <summary> /// Divides the components of a <see cref="Vector4"/> by a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="divider">Divisor scalar.</param> /// <param name="result">The result of dividing a vector by a scalar as an output parameter.</param> public static void Divide(ref Vector4 value1, float divider, out Vector4 result) { float factor = 1f / divider; result.W = value1.W * factor; result.X = value1.X * factor; result.Y = value1.Y * factor; result.Z = value1.Z * factor; } /// <summary> /// Divides the components of a <see cref="Vector4"/> by the components of another <see cref="Vector4"/>. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="value2">Divisor <see cref="Vector4"/>.</param> /// <param name="result">The result of dividing the vectors as an output parameter.</param> public static void Divide(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result.W = value1.W / value2.W; result.X = value1.X / value2.X; result.Y = value1.Y / value2.Y; result.Z = value1.Z / value2.Z; } /// <summary> /// Returns a dot product of two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The dot product of two vectors.</returns> public static float Dot(Vector4 value1, Vector4 value2) { return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z + value1.W * value2.W; } /// <summary> /// Returns a dot product of two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="result">The dot product of two vectors as an output parameter.</param> public static void Dot(ref Vector4 value1, ref Vector4 value2, out float result) { result = value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z + value1.W * value2.W; } /// <summary> /// Compares whether current instance is equal to specified <see cref="Object"/>. /// </summary> /// <param name="obj">The <see cref="Object"/> to compare.</param> /// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns> public override bool Equals(object obj) { return (obj is Vector4) ? this == (Vector4)obj : false; } /// <summary> /// Compares whether current instance is equal to specified <see cref="Vector4"/>. /// </summary> /// <param name="other">The <see cref="Vector4"/> to compare.</param> /// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns> public bool Equals(Vector4 other) { return this.W == other.W && this.X == other.X && this.Y == other.Y && this.Z == other.Z; } /// <summary> /// Gets the hash code of this <see cref="Vector4"/>. /// </summary> /// <returns>Hash code of this <see cref="Vector4"/>.</returns> public override int GetHashCode() { return (int)(this.W + this.X + this.Y + this.Y); } /// <summary> /// Returns the length of this <see cref="Vector4"/>. /// </summary> /// <returns>The length of this <see cref="Vector4"/>.</returns> public float Length() { float result = DistanceSquared(this, zero); return (float)Math.Sqrt(result); } /// <summary> /// Returns the squared length of this <see cref="Vector4"/>. /// </summary> /// <returns>The squared length of this <see cref="Vector4"/>.</returns> public float LengthSquared() { return DistanceSquared(this, zero); } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a multiplication of two vectors. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="value2">Source <see cref="Vector4"/>.</param> /// <returns>The result of the vector multiplication.</returns> public static Vector4 Multiply(Vector4 value1, Vector4 value2) { value1.W *= value2.W; value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a multiplication of <see cref="Vector4"/> and a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="scaleFactor">Scalar value.</param> /// <returns>The result of the vector multiplication with a scalar.</returns> public static Vector4 Multiply(Vector4 value1, float scaleFactor) { value1.W *= scaleFactor; value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a multiplication of <see cref="Vector4"/> and a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="scaleFactor">Scalar value.</param> /// <param name="result">The result of the multiplication with a scalar as an output parameter.</param> public static void Multiply(ref Vector4 value1, float scaleFactor, out Vector4 result) { result.W = value1.W * scaleFactor; result.X = value1.X * scaleFactor; result.Y = value1.Y * scaleFactor; result.Z = value1.Z * scaleFactor; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a multiplication of two vectors. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="value2">Source <see cref="Vector4"/>.</param> /// <param name="result">The result of the vector multiplication as an output parameter.</param> public static void Multiply(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result.W = value1.W * value2.W; result.X = value1.X * value2.X; result.Y = value1.Y * value2.Y; result.Z = value1.Z * value2.Z; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains the specified vector inversion. /// </summary> /// <param name="value">Source <see cref="Vector4"/>.</param> /// <returns>The result of the vector inversion.</returns> public static Vector4 Negate(Vector4 value) { value = new Vector4(-value.X, -value.Y, -value.Z, -value.W); return value; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains the specified vector inversion. /// </summary> /// <param name="value">Source <see cref="Vector4"/>.</param> /// <param name="result">The result of the vector inversion as an output parameter.</param> public static void Negate(ref Vector4 value, out Vector4 result) { result.X = -value.X; result.Y = -value.Y; result.Z = -value.Z; result.W = -value.W; } /// <summary> /// Turns this <see cref="Vector4"/> to a unit vector with the same direction. /// </summary> public void Normalize() { Normalize(ref this, out this); } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a normalized values from another vector. /// </summary> /// <param name="value">Source <see cref="Vector4"/>.</param> /// <returns>Unit vector.</returns> public static Vector4 Normalize(Vector4 value) { float factor = DistanceSquared(value, zero); factor = 1f / (float)Math.Sqrt(factor); return new Vector4(value.X*factor,value.Y*factor,value.Z*factor,value.W*factor); } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a normalized values from another vector. /// </summary> /// <param name="value">Source <see cref="Vector4"/>.</param> /// <param name="result">Unit vector as an output parameter.</param> public static void Normalize(ref Vector4 value, out Vector4 result) { float factor = DistanceSquared(value, zero); factor = 1f / (float)Math.Sqrt(factor); result.W = value.W * factor; result.X = value.X * factor; result.Y = value.Y * factor; result.Z = value.Z * factor; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains subtraction of on <see cref="Vector4"/> from a another. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="value2">Source <see cref="Vector4"/>.</param> /// <returns>The result of the vector subtraction.</returns> public static Vector4 Subtract(Vector4 value1, Vector4 value2) { value1.W -= value2.W; value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains subtraction of on <see cref="Vector4"/> from a another. /// </summary> /// <param name="value1">Source <see cref="Vector4"/>.</param> /// <param name="value2">Source <see cref="Vector4"/>.</param> /// <param name="result">The result of the vector subtraction as an output parameter.</param> public static void Subtract(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result.W = value1.W - value2.W; result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; result.Z = value1.Z - value2.Z; } #region Transform /// <summary> /// Creates a new <see cref="Vector4"/> that contains a transformation of 3d-vector by the specified <see cref="Matrix4"/>. /// </summary> /// <param name="value">Source <see cref="Vector3"/>.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <returns>Transformed <see cref="Vector4"/>.</returns> public static Vector4 Transform(Vector3 value, Matrix4 matrix) { Vector4 result; Transform(ref value, ref matrix, out result); return result; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a transformation of 4d-vector by the specified <see cref="Matrix4"/>. /// </summary> /// <param name="value">Source <see cref="Vector4"/>.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <returns>Transformed <see cref="Vector4"/>.</returns> public static Vector4 Transform(Vector4 value, Matrix4 matrix) { Transform(ref value, ref matrix, out value); return value; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a transformation of 3d-vector by the specified <see cref="Matrix4"/>. /// </summary> /// <param name="value">Source <see cref="Vector3"/>.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="result">Transformed <see cref="Vector4"/> as an output parameter.</param> public static void Transform(ref Vector3 value, ref Matrix4 matrix, out Vector4 result) { result.X = (value.X * matrix.M11) + (value.Y * matrix.M21) + (value.Z * matrix.M31) + matrix.M41; result.Y = (value.X * matrix.M12) + (value.Y * matrix.M22) + (value.Z * matrix.M32) + matrix.M42; result.Z = (value.X * matrix.M13) + (value.Y * matrix.M23) + (value.Z * matrix.M33) + matrix.M43; result.W = (value.X * matrix.M14) + (value.Y * matrix.M24) + (value.Z * matrix.M34) + matrix.M44; } /// <summary> /// Creates a new <see cref="Vector4"/> that contains a transformation of 4d-vector by the specified <see cref="Matrix4"/>. /// </summary> /// <param name="value">Source <see cref="Vector4"/>.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="result">Transformed <see cref="Vector4"/> as an output parameter.</param> public static void Transform(ref Vector4 value, ref Matrix4 matrix, out Vector4 result) { var x = (value.X * matrix.M11) + (value.Y * matrix.M21) + (value.Z * matrix.M31) + (value.W * matrix.M41); var y = (value.X * matrix.M12) + (value.Y * matrix.M22) + (value.Z * matrix.M32) + (value.W * matrix.M42); var z = (value.X * matrix.M13) + (value.Y * matrix.M23) + (value.Z * matrix.M33) + (value.W * matrix.M43); var w = (value.X * matrix.M14) + (value.Y * matrix.M24) + (value.Z * matrix.M34) + (value.W * matrix.M44); result.X = x; result.Y = y; result.Z = z; result.W = w; } /// <summary> /// Apply transformation on vectors within array of <see cref="Vector4"/> by the specified <see cref="Matrix4"/> and places the results in an another array. /// </summary> /// <param name="sourceArray">Source array.</param> /// <param name="sourceIndex">The starting index of transformation in the source array.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="destinationArray">Destination array.</param> /// <param name="destinationIndex">The starting index in the destination array, where the first <see cref="Vector4"/> should be written.</param> /// <param name="length">The number of vectors to be transformed.</param> public static void Transform ( Vector4[] sourceArray, int sourceIndex, ref Matrix4 matrix, Vector4[] destinationArray, int destinationIndex, int length ) { if (sourceArray == null) throw new ArgumentNullException("sourceArray"); if (destinationArray == null) throw new ArgumentNullException("destinationArray"); if (sourceArray.Length < sourceIndex + length) throw new ArgumentException("Source array length is lesser than sourceIndex + length"); if (destinationArray.Length < destinationIndex + length) throw new ArgumentException("Destination array length is lesser than destinationIndex + length"); for (var i = 0; i < length; i++) { var value = sourceArray[sourceIndex + i]; destinationArray[destinationIndex + i] = Transform(value, matrix); } } /// <summary> /// Apply transformation on all vectors within array of <see cref="Vector4"/> by the specified <see cref="Matrix4"/> and places the results in an another array. /// </summary> /// <param name="sourceArray">Source array.</param> /// <param name="matrix">The transformation <see cref="Matrix4"/>.</param> /// <param name="destinationArray">Destination array.</param> public static void Transform(Vector4[] sourceArray, ref Matrix4 matrix, Vector4[] destinationArray) { if (sourceArray == null) throw new ArgumentNullException("sourceArray"); if (destinationArray == null) throw new ArgumentNullException("destinationArray"); if (destinationArray.Length < sourceArray.Length) throw new ArgumentException("Destination array length is lesser than source array length"); for (var i = 0; i < sourceArray.Length; i++) { var value = sourceArray[i]; destinationArray[i] = Transform(value, matrix); } } #endregion /// <summary> /// Returns a <see cref="String"/> representation of this <see cref="Vector4"/> in the format: /// {X:[<see cref="X"/>] Y:[<see cref="Y"/>] Z:[<see cref="Z"/>] W:[<see cref="W"/>]} /// </summary> /// <returns>A <see cref="String"/> representation of this <see cref="Vector4"/>.</returns> public override string ToString() { return "{X:" + X + " Y:" + Y + " Z:" + Z + " W:" + W + "}"; } #endregion #region Operators /// <summary> /// Inverts values in the specified <see cref="Vector4"/>. /// </summary> /// <param name="value">Source <see cref="Vector4"/> on the right of the sub sign.</param> /// <returns>Result of the inversion.</returns> public static Vector4 operator -(Vector4 value) { return new Vector4(-value.X, -value.Y, -value.Z, -value.W); } /// <summary> /// Compares whether two <see cref="Vector4"/> instances are equal. /// </summary> /// <param name="value1"><see cref="Vector4"/> instance on the left of the equal sign.</param> /// <param name="value2"><see cref="Vector4"/> instance on the right of the equal sign.</param> /// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns> public static bool operator ==(Vector4 value1, Vector4 value2) { return value1.W == value2.W && value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z; } /// <summary> /// Compares whether two <see cref="Vector4"/> instances are not equal. /// </summary> /// <param name="value1"><see cref="Vector4"/> instance on the left of the not equal sign.</param> /// <param name="value2"><see cref="Vector4"/> instance on the right of the not equal sign.</param> /// <returns><c>true</c> if the instances are not equal; <c>false</c> otherwise.</returns> public static bool operator !=(Vector4 value1, Vector4 value2) { return !(value1 == value2); } /// <summary> /// Adds two vectors. /// </summary> /// <param name="value1">Source <see cref="Vector4"/> on the left of the add sign.</param> /// <param name="value2">Source <see cref="Vector4"/> on the right of the add sign.</param> /// <returns>Sum of the vectors.</returns> public static Vector4 operator +(Vector4 value1, Vector4 value2) { value1.W += value2.W; value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } /// <summary> /// Subtracts a <see cref="Vector4"/> from a <see cref="Vector4"/>. /// </summary> /// <param name="value1">Source <see cref="Vector4"/> on the left of the sub sign.</param> /// <param name="value2">Source <see cref="Vector4"/> on the right of the sub sign.</param> /// <returns>Result of the vector subtraction.</returns> public static Vector4 operator -(Vector4 value1, Vector4 value2) { value1.W -= value2.W; value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } /// <summary> /// Multiplies the components of two vectors by each other. /// </summary> /// <param name="value1">Source <see cref="Vector4"/> on the left of the mul sign.</param> /// <param name="value2">Source <see cref="Vector4"/> on the right of the mul sign.</param> /// <returns>Result of the vector multiplication.</returns> public static Vector4 operator *(Vector4 value1, Vector4 value2) { value1.W *= value2.W; value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } /// <summary> /// Multiplies the components of vector by a scalar. /// </summary> /// <param name="value">Source <see cref="Vector4"/> on the left of the mul sign.</param> /// <param name="scaleFactor">Scalar value on the right of the mul sign.</param> /// <returns>Result of the vector multiplication with a scalar.</returns> public static Vector4 operator *(Vector4 value, float scaleFactor) { value.W *= scaleFactor; value.X *= scaleFactor; value.Y *= scaleFactor; value.Z *= scaleFactor; return value; } /// <summary> /// Multiplies the components of vector by a scalar. /// </summary> /// <param name="scaleFactor">Scalar value on the left of the mul sign.</param> /// <param name="value">Source <see cref="Vector4"/> on the right of the mul sign.</param> /// <returns>Result of the vector multiplication with a scalar.</returns> public static Vector4 operator *(float scaleFactor, Vector4 value) { value.W *= scaleFactor; value.X *= scaleFactor; value.Y *= scaleFactor; value.Z *= scaleFactor; return value; } /// <summary> /// Divides the components of a <see cref="Vector4"/> by the components of another <see cref="Vector4"/>. /// </summary> /// <param name="value1">Source <see cref="Vector4"/> on the left of the div sign.</param> /// <param name="value2">Divisor <see cref="Vector4"/> on the right of the div sign.</param> /// <returns>The result of dividing the vectors.</returns> public static Vector4 operator /(Vector4 value1, Vector4 value2) { value1.W /= value2.W; value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } /// <summary> /// Divides the components of a <see cref="Vector4"/> by a scalar. /// </summary> /// <param name="value1">Source <see cref="Vector4"/> on the left of the div sign.</param> /// <param name="divider">Divisor scalar on the right of the div sign.</param> /// <returns>The result of dividing a vector by a scalar.</returns> public static Vector4 operator /(Vector4 value1, float divider) { float factor = 1f / divider; value1.W *= factor; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } #endregion } }
using System; using System.Text; using NBitcoin.BouncyCastle.Crypto.Parameters; using NBitcoin.BouncyCastle.Crypto.Utilities; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Engines { /// <summary> /// Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005 /// </summary> public class Salsa20Engine : IStreamCipher { public static readonly int DEFAULT_ROUNDS = 20; /** Constants */ private const int StateSize = 16; // 16, 32 bit ints = 64 bytes protected readonly static byte[] sigma = Strings.ToAsciiByteArray("expand 32-byte k"), tau = Strings.ToAsciiByteArray("expand 16-byte k"); protected int rounds; /* * variables to hold the state of the engine * during encryption and decryption */ private int index = 0; internal uint[] engineState = new uint[StateSize]; // state internal uint[] x = new uint[StateSize]; // internal buffer private byte[] keyStream = new byte[StateSize * 4]; // expanded state, 64 bytes private bool initialised = false; /* * internal counter */ private uint cW0, cW1, cW2; /// <summary> /// Creates a 20 round Salsa20 engine. /// </summary> public Salsa20Engine() : this(DEFAULT_ROUNDS) { } /// <summary> /// Creates a Salsa20 engine with a specific number of rounds. /// </summary> /// <param name="rounds">the number of rounds (must be an even number).</param> public Salsa20Engine(int rounds) { if (rounds <= 0 || (rounds & 1) != 0) { throw new ArgumentException("'rounds' must be a positive, even number"); } this.rounds = rounds; } public void Init( bool forEncryption, ICipherParameters parameters) { /* * Salsa20 encryption and decryption is completely * symmetrical, so the 'forEncryption' is * irrelevant. (Like 90% of stream ciphers) */ ParametersWithIV ivParams = parameters as ParametersWithIV; if (ivParams == null) throw new ArgumentException(AlgorithmName + " Init requires an IV", "parameters"); byte[] iv = ivParams.GetIV(); if (iv == null || iv.Length != NonceSize) throw new ArgumentException(AlgorithmName + " requires exactly " + NonceSize + " bytes of IV"); KeyParameter key = ivParams.Parameters as KeyParameter; if (key == null) throw new ArgumentException(AlgorithmName + " Init requires a key", "parameters"); SetKey(key.GetKey(), iv); Reset(); initialised = true; } protected virtual int NonceSize { get { return 8; } } public virtual string AlgorithmName { get { string name = "Salsa20"; if (rounds != DEFAULT_ROUNDS) { name += "/" + rounds; } return name; } } public byte ReturnByte( byte input) { if (LimitExceeded()) { throw new MaxBytesExceededException("2^70 byte limit per IV; Change IV"); } if (index == 0) { GenerateKeyStream(keyStream); AdvanceCounter(); } byte output = (byte)(keyStream[index] ^ input); index = (index + 1) & 63; return output; } protected virtual void AdvanceCounter() { if (++engineState[8] == 0) { ++engineState[9]; } } public void ProcessBytes( byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff) { if (!initialised) { throw new InvalidOperationException(AlgorithmName + " not initialised"); } if ((inOff + len) > inBytes.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + len) > outBytes.Length) { throw new DataLengthException("output buffer too short"); } if (LimitExceeded((uint)len)) { throw new MaxBytesExceededException("2^70 byte limit per IV would be exceeded; Change IV"); } for (int i = 0; i < len; i++) { if (index == 0) { GenerateKeyStream(keyStream); AdvanceCounter(); } outBytes[i+outOff] = (byte)(keyStream[index]^inBytes[i+inOff]); index = (index + 1) & 63; } } public void Reset() { index = 0; ResetLimitCounter(); ResetCounter(); } protected virtual void ResetCounter() { engineState[8] = engineState[9] = 0; } protected virtual void SetKey(byte[] keyBytes, byte[] ivBytes) { if ((keyBytes.Length != 16) && (keyBytes.Length != 32)) { throw new ArgumentException(AlgorithmName + " requires 128 bit or 256 bit key"); } int offset = 0; byte[] constants; // Key engineState[1] = Pack.LE_To_UInt32(keyBytes, 0); engineState[2] = Pack.LE_To_UInt32(keyBytes, 4); engineState[3] = Pack.LE_To_UInt32(keyBytes, 8); engineState[4] = Pack.LE_To_UInt32(keyBytes, 12); if (keyBytes.Length == 32) { constants = sigma; offset = 16; } else { constants = tau; } engineState[11] = Pack.LE_To_UInt32(keyBytes, offset); engineState[12] = Pack.LE_To_UInt32(keyBytes, offset + 4); engineState[13] = Pack.LE_To_UInt32(keyBytes, offset + 8); engineState[14] = Pack.LE_To_UInt32(keyBytes, offset + 12); engineState[0] = Pack.LE_To_UInt32(constants, 0); engineState[5] = Pack.LE_To_UInt32(constants, 4); engineState[10] = Pack.LE_To_UInt32(constants, 8); engineState[15] = Pack.LE_To_UInt32(constants, 12); // IV engineState[6] = Pack.LE_To_UInt32(ivBytes, 0); engineState[7] = Pack.LE_To_UInt32(ivBytes, 4); ResetCounter(); } protected virtual void GenerateKeyStream(byte[] output) { SalsaCore(rounds, engineState, x); Pack.UInt32_To_LE(x, output, 0); } internal static void SalsaCore(int rounds, uint[] input, uint[] x) { if (input.Length != 16) { throw new ArgumentException(); } if (x.Length != 16) { throw new ArgumentException(); } if (rounds % 2 != 0) { throw new ArgumentException("Number of rounds must be even"); } uint x00 = input[ 0]; uint x01 = input[ 1]; uint x02 = input[ 2]; uint x03 = input[ 3]; uint x04 = input[ 4]; uint x05 = input[ 5]; uint x06 = input[ 6]; uint x07 = input[ 7]; uint x08 = input[ 8]; uint x09 = input[ 9]; uint x10 = input[10]; uint x11 = input[11]; uint x12 = input[12]; uint x13 = input[13]; uint x14 = input[14]; uint x15 = input[15]; for (int i = rounds; i > 0; i -= 2) { x04 ^= R((x00+x12), 7); x08 ^= R((x04+x00), 9); x12 ^= R((x08+x04),13); x00 ^= R((x12+x08),18); x09 ^= R((x05+x01), 7); x13 ^= R((x09+x05), 9); x01 ^= R((x13+x09),13); x05 ^= R((x01+x13),18); x14 ^= R((x10+x06), 7); x02 ^= R((x14+x10), 9); x06 ^= R((x02+x14),13); x10 ^= R((x06+x02),18); x03 ^= R((x15+x11), 7); x07 ^= R((x03+x15), 9); x11 ^= R((x07+x03),13); x15 ^= R((x11+x07),18); x01 ^= R((x00+x03), 7); x02 ^= R((x01+x00), 9); x03 ^= R((x02+x01),13); x00 ^= R((x03+x02),18); x06 ^= R((x05+x04), 7); x07 ^= R((x06+x05), 9); x04 ^= R((x07+x06),13); x05 ^= R((x04+x07),18); x11 ^= R((x10+x09), 7); x08 ^= R((x11+x10), 9); x09 ^= R((x08+x11),13); x10 ^= R((x09+x08),18); x12 ^= R((x15+x14), 7); x13 ^= R((x12+x15), 9); x14 ^= R((x13+x12),13); x15 ^= R((x14+x13),18); } x[ 0] = x00 + input[ 0]; x[ 1] = x01 + input[ 1]; x[ 2] = x02 + input[ 2]; x[ 3] = x03 + input[ 3]; x[ 4] = x04 + input[ 4]; x[ 5] = x05 + input[ 5]; x[ 6] = x06 + input[ 6]; x[ 7] = x07 + input[ 7]; x[ 8] = x08 + input[ 8]; x[ 9] = x09 + input[ 9]; x[10] = x10 + input[10]; x[11] = x11 + input[11]; x[12] = x12 + input[12]; x[13] = x13 + input[13]; x[14] = x14 + input[14]; x[15] = x15 + input[15]; } /** * Rotate left * * @param x value to rotate * @param y amount to rotate x * * @return rotated x */ internal static uint R(uint x, int y) { return (x << y) | (x >> (32 - y)); } private void ResetLimitCounter() { cW0 = 0; cW1 = 0; cW2 = 0; } private bool LimitExceeded() { if (++cW0 == 0) { if (++cW1 == 0) { return (++cW2 & 0x20) != 0; // 2^(32 + 32 + 6) } } return false; } /* * this relies on the fact len will always be positive. */ private bool LimitExceeded( uint len) { uint old = cW0; cW0 += len; if (cW0 < old) { if (++cW1 == 0) { return (++cW2 & 0x20) != 0; // 2^(32 + 32 + 6) } } return false; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Compute { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Unmanaged; /// <summary> /// Compute implementation. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class ComputeImpl : PlatformTarget { /** */ private const int OpAffinity = 1; /** */ private const int OpBroadcast = 2; /** */ private const int OpExec = 3; /** */ private const int OpExecAsync = 4; /** */ private const int OpUnicast = 5; /** */ private const int OpWithNoFailover = 6; /** */ private const int OpWithTimeout = 7; /** */ private const int OpExecNative = 8; /** Underlying projection. */ private readonly ClusterGroupImpl _prj; /** Whether objects must be kept in binary form. */ private readonly ThreadLocal<bool> _keepBinary = new ThreadLocal<bool>(() => false); /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="prj">Projection.</param> /// <param name="keepBinary">Binary flag.</param> public ComputeImpl(IUnmanagedTarget target, Marshaller marsh, ClusterGroupImpl prj, bool keepBinary) : base(target, marsh) { _prj = prj; _keepBinary.Value = keepBinary; } /// <summary> /// Grid projection to which this compute instance belongs. /// </summary> public IClusterGroup ClusterGroup { get { return _prj; } } /// <summary> /// Sets no-failover flag for the next executed task on this projection in the current thread. /// If flag is set, job will be never failed over even if remote node crashes or rejects execution. /// When task starts execution, the no-failover flag is reset, so all other task will use default /// failover policy, unless this flag is set again. /// </summary> public void WithNoFailover() { DoOutInOp(OpWithNoFailover); } /// <summary> /// Sets task timeout for the next executed task on this projection in the current thread. /// When task starts execution, the timeout is reset, so one timeout is used only once. /// </summary> /// <param name="timeout">Computation timeout in milliseconds.</param> public void WithTimeout(long timeout) { DoOutInOp(OpWithTimeout, timeout); } /// <summary> /// Sets keep-binary flag for the next executed Java task on this projection in the current /// thread so that task argument passed to Java and returned task results will not be /// deserialized. /// </summary> public void WithKeepBinary() { _keepBinary.Value = true; } /// <summary> /// Executes given Java task on the grid projection. If task for given name has not been deployed yet, /// then 'taskName' will be used as task class name to auto-deploy the task. /// </summary> public TReduceRes ExecuteJavaTask<TReduceRes>(string taskName, object taskArg) { IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName"); ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes(); try { return DoOutInOp<TReduceRes>(OpExec, writer => WriteTask(writer, taskName, taskArg, nodes)); } finally { _keepBinary.Value = false; } } /// <summary> /// Executes given Java task asynchronously on the grid projection. /// If task for given name has not been deployed yet, /// then 'taskName' will be used as task class name to auto-deploy the task. /// </summary> public Future<TReduceRes> ExecuteJavaTaskAsync<TReduceRes>(string taskName, object taskArg) { IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName"); ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes(); try { return DoOutOpObjectAsync<TReduceRes>(OpExecAsync, w => WriteTask(w, taskName, taskArg, nodes)); } finally { _keepBinary.Value = false; } } /// <summary> /// Executes given task on the grid projection. For step-by-step explanation of task execution process /// refer to <see cref="IComputeTask{A,T,R}"/> documentation. /// </summary> /// <param name="task">Task to execute.</param> /// <param name="taskArg">Optional task argument.</param> /// <returns>Task result.</returns> public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(IComputeTask<TArg, TJobRes, TReduceRes> task, TArg taskArg) { IgniteArgumentCheck.NotNull(task, "task"); var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, taskArg); long ptr = Marshaller.Ignite.HandleRegistry.Allocate(holder); var futTarget = DoOutOpObject(OpExecNative, w => { w.WriteLong(ptr); w.WriteLong(_prj.TopologyVersion); }); var future = holder.Future; future.SetTarget(new Listenable(futTarget, Marshaller)); return future; } /// <summary> /// Executes given task on the grid projection. For step-by-step explanation of task execution process /// refer to <see cref="IComputeTask{A,T,R}"/> documentation. /// </summary> /// <param name="taskType">Task type.</param> /// <param name="taskArg">Optional task argument.</param> /// <returns>Task result.</returns> public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg) { IgniteArgumentCheck.NotNull(taskType, "taskType"); object task = FormatterServices.GetUninitializedObject(taskType); var task0 = task as IComputeTask<TArg, TJobRes, TReduceRes>; if (task0 == null) throw new IgniteException("Task type doesn't implement IComputeTask: " + taskType.Name); return Execute(task0, taskArg); } /// <summary> /// Executes provided job on a node in this grid projection. The result of the /// job execution is returned from the result closure. /// </summary> /// <param name="clo">Job to execute.</param> /// <returns>Job result for this execution.</returns> public Future<TJobRes> Execute<TJobRes>(IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(), new ComputeOutFuncJob(clo.ToNonGeneric()), null, false); } /// <summary> /// Executes provided delegate on a node in this grid projection. The result of the /// job execution is returned from the result closure. /// </summary> /// <param name="func">Func to execute.</param> /// <returns>Job result for this execution.</returns> public Future<TJobRes> Execute<TJobRes>(Func<TJobRes> func) { IgniteArgumentCheck.NotNull(func, "func"); var wrappedFunc = new ComputeOutFuncWrapper(func, () => func()); return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(), new ComputeOutFuncJob(wrappedFunc), null, false); } /// <summary> /// Executes collection of jobs on nodes within this grid projection. /// </summary> /// <param name="clos">Collection of jobs to execute.</param> /// <returns>Collection of job results for this execution.</returns> public Future<ICollection<TJobRes>> Execute<TJobRes>(IEnumerable<IComputeFunc<TJobRes>> clos) { IgniteArgumentCheck.NotNull(clos, "clos"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos)); foreach (IComputeFunc<TJobRes> clo in clos) jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric())); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(jobs.Count), null, jobs, false); } /// <summary> /// Executes collection of jobs on nodes within this grid projection. /// </summary> /// <param name="clos">Collection of jobs to execute.</param> /// <param name="rdc">Reducer to reduce all job results into one individual return value.</param> /// <returns>Collection of job results for this execution.</returns> public Future<TReduceRes> Execute<TJobRes, TReduceRes>(IEnumerable<IComputeFunc<TJobRes>> clos, IComputeReducer<TJobRes, TReduceRes> rdc) { IgniteArgumentCheck.NotNull(clos, "clos"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos)); foreach (var clo in clos) jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric())); return ExecuteClosures0(new ComputeReducingClosureTask<object, TJobRes, TReduceRes>(rdc), null, jobs, false); } /// <summary> /// Broadcasts given job to all nodes in grid projection. Every participating node will return a job result. /// </summary> /// <param name="clo">Job to broadcast to all projection nodes.</param> /// <returns>Collection of results for this execution.</returns> public Future<ICollection<TJobRes>> Broadcast<TJobRes>(IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1), new ComputeOutFuncJob(clo.ToNonGeneric()), null, true); } /// <summary> /// Broadcasts given closure job with passed in argument to all nodes in grid projection. /// Every participating node will return a job result. /// </summary> /// <param name="clo">Job to broadcast to all projection nodes.</param> /// <param name="arg">Job closure argument.</param> /// <returns>Collection of results for this execution.</returns> public Future<ICollection<TJobRes>> Broadcast<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1), new ComputeFuncJob(clo.ToNonGeneric(), arg), null, true); } /// <summary> /// Broadcasts given job to all nodes in grid projection. /// </summary> /// <param name="action">Job to broadcast to all projection nodes.</param> public Future<object> Broadcast(IComputeAction action) { IgniteArgumentCheck.NotNull(action, "action"); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), new ComputeActionJob(action), opId: OpBroadcast); } /// <summary> /// Executes provided job on a node in this grid projection. /// </summary> /// <param name="action">Job to execute.</param> public Future<object> Run(IComputeAction action) { IgniteArgumentCheck.NotNull(action, "action"); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), new ComputeActionJob(action)); } /// <summary> /// Executes collection of jobs on Ignite nodes within this grid projection. /// </summary> /// <param name="actions">Jobs to execute.</param> public Future<object> Run(IEnumerable<IComputeAction> actions) { IgniteArgumentCheck.NotNull(actions, "actions"); var actions0 = actions as ICollection; if (actions0 == null) { var jobs = actions.Select(a => new ComputeActionJob(a)).ToList(); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs, jobsCount: jobs.Count); } else { var jobs = actions.Select(a => new ComputeActionJob(a)); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs, jobsCount: actions0.Count); } } /// <summary> /// Executes provided closure job on a node in this grid projection. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="arg">Job argument.</param> /// <returns>Job result for this execution.</returns> public Future<TJobRes> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeSingleClosureTask<TArg, TJobRes, TJobRes>(), new ComputeFuncJob(clo.ToNonGeneric(), arg), null, false); } /// <summary> /// Executes provided closure job on nodes within this grid projection. A new job is executed for /// every argument in the passed in collection. The number of actual job executions will be /// equal to size of the job arguments collection. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="args">Job arguments.</param> /// <returns>Collection of job results.</returns> public Future<ICollection<TJobRes>> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, IEnumerable<TArg> args) { IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); var jobs = new List<IComputeJob>(GetCountOrZero(args)); var func = clo.ToNonGeneric(); foreach (TArg arg in args) jobs.Add(new ComputeFuncJob(func, arg)); return ExecuteClosures0(new ComputeMultiClosureTask<TArg, TJobRes, ICollection<TJobRes>>(jobs.Count), null, jobs, false); } /// <summary> /// Executes provided closure job on nodes within this grid projection. A new job is executed for /// every argument in the passed in collection. The number of actual job executions will be /// equal to size of the job arguments collection. The returned job results will be reduced /// into an individual result by provided reducer. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="args">Job arguments.</param> /// <param name="rdc">Reducer to reduce all job results into one individual return value.</param> /// <returns>Reduced job result for this execution.</returns> public Future<TReduceRes> Apply<TArg, TJobRes, TReduceRes>(IComputeFunc<TArg, TJobRes> clo, IEnumerable<TArg> args, IComputeReducer<TJobRes, TReduceRes> rdc) { IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(args)); var func = clo.ToNonGeneric(); foreach (TArg arg in args) jobs.Add(new ComputeFuncJob(func, arg)); return ExecuteClosures0(new ComputeReducingClosureTask<TArg, TJobRes, TReduceRes>(rdc), null, jobs, false); } /// <summary> /// Executes given job on the node where data for provided affinity key is located /// (a.k.a. affinity co-location). /// </summary> /// <param name="cacheName">Name of the cache to use for affinity co-location.</param> /// <param name="affinityKey">Affinity key.</param> /// <param name="action">Job to execute.</param> public Future<object> AffinityRun(string cacheName, object affinityKey, IComputeAction action) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); IgniteArgumentCheck.NotNull(action, "action"); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), new ComputeActionJob(action), opId: OpAffinity, writeAction: w => WriteAffinity(w, cacheName, affinityKey)); } /// <summary> /// Executes given job on the node where data for provided affinity key is located /// (a.k.a. affinity co-location). /// </summary> /// <param name="cacheName">Name of the cache to use for affinity co-location.</param> /// <param name="affinityKey">Affinity key.</param> /// <param name="clo">Job to execute.</param> /// <returns>Job result for this execution.</returns> /// <typeparam name="TJobRes">Type of job result.</typeparam> public Future<TJobRes> AffinityCall<TJobRes>(string cacheName, object affinityKey, IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(), new ComputeOutFuncJob(clo.ToNonGeneric()), opId: OpAffinity, writeAction: w => WriteAffinity(w, cacheName, affinityKey)); } /** <inheritDoc /> */ protected override T Unmarshal<T>(IBinaryStream stream) { bool keep = _keepBinary.Value; return Marshaller.Unmarshal<T>(stream, keep); } /// <summary> /// Internal routine for closure-based task execution. /// </summary> /// <param name="task">Task.</param> /// <param name="job">Job.</param> /// <param name="jobs">Jobs.</param> /// <param name="broadcast">Broadcast flag.</param> /// <returns>Future.</returns> private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>( IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job, ICollection<IComputeJob> jobs, bool broadcast) { return ExecuteClosures0(task, job, jobs, broadcast ? OpBroadcast : OpUnicast, jobs == null ? 1 : jobs.Count); } /// <summary> /// Internal routine for closure-based task execution. /// </summary> /// <param name="task">Task.</param> /// <param name="job">Job.</param> /// <param name="jobs">Jobs.</param> /// <param name="opId">Op code.</param> /// <param name="jobsCount">Jobs count.</param> /// <param name="writeAction">Custom write action.</param> /// <returns>Future.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User code can throw any exception")] private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>( IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job = null, IEnumerable<IComputeJob> jobs = null, int opId = OpUnicast, int jobsCount = 0, Action<BinaryWriter> writeAction = null) { Debug.Assert(job != null || jobs != null); var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, default(TArg)); var taskHandle = Marshaller.Ignite.HandleRegistry.Allocate(holder); var jobHandles = new List<long>(job != null ? 1 : jobsCount); try { Exception err = null; try { var futTarget = DoOutOpObject(opId, writer => { writer.WriteLong(taskHandle); if (job != null) { writer.WriteInt(1); jobHandles.Add(WriteJob(job, writer)); } else { writer.WriteInt(jobsCount); Debug.Assert(jobs != null, "jobs != null"); jobHandles.AddRange(jobs.Select(jobEntry => WriteJob(jobEntry, writer))); } holder.JobHandles(jobHandles); if (writeAction != null) writeAction(writer); }); holder.Future.SetTarget(new Listenable(futTarget, Marshaller)); } catch (Exception e) { err = e; } if (err != null) { // Manual job handles release because they were not assigned to the task yet. foreach (var hnd in jobHandles) Marshaller.Ignite.HandleRegistry.Release(hnd); holder.CompleteWithError(taskHandle, err); } } catch (Exception e) { // This exception means that out-op failed. holder.CompleteWithError(taskHandle, e); } return holder.Future; } /// <summary> /// Writes the job. /// </summary> /// <param name="job">The job.</param> /// <param name="writer">The writer.</param> /// <returns>Handle to the job holder</returns> private long WriteJob(IComputeJob job, BinaryWriter writer) { var jobHolder = new ComputeJobHolder((Ignite) _prj.Ignite, job); var jobHandle = Marshaller.Ignite.HandleRegistry.Allocate(jobHolder); writer.WriteLong(jobHandle); try { writer.WriteObject(jobHolder); } catch (Exception) { Marshaller.Ignite.HandleRegistry.Release(jobHandle); throw; } return jobHandle; } /// <summary> /// Write task to the writer. /// </summary> /// <param name="writer">Writer.</param> /// <param name="taskName">Task name.</param> /// <param name="taskArg">Task arg.</param> /// <param name="nodes">Nodes.</param> private void WriteTask(IBinaryRawWriter writer, string taskName, object taskArg, ICollection<IClusterNode> nodes) { writer.WriteString(taskName); writer.WriteBoolean(_keepBinary.Value); writer.WriteObject(taskArg); WriteNodeIds(writer, nodes); } /// <summary> /// Write node IDs. /// </summary> /// <param name="writer">Writer.</param> /// <param name="nodes">Nodes.</param> private static void WriteNodeIds(IBinaryRawWriter writer, ICollection<IClusterNode> nodes) { if (nodes == null) writer.WriteBoolean(false); else { writer.WriteBoolean(true); writer.WriteInt(nodes.Count); foreach (IClusterNode node in nodes) writer.WriteGuid(node.Id); } } /// <summary> /// Writes the affinity info. /// </summary> /// <param name="writer">The writer.</param> /// <param name="cacheName">Name of the cache to use for affinity co-location.</param> /// <param name="affinityKey">Affinity key.</param> private static void WriteAffinity(BinaryWriter writer, string cacheName, object affinityKey) { writer.WriteString(cacheName); writer.WriteObject(affinityKey); } /// <summary> /// Gets element count or zero. /// </summary> private static int GetCountOrZero(object collection) { var coll = collection as ICollection; return coll == null ? 0 : coll.Count; } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.Text; using System.IO; using System.Collections; using NUnit.Core; namespace NUnit.UiKit { /// <summary> /// Summary description for TestPropertiesDialog. /// </summary> public class TestPropertiesDialog : System.Windows.Forms.Form { #region Instance Variables; private TestSuiteTreeNode node; private ITest test; private TestResult result; private Image pinnedImage; private Image unpinnedImage; private System.Windows.Forms.CheckBox pinButton; private System.Windows.Forms.Label testResult; private System.Windows.Forms.Label testName; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label7; private CP.Windows.Forms.ExpandingLabel description; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label testCaseCount; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label shouldRun; private System.Windows.Forms.Label label2; private CP.Windows.Forms.ExpandingLabel fullName; private System.Windows.Forms.Label label1; private CP.Windows.Forms.ExpandingLabel ignoreReason; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label testType; private System.Windows.Forms.Label label3; private CP.Windows.Forms.ExpandingLabel stackTrace; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label elapsedTime; private CP.Windows.Forms.ExpandingLabel message; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label assertCount; private System.Windows.Forms.ListBox properties; private System.Windows.Forms.ListBox categories; private System.ComponentModel.IContainer components = null; #endregion #region Construction and Disposal public TestPropertiesDialog( TestSuiteTreeNode node ) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // this.node = node; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pinButton = new System.Windows.Forms.CheckBox(); this.testResult = new System.Windows.Forms.Label(); this.testName = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.categories = new System.Windows.Forms.ListBox(); this.properties = new System.Windows.Forms.ListBox(); this.label11 = new System.Windows.Forms.Label(); this.ignoreReason = new CP.Windows.Forms.ExpandingLabel(); this.label5 = new System.Windows.Forms.Label(); this.testType = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.description = new CP.Windows.Forms.ExpandingLabel(); this.label6 = new System.Windows.Forms.Label(); this.testCaseCount = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.shouldRun = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.fullName = new CP.Windows.Forms.ExpandingLabel(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.stackTrace = new CP.Windows.Forms.ExpandingLabel(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.assertCount = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.elapsedTime = new System.Windows.Forms.Label(); this.message = new CP.Windows.Forms.ExpandingLabel(); this.label12 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // pinButton // this.pinButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pinButton.Appearance = System.Windows.Forms.Appearance.Button; this.pinButton.Location = new System.Drawing.Point(440, 8); this.pinButton.Name = "pinButton"; this.pinButton.Size = new System.Drawing.Size(20, 20); this.pinButton.TabIndex = 14; this.pinButton.Click += new System.EventHandler(this.pinButton_Click); this.pinButton.CheckedChanged += new System.EventHandler(this.pinButton_CheckedChanged); // // testResult // this.testResult.Font = new System.Drawing.Font(FontFamily.GenericSansSerif, 9F, System.Drawing.FontStyle.Bold); this.testResult.Location = new System.Drawing.Point(16, 16); this.testResult.Name = "testResult"; this.testResult.Size = new System.Drawing.Size(120, 16); this.testResult.TabIndex = 46; this.testResult.Text = "Failure"; this.testResult.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // testName // this.testName.Location = new System.Drawing.Point(144, 16); this.testName.Name = "testName"; this.testName.Size = new System.Drawing.Size(280, 16); this.testName.TabIndex = 49; this.testName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.categories); this.groupBox1.Controls.Add(this.properties); this.groupBox1.Controls.Add(this.label11); this.groupBox1.Controls.Add(this.ignoreReason); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.testType); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.description); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.testCaseCount); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.shouldRun); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.fullName); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Location = new System.Drawing.Point(16, 48); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(440, 376); this.groupBox1.TabIndex = 50; this.groupBox1.TabStop = false; this.groupBox1.Text = "Test Details"; // // categories // this.categories.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.categories.ItemHeight = 16; this.categories.Location = new System.Drawing.Point(104, 152); this.categories.Name = "categories"; this.categories.Size = new System.Drawing.Size(320, 52); this.categories.TabIndex = 58; // // properties // this.properties.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.properties.ItemHeight = 16; this.properties.Location = new System.Drawing.Point(104, 304); this.properties.Name = "properties"; this.properties.Size = new System.Drawing.Size(320, 52); this.properties.TabIndex = 57; // // label11 // this.label11.Location = new System.Drawing.Point(24, 312); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(80, 16); this.label11.TabIndex = 56; this.label11.Text = "Properties:"; // // ignoreReason // this.ignoreReason.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ignoreReason.CopySupported = true; this.ignoreReason.Expansion = CP.Windows.Forms.TipWindow.ExpansionStyle.Vertical; this.ignoreReason.Location = new System.Drawing.Point(112, 248); this.ignoreReason.Name = "ignoreReason"; this.ignoreReason.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ignoreReason.Size = new System.Drawing.Size(312, 48); this.ignoreReason.TabIndex = 42; // // label5 // this.label5.Location = new System.Drawing.Point(24, 248); this.label5.Name = "label5"; this.label5.RightToLeft = System.Windows.Forms.RightToLeft.No; this.label5.Size = new System.Drawing.Size(80, 16); this.label5.TabIndex = 43; this.label5.Text = "Reason:"; // // testType // this.testType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.testType.Location = new System.Drawing.Point(112, 32); this.testType.Name = "testType"; this.testType.Size = new System.Drawing.Size(312, 16); this.testType.TabIndex = 55; // // label8 // this.label8.Location = new System.Drawing.Point(24, 32); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(80, 16); this.label8.TabIndex = 54; this.label8.Text = "Test Type:"; // // label7 // this.label7.Location = new System.Drawing.Point(24, 152); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(80, 16); this.label7.TabIndex = 52; this.label7.Text = "Categories:"; // // description // this.description.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.description.CopySupported = true; this.description.Expansion = CP.Windows.Forms.TipWindow.ExpansionStyle.Both; this.description.Location = new System.Drawing.Point(112, 96); this.description.Name = "description"; this.description.Size = new System.Drawing.Size(312, 48); this.description.TabIndex = 51; // // label6 // this.label6.Location = new System.Drawing.Point(24, 96); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(80, 17); this.label6.TabIndex = 50; this.label6.Text = "Description:"; // // testCaseCount // this.testCaseCount.Location = new System.Drawing.Point(112, 216); this.testCaseCount.Name = "testCaseCount"; this.testCaseCount.Size = new System.Drawing.Size(48, 15); this.testCaseCount.TabIndex = 49; // // label4 // this.label4.Location = new System.Drawing.Point(24, 216); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(80, 15); this.label4.TabIndex = 48; this.label4.Text = "Test Count:"; // // shouldRun // this.shouldRun.Location = new System.Drawing.Point(304, 216); this.shouldRun.Name = "shouldRun"; this.shouldRun.Size = new System.Drawing.Size(88, 15); this.shouldRun.TabIndex = 47; this.shouldRun.Text = "Yes"; // // label2 // this.label2.Location = new System.Drawing.Point(188, 216); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(84, 15); this.label2.TabIndex = 46; this.label2.Text = "Should Run?"; // // fullName // this.fullName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.fullName.CopySupported = true; this.fullName.Location = new System.Drawing.Point(112, 63); this.fullName.Name = "fullName"; this.fullName.Size = new System.Drawing.Size(312, 17); this.fullName.TabIndex = 45; // // label1 // this.label1.Location = new System.Drawing.Point(24, 63); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(80, 17); this.label1.TabIndex = 44; this.label1.Text = "Full Name:"; // // label3 // this.label3.Location = new System.Drawing.Point(16, 392); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 15); this.label3.TabIndex = 47; this.label3.Text = "Message:"; this.label3.TextAlign = System.Drawing.ContentAlignment.TopRight; // // stackTrace // this.stackTrace.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.stackTrace.CopySupported = true; this.stackTrace.Expansion = CP.Windows.Forms.TipWindow.ExpansionStyle.Both; this.stackTrace.Location = new System.Drawing.Point(112, 128); this.stackTrace.Name = "stackTrace"; this.stackTrace.Size = new System.Drawing.Size(312, 49); this.stackTrace.TabIndex = 45; // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.assertCount); this.groupBox2.Controls.Add(this.label10); this.groupBox2.Controls.Add(this.elapsedTime); this.groupBox2.Controls.Add(this.message); this.groupBox2.Controls.Add(this.stackTrace); this.groupBox2.Controls.Add(this.label12); this.groupBox2.Location = new System.Drawing.Point(16, 432); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(440, 192); this.groupBox2.TabIndex = 51; this.groupBox2.TabStop = false; this.groupBox2.Text = "Result"; // // assertCount // this.assertCount.Location = new System.Drawing.Point(240, 32); this.assertCount.Name = "assertCount"; this.assertCount.Size = new System.Drawing.Size(176, 16); this.assertCount.TabIndex = 61; this.assertCount.Text = "Assert Count:"; // // label10 // this.label10.Location = new System.Drawing.Point(24, 63); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(80, 17); this.label10.TabIndex = 60; this.label10.Text = "Message:"; // // elapsedTime // this.elapsedTime.Location = new System.Drawing.Point(24, 32); this.elapsedTime.Name = "elapsedTime"; this.elapsedTime.Size = new System.Drawing.Size(192, 16); this.elapsedTime.TabIndex = 58; this.elapsedTime.Text = "Execution Time:"; // // message // this.message.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.message.CopySupported = true; this.message.Expansion = CP.Windows.Forms.TipWindow.ExpansionStyle.Both; this.message.Location = new System.Drawing.Point(112, 63); this.message.Name = "message"; this.message.Size = new System.Drawing.Size(312, 49); this.message.TabIndex = 57; // // label12 // this.label12.Location = new System.Drawing.Point(24, 128); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(80, 16); this.label12.TabIndex = 56; this.label12.Text = "Stack:"; // // TestPropertiesDialog // this.ClientSize = new System.Drawing.Size(472, 634); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.testName); this.Controls.Add(this.testResult); this.Controls.Add(this.pinButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "TestPropertiesDialog"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.Text = "Test Properties"; this.Load += new System.EventHandler(this.TestPropertiesDialog_Load); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Properties [Browsable( false )] public bool Pinned { get { return pinButton.Checked; } set { pinButton.Checked = value; } } #endregion #region Methods private void SetTitleBarText() { string name = test.TestName.Name; int index = name.LastIndexOfAny( new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar } ); if ( index >= 0 ) name = name.Substring( index + 1 ); this.Text = string.Format( "{0} Properties - {1}", node.TestType, name ); } /// <summary> /// Set up all dialog fields when it loads /// </summary> private void TestPropertiesDialog_Load(object sender, System.EventArgs e) { pinnedImage = new Bitmap( typeof( TestPropertiesDialog ), "pinned.gif" ); unpinnedImage = new Bitmap( typeof( TestPropertiesDialog ), "unpinned.gif" ); pinButton.Image = unpinnedImage; DisplayProperties(); node.TreeView.AfterSelect += new TreeViewEventHandler( OnSelectedNodeChanged ); } private void OnSelectedNodeChanged( object sender, TreeViewEventArgs e ) { if ( pinButton.Checked ) { DisplayProperties( (TestSuiteTreeNode)e.Node ); } else this.Close(); } public void DisplayProperties( ) { DisplayProperties( this.node ); } public void DisplayProperties( TestSuiteTreeNode node) { this.node = node; this.test = node.Test; this.result = node.Result; SetTitleBarText(); categories.Items.Clear(); foreach( string cat in test.Categories ) categories.Items.Add( cat ); testResult.Text = node.StatusText; testName.Text = test.TestName.Name; testType.Text = node.TestType; fullName.Text = test.TestName.FullName; switch( test.RunState ) { case RunState.Explicit: shouldRun.Text = "Explicit"; break; case RunState.Runnable: shouldRun.Text = "Yes"; break; default: shouldRun.Text = "No"; break; } description.Text = test.Description; ignoreReason.Text = test.IgnoreReason; testCaseCount.Text = test.TestCount.ToString(); properties.Items.Clear(); foreach (DictionaryEntry entry in test.Properties) { if (entry.Value is ICollection) { ICollection items = (ICollection)entry.Value; if (items.Count == 0) continue; StringBuilder sb = new StringBuilder(); foreach (object item in items) { if (sb.Length > 0) sb.Append(","); sb.Append(item.ToString()); } properties.Items.Add( entry.Key.ToString() + "=" +sb.ToString() ); } else properties.Items.Add( entry.Key.ToString() + "=" + entry.Value.ToString()); } message.Text = ""; elapsedTime.Text = "Execution Time:"; assertCount.Text = "Assert Count:"; stackTrace.Text = ""; if ( result != null ) { // message may have a leading blank line // TODO: take care of this in label? if (result.Message != null) { if (result.Message.Length > 64000) message.Text = TrimLeadingBlankLines(result.Message.Substring(0, 64000)); else message.Text = TrimLeadingBlankLines(result.Message); } elapsedTime.Text = string.Format( "Execution Time: {0}", result.Time ); assertCount.Text = string.Format( "Assert Count: {0}", result.AssertCount ); stackTrace.Text = result.StackTrace; } } private string TrimLeadingBlankLines( string s ) { if ( s == null ) return s; int start = 0; for( int i = 0; i < s.Length; i++ ) { switch( s[i] ) { case ' ': case '\t': break; case '\r': case '\n': start = i + 1; break; default: goto getout; } } getout: return start == 0 ? s : s.Substring( start ); } protected override bool ProcessKeyPreview(ref System.Windows.Forms.Message m) { const int ESCAPE = 27; const int WM_CHAR = 258; if (m.Msg == WM_CHAR && m.WParam.ToInt32() == ESCAPE ) { this.Close(); return true; } return base.ProcessKeyEventArgs( ref m ); } private void pinButton_Click(object sender, System.EventArgs e) { if ( pinButton.Checked ) pinButton.Image = pinnedImage; else pinButton.Image = unpinnedImage; } private void pinButton_CheckedChanged(object sender, System.EventArgs e) { } } #endregion }
<?cs include:"doctype.cs" ?> <?cs include:"macros.cs" ?> <html> <?cs include:"head_tag.cs" ?> <body class="<?cs var:class.since.key ?>"> <?cs include:"header.cs" ?> <div class="g-unit" id="doc-content"> <div id="api-info-block"> <?cs # are there inherited members ?> <?cs each:cl=class.inherited ?> <?cs if:subcount(cl.methods) ?> <?cs set:inhmethods = #1 ?> <?cs /if ?> <?cs if:subcount(cl.constants) ?> <?cs set:inhconstants = #1 ?> <?cs /if ?> <?cs if:subcount(cl.fields) ?> <?cs set:inhfields = #1 ?> <?cs /if ?> <?cs if:subcount(cl.attrs) ?> <?cs set:inhattrs = #1 ?> <?cs /if ?> <?cs /each ?> <div class="sum-details-links"> <?cs if:doclava.generate.sources ?> <div> <a href="<?cs var:class.name ?>-source.html">View Source</a> </div> <?cs /if ?> <?cs if:inhattrs || inhconstants || inhfields || inhmethods || (!class.subclasses.hidden && (subcount(class.subclasses.direct) || subcount(class.subclasses.indirect))) ?> Summary: <?cs if:subcount(class.inners) ?> <a href="#nestedclasses">Nested Classes</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:subcount(class.attrs) ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#lattrs">XML Attrs</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:inhattrs ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#inhattrs">Inherited XML Attrs</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:subcount(class.enumConstants) ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#enumconstants">Enums</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:subcount(class.constants) ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#constants">Constants</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:inhconstants ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#inhconstants">Inherited Constants</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:subcount(class.fields) ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#lfields">Fields</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:inhfields ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#inhfields">Inherited Fields</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:subcount(class.ctors.public) ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#pubctors">Ctors</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:subcount(class.ctors.protected) ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#proctors">Protected Ctors</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:subcount(class.methods.public) ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#pubmethods">Methods</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:subcount(class.methods.protected) ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#promethods">Protected Methods</a> <?cs set:linkcount = #1 ?> <?cs /if ?> <?cs if:inhmethods ?> <?cs if:linkcount ?>&#124; <?cs /if ?><a href="#inhmethods">Inherited Methods</a> <?cs /if ?> &#124; <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a> <?cs /if ?> </div><!-- end sum-details-links --> <div class="api-level"> <?cs call:since_tags(class) ?> <?cs call:federated_refs(class) ?> </div> </div><!-- end api-info-block --> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ======== START OF CLASS DATA ======== --> <div id="jd-header"> <?cs var:class.scope ?> <?cs var:class.static ?> <?cs var:class.final ?> <?cs var:class.abstract ?> <?cs var:class.kind ?> <h1><?cs var:class.name ?></h1> <?cs set:colspan = subcount(class.inheritance) ?> <?cs each:supr = class.inheritance ?> <?cs if:colspan == 2 ?> extends <?cs call:type_link(supr.short_class) ?><br/> <?cs /if ?> <?cs if:last(supr) && subcount(supr.interfaces) ?> implements <?cs each:t=supr.interfaces ?> <?cs call:type_link(t) ?> <?cs /each ?> <?cs /if ?> <?cs set:colspan = colspan-1 ?> <?cs /each ?> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-<?cs var:class.since.key ?>"> <table class="jd-inheritance-table"> <?cs set:colspan = subcount(class.inheritance) ?> <?cs each:supr = class.inheritance ?> <tr> <?cs loop:i = 1, (subcount(class.inheritance)-colspan), 1 ?> <td class="jd-inheritance-space">&nbsp;<?cs if:(subcount(class.inheritance)-colspan) == i ?>&nbsp;&nbsp;&#x21b3;<?cs /if ?></td> <?cs /loop ?> <td colspan="<?cs var:colspan ?>" class="jd-inheritance-class-cell"><?cs if:colspan == 1 ?><?cs call:class_name(class.qualifiedType) ?><?cs else ?><?cs call:type_link(supr.class) ?><?cs /if ?></td> </tr> <?cs set:colspan = colspan-1 ?> <?cs /each ?> </table> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <?cs if:subcount(class.subclasses.direct) && !class.subclasses.hidden ?> <table class="jd-sumtable jd-sumtable-subclasses"><tr><td colspan="12" style="border:none;margin:0;padding:0;"> <?cs call:expando_trigger("subclasses-direct", "closed") ?>Known Direct Subclasses <?cs call:expandable_class_list("subclasses-direct", class.subclasses.direct, "list") ?> </td></tr></table> <?cs /if ?> <?cs if:subcount(class.subclasses.indirect) && !class.subclasses.hidden ?> <table class="jd-sumtable jd-sumtable-subclasses"><tr><td colspan="12" style="border:none;margin:0;padding:0;"> <?cs call:expando_trigger("subclasses-indirect", "closed") ?>Known Indirect Subclasses <?cs call:expandable_class_list("subclasses-indirect", class.subclasses.indirect, "list") ?> </td></tr></table> <?cs /if ?> <div class="jd-descr"> <?cs call:deprecated_warning(class) ?> <?cs if:subcount(class.descr) ?> <h2>Class Overview</h2> <p><?cs call:tag_list(class.descr) ?></p> <?cs /if ?> <?cs call:see_also_tags(class.seeAlso) ?> </div><!-- jd-descr --> <?cs # summary macros ?> <?cs def:write_method_summary(methods, included) ?> <?cs set:count = #1 ?> <?cs each:method = methods ?> <?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?> <tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:method.since.key ?>" > <td class="jd-typecol"> <?cs var:method.abstract ?> <?cs var:method.synchronized ?> <?cs var:method.final ?> <?cs var:method.static ?> <?cs call:type_link(method.generic) ?> <?cs call:type_link(method.returnType) ?> </td> <td class="jd-linkcol" width="100%"> <span class="sympad"><?cs call:cond_link(method.name, toroot, method.href, included) ?></span>(<?cs call:parameter_list(method.params) ?>) <?cs if:subcount(method.shortDescr) || subcount(method.deprecated) ?> <div class="jd-descrdiv"><?cs call:short_descr(method) ?></div> <?cs /if ?> </td></tr> <?cs set:count = count + #1 ?> <?cs /each ?> <?cs /def ?> <?cs def:write_field_summary(fields, included) ?> <?cs set:count = #1 ?> <?cs each:field=fields ?> <tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:field.since.key ?>" > <td class="jd-typecol"> <?cs var:field.scope ?> <?cs var:field.static ?> <?cs var:field.final ?> <?cs call:type_link(field.type) ?></td> <td class="jd-linkcol"><?cs call:cond_link(field.name, toroot, field.href, included) ?></td> <td class="jd-descrcol" width="100%"><?cs call:short_descr(field) ?></td> </tr> <?cs set:count = count + #1 ?> <?cs /each ?> <?cs /def ?> <?cs def:write_constant_summary(fields, included) ?> <?cs set:count = #1 ?> <?cs each:field=fields ?> <tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:field.since.key ?>" > <td class="jd-typecol"><?cs call:type_link(field.type) ?></td> <td class="jd-linkcol"><?cs call:cond_link(field.name, toroot, field.href, included) ?></td> <td class="jd-descrcol" width="100%"><?cs call:short_descr(field) ?></td> </tr> <?cs set:count = count + #1 ?> <?cs /each ?> <?cs /def ?> <?cs def:write_attr_summary(attrs, included) ?> <?cs set:count = #1 ?> <tr> <td><em>Attribute Name</em></td> <td><em>Related Method</em></td> <td><em>Description</em></td> </tr> <?cs each:attr=attrs ?> <tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:attr.since.key ?>" > <td class="jd-linkcol"><?cs if:included ?><a href="<?cs var:toroot ?><?cs var:attr.href ?>"><?cs /if ?><?cs var:attr.name ?><?cs if:included ?></a><?cs /if ?></td> <td class="jd-linkcol"><?cs each:m=attr.methods ?> <?cs call:cond_link(m.name, toroot, m.href, included) ?> <?cs /each ?> </td> <td class="jd-descrcol" width="100%"><?cs call:short_descr(attr) ?>&nbsp;</td> </tr> <?cs set:count = count + #1 ?> <?cs /each ?> <?cs /def ?> <?cs def:write_inners_summary(classes) ?> <?cs set:count = #1 ?> <?cs each:cl=class.inners ?> <tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:cl.since.key ?>" > <td class="jd-typecol"> <?cs var:cl.scope ?> <?cs var:cl.static ?> <?cs var:cl.final ?> <?cs var:cl.abstract ?> <?cs var:cl.kind ?></td> <td class="jd-linkcol"><?cs call:type_link(cl.type) ?></td> <td class="jd-descrcol" width="100%"><?cs call:short_descr(cl) ?>&nbsp;</td> </tr> <?cs set:count = count + #1 ?> <?cs /each ?> <?cs /def ?> <?cs # end macros ?> <div class="jd-descr"> <?cs # make sure there's a summary view to display ?> <?cs if:subcount(class.inners) || subcount(class.attrs) || inhattrs || subcount(class.enumConstants) || subcount(class.constants) || inhconstants || subcount(class.fields) || inhfields || subcount(class.ctors.public) || subcount(class.ctors.protected) || subcount(class.methods.public) || subcount(class.methods.protected) || inhmethods ?> <h2>Summary</h2> <?cs if:subcount(class.inners) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ======== NESTED CLASS SUMMARY ======== --> <table id="nestedclasses" class="jd-sumtable"><tr><th colspan="12">Nested Classes</th></tr> <?cs call:write_inners_summary(class.inners) ?> </table> <?cs /if ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <?cs if:subcount(class.attrs) ?> <!-- =========== FIELD SUMMARY =========== --> <table id="lattrs" class="jd-sumtable"><tr><th colspan="12">XML Attributes</th></tr> <?cs call:write_attr_summary(class.attrs, 1) ?> </table> <?cs /if ?> <?cs # if there are inherited attrs, write the table ?> <?cs if:inhattrs ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- =========== FIELD SUMMARY =========== --> <table id="inhattrs" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited XML Attributes</div></th></tr> <?cs each:cl=class.inherited ?> <?cs if:subcount(cl.attrs) ?> <tr class="api apilevel-<?cs var:cl.since.key ?>" > <td colspan="12"> <?cs call:expando_trigger("inherited-attrs-"+cl.qualified, "closed") ?>From <?cs var:cl.kind ?> <?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?> <div id="inherited-attrs-<?cs var:cl.qualified ?>"> <div id="inherited-attrs-<?cs var:cl.qualified ?>-list" class="jd-inheritedlinks"> </div> <div id="inherited-attrs-<?cs var:cl.qualified ?>-summary" style="display: none;"> <table class="jd-sumtable-expando"> <?cs call:write_attr_summary(cl.attrs, cl.included) ?></table> </div> </div> </td></tr> <?cs /if ?> <?cs /each ?> </table> <?cs /if ?> <?cs if:subcount(class.enumConstants) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <table id="enumconstants" class="jd-sumtable"><tr><th colspan="12">Enum Values</th></tr> <?cs set:count = #1 ?> <?cs each:field=class.enumConstants ?> <tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:field.since.key ?>" > <td class="jd-descrcol"><?cs call:type_link(field.type) ?>&nbsp;</td> <td class="jd-linkcol"><?cs call:cond_link(field.name, toroot, field.href, cl.included) ?>&nbsp;</td> <td class="jd-descrcol" width="100%"><?cs call:short_descr(field) ?>&nbsp;</td> </tr> <?cs set:count = count + #1 ?> <?cs /each ?> </table> <?cs /if ?> <?cs if:subcount(class.constants) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <table id="constants" class="jd-sumtable"><tr><th colspan="12">Constants</th></tr> <?cs call:write_constant_summary(class.constants, 1) ?> </table> <?cs /if ?> <?cs # if there are inherited constants, write the table ?> <?cs if:inhconstants ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <table id="inhconstants" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Constants</div></th></tr> <?cs each:cl=class.inherited ?> <?cs if:subcount(cl.constants) ?> <tr class="api apilevel-<?cs var:cl.since.key ?>" > <td colspan="12"> <?cs call:expando_trigger("inherited-constants-"+cl.qualified, "closed") ?>From <?cs var:cl.kind ?> <?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?> <div id="inherited-constants-<?cs var:cl.qualified ?>"> <div id="inherited-constants-<?cs var:cl.qualified ?>-list" class="jd-inheritedlinks"> </div> <div id="inherited-constants-<?cs var:cl.qualified ?>-summary" style="display: none;"> <table class="jd-sumtable-expando"> <?cs call:write_constant_summary(cl.constants, cl.included) ?></table> </div> </div> </td></tr> <?cs /if ?> <?cs /each ?> </table> <?cs /if ?> <?cs if:subcount(class.fields) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- =========== FIELD SUMMARY =========== --> <table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr> <?cs call:write_field_summary(class.fields, 1) ?> </table> <?cs /if ?> <?cs # if there are inherited fields, write the table ?> <?cs if:inhfields ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- =========== FIELD SUMMARY =========== --> <table id="inhfields" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Fields</div></th></tr> <?cs each:cl=class.inherited ?> <?cs if:subcount(cl.fields) ?> <tr class="api apilevel-<?cs var:cl.since.key ?>" > <td colspan="12"> <?cs call:expando_trigger("inherited-fields-"+cl.qualified, "closed") ?>From <?cs var:cl.kind ?> <?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?> <div id="inherited-fields-<?cs var:cl.qualified ?>"> <div id="inherited-fields-<?cs var:cl.qualified ?>-list" class="jd-inheritedlinks"> </div> <div id="inherited-fields-<?cs var:cl.qualified ?>-summary" style="display: none;"> <table class="jd-sumtable-expando"> <?cs call:write_field_summary(cl.fields, cl.included) ?></table> </div> </div> </td></tr> <?cs /if ?> <?cs /each ?> </table> <?cs /if ?> <?cs if:subcount(class.ctors.public) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr> <?cs call:write_method_summary(class.ctors.public, 1) ?> </table> <?cs /if ?> <?cs if:subcount(class.ctors.protected) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <table id="proctors" class="jd-sumtable"><tr><th colspan="12">Protected Constructors</th></tr> <?cs call:write_method_summary(class.ctors.protected, 1) ?> </table> <?cs /if ?> <?cs if:subcount(class.methods.public) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========== METHOD SUMMARY =========== --> <table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr> <?cs call:write_method_summary(class.methods.public, 1) ?> </table> <?cs /if ?> <?cs if:subcount(class.methods.protected) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========== METHOD SUMMARY =========== --> <table id="promethods" class="jd-sumtable"><tr><th colspan="12">Protected Methods</th></tr> <?cs call:write_method_summary(class.methods.protected, 1) ?> </table> <?cs /if ?> <?cs # if there are inherited methods, write the table ?> <?cs if:inhmethods ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========== METHOD SUMMARY =========== --> <table id="inhmethods" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Methods</div></th></tr> <?cs each:cl=class.inherited ?> <?cs if:subcount(cl.methods) ?> <tr class="api apilevel-<?cs var:cl.since.key ?>" > <td colspan="12"><?cs call:expando_trigger("inherited-methods-"+cl.qualified, "closed") ?> From <?cs var:cl.kind ?> <?cs if:cl.included ?> <a href="<?cs var:toroot ?><?cs var:cl.link ?>"><?cs var:cl.qualified ?></a> <?cs elif:cl.federated ?> <a href="<?cs var:cl.link ?>"><?cs var:cl.qualified ?></a> <?cs else ?> <?cs var:cl.qualified ?> <?cs /if ?> <div id="inherited-methods-<?cs var:cl.qualified ?>"> <div id="inherited-methods-<?cs var:cl.qualified ?>-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-<?cs var:cl.qualified ?>-summary" style="display: none;"> <table class="jd-sumtable-expando"> <?cs call:write_method_summary(cl.methods, cl.included) ?></table> </div> </div> </td></tr> <?cs /if ?> <?cs /each ?> </table> <?cs /if ?> <?cs /if ?> </div><!-- jd-descr (summary) --> <!-- Details --> <?cs def:write_field_details(fields) ?> <?cs each:field=fields ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?> <a id="<?cs var:field.anchor ?>"></a> <?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?> <div class="jd-details api apilevel-<?cs var:field.since.key ?>"> <h4 class="jd-details-title"> <span class="normal"> <?cs var:field.scope ?> <?cs var:field.static ?> <?cs var:field.final ?> <?cs call:type_link(field.type) ?> </span> <?cs var:field.name ?> </h4> <div class="api-level"> <?cs call:since_tags(field) ?> <?cs call:federated_refs(field) ?> </div> <div class="jd-details-descr"> <?cs call:description(field) ?> <?cs if:subcount(field.constantValue) ?> <div class="jd-tagdata"> <span class="jd-tagtitle">Constant Value: </span> <span> <?cs if:field.constantValue.isString ?> <?cs var:field.constantValue.str ?> <?cs else ?> <?cs var:field.constantValue.dec ?> (<?cs var:field.constantValue.hex ?>) <?cs /if ?> </span> </div> <?cs /if ?> </div> </div> <?cs /each ?> <?cs /def ?> <?cs def:write_method_details(methods) ?> <?cs each:method=methods ?> <?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?> <a id="<?cs var:method.anchor ?>"></a> <?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?> <div class="jd-details api apilevel-<?cs var:method.since.key ?>"> <h4 class="jd-details-title"> <span class="normal"> <?cs var:method.scope ?> <?cs var:method.static ?> <?cs var:method.final ?> <?cs var:method.abstract ?> <?cs var:method.synchronized ?> <?cs call:type_link(method.returnType) ?> </span> <span class="sympad"><?cs var:method.name ?></span> <span class="normal">(<?cs call:parameter_list(method.params) ?>)</span> </h4> <div class="api-level"> <div><?cs call:since_tags(method) ?></div> <?cs call:federated_refs(method) ?> </div> <div class="jd-details-descr"> <?cs call:description(method) ?> </div> </div> <?cs /each ?> <?cs /def ?> <?cs def:write_attr_details(attrs) ?> <?cs each:attr=attrs ?> <?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?> <a id="<?cs var:attr.anchor ?>"></a> <?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?> <div class="jd-details api apilevel-<?cs var:attr.since.key ?>"> <h4 class="jd-details-title"><?cs var:attr.name ?> </h4> <div class="api-level"> <?cs call:since_tags(attr) ?> </div> <div class="jd-details-descr"> <?cs call:description(attr) ?> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Related Methods</h5> <ul class="nolist"> <?cs each:m=attr.methods ?> <li><a href="<?cs var:toroot ?><?cs var:m.href ?>"><?cs var:m.name ?></a></li> <?cs /each ?> </ul> </div> </div> </div> <?cs /each ?> <?cs /def ?> <!-- XML Attributes --> <?cs if:subcount(class.attrs) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= FIELD DETAIL ======== --> <h2>XML Attributes</h2> <?cs call:write_attr_details(class.attrs) ?> <?cs /if ?> <!-- Enum Values --> <?cs if:subcount(class.enumConstants) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= ENUM CONSTANTS DETAIL ======== --> <h2>Enum Values</h2> <?cs call:write_field_details(class.enumConstants) ?> <?cs /if ?> <!-- Constants --> <?cs if:subcount(class.constants) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= ENUM CONSTANTS DETAIL ======== --> <h2>Constants</h2> <?cs call:write_field_details(class.constants) ?> <?cs /if ?> <!-- Fields --> <?cs if:subcount(class.fields) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= FIELD DETAIL ======== --> <h2>Fields</h2> <?cs call:write_field_details(class.fields) ?> <?cs /if ?> <!-- Public ctors --> <?cs if:subcount(class.ctors.public) ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= CONSTRUCTOR DETAIL ======== --> <h2>Public Constructors</h2> <?cs call:write_method_details(class.ctors.public) ?> <?cs /if ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- Protected ctors --> <?cs if:subcount(class.ctors.protected) ?> <h2>Protected Constructors</h2> <?cs call:write_method_details(class.ctors.protected) ?> <?cs /if ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= METHOD DETAIL ======== --> <!-- Public methdos --> <?cs if:subcount(class.methods.public) ?> <h2>Public Methods</h2> <?cs call:write_method_details(class.methods.public) ?> <?cs /if ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= METHOD DETAIL ======== --> <?cs if:subcount(class.methods.protected) ?> <h2>Protected Methods</h2> <?cs call:write_method_details(class.methods.protected) ?> <?cs /if ?> <?cs # this next line must be exactly like this to be parsed by eclipse ?> <!-- ========= METHOD DETAIL ======== --> <?cs if:subcount(class.methods.private) ?> <h2>Private Methods</h2> <?cs call:write_method_details(class.methods.private) ?> <?cs /if ?> <?cs # the next two lines must be exactly like this to be parsed by eclipse ?> <!-- ========= END OF CLASS DATA ========= --> <a id="navbar_top"></a> <?cs include:"footer.cs" ?> </div> <!-- jd-content --> </div><!-- end doc-content --> <?cs include:"trailer.cs" ?> </body> </html>
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // BufferBlock.cs // // // A propagator block that provides support for unbounded and bounded FIFO buffers. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Threading.Tasks.Dataflow.Internal; using System.Diagnostics.CodeAnalysis; namespace System.Threading.Tasks.Dataflow { /// <summary>Provides a buffer for storing data.</summary> /// <typeparam name="T">Specifies the type of the data buffered by this dataflow block.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BufferBlock<>.DebugView))] public sealed class BufferBlock<T> : IPropagatorBlock<T, T>, IReceivableSourceBlock<T>, IDebuggerDisplay { /// <summary>The core logic for the buffer block.</summary> private readonly SourceCore<T> _source; /// <summary>The bounding state for when in bounding mode; null if not bounding.</summary> private readonly BoundingStateWithPostponedAndTask<T> _boundingState; /// <summary>Whether all future messages should be declined on the target.</summary> private bool _targetDecliningPermanently; /// <summary>A task has reserved the right to run the target's completion routine.</summary> private bool _targetCompletionReserved; /// <summary>Gets the lock object used to synchronize incoming requests.</summary> private object IncomingLock { get { return _source; } } /// <summary>Initializes the <see cref="BufferBlock{T}"/>.</summary> public BufferBlock() : this(DataflowBlockOptions.Default) { } /// <summary>Initializes the <see cref="BufferBlock{T}"/> with the specified <see cref="DataflowBlockOptions"/>.</summary> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BufferBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public BufferBlock(DataflowBlockOptions dataflowBlockOptions) { if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); Contract.EndContractBlock(); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Initialize bounding state if necessary Action<ISourceBlock<T>, int> onItemsRemoved = null; if (dataflowBlockOptions.BoundedCapacity > 0) { onItemsRemoved = (owningSource, count) => ((BufferBlock<T>)owningSource).OnItemsRemoved(count); _boundingState = new BoundingStateWithPostponedAndTask<T>(dataflowBlockOptions.BoundedCapacity); } // Initialize the source state _source = new SourceCore<T>(this, dataflowBlockOptions, owningSource => ((BufferBlock<T>)owningSource).Complete(), onItemsRemoved); // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception. // In those cases we need to fault the target half to drop its buffered messages and to release its // reservations. This should not create an infinite loop, because all our implementations are designed // to handle multiple completion requests and to carry over only one. _source.Completion.ContinueWith((completed, state) => { var thisBlock = ((BufferBlock<T>)state) as IDataflowBlock; Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion."); thisBlock.Fault(completed.Exception); }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _source.Completion, owningSource => ((BufferBlock<T>)owningSource).Complete(), this); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, bool consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept)); Contract.EndContractBlock(); lock (IncomingLock) { // If we've already stopped accepting messages, decline permanently if (_targetDecliningPermanently) { CompleteTargetIfPossible(); return DataflowMessageStatus.DecliningPermanently; } // We can directly accept the message if: // 1) we are not bounding, OR // 2) we are bounding AND there is room available AND there are no postponed messages AND we are not currently processing. // (If there were any postponed messages, we would need to postpone so that ordering would be maintained.) // (We should also postpone if we are currently processing, because there may be a race between consuming postponed messages and // accepting new ones directly into the queue.) if (_boundingState == null || (_boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count == 0 && _boundingState.TaskForInputProcessing == null)) { // Consume the message from the source if necessary if (consumeToAccept) { Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true."); bool consumed; messageValue = source.ConsumeMessage(messageHeader, this, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } // Once consumed, pass it to the source _source.AddMessage(messageValue); if (_boundingState != null) _boundingState.CurrentCount++; return DataflowMessageStatus.Accepted; } // Otherwise, we try to postpone if a source was provided else if (source != null) { Debug.Assert(_boundingState != null && _boundingState.PostponedMessages != null, "PostponedMessages must have been initialized during construction in bounding mode."); _boundingState.PostponedMessages.Push(source, messageHeader); return DataflowMessageStatus.Postponed; } // We can't do anything else about this message return DataflowMessageStatus.Declined; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { CompleteCore(exception: null, storeExceptionEvenIfAlreadyCompleting: false); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } private void CompleteCore(Exception exception, bool storeExceptionEvenIfAlreadyCompleting, bool revertProcessingState = false) { Debug.Assert(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState, "Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true."); Contract.EndContractBlock(); lock (IncomingLock) { // Faulting from outside is allowed until we start declining permanently. // Faulting from inside is allowed at any time. if (exception != null && (!_targetDecliningPermanently || storeExceptionEvenIfAlreadyCompleting)) { _source.AddException(exception); } // Revert the dirty processing state if requested if (revertProcessingState) { Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null, "The processing state must be dirty when revertProcessingState==true."); _boundingState.TaskForInputProcessing = null; } // Trigger completion _targetDecliningPermanently = true; CompleteTargetIfPossible(); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> public bool TryReceive(Predicate<T> filter, out T item) { return _source.TryReceive(filter, out item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> public bool TryReceiveAll(out IList<T> items) { return _source.TryReceiveAll(out items); } /// <summary>Gets the number of items currently stored in the buffer.</summary> public int Count { get { return _source.OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _source.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out bool messageConsumed) { return _source.ConsumeMessage(messageHeader, target, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { return _source.ReserveMessage(messageHeader, target); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { _source.ReleaseReservation(messageHeader, target); } /// <summary>Notifies the block that one or more items was removed from the queue.</summary> /// <param name="numItemsRemoved">The number of items removed.</param> private void OnItemsRemoved(int numItemsRemoved) { Debug.Assert(numItemsRemoved > 0, "A positive number of items to remove is required."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); // If we're bounding, we need to know when an item is removed so that we // can update the count that's mirroring the actual count in the source's queue, // and potentially kick off processing to start consuming postponed messages. if (_boundingState != null) { lock (IncomingLock) { // Decrement the count, which mirrors the count in the source half Debug.Assert(_boundingState.CurrentCount - numItemsRemoved >= 0, "It should be impossible to have a negative number of items."); _boundingState.CurrentCount -= numItemsRemoved; ConsumeAsyncIfNecessary(); CompleteTargetIfPossible(); } } } /// <summary>Called when postponed messages may need to be consumed.</summary> /// <param name="isReplacementReplica">Whether this call is the continuation of a previous message loop.</param> internal void ConsumeAsyncIfNecessary(bool isReplacementReplica = false) { Common.ContractAssertMonitorStatus(IncomingLock, held: true); Debug.Assert(_boundingState != null, "Must be in bounded mode."); if (!_targetDecliningPermanently && _boundingState.TaskForInputProcessing == null && _boundingState.PostponedMessages.Count > 0 && _boundingState.CountIsLessThanBound) { // Create task and store into _taskForInputProcessing prior to scheduling the task // so that _taskForInputProcessing will be visibly set in the task loop. _boundingState.TaskForInputProcessing = new Task(state => ((BufferBlock<T>)state).ConsumeMessagesLoopCore(), this, Common.GetCreationOptionsForTask(isReplacementReplica)); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TaskLaunchedForMessageHandling( this, _boundingState.TaskForInputProcessing, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages, _boundingState.PostponedMessages.Count); } #endif // Start the task handling scheduling exceptions Exception exception = Common.StartTaskSafe(_boundingState.TaskForInputProcessing, _source.DataflowBlockOptions.TaskScheduler); if (exception != null) { // Get out from under currently held locks. CompleteCore re-acquires the locks it needs. Task.Factory.StartNew(exc => CompleteCore(exception: (Exception)exc, storeExceptionEvenIfAlreadyCompleting: true, revertProcessingState: true), exception, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } } } /// <summary>Task body used to consume postponed messages.</summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ConsumeMessagesLoopCore() { Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null, "May only be called in bounded mode and when a task is in flight."); Debug.Assert(_boundingState.TaskForInputProcessing.Id == Task.CurrentId, "This must only be called from the in-flight processing task."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); try { int maxMessagesPerTask = _source.DataflowBlockOptions.ActualMaxMessagesPerTask; for (int i = 0; i < maxMessagesPerTask && ConsumeAndStoreOneMessageIfAvailable(); i++) ; } catch (Exception exc) { // Prevent the creation of new processing tasks CompleteCore(exc, storeExceptionEvenIfAlreadyCompleting: true); } finally { lock (IncomingLock) { // We're no longer processing, so null out the processing task _boundingState.TaskForInputProcessing = null; // However, we may have given up early because we hit our own configured // processing limits rather than because we ran out of work to do. If that's // the case, make sure we spin up another task to keep going. ConsumeAsyncIfNecessary(isReplacementReplica: true); // If, however, we stopped because we ran out of work to do and we // know we'll never get more, then complete. CompleteTargetIfPossible(); } } } /// <summary> /// Retrieves one postponed message if there's room and if we can consume a postponed message. /// Stores any consumed message into the source half. /// </summary> /// <returns>true if a message could be consumed and stored; otherwise, false.</returns> /// <remarks>This must only be called from the asynchronous processing loop.</remarks> private bool ConsumeAndStoreOneMessageIfAvailable() { Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null, "May only be called in bounded mode and when a task is in flight."); Debug.Assert(_boundingState.TaskForInputProcessing.Id == Task.CurrentId, "This must only be called from the in-flight processing task."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); // Loop through the postponed messages until we get one. while (true) { // Get the next item to retrieve. If there are no more, bail. KeyValuePair<ISourceBlock<T>, DataflowMessageHeader> sourceAndMessage; lock (IncomingLock) { if (_targetDecliningPermanently) return false; if (!_boundingState.CountIsLessThanBound) return false; if (!_boundingState.PostponedMessages.TryPop(out sourceAndMessage)) return false; // Optimistically assume we're going to get the item. This avoids taking the lock // again if we're right. If we're wrong, we decrement it later under lock. _boundingState.CurrentCount++; } // Consume the item bool consumed = false; try { T consumedValue = sourceAndMessage.Key.ConsumeMessage(sourceAndMessage.Value, this, out consumed); if (consumed) { _source.AddMessage(consumedValue); return true; } } finally { // We didn't get the item, so decrement the count to counteract our optimistic assumption. if (!consumed) { lock (IncomingLock) _boundingState.CurrentCount--; } } } } /// <summary>Completes the target, notifying the source, once all completion conditions are met.</summary> private void CompleteTargetIfPossible() { Common.ContractAssertMonitorStatus(IncomingLock, held: true); if (_targetDecliningPermanently && !_targetCompletionReserved && (_boundingState == null || _boundingState.TaskForInputProcessing == null)) { _targetCompletionReserved = true; // If we're in bounding mode and we have any postponed messages, we need to clear them, // which means calling back to the source, which means we need to escape the incoming lock. if (_boundingState != null && _boundingState.PostponedMessages.Count > 0) { Task.Factory.StartNew(state => { var thisBufferBlock = (BufferBlock<T>)state; // Release any postponed messages List<Exception> exceptions = null; if (thisBufferBlock._boundingState != null) { // Note: No locks should be held at this point Common.ReleaseAllPostponedMessages(thisBufferBlock, thisBufferBlock._boundingState.PostponedMessages, ref exceptions); } if (exceptions != null) { // It is important to migrate these exceptions to the source part of the owning batch, // because that is the completion task that is publicly exposed. thisBufferBlock._source.AddExceptions(exceptions); } thisBufferBlock._source.Complete(); }, this, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } // Otherwise, we can just decline the source directly. else { _source.Complete(); } } } /// <summary>Gets the number of messages in the buffer. This must only be used from the debugger as it avoids taking necessary locks.</summary> private int CountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, Count={1}", Common.GetNameForDebugger(this, _source.DataflowBlockOptions), CountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the BufferBlock.</summary> private sealed class DebugView { /// <summary>The buffer block.</summary> private readonly BufferBlock<T> _bufferBlock; /// <summary>The buffer's source half.</summary> private readonly SourceCore<T>.DebuggingInformation _sourceDebuggingInformation; /// <summary>Initializes the debug view.</summary> /// <param name="bufferBlock">The BufferBlock being viewed.</param> public DebugView(BufferBlock<T> bufferBlock) { Debug.Assert(bufferBlock != null, "Need a block with which to construct the debug view."); _bufferBlock = bufferBlock; _sourceDebuggingInformation = bufferBlock._source.GetDebuggingInformation(); } /// <summary>Gets the collection of postponed message headers.</summary> public QueuedMap<ISourceBlock<T>, DataflowMessageHeader> PostponedMessages { get { return _bufferBlock._boundingState != null ? _bufferBlock._boundingState.PostponedMessages : null; } } /// <summary>Gets the messages in the buffer.</summary> public IEnumerable<T> Queue { get { return _sourceDebuggingInformation.OutputQueue; } } /// <summary>The task used to process messages.</summary> public Task TaskForInputProcessing { get { return _bufferBlock._boundingState != null ? _bufferBlock._boundingState.TaskForInputProcessing : null; } } /// <summary>Gets the task being used for output processing.</summary> public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public DataflowBlockOptions DataflowBlockOptions { get { return _sourceDebuggingInformation.DataflowBlockOptions; } } /// <summary>Gets whether the block is declining further messages.</summary> public bool IsDecliningPermanently { get { return _bufferBlock._targetDecliningPermanently; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_bufferBlock); } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<T> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } } /// <summary>Gets the set of all targets linked from this block.</summary> public ITargetBlock<T> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Dispatcher { using System; using System.Collections.Generic; using System.ServiceModel.Diagnostics; using System.Runtime; using System.ServiceModel.Channels; using System.Threading; class MultipleReceiveBinder : IChannelBinder { internal static class MultipleReceiveDefaults { internal const int MaxPendingReceives = 1; } static AsyncCallback onInnerReceiveCompleted = Fx.ThunkCallback(OnInnerReceiveCompleted); MultipleReceiveAsyncResult outstanding; IChannelBinder channelBinder; ReceiveScopeQueue pendingResults; bool ordered; public MultipleReceiveBinder(IChannelBinder channelBinder, int size, bool ordered) { this.ordered = ordered; this.channelBinder = channelBinder; this.pendingResults = new ReceiveScopeQueue(size); } public IChannel Channel { get { return this.channelBinder.Channel; } } public bool HasSession { get { return this.channelBinder.HasSession; } } public Uri ListenUri { get { return this.channelBinder.ListenUri; } } public EndpointAddress LocalAddress { get { return this.channelBinder.LocalAddress; } } public EndpointAddress RemoteAddress { get { return this.channelBinder.RemoteAddress; } } public void Abort() { this.channelBinder.Abort(); } public void CloseAfterFault(TimeSpan timeout) { this.channelBinder.CloseAfterFault(timeout); } public bool TryReceive(TimeSpan timeout, out RequestContext requestContext) { return this.channelBinder.TryReceive(timeout, out requestContext); } public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state) { // At anytime there can be only one thread in BeginTryReceive and the // outstanding AsyncResult should have completed before the next one. // There should be no pending oustanding result here. Fx.AssertAndThrow(this.outstanding == null, "BeginTryReceive should not have a pending result."); MultipleReceiveAsyncResult multipleReceiveResult = new MultipleReceiveAsyncResult(callback, state); this.outstanding = multipleReceiveResult; EnsurePump(timeout); IAsyncResult innerResult; if (this.pendingResults.TryDequeueHead(out innerResult)) { HandleReceiveRequestComplete(innerResult, true); } return multipleReceiveResult; } void EnsurePump(TimeSpan timeout) { // ensure we're running at full throttle, the BeginTryReceive calls we make below on the // IChannelBinder will typically complete future calls to BeginTryReceive made by CannelHandler // corollary to that is that most times these calls will be completed sycnhronously while (!this.pendingResults.IsFull) { ReceiveScopeSignalGate receiveScope = new ReceiveScopeSignalGate(this); // Enqueue the result without locks since this is the pump. // BeginTryReceive can be called only from one thread and // the head is not yet unlocked so no items can proceed. this.pendingResults.Enqueue(receiveScope); IAsyncResult result = this.channelBinder.BeginTryReceive(timeout, onInnerReceiveCompleted, receiveScope); if (result.CompletedSynchronously) { this.SignalReceiveCompleted(result); } } } static void OnInnerReceiveCompleted(IAsyncResult nestedResult) { if (nestedResult.CompletedSynchronously) { return; } ReceiveScopeSignalGate thisPtr = nestedResult.AsyncState as ReceiveScopeSignalGate; thisPtr.Binder.HandleReceiveAndSignalCompletion(nestedResult, false); } void HandleReceiveAndSignalCompletion(IAsyncResult nestedResult, bool completedSynchronosly) { if (SignalReceiveCompleted(nestedResult)) { HandleReceiveRequestComplete(nestedResult, completedSynchronosly); } } private bool SignalReceiveCompleted(IAsyncResult nestedResult) { if (this.ordered) { // Ordered recevies can proceed only if its own gate has // been unlocked. Head is the only gate unlocked and only the // result that owns the is the gate at the head can proceed. return this.pendingResults.TrySignal((ReceiveScopeSignalGate)nestedResult.AsyncState, nestedResult); } else { // Unordered receives can proceed with any gate. If the is head // is not unlocked by BeginTryReceive then the result will // be put on the last pending gate. return this.pendingResults.TrySignalPending(nestedResult); } } void HandleReceiveRequestComplete(IAsyncResult innerResult, bool completedSynchronously) { MultipleReceiveAsyncResult receiveResult = this.outstanding; Exception completionException = null; try { Fx.AssertAndThrow(receiveResult != null, "HandleReceive invoked without an outstanding result"); // Cleanup states this.outstanding = null; // set the context on the outer result for the ChannelHandler. RequestContext context; receiveResult.Valid = this.channelBinder.EndTryReceive(innerResult, out context); receiveResult.RequestContext = context; } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } completionException = ex; } receiveResult.Complete(completedSynchronously, completionException); } public bool EndTryReceive(IAsyncResult result, out RequestContext requestContext) { return MultipleReceiveAsyncResult.End(result, out requestContext); } public RequestContext CreateRequestContext(Message message) { return this.channelBinder.CreateRequestContext(message); } public void Send(Message message, TimeSpan timeout) { this.channelBinder.Send(message, timeout); } public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return this.channelBinder.BeginSend(message, timeout, callback, state); } public void EndSend(IAsyncResult result) { this.channelBinder.EndSend(result); } public Message Request(Message message, TimeSpan timeout) { return this.channelBinder.Request(message, timeout); } public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return this.channelBinder.BeginRequest(message, timeout, callback, state); } public Message EndRequest(IAsyncResult result) { return this.channelBinder.EndRequest(result); } public bool WaitForMessage(TimeSpan timeout) { return this.channelBinder.WaitForMessage(timeout); } public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state) { return this.channelBinder.BeginWaitForMessage(timeout, callback, state); } public bool EndWaitForMessage(IAsyncResult result) { return this.channelBinder.EndWaitForMessage(result); } class MultipleReceiveAsyncResult : AsyncResult { public MultipleReceiveAsyncResult(AsyncCallback callback, object state) : base(callback, state) { } public bool Valid { get; set; } public RequestContext RequestContext { get; set; } public new void Complete(bool completedSynchronously, Exception completionException) { base.Complete(completedSynchronously, completionException); } public static bool End(IAsyncResult result, out RequestContext context) { MultipleReceiveAsyncResult thisPtr = AsyncResult.End<MultipleReceiveAsyncResult>(result); context = thisPtr.RequestContext; return thisPtr.Valid; } } class ReceiveScopeSignalGate : SignalGate<IAsyncResult> { public ReceiveScopeSignalGate(MultipleReceiveBinder binder) { this.Binder = binder; } public MultipleReceiveBinder Binder { get; private set; } } class ReceiveScopeQueue { // This class is a circular queue with 2 pointers for pending items and head. // Ordered Receives : The head is unlocked by BeginTryReceive. The ReceiveGate can signal only the // the gate that it owns. If the gate is the head then it will proceed. // Unordered Receives: Any pending item can be signalled. The pending index keeps track // of results that haven't been completed. If the head is unlocked then it will proceed. int pending; int head; int count; readonly int size; ReceiveScopeSignalGate[] items; public ReceiveScopeQueue(int size) { this.size = size; this.head = 0; this.count = 0; this.pending = 0; items = new ReceiveScopeSignalGate[size]; } internal bool IsFull { get { return this.count == this.size; } } internal void Enqueue(ReceiveScopeSignalGate receiveScope) { // This should only be called from EnsurePump which itself should only be // BeginTryReceive. This makes sure that we don't need locks to enqueue an item. Fx.AssertAndThrow(this.count < this.size, "Cannot Enqueue into a full queue."); this.items[(this.head + this.count) % this.size] = receiveScope; count++; } void Dequeue() { // Dequeue should not be called outside a signal/unlock boundary. // There are no locks as this boundary ensures that only one thread // Tries to dequeu an item either in the unlock or Signal thread. Fx.AssertAndThrow(this.count > 0, "Cannot Dequeue and empty queue."); this.items[head] = null; this.head = (head + 1) % this.size; this.count--; } internal bool TryDequeueHead(out IAsyncResult result) { // Invoked only from BeginTryReceive as only the main thread can // dequeue the head and is Successful only if it's already been signaled and completed. Fx.AssertAndThrow(this.count > 0, "Cannot unlock item when queue is empty"); if (this.items[head].Unlock(out result)) { this.Dequeue(); return true; } return false; } public bool TrySignal(ReceiveScopeSignalGate scope, IAsyncResult nestedResult) { // Ordered receives can only signal the gate that the AsyncResult owns. // If the head has already been unlocked then it can proceed. if (scope.Signal(nestedResult)) { Dequeue(); return true; } return false; } public bool TrySignalPending(IAsyncResult result) { // free index will wrap around and always return the next free index; // Only the head of the queue can proceed as the head would be unlocked by // BeginTryReceive. All other requests will just submit their completed result. int nextPending = GetNextPending(); if (this.items[nextPending].Signal(result)) { Dequeue(); return true; } return false; } int GetNextPending() { int slot = this.pending; while (true) { if (slot == (slot = Interlocked.CompareExchange(ref this.pending, (slot + 1) % this.size, slot))) { return slot; } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading; using System.Threading.Tasks; using RestWell.Client; using RestWell.Client.Enums; using RestWell.Client.Request; using RestWell.Client.Response; using RestWell.Test.Resource.WebApi.Controllers; using RestWell.Test.Resource.WebApi.Dtos; using Shouldly; using TestWell.Environment; namespace RestWell.Test.Integration.Client { internal class ProxySteps : IDisposable { #region Private Fields private readonly Dictionary<Type, DelegatingHandler> delegatingHandlers; private readonly TestWellEnvironment testEnvironment; private string acceptHeaderValue; private string basicMessage; private IProxyRequest<Missing, string> basicRequestProxyRequest; private IProxyResponse<string> basicRequestProxyResponse; private MediaTypeWithQualityHeaderValue defaultAcceptHeader; private AuthenticationHeaderValue defaultAuthorizationHeader; private Action<HttpRequestMessage, CancellationToken> delegatingAction; private bool disposedValue; private HttpRequestMethod httpRequestMethod; private IProxyRequest<MessageRequestDto, MessageResponseDto> messageDtoRequestProxyRequest; private IProxyResponse<MessageResponseDto> messageDtoRequestProxyResponse; private IProxyRequest<Missing, MessageResponseDto> messageDtoResponseRequestProxyRequest; private IProxyResponse<MessageResponseDto> messageDtoResponseRequestProxyResponse; private MessageRequestDto messageRequestDto; private IProxy proxy; private IProxyConfiguration proxyConfiguration; private IProxyRequest<Missing, MessageResponseDto> secureRequestProxyRequest; private IProxyResponse<MessageResponseDto> secureRequestProxyResponse; #endregion Private Fields #region Public Constructors public ProxySteps(TestWellEnvironment testEnvironment) { this.delegatingHandlers = new Dictionary<Type, DelegatingHandler>(); this.testEnvironment = testEnvironment; } #endregion Public Constructors #region Public Methods public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion Public Methods #region Internal Methods internal void GivenIAccept(string acceptHeaderValue) { this.acceptHeaderValue = acceptHeaderValue; } internal void GivenIAmUsingTheHttpRequestMethodOf(HttpRequestMethod requestMethod) { this.httpRequestMethod = requestMethod; } internal void GivenIHaveABasicRequestMessage(string message) { this.basicMessage = message; } internal void GivenIHaveABasicRequestProxyRequest() { this.basicRequestProxyRequest = ProxyRequestBuilder<string> .CreateBuilder(this.testEnvironment.GetResourceWebService<Resource.WebApi.Startup>().BaseUri, this.httpRequestMethod) .Accept(this.acceptHeaderValue) .AppendToRoute($"api/{nameof(BasicRequestController).Replace("Controller", "")}") .AddPathArguments(this.basicMessage) .Build(); } internal void GivenIHaveABasicRequestProxyRequestForException() { this.basicRequestProxyRequest = ProxyRequestBuilder<string> .CreateBuilder(this.testEnvironment.GetResourceWebService<Resource.WebApi.Startup>().BaseUri, this.httpRequestMethod) .Accept(this.acceptHeaderValue) .AppendToRoute($"api/{nameof(BasicRequestController).Replace("Controller", "")}/error") .AddPathArguments(this.basicMessage) .Build(); } internal void GivenIHaveABasicRequestProxyRequestForNonExistingResource() { this.basicRequestProxyRequest = ProxyRequestBuilder<string> .CreateBuilder(this.testEnvironment.GetResourceWebService<Resource.WebApi.Startup>().BaseUri, this.httpRequestMethod) .Accept(this.acceptHeaderValue) .AppendToRoute($"api/does/not/exist/{nameof(BasicRequestController).Replace("Controller", "")}") .AddPathArguments(this.basicMessage) .Build(); } internal void GivenIHaveABasicRequestProxyRequestWithNoAcceptHeader() { this.basicRequestProxyRequest = ProxyRequestBuilder<string> .CreateBuilder(this.testEnvironment.GetResourceWebService<Resource.WebApi.Startup>().BaseUri, this.httpRequestMethod) .AppendToRoute($"api/{nameof(BasicRequestController).Replace("Controller", "")}") .AddPathArguments(this.basicMessage) .Build(); } internal void GivenIHaveADefaultAcceptHeader(string mediaType) { this.defaultAcceptHeader = new MediaTypeWithQualityHeaderValue(mediaType); } internal void GivenIHaveADefaultAuthorizationHeader() { this.defaultAuthorizationHeader = new AuthenticationHeaderValue("Basic", "Username:Password"); } internal void GivenIHaveAMessageDtoRequestProxyRequest() { this.messageDtoRequestProxyRequest = ProxyRequestBuilder<MessageRequestDto, MessageResponseDto> .CreateBuilder(this.testEnvironment.GetResourceWebService<Resource.WebApi.Startup>().BaseUri, this.httpRequestMethod) .Accept(this.acceptHeaderValue) .AppendToRoute($"api/{nameof(MessageDtoRequestController).Replace("Controller", "")}") .SetRequestDto(this.messageRequestDto) .Build(); } internal void GivenIHaveAMessageDtoResponseRequestProxyRequest() { this.messageDtoResponseRequestProxyRequest = ProxyRequestBuilder<MessageResponseDto> .CreateBuilder(this.testEnvironment.GetResourceWebService<Resource.WebApi.Startup>().BaseUri, this.httpRequestMethod) .Accept(this.acceptHeaderValue) .AppendToRoute($"api/{nameof(MessageDtoResponseRequestController).Replace("Controller", "")}") .AddPathArguments(this.basicMessage) .Build(); } internal void GivenIHaveAMessageRequestDto(string message) { this.basicMessage = message; this.messageRequestDto = new MessageRequestDto { Message = this.basicMessage }; } internal void GivenIHaveAProxy() { this.proxy = new Proxy(this.proxyConfiguration); } internal void GivenIHaveAProxyConfiguration() { var proxyConfigurationBuilder = ProxyConfigurationBuilder.CreateBuilder(); if (this.delegatingHandlers != null) { proxyConfigurationBuilder.AddDelegatingHandlers(this.delegatingHandlers.Values.ToArray()); } if (this.defaultAuthorizationHeader != null) { proxyConfigurationBuilder.UseDefaultAuthorizationHeader(this.defaultAuthorizationHeader); } if (this.defaultAcceptHeader != null) { proxyConfigurationBuilder.UseDefaultAcceptHeader(this.defaultAcceptHeader); } if (this.delegatingAction != null) { proxyConfigurationBuilder.AddDelegatingAction(this.delegatingAction); } this.proxyConfiguration = proxyConfigurationBuilder.Build(); } internal void GivenIHaveAProxyUsingDefaultConstructor() { this.proxy = new Proxy(); } internal void GivenIHaveASecureRequestDelegatingAction() { this.delegatingAction = new Action<HttpRequestMessage, CancellationToken>((request, cancellationToken) => request.Headers.Authorization = new AuthenticationHeaderValue("Basic", "Username:Password")); } internal void GivenIHaveASecureRequestDelegatingHandler() { this.delegatingHandlers.Add(typeof(SecureRequestDelegatingHandler), new SecureRequestDelegatingHandler()); } internal void GivenIHaveASecureRequestDelegatingHandler(string scheme, string token) { this.delegatingHandlers.Add(typeof(SecureRequestDelegatingHandler), new SecureRequestDelegatingHandler(scheme, token)); } internal void GivenIHaveASecureRequestProxyRequest() { this.secureRequestProxyRequest = ProxyRequestBuilder<MessageResponseDto> .CreateBuilder(this.testEnvironment.GetResourceWebService<Resource.WebApi.Startup>().BaseUri, this.httpRequestMethod) .AddHeader("Accept", this.acceptHeaderValue) .AppendToRoute($"api/{nameof(SecureRequestController).Replace("Controller", "")}") .AddPathArguments(this.basicMessage) .Build(); } internal void GivenIHaveASecureRequestProxyRequestWithNoAuthHeader() { this.secureRequestProxyRequest = ProxyRequestBuilder<MessageResponseDto> .CreateBuilder(this.testEnvironment.GetResourceWebService<Resource.WebApi.Startup>().BaseUri, this.httpRequestMethod) .Accept(this.acceptHeaderValue) .AppendToRoute($"api/{nameof(SecureRequestController).Replace("Controller", "")}") .AddPathArguments(this.basicMessage) .Build(); } internal void ThenICanVerifyICanIssueBasicRequest() { this.ThenICanVerifyIGotAResponse(this.basicRequestProxyResponse, this.basicRequestProxyRequest, HttpStatusCode.OK, true); if (this.httpRequestMethod != HttpRequestMethod.Head) { this.basicRequestProxyResponse.ResponseDto.ShouldNotBeNull(); this.basicRequestProxyResponse.ResponseDto.ShouldBeOfType<string>(); this.basicRequestProxyResponse.ResponseDto.ShouldNotBeEmpty(); this.basicRequestProxyResponse.ResponseDto.ShouldBe(this.basicMessage); } } internal void ThenICanVerifyICanIssueBasicRequestWithDefaultAcceptHeader() { this.basicRequestProxyResponse.RequestHeaders.Accept.ShouldContain(this.defaultAcceptHeader); } internal void ThenICanVerifyICanIssueMessageDtoRequest() { this.ThenICanVerifyIGotAResponse(this.messageDtoRequestProxyResponse, this.messageDtoRequestProxyRequest, HttpStatusCode.OK, true); if (this.httpRequestMethod != HttpRequestMethod.Head) { this.messageDtoRequestProxyResponse.ResponseDto.ShouldNotBeNull(); this.messageDtoRequestProxyResponse.ResponseDto.ShouldBeOfType<MessageResponseDto>(); this.messageDtoRequestProxyResponse.ResponseDto.Message.ShouldNotBeNull(); this.messageDtoRequestProxyResponse.ResponseDto.Message.ShouldNotBeEmpty(); this.messageDtoRequestProxyResponse.ResponseDto.Message.ShouldBe(this.basicMessage); } } internal void ThenICanVerifyICanIssueMessageDtoResponseRequest() { this.ThenICanVerifyIGotAResponse(this.messageDtoResponseRequestProxyResponse, this.messageDtoResponseRequestProxyRequest, HttpStatusCode.OK, true); if (this.httpRequestMethod != HttpRequestMethod.Head) { this.messageDtoResponseRequestProxyResponse.ResponseDto.ShouldNotBeNull(); this.messageDtoResponseRequestProxyResponse.ResponseDto.ShouldBeOfType<MessageResponseDto>(); this.messageDtoResponseRequestProxyResponse.ResponseDto.Message.ShouldNotBeNull(); this.messageDtoResponseRequestProxyResponse.ResponseDto.Message.ShouldNotBeEmpty(); this.messageDtoResponseRequestProxyResponse.ResponseDto.Message.ShouldBe(this.basicMessage); } } internal void ThenICanVerifyICanIssueSecureRequestUsingDelegatingHandler() { this.ThenICanVerifyIGotAResponse(this.secureRequestProxyResponse, this.secureRequestProxyRequest, HttpStatusCode.OK, true); if (this.httpRequestMethod != HttpRequestMethod.Head) { this.secureRequestProxyResponse.ResponseDto.ShouldNotBeNull(); this.secureRequestProxyResponse.ResponseDto.ShouldBeOfType<MessageResponseDto>(); this.secureRequestProxyResponse.ResponseDto.Message.ShouldNotBeNull(); this.secureRequestProxyResponse.ResponseDto.Message.ShouldNotBeEmpty(); this.secureRequestProxyResponse.ResponseDto.Message.ShouldBe(this.basicMessage); } } internal void ThenICanVerifyICannotIssueBasicRequestDueToException() { this.basicRequestProxyResponse.ShouldNotBeNull(); this.basicRequestProxyResponse.HttpRequestMethod.ShouldBe(httpRequestMethod); this.basicRequestProxyResponse.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); this.basicRequestProxyResponse.IsSuccessfulStatusCode.ShouldBe(false); this.basicRequestProxyResponse.RequestUri.ToString().ShouldBe(this.basicRequestProxyResponse.RequestUri.ToString()); } internal void ThenICanVerifyICannotIssueBasicRequestForNonExistingResource() { this.basicRequestProxyResponse.ShouldNotBeNull(); this.basicRequestProxyResponse.HttpRequestMethod.ShouldBe(httpRequestMethod); this.basicRequestProxyResponse.StatusCode.ShouldBe(HttpStatusCode.NotFound); this.basicRequestProxyResponse.IsSuccessfulStatusCode.ShouldBe(false); this.basicRequestProxyResponse.RequestUri.ToString().ShouldBe(this.basicRequestProxyResponse.RequestUri.ToString()); } internal void ThenICanVerifyICannotIssueSecureRequestDueNoAuthHeader() { this.secureRequestProxyResponse.ShouldNotBeNull(); this.secureRequestProxyResponse.HttpRequestMethod.ShouldBe(httpRequestMethod); this.secureRequestProxyResponse.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); this.secureRequestProxyResponse.IsSuccessfulStatusCode.ShouldBe(false); this.secureRequestProxyResponse.RequestUri.ToString().ShouldBe(this.secureRequestProxyResponse.RequestUri.ToString()); } internal void ThenICanVerifyIHaveAProxy() { this.proxy.ShouldNotBeNull(); } internal async Task WhenIInvokeAsyncForBasicRequest() { this.basicRequestProxyResponse = await this.proxy.InvokeAsync(this.basicRequestProxyRequest); } internal async Task WhenIInvokeAsyncForMessageDtoRequest() { this.messageDtoRequestProxyResponse = await this.proxy.InvokeAsync(this.messageDtoRequestProxyRequest); } internal async Task WhenIInvokeAsyncForMessageDtoResponseRequest() { this.messageDtoResponseRequestProxyResponse = await this.proxy.InvokeAsync(this.messageDtoResponseRequestProxyRequest); } internal async Task WhenIInvokeAsyncForSecureRequest() { this.secureRequestProxyResponse = await this.proxy.InvokeAsync(this.secureRequestProxyRequest); } #endregion Internal Methods #region Protected Methods protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { this.proxy?.Dispose(); } disposedValue = true; } } #endregion Protected Methods #region Private Methods private void ThenICanVerifyIGotAResponse<TRequestDto, TResponseDto>(IProxyResponse<TResponseDto> proxyResponse, IProxyRequest<TRequestDto, TResponseDto> proxyRequest, HttpStatusCode statusCode, bool isSuccessfulStatusCode) { proxyResponse.ShouldNotBeNull(); proxyResponse.HttpRequestMethod.ShouldBe(httpRequestMethod); proxyResponse.StatusCode.ShouldBe(statusCode); proxyResponse.IsSuccessfulStatusCode.ShouldBe(isSuccessfulStatusCode); proxyResponse.RequestHeaders.ShouldNotBeNull(); proxyResponse.RequestHeaders.ShouldNotBeEmpty(); proxyResponse.RequestUri.ToString().ShouldBe(proxyRequest.RequestUri.ToString()); proxyResponse.ResponseHeaders.ShouldNotBeNull(); proxyResponse.ResponseHeaders.ShouldNotBeEmpty(); } #endregion Private Methods } }