content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; namespace AwesomeTodoList.Model { public class TodoList { public TodoList() { } public TodoList(string name) { Name = name; } public int Id { get; set; } public string Name { get; set; } public DateTime? Done { get; set; } } }
17.35
43
0.48415
[ "MIT" ]
edineidev/awesome-todo-list
backend/AwesomeTodoList/Model/TodoList.cs
347
C#
using Cso.IfnsExporter.Protocol; namespace Cso.IfnsExporter.Models { public class PriodItemModel { public PriodItemModel(string name, PeriodCode priodCode) { Name = name; PriodCode = priodCode; } private string Name { get; } public PeriodCode PriodCode { get; } /// <inheritdoc /> public override string ToString() { return Name; } } }
20
64
0.552174
[ "MIT" ]
igolets/DevExpressMvvm
IfnsExporter/Models/PriodItemModel.cs
462
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; // StringBuilder namespace System.Data.Odbc { public sealed class OdbcDataReader : DbDataReader { private OdbcCommand _command; private int _recordAffected = -1; private FieldNameLookup _fieldNameLookup; private DbCache _dataCache; private enum HasRowsStatus { DontKnow = 0, HasRows = 1, HasNoRows = 2, } private HasRowsStatus _hasRows = HasRowsStatus.DontKnow; private bool _isClosed; private bool _isRead; private bool _isValidResult; private bool _noMoreResults; private bool _noMoreRows; private bool _skipReadOnce; private int _hiddenColumns; // number of hidden columns private CommandBehavior _commandBehavior; // track current row and column, will be set on the first Fetch call private int _row = -1; private int _column = -1; // used to track position in field for sucessive reads in case of Sequential Access private long _sequentialBytesRead; private static int s_objectTypeCount; // Bid counter internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); // the statement handle here is just a copy of the statement handle owned by the command // the DataReader must not free the statement handle. this is done by the command // private MetaData[] _metadata; private DataTable _schemaTable; // MDAC 68336 private string _cmdText; // get a copy in case the command text on the command is changed ... private CMDWrapper _cmdWrapper; internal OdbcDataReader(OdbcCommand command, CMDWrapper cmdWrapper, CommandBehavior commandbehavior) { Debug.Assert(command != null, "Command null on OdbcDataReader ctor"); _command = command; _commandBehavior = commandbehavior; _cmdText = command.CommandText; // get a copy in case the command text on the command is changed ... _cmdWrapper = cmdWrapper; } private CNativeBuffer Buffer { get { CNativeBuffer value = _cmdWrapper._dataReaderBuf; if (null == value) { Debug.Assert(false, "object is disposed"); throw new ObjectDisposedException(GetType().Name); } return value; } } private OdbcConnection Connection { get { if (null != _cmdWrapper) { return _cmdWrapper.Connection; } else { return null; } } } internal OdbcCommand Command { get { return _command; } set { _command = value; } } private OdbcStatementHandle StatementHandle { get { return _cmdWrapper.StatementHandle; } } private OdbcStatementHandle KeyInfoStatementHandle { get { return _cmdWrapper.KeyInfoStatement; } } internal bool IsBehavior(CommandBehavior behavior) { return IsCommandBehavior(behavior); } internal bool IsCancelingCommand { get { if (_command != null) { return _command.Canceling; } return false; } } internal bool IsNonCancelingCommand { get { if (_command != null) { return !_command.Canceling; } return false; } } public override int Depth { get { if (IsClosed) { // MDAC 63669 throw ADP.DataReaderClosed("Depth"); } return 0; } } public override int FieldCount { get { if (IsClosed) { // MDAC 63669 throw ADP.DataReaderClosed("FieldCount"); } if (_noMoreResults) { // MDAC 93325 return 0; } if (null == _dataCache) { Int16 cColsAffected; ODBC32.RetCode retcode = this.FieldCountNoThrow(out cColsAffected); if (retcode != ODBC32.RetCode.SUCCESS) { Connection.HandleError(StatementHandle, retcode); } } return ((null != _dataCache) ? _dataCache._count : 0); } } // HasRows // // Use to detect wheter there are one ore more rows in the result without going through Read // May be called at any time // Basically it calls Read and sets a flag so that the actual Read call will be skipped once // public override bool HasRows { get { if (IsClosed) { throw ADP.DataReaderClosed("HasRows"); } if (_hasRows == HasRowsStatus.DontKnow) { Read(); // _skipReadOnce = true; // need to skip Read once because we just did it } return (_hasRows == HasRowsStatus.HasRows); } } internal ODBC32.RetCode FieldCountNoThrow(out Int16 cColsAffected) { if (IsCancelingCommand) { cColsAffected = 0; return ODBC32.RetCode.ERROR; } ODBC32.RetCode retcode = StatementHandle.NumberOfResultColumns(out cColsAffected); if (retcode == ODBC32.RetCode.SUCCESS) { _hiddenColumns = 0; if (IsCommandBehavior(CommandBehavior.KeyInfo)) { // we need to search for the first hidden column // if (!Connection.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns) { for (int i = 0; i < cColsAffected; i++) { SQLLEN isHidden = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_HIDDEN, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE); if (isHidden.ToInt64() == 1) { _hiddenColumns = (int)cColsAffected - i; cColsAffected = (Int16)i; break; } } } } _dataCache = new DbCache(this, cColsAffected); } else { cColsAffected = 0; } return retcode; } public override bool IsClosed { get { return _isClosed; } } private SQLLEN GetRowCount() { if (!IsClosed) { SQLLEN cRowsAffected; ODBC32.RetCode retcode = StatementHandle.RowCount(out cRowsAffected); if (ODBC32.RetCode.SUCCESS == retcode || ODBC32.RetCode.SUCCESS_WITH_INFO == retcode) { return cRowsAffected; } } return -1; } internal int CalculateRecordsAffected(int cRowsAffected) { if (0 <= cRowsAffected) { if (-1 == _recordAffected) { _recordAffected = cRowsAffected; } else { _recordAffected += cRowsAffected; } } return _recordAffected; } public override int RecordsAffected { get { return _recordAffected; } } public override object this[int i] { get { return GetValue(i); } } public override object this[string value] { get { return GetValue(GetOrdinal(value)); } } public override void Close() { Close(false); } private void Close(bool disposing) { Exception error = null; CMDWrapper wrapper = _cmdWrapper; if (null != wrapper && wrapper.StatementHandle != null) { // disposing // true to release both managed and unmanaged resources; false to release only unmanaged resources. // if (IsNonCancelingCommand) { //Read any remaining results off the wire // some batch statements may not be executed until SQLMoreResults is called. // We want the user to be able to do ExecuteNonQuery or ExecuteReader // and close without having iterate to get params or batch. // NextResult(disposing, !disposing); // false,true or true,false if (null != _command) { if (_command.HasParameters) { // Output Parameters are not guareenteed to be returned until all the data // from any restssets are read, so we do this after the above NextResult call(s) _command.Parameters.GetOutputValues(_cmdWrapper); } wrapper.FreeStatementHandle(ODBC32.STMT.CLOSE); _command.CloseFromDataReader(); } } wrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.CLOSE); } // if the command is still around we call CloseFromDataReader, // otherwise we need to dismiss the statement handle ourselves // if (null != _command) { _command.CloseFromDataReader(); if (IsCommandBehavior(CommandBehavior.CloseConnection)) { Debug.Assert(null != Connection, "null cmd connection"); _command.Parameters.RebindCollection = true; Connection.Close(); } } else if (null != wrapper) { wrapper.Dispose(); } _command = null; _isClosed = true; _dataCache = null; _metadata = null; _schemaTable = null; _isRead = false; _hasRows = HasRowsStatus.DontKnow; _isValidResult = false; _noMoreResults = true; _noMoreRows = true; _fieldNameLookup = null; SetCurrentRowColumnInfo(-1, 0); if ((null != error) && !disposing) { throw error; } _cmdWrapper = null; } protected override void Dispose(bool disposing) { if (disposing) { Close(true); } // not delegating to base class because we know it only calls Close //base.Dispose(disposing) } public override String GetDataTypeName(int i) { if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); if (info._typename == null) { info._typename = GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW); } return info._typename; } throw ADP.DataReaderNoData(); } public override IEnumerator GetEnumerator() { return new DbEnumerator((IDataReader)this, IsCommandBehavior(CommandBehavior.CloseConnection)); } public override Type GetFieldType(int i) { if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); if (info._type == null) { info._type = GetSqlType(i)._type; } return info._type; } throw ADP.DataReaderNoData(); } public override String GetName(int i) { if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); if (info._name == null) { info._name = GetColAttributeStr(i, ODBC32.SQL_DESC.NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.THROW); if (null == info._name) { // MDAC 66681 info._name = ""; } } return info._name; } throw ADP.DataReaderNoData(); } public override int GetOrdinal(string value) { if (null == _fieldNameLookup) { if (null == _dataCache) { throw ADP.DataReaderNoData(); } _fieldNameLookup = new FieldNameLookup(this, -1); } return _fieldNameLookup.GetOrdinal(value); // MDAC 71470 } private int IndexOf(string value) { if (null == _fieldNameLookup) { if (null == _dataCache) { throw ADP.DataReaderNoData(); } _fieldNameLookup = new FieldNameLookup(this, -1); } return _fieldNameLookup.IndexOf(value); } private bool IsCommandBehavior(CommandBehavior condition) { return (condition == (condition & _commandBehavior)); } internal object GetValue(int i, TypeMap typemap) { switch (typemap._sql_type) { case ODBC32.SQL_TYPE.CHAR: case ODBC32.SQL_TYPE.VARCHAR: case ODBC32.SQL_TYPE.LONGVARCHAR: case ODBC32.SQL_TYPE.WCHAR: case ODBC32.SQL_TYPE.WVARCHAR: case ODBC32.SQL_TYPE.WLONGVARCHAR: return internalGetString(i); case ODBC32.SQL_TYPE.DECIMAL: case ODBC32.SQL_TYPE.NUMERIC: return internalGetDecimal(i); case ODBC32.SQL_TYPE.SMALLINT: return internalGetInt16(i); case ODBC32.SQL_TYPE.INTEGER: return internalGetInt32(i); case ODBC32.SQL_TYPE.REAL: return internalGetFloat(i); case ODBC32.SQL_TYPE.FLOAT: case ODBC32.SQL_TYPE.DOUBLE: return internalGetDouble(i); case ODBC32.SQL_TYPE.BIT: return internalGetBoolean(i); case ODBC32.SQL_TYPE.TINYINT: return internalGetByte(i); case ODBC32.SQL_TYPE.BIGINT: return internalGetInt64(i); case ODBC32.SQL_TYPE.BINARY: case ODBC32.SQL_TYPE.VARBINARY: case ODBC32.SQL_TYPE.LONGVARBINARY: return internalGetBytes(i); case ODBC32.SQL_TYPE.TYPE_DATE: return internalGetDate(i); case ODBC32.SQL_TYPE.TYPE_TIME: return internalGetTime(i); // case ODBC32.SQL_TYPE.TIMESTAMP: case ODBC32.SQL_TYPE.TYPE_TIMESTAMP: return internalGetDateTime(i); case ODBC32.SQL_TYPE.GUID: return internalGetGuid(i); case ODBC32.SQL_TYPE.SS_VARIANT: //Note: SQL Variant is not an ODBC defined type. //Instead of just binding it as a byte[], which is not very useful, //we will actually code this specific for SQL Server. //To obtain the sub-type, we need to first load the context (obtaining the length //will work), and then query for a speicial SQLServer specific attribute. if (_isRead) { if (_dataCache.AccessIndex(i) == null) { int dummy; bool isNotDbNull = QueryFieldInfo(i, ODBC32.SQL_C.BINARY, out dummy); // if the value is DBNull, QueryFieldInfo will cache it if (isNotDbNull) { //Delegate (for the sub type) ODBC32.SQL_TYPE subtype = (ODBC32.SQL_TYPE)(int)GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.VARIANT_SQL_TYPE, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.THROW); return GetValue(i, TypeMap.FromSqlType(subtype)); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); default: //Unknown types are bound strictly as binary return internalGetBytes(i); } } public override object GetValue(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { _dataCache[i] = GetValue(i, GetSqlType(i)); } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override int GetValues(object[] values) { if (_isRead) { int nValues = Math.Min(values.Length, FieldCount); for (int i = 0; i < nValues; ++i) { values[i] = GetValue(i); } return nValues; } throw ADP.DataReaderNoData(); } private TypeMap GetSqlType(int i) { //Note: Types are always returned (advertised) from ODBC as SQL_TYPEs, and //are always bound by the user as SQL_C types. TypeMap typeMap; DbSchemaInfo info = _dataCache.GetSchema(i); if (!info._dbtype.HasValue) { info._dbtype = unchecked((ODBC32.SQL_TYPE)(int)GetColAttribute(i, ODBC32.SQL_DESC.CONCISE_TYPE, ODBC32.SQL_COLUMN.TYPE, ODBC32.HANDLER.THROW)); typeMap = TypeMap.FromSqlType(info._dbtype.Value); if (typeMap._signType == true) { bool sign = (GetColAttribute(i, ODBC32.SQL_DESC.UNSIGNED, ODBC32.SQL_COLUMN.UNSIGNED, ODBC32.HANDLER.THROW).ToInt64() != 0); typeMap = TypeMap.UpgradeSignedType(typeMap, sign); info._dbtype = typeMap._sql_type; } } else { typeMap = TypeMap.FromSqlType(info._dbtype.Value); } Connection.SetSupportedType(info._dbtype.Value); return typeMap; } public override bool IsDBNull(int i) { // Note: ODBC SQLGetData doesn't allow retriving the column value twice. // The reational is that for ForwardOnly access (the default and LCD of drivers) // we cannot obtain the data more than once, and even GetData(0) (to determine is-null) // still obtains data for fixed length types. // So simple code like: // if(!rReader.IsDBNull(i)) // rReader.GetInt32(i) // // Would fail, unless we cache on the IsDBNull call, and return the cached // item for GetInt32. This actually improves perf anyway, (even if the driver could // support it), since we are not making a separate interop call... // Bug SQLBUVSTS01:110664 - available cases: // 1. random access - always cache the value (as before the fix), to minimize regression risk // 2. sequential access, fixed-size value: continue caching the value as before, again to minimize regression risk // 3. sequential access, variable-length value: this scenario did not work properly before the fix. Fix // it now by calling GetData(length = 0). // 4. sequential access, cache value exists: just check the cache for DbNull (no validations done, again to minimize regressions) if (!IsCommandBehavior(CommandBehavior.SequentialAccess)) return Convert.IsDBNull(GetValue(i)); // case 1, cache the value // in 'ideal' Sequential access support, we do not want cache the value in order to check if it is DbNull or not. // But, to minimize regressions, we will continue caching the fixed-size values (case 2), even with SequentialAccess // only in case of SequentialAccess with variable length data types (case 3), we will use GetData with zero length. object cachedObj = _dataCache[i]; if (cachedObj != null) { // case 4 - if cached object was created before, use it return Convert.IsDBNull(cachedObj); } // no cache, check for the type (cases 2 and 3) TypeMap typeMap = GetSqlType(i); if (typeMap._bufferSize > 0) { // case 2 - fixed-size types have _bufferSize set to positive value // call GetValue(i) as before the fix of SQLBUVSTS01:110664 // note, when SQLGetData is called for a fixed length type, the buffer size is always ignored and // the data will always be read off the wire return Convert.IsDBNull(GetValue(i)); } else { // case 3 - the data has variable-length type, read zero-length data to query for null // QueryFieldInfo will return false only if the object cached as DbNull // QueryFieldInfo will put DbNull in cache only if the SQLGetData returns SQL_NULL_DATA, otherwise it does not change it int dummy; return !QueryFieldInfo(i, typeMap._sql_c, out dummy); } } public override Byte GetByte(int i) { return (Byte)internalGetByte(i); } private object internalGetByte(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.UTINYINT)) { _dataCache[i] = Buffer.ReadByte(0); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override Char GetChar(int i) { return (Char)internalGetChar(i); } private object internalGetChar(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { _dataCache[i] = Buffer.ReadChar(0); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override Int16 GetInt16(int i) { return (Int16)internalGetInt16(i); } private object internalGetInt16(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.SSHORT)) { _dataCache[i] = Buffer.ReadInt16(0); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override Int32 GetInt32(int i) { return (Int32)internalGetInt32(i); } private object internalGetInt32(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.SLONG)) { _dataCache[i] = Buffer.ReadInt32(0); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override Int64 GetInt64(int i) { return (Int64)internalGetInt64(i); } // ---------------------------------------------------------------------------------------------- // // internal internalGetInt64 // ------------------------- // Get Value of type SQL_BIGINT // Since the driver refused to accept the type SQL_BIGINT we read that // as SQL_C_WCHAR and convert it back to the Int64 data type // private object internalGetInt64(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { string value = (string)Buffer.MarshalToManaged(0, ODBC32.SQL_C.WCHAR, ODBC32.SQL_NTS); _dataCache[i] = Int64.Parse(value, CultureInfo.InvariantCulture); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override bool GetBoolean(int i) { return (bool)internalGetBoolean(i); } private object internalGetBoolean(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.BIT)) { _dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.BIT, -1); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override float GetFloat(int i) { return (float)internalGetFloat(i); } private object internalGetFloat(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.REAL)) { _dataCache[i] = Buffer.ReadSingle(0); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public DateTime GetDate(int i) { return (DateTime)internalGetDate(i); } private object internalGetDate(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.TYPE_DATE)) { _dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_DATE, -1); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override DateTime GetDateTime(int i) { return (DateTime)internalGetDateTime(i); } private object internalGetDateTime(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.TYPE_TIMESTAMP)) { _dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_TIMESTAMP, -1); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override decimal GetDecimal(int i) { return (decimal)internalGetDecimal(i); } // ---------------------------------------------------------------------------------------------- // // internal GetDecimal // ------------------- // Get Value of type SQL_DECIMAL or SQL_NUMERIC // Due to provider incompatibilities with SQL_DECIMAL or SQL_NUMERIC types we always read the value // as SQL_C_WCHAR and convert it back to the Decimal data type // private object internalGetDecimal(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.WCHAR)) { string s = null; try { s = (string)Buffer.MarshalToManaged(0, ODBC32.SQL_C.WCHAR, ODBC32.SQL_NTS); _dataCache[i] = Decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture); } catch (OverflowException e) { _dataCache[i] = s; throw e; } } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override double GetDouble(int i) { return (double)internalGetDouble(i); } private object internalGetDouble(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.DOUBLE)) { _dataCache[i] = Buffer.ReadDouble(0); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override Guid GetGuid(int i) { return (Guid)internalGetGuid(i); } private object internalGetGuid(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.GUID)) { _dataCache[i] = Buffer.ReadGuid(0); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public override String GetString(int i) { return (String)internalGetString(i); } private object internalGetString(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { // Obtain _ALL_ the characters // Note: We can bind directly as WCHAR in ODBC and the DM will convert to and // from ANSI if not supported by the driver. // // Note: The driver always returns the raw length of the data, minus the // terminator. This means that our buffer length always includes the terminator // charactor, so when determining which characters to count, and if more data // exists, it should not take the terminator into effect. // CNativeBuffer buffer = Buffer; // that does not make sense unless we expect four byte terminators int cbMaxData = buffer.Length - 4; // The first time GetData returns the true length (so we have to min it). // We also pass in the true length to the marshal function since there could be // embedded nulls // int lengthOrIndicator; if (GetData(i, ODBC32.SQL_C.WCHAR, buffer.Length - 2, out lengthOrIndicator)) { // RFC 50002644: we do not expect negative values from GetData call except SQL_NO_TOTAL(== -4) // note that in general you should not trust third-party providers so such asserts should be // followed by exception. I did not add it now to avoid breaking change Debug.Assert(lengthOrIndicator >= 0 || lengthOrIndicator == ODBC32.SQL_NO_TOTAL, "unexpected lengthOrIndicator value"); if (lengthOrIndicator <= cbMaxData && (ODBC32.SQL_NO_TOTAL != lengthOrIndicator)) { // all data read? good! Directly marshal to a string and we're done // string strdata = buffer.PtrToStringUni(0, Math.Min(lengthOrIndicator, cbMaxData) / 2); _dataCache[i] = strdata; return strdata; } // We need to chunk the data // Char[] buffer for the junks // StringBuilder for the actual string // Char[] rgChars = new Char[cbMaxData / 2]; // RFC 50002644: negative value cannot be used for capacity. // in case of SQL_NO_TOTAL, set the capacity to cbMaxData, StringBuilder will automatically reallocate // its internal buffer when appending more data int cbBuilderInitialCapacity = (lengthOrIndicator == ODBC32.SQL_NO_TOTAL) ? cbMaxData : lengthOrIndicator; StringBuilder builder = new StringBuilder(cbBuilderInitialCapacity / 2); bool gotData; int cchJunk; int cbActual = cbMaxData; int cbMissing = (ODBC32.SQL_NO_TOTAL == lengthOrIndicator) ? -1 : lengthOrIndicator - cbActual; do { cchJunk = cbActual / 2; buffer.ReadChars(0, rgChars, 0, cchJunk); builder.Append(rgChars, 0, cchJunk); if (0 == cbMissing) { break; // done } gotData = GetData(i, ODBC32.SQL_C.WCHAR, buffer.Length - 2, out lengthOrIndicator); // RFC 50002644: we do not expect negative values from GetData call except SQL_NO_TOTAL(== -4) // note that in general you should not trust third-party providers so such asserts should be // followed by exception. I did not add it now to avoid breaking change Debug.Assert(lengthOrIndicator >= 0 || lengthOrIndicator == ODBC32.SQL_NO_TOTAL, "unexpected lengthOrIndicator value"); if (ODBC32.SQL_NO_TOTAL != lengthOrIndicator) { cbActual = Math.Min(lengthOrIndicator, cbMaxData); if (0 < cbMissing) { cbMissing -= cbActual; } else { // it is a last call to SqlGetData that started with SQL_NO_TOTAL // the last call to SqlGetData must always return the length of the // data, not zero or SqlNoTotal (see Odbc Programmers Reference) Debug.Assert(cbMissing == -1 && lengthOrIndicator <= cbMaxData); cbMissing = 0; } } } while (gotData); _dataCache[i] = builder.ToString(); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } public TimeSpan GetTime(int i) { return (TimeSpan)internalGetTime(i); } private object internalGetTime(int i) { if (_isRead) { if (_dataCache.AccessIndex(i) == null) { if (GetData(i, ODBC32.SQL_C.TYPE_TIME)) { _dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_TIME, -1); } } return _dataCache[i]; } throw ADP.DataReaderNoData(); } private void SetCurrentRowColumnInfo(int row, int column) { if (_row != row || _column != column) { _row = row; _column = column; // reset the blob reader when moved to new column _sequentialBytesRead = 0; } } public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { return GetBytesOrChars(i, dataIndex, buffer, false /* bytes buffer */, bufferIndex, length); } public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) { return GetBytesOrChars(i, dataIndex, buffer, true /* chars buffer */, bufferIndex, length); } // unify the implementation of GetChars and GetBytes to prevent code duplicate private long GetBytesOrChars(int i, long dataIndex, Array buffer, bool isCharsBuffer, int bufferIndex, int length) { if (IsClosed) { throw ADP.DataReaderNoData(); } if (!_isRead) { throw ADP.DataReaderNoData(); } if (dataIndex < 0) { // test only for negative value here, Int32.MaxValue will be validated only in case of random access throw ADP.ArgumentOutOfRange(nameof(dataIndex)); } if (bufferIndex < 0) { throw ADP.ArgumentOutOfRange(nameof(bufferIndex)); } if (length < 0) { throw ADP.ArgumentOutOfRange(nameof(length)); } string originalMethodName = isCharsBuffer ? "GetChars" : "GetBytes"; // row/column info will be reset only if changed SetCurrentRowColumnInfo(_row, i); // Possible cases: // 1. random access, user asks for the value first time: bring it and cache the value // 2. random access, user already queried the value: use the cache // 3. sequential access, cache exists: user already read this value using different method (it becomes cached) // use the cache - preserve the original behavior to minimize regression risk // 4. sequential access, no cache: (fixed now) user reads the bytes/chars in sequential order (no cache) object cachedObj = null; // The cached object (if there is one) // Get cached object, ensure the correct type using explicit cast, to preserve same behavior as before if (isCharsBuffer) cachedObj = (string)_dataCache[i]; else cachedObj = (byte[])_dataCache[i]; bool isRandomAccess = !IsCommandBehavior(CommandBehavior.SequentialAccess); if (isRandomAccess || (cachedObj != null)) { // random access (cases 1 or 2) and sequential access with cache (case 3) // preserve the original behavior as before the fix if (Int32.MaxValue < dataIndex) { // indices greater than allocable size are not supported in random access // (negative value is already tested in the beginning of ths function) throw ADP.ArgumentOutOfRange(nameof(dataIndex)); } if (cachedObj == null) { // case 1, get the value and cache it // internalGetString/internalGetBytes will get the entire value and cache it, // since we are not in SequentialAccess (isRandomAccess is true), it is OK if (isCharsBuffer) { cachedObj = (String)internalGetString(i); Debug.Assert((cachedObj != null), "internalGetString should always return non-null or raise exception"); } else { cachedObj = (byte[])internalGetBytes(i); Debug.Assert((cachedObj != null), "internalGetBytes should always return non-null or raise exception"); } // continue to case 2 } // after this point the value is cached (case 2 or 3) // if it is DbNull, cast exception will be raised (same as before the 110664 fix) int cachedObjectLength = isCharsBuffer ? ((string)cachedObj).Length : ((byte[])cachedObj).Length; // the user can ask for the length of the field by passing in a null pointer for the buffer if (buffer == null) { // return the length if that's all what user needs return cachedObjectLength; } // user asks for bytes if (length == 0) { return 0; // Nothing to do ... } if (dataIndex >= cachedObjectLength) { // no more bytes to read // see also MDAC bug 73298 return 0; } int lengthFromDataIndex = cachedObjectLength - (int)dataIndex; int lengthOfCopy = Math.Min(lengthFromDataIndex, length); // silently reduce the length to avoid regression from EVERETT lengthOfCopy = Math.Min(lengthOfCopy, buffer.Length - bufferIndex); if (lengthOfCopy <= 0) return 0; // MDAC Bug 73298 if (isCharsBuffer) ((string)cachedObj).CopyTo((int)dataIndex, (char[])buffer, bufferIndex, lengthOfCopy); else Array.Copy((byte[])cachedObj, (int)dataIndex, (byte[])buffer, bufferIndex, lengthOfCopy); return lengthOfCopy; } else { // sequential access, case 4 // SQLBU:532243 -- For SequentialAccess we need to read a chunk of // data and not cache it. // Note: If the object was previous cached (see case 3 above), the function will go thru 'if' path, to minimize // regressions // the user can ask for the length of the field by passing in a null pointer for the buffer if (buffer == null) { // Get len. of remaining data from provider ODBC32.SQL_C sqlctype; int cbLengthOrIndicator; bool isDbNull; sqlctype = isCharsBuffer ? ODBC32.SQL_C.WCHAR : ODBC32.SQL_C.BINARY; isDbNull = !QueryFieldInfo(i, sqlctype, out cbLengthOrIndicator); if (isDbNull) { // SQLBU 266054: // GetChars: // in Orcas RTM: GetChars has always raised InvalidCastException. // in Orcas SP1: GetChars returned 0 if DbNull is not cached yet and InvalidCastException if it is in cache (from case 3). // Managed Providers team has decided to fix the GetChars behavior and raise InvalidCastException, as it was in RTM // Reason: returing 0 is wrong behavior since it conflicts with return value in case of empty data // GetBytes: // In Orcas RTM: GetBytes(null buffer) returned -1 for null value if DbNull is not cached yet. // But, after calling IsDBNull, GetBytes(null) raised InvalidCastException. // In Orcas SP1: GetBytes always raises InvalidCastException for null value. // Managed Providers team has decided to keep the behavior of RTM for this case to fix the RTM's breaking change. // Reason: while -1 is wrong behavior, people might be already relying on it, so we should not be changing it. // Note: this will happen only on the first call to GetBytes(with null buffer). // If IsDbNull has already been called before or for second call to query for size, // DBNull is cached and GetBytes raises InvalidCastException in case 3 (see the cases above in this method). if (isCharsBuffer) { throw ADP.InvalidCast(); } else { return -1; } } else { // the value is not null // SQLBU 266054: // If cbLengthOrIndicator is SQL_NO_TOTAL (-4), this call returns -4 or -2, depending on the type (GetChars=>-2, GetBytes=>-4). // This is the Orcas RTM and SP1 behavior, changing this would be a breaking change. // SQL_NO_TOTAL means that the driver does not know what is the remained lenght of the data, so we cannot really guess the value here. // Reason: while returning different negative values depending on the type seems inconsistent, // this is what we did in Orcas RTM and SP1 and user code might rely on this behavior => changing it would be a breaking change. if (isCharsBuffer) { return cbLengthOrIndicator / 2; // return length in wide characters or -2 if driver returns SQL_NO_TOTAL } else { return cbLengthOrIndicator; // return length in bytes or -4 if driver returns SQL_NO_TOTAL } } } else { // buffer != null, read the data // check if user tries to read data that was already received // if yes, this violates 'sequential access' if ((isCharsBuffer && dataIndex < _sequentialBytesRead / 2) || (!isCharsBuffer && dataIndex < _sequentialBytesRead)) { // backward reading is not allowed in sequential access throw ADP.NonSeqByteAccess( dataIndex, _sequentialBytesRead, originalMethodName ); } // note that it is actually not possible to read with an offset (dataIndex) // therefore, adjust the data index relative to number of bytes already read if (isCharsBuffer) dataIndex -= _sequentialBytesRead / 2; else dataIndex -= _sequentialBytesRead; if (dataIndex > 0) { // user asked to skip bytes - it is OK, even in case of sequential access // forward the stream by dataIndex bytes/chars int charsOrBytesRead = readBytesOrCharsSequentialAccess(i, null, isCharsBuffer, 0, dataIndex); if (charsOrBytesRead < dataIndex) { // the stream ended before we forwarded to the requested index, stop now return 0; } } // ODBC driver now points to the correct position, start filling the user buffer from now // Make sure we don't overflow the user provided buffer // Note: SqlDataReader will raise exception if there is no enough room for length requested. // In case of ODBC, I decided to keep this consistent with random access after consulting with PM. length = Math.Min(length, buffer.Length - bufferIndex); if (length <= 0) { // SQLBU 266054: // if the data is null, the ideal behavior here is to raise InvalidCastException. But, // * GetBytes returned 0 in Orcas RTM and SP1, continue to do so to avoid breaking change from Orcas RTM and SP1. // * GetChars raised exception in RTM, and returned 0 in SP1: we decided to revert back to the RTM's behavior and raise InvalidCast if (isCharsBuffer) { // for GetChars, ensure data is not null // 2 bytes for '\0' termination, no data is actually read from the driver int cbLengthOrIndicator; bool isDbNull = !QueryFieldInfo(i, ODBC32.SQL_C.WCHAR, out cbLengthOrIndicator); if (isDbNull) { throw ADP.InvalidCast(); } } // else - GetBytes - return now return 0; } // fill the user's buffer return readBytesOrCharsSequentialAccess(i, buffer, isCharsBuffer, bufferIndex, length); } } } // fill the user's buffer (char[] or byte[], depending on isCharsBuffer) // if buffer is null, just skip the bytesOrCharsLength bytes or chars private int readBytesOrCharsSequentialAccess(int i, Array buffer, bool isCharsBuffer, int bufferIndex, long bytesOrCharsLength) { Debug.Assert(bufferIndex >= 0, "Negative buffer index"); Debug.Assert(bytesOrCharsLength >= 0, "Negative number of bytes or chars to read"); // validated by the caller Debug.Assert(buffer == null || bytesOrCharsLength <= (buffer.Length - bufferIndex), "Not enough space in user's buffer"); int totalBytesOrCharsRead = 0; string originalMethodName = isCharsBuffer ? "GetChars" : "GetBytes"; // we need length in bytes, b/c that is what SQLGetData expects long cbLength = (isCharsBuffer) ? checked(bytesOrCharsLength * 2) : bytesOrCharsLength; // continue reading from the driver until we fill the user's buffer or until no more data is available // the data is pumped first into the internal native buffer and after that copied into the user's one if buffer is not null CNativeBuffer internalNativeBuffer = this.Buffer; // read the data in loop up to th user's length // if the data size is less than requested or in case of error, the while loop will stop in the middle while (cbLength > 0) { // max data to be read, in bytes, not including null-terminator for WCHARs int cbReadMax; // read from the driver bool isNotDbNull; int cbTotal; // read either bytes or chars, depending on the method called if (isCharsBuffer) { // for WCHAR buffers, we need to leave space for null-terminator (2 bytes) // reserve 2 bytes for null-terminator and 2 bytes to prevent assert in GetData // if SQL_NO_TOTAL is returned, this ammount is read from the wire, in bytes cbReadMax = (int)Math.Min(cbLength, internalNativeBuffer.Length - 4); // SQLGetData will always append it - we do not to copy it to user's buffer isNotDbNull = GetData(i, ODBC32.SQL_C.WCHAR, cbReadMax + 2, out cbTotal); } else { // reserve 2 bytes to prevent assert in GetData // when querying bytes, no need to reserve space for null cbReadMax = (int)Math.Min(cbLength, internalNativeBuffer.Length - 2); isNotDbNull = GetData(i, ODBC32.SQL_C.BINARY, cbReadMax, out cbTotal); } if (!isNotDbNull) { // DbNull received, neither GetBytes nor GetChars should be used with DbNull value // two options // 1. be consistent with SqlDataReader, raise SqlNullValueException // 2. be consistent with other Get* methods of OdbcDataReader and raise InvalidCastException // after consulting with Himanshu (PM), decided to go with option 2 (raise cast exception) throw ADP.InvalidCast(); } int cbRead; // will hold number of bytes read in this loop bool noDataRemained = false; if (cbTotal == 0) { // no bytes read, stop break; } else if (ODBC32.SQL_NO_TOTAL == cbTotal) { // the driver has filled the internal buffer, but the length of remained data is still unknown // we will continue looping until SQLGetData indicates the end of data or user buffer is fully filled cbRead = cbReadMax; } else { Debug.Assert((cbTotal > 0), "GetData returned negative value, which is not SQL_NO_TOTAL"); // GetData uses SQLGetData, which StrLen_or_IndPtr (cbTotal in our case) to the current buf + remained buf (if any) if (cbTotal > cbReadMax) { // in this case the amount of bytes/chars read will be the max requested (and more bytes can be read) cbRead = cbReadMax; } else { // SQLGetData read all the available data, no more remained // continue processing this chunk and stop cbRead = cbTotal; noDataRemained = true; } } _sequentialBytesRead += cbRead; // update internal state and copy the data to user's buffer if (isCharsBuffer) { int cchRead = cbRead / 2; if (buffer != null) { internalNativeBuffer.ReadChars(0, (char[])buffer, bufferIndex, cchRead); bufferIndex += cchRead; } totalBytesOrCharsRead += cchRead; } else { if (buffer != null) { internalNativeBuffer.ReadBytes(0, (byte[])buffer, bufferIndex, cbRead); bufferIndex += cbRead; } totalBytesOrCharsRead += cbRead; } cbLength -= cbRead; // stop if no data remained if (noDataRemained) break; } return totalBytesOrCharsRead; } private object internalGetBytes(int i) { if (_dataCache.AccessIndex(i) == null) { // Obtain _ALL_ the bytes... // The first time GetData returns the true length (so we have to min it). Byte[] rgBytes; int cbBufferLen = Buffer.Length - 4; int cbActual; int cbOffset = 0; if (GetData(i, ODBC32.SQL_C.BINARY, cbBufferLen, out cbActual)) { CNativeBuffer buffer = Buffer; if (ODBC32.SQL_NO_TOTAL != cbActual) { rgBytes = new Byte[cbActual]; Buffer.ReadBytes(0, rgBytes, cbOffset, Math.Min(cbActual, cbBufferLen)); // Chunking. The data may be larger than our native buffer. In which case // instead of growing the buffer (out of control), we will read in chunks to // reduce memory footprint size. while (cbActual > cbBufferLen) { // The first time GetData returns the true length. Then successive calls // return the remaining data. bool flag = GetData(i, ODBC32.SQL_C.BINARY, cbBufferLen, out cbActual); Debug.Assert(flag, "internalGetBytes - unexpected invalid result inside if-block"); cbOffset += cbBufferLen; buffer.ReadBytes(0, rgBytes, cbOffset, Math.Min(cbActual, cbBufferLen)); } } else { List<Byte[]> junkArray = new List<Byte[]>(); int junkSize; int totalSize = 0; do { junkSize = (ODBC32.SQL_NO_TOTAL != cbActual) ? cbActual : cbBufferLen; rgBytes = new Byte[junkSize]; totalSize += junkSize; buffer.ReadBytes(0, rgBytes, 0, junkSize); junkArray.Add(rgBytes); } while ((ODBC32.SQL_NO_TOTAL == cbActual) && GetData(i, ODBC32.SQL_C.BINARY, cbBufferLen, out cbActual)); rgBytes = new Byte[totalSize]; foreach (Byte[] junk in junkArray) { junk.CopyTo(rgBytes, cbOffset); cbOffset += junk.Length; } } // always update the cache _dataCache[i] = rgBytes; } } return _dataCache[i]; } // GetColAttribute // --------------- // [IN] iColumn ColumnNumber // [IN] v3FieldId FieldIdentifier of the attribute for version3 drivers (>=3.0) // [IN] v2FieldId FieldIdentifier of the attribute for version2 drivers (<3.0) // // returns the value of the FieldIdentifier field of the column // or -1 if the FieldIdentifier wasn't supported by the driver // private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId, ODBC32.HANDLER handler) { Int16 cchNameLength = 0; SQLLEN numericAttribute; ODBC32.RetCode retcode; // protect against dead connection, dead or canceling command. if ((Connection == null) || _cmdWrapper.Canceling) { return -1; } //Ordinals are 1:base in odbc OdbcStatementHandle stmt = StatementHandle; if (Connection.IsV3Driver) { retcode = stmt.ColumnAttribute(iColumn + 1, (short)v3FieldId, Buffer, out cchNameLength, out numericAttribute); } else if (v2FieldId != (ODBC32.SQL_COLUMN)(-1)) { retcode = stmt.ColumnAttribute(iColumn + 1, (short)v2FieldId, Buffer, out cchNameLength, out numericAttribute); } else { return 0; } if (retcode != ODBC32.RetCode.SUCCESS) { if (retcode == ODBC32.RetCode.ERROR) { if ("HY091" == Command.GetDiagSqlState()) { Connection.FlagUnsupportedColAttr(v3FieldId, v2FieldId); } } if (handler == ODBC32.HANDLER.THROW) { Connection.HandleError(stmt, retcode); } return -1; } return numericAttribute; } // GetColAttributeStr // --------------- // [IN] iColumn ColumnNumber // [IN] v3FieldId FieldIdentifier of the attribute for version3 drivers (>=3.0) // [IN] v2FieldId FieldIdentifier of the attribute for version2 drivers (<3.0) // // returns the stringvalue of the FieldIdentifier field of the column // or null if the string returned was empty or if the FieldIdentifier wasn't supported by the driver // private String GetColAttributeStr(int i, ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId, ODBC32.HANDLER handler) { ODBC32.RetCode retcode; Int16 cchNameLength = 0; SQLLEN numericAttribute; CNativeBuffer buffer = Buffer; buffer.WriteInt16(0, 0); OdbcStatementHandle stmt = StatementHandle; // protect against dead connection if (Connection == null || _cmdWrapper.Canceling || stmt == null) { return ""; } if (Connection.IsV3Driver) { retcode = stmt.ColumnAttribute(i + 1, (short)v3FieldId, buffer, out cchNameLength, out numericAttribute); } else if (v2FieldId != (ODBC32.SQL_COLUMN)(-1)) { retcode = stmt.ColumnAttribute(i + 1, (short)v2FieldId, buffer, out cchNameLength, out numericAttribute); } else { return null; } if ((retcode != ODBC32.RetCode.SUCCESS) || (cchNameLength == 0)) { if (retcode == ODBC32.RetCode.ERROR) { if ("HY091" == Command.GetDiagSqlState()) { Connection.FlagUnsupportedColAttr(v3FieldId, v2FieldId); } } if (handler == ODBC32.HANDLER.THROW) { Connection.HandleError(stmt, retcode); } return null; } string retval = buffer.PtrToStringUni(0, cchNameLength / 2 /*cch*/); return retval; } // todo: Another 3.0 only attribute that is guaranteed to fail on V2 driver. // need to special case this for V2 drivers. // private String GetDescFieldStr(int i, ODBC32.SQL_DESC attribute, ODBC32.HANDLER handler) { Int32 numericAttribute = 0; // protect against dead connection, dead or canceling command. if ((Connection == null) || _cmdWrapper.Canceling) { return ""; } // APP_PARAM_DESC is a (ODBCVER >= 0x0300) attribute if (!Connection.IsV3Driver) { Debug.Assert(false, "Non-V3 driver. Must not call GetDescFieldStr"); return null; } ODBC32.RetCode retcode; CNativeBuffer buffer = Buffer; // Need to set the APP_PARAM_DESC values here using (OdbcDescriptorHandle hdesc = new OdbcDescriptorHandle(StatementHandle, ODBC32.SQL_ATTR.APP_PARAM_DESC)) { //SQLGetDescField retcode = hdesc.GetDescriptionField(i + 1, attribute, buffer, out numericAttribute); //Since there are many attributes (column, statement, etc), that may or may not be //supported, we don't want to throw (which obtains all errorinfo, marshals strings, //builds exceptions, etc), in common cases, unless we absolutely need this info... if ((retcode != ODBC32.RetCode.SUCCESS) || (numericAttribute == 0)) { if (retcode == ODBC32.RetCode.ERROR) { if ("HY091" == Command.GetDiagSqlState()) { Connection.FlagUnsupportedColAttr(attribute, (ODBC32.SQL_COLUMN)0); } } if (handler == ODBC32.HANDLER.THROW) { Connection.HandleError(StatementHandle, retcode); } return null; } } string retval = buffer.PtrToStringUni(0, numericAttribute / 2 /*cch*/); return retval; } /// <summary> /// This methods queries the following field information: isDbNull and remained size/indicator. No data is read from the driver. /// If the value is DbNull, this value will be cached. Refer to GetData for more details. /// </summary> /// <returns>false if value is DbNull, true otherwise</returns> private bool QueryFieldInfo(int i, ODBC32.SQL_C sqlctype, out int cbLengthOrIndicator) { int cb = 0; if (sqlctype == ODBC32.SQL_C.WCHAR) { // SQLBU 266054 - in case of WCHAR data, we need to provide buffer with a space for null terminator (two bytes) cb = 2; } return GetData(i, sqlctype, cb /* no data should be lost */, out cbLengthOrIndicator); } private bool GetData(int i, ODBC32.SQL_C sqlctype) { // Never call GetData with anything larger than _buffer.Length-2. // We keep reallocating native buffers and it kills performance!!! int dummy; return GetData(i, sqlctype, Buffer.Length - 4, out dummy); } /// <summary> /// Note: use only this method to call SQLGetData! It caches the null value so the fact that the value is null is kept and no other calls /// are made after it. /// /// retrieves the data into this.Buffer. /// * If the data is DbNull, the value be also cached and false is returned. /// * if the data is not DbNull, the value is not cached and true is returned /// /// Note: cbLengthOrIndicator can be either the length of (remained) data or SQL_NO_TOTAL (-4) when the length is not known. /// in case of SQL_NO_TOTAL, driver fills the buffer till the end. /// The indicator will NOT be SQL_NULL_DATA, GetData will replace it with zero and return false. /// </summary> /// <returns>false if value is DbNull, true otherwise</returns> private bool GetData(int i, ODBC32.SQL_C sqlctype, int cb, out int cbLengthOrIndicator) { IntPtr cbActual = IntPtr.Zero; // Length or an indicator value if (IsCancelingCommand) { throw ADP.DataReaderNoData(); } Debug.Assert(null != StatementHandle, "Statement handle is null in DateReader"); // see notes on ODBC32.RetCode.NO_DATA case below. Debug.Assert(_dataCache == null || !Convert.IsDBNull(_dataCache[i]), "Cannot call GetData without checking for cache first!"); // Never call GetData with anything larger than _buffer.Length-2. // We keep reallocating native buffers and it kills performance!!! Debug.Assert(cb <= Buffer.Length - 2, "GetData needs to Reallocate. Perf bug"); // SQLGetData CNativeBuffer buffer = Buffer; ODBC32.RetCode retcode = StatementHandle.GetData( (i + 1), // Column ordinals start at 1 in odbc sqlctype, buffer, cb, out cbActual); switch (retcode) { case ODBC32.RetCode.SUCCESS: break; case ODBC32.RetCode.SUCCESS_WITH_INFO: if ((Int32)cbActual == ODBC32.SQL_NO_TOTAL) { break; } // devnote: don't we want to fire an event? break; case ODBC32.RetCode.NO_DATA: // SQLBU 266054: System.Data.Odbc: Fails with truncated error when we pass BufferLength as 0 // NO_DATA return value is success value - it means that the driver has fully consumed the current column value // but did not move to the next column yet. // For fixed-size values, we do not expect this to happen because we fully consume the data and store it in cache after the first call. // For variable-length values (any character or binary data), SQLGetData can be called several times on the same column, // to query for the next chunk of value, even after reaching its end! // Thus, ignore NO_DATA for variable length data, but raise exception for fixed-size types if (sqlctype != ODBC32.SQL_C.WCHAR && sqlctype != ODBC32.SQL_C.BINARY) { Connection.HandleError(StatementHandle, retcode); } if (cbActual == (IntPtr)ODBC32.SQL_NO_TOTAL) { // ensure SQL_NO_TOTAL value gets replaced with zero if the driver has fully consumed the current column cbActual = (IntPtr)0; } break; default: Connection.HandleError(StatementHandle, retcode); break; } // reset the current row and column SetCurrentRowColumnInfo(_row, i); // test for SQL_NULL_DATA if (cbActual == (IntPtr)ODBC32.SQL_NULL_DATA) { // Store the DBNull value in cache. Note that if we need to do it, because second call into the SQLGetData returns NO_DATA, which means // we already consumed the value (see above) and the NULL information is lost. By storing the null in cache, we avoid second call into the driver // for the same row/column. _dataCache[i] = DBNull.Value; // the indicator is never -1 (and it should not actually be used if the data is DBNull) cbLengthOrIndicator = 0; return false; } else { //Return the actual size (for chunking scenarios) // note the return value can be SQL_NO_TOTAL (-4) cbLengthOrIndicator = (int)cbActual; return true; } } public override bool Read() { if (IsClosed) { throw ADP.DataReaderClosed("Read"); } if (IsCancelingCommand) { _isRead = false; return false; } // HasRows needs to call into Read so we don't want to read on the actual Read call if (_skipReadOnce) { _skipReadOnce = false; return _isRead; } if (_noMoreRows || _noMoreResults || IsCommandBehavior(CommandBehavior.SchemaOnly)) return false; if (!_isValidResult) { return false; } ODBC32.RetCode retcode; //SQLFetch is only valid to call for row returning queries //We get: [24000]Invalid cursor state. So we could either check the count //ahead of time (which is cached), or check on error and compare error states. //Note: SQLFetch is also invalid to be called on a prepared (schemaonly) statement //SqlFetch retcode = StatementHandle.Fetch(); switch (retcode) { case ODBC32.RetCode.SUCCESS_WITH_INFO: Connection.HandleErrorNoThrow(StatementHandle, retcode); _hasRows = HasRowsStatus.HasRows; _isRead = true; break; case ODBC32.RetCode.SUCCESS: _hasRows = HasRowsStatus.HasRows; _isRead = true; break; case ODBC32.RetCode.NO_DATA: _isRead = false; if (_hasRows == HasRowsStatus.DontKnow) { _hasRows = HasRowsStatus.HasNoRows; } break; default: Connection.HandleError(StatementHandle, retcode); break; } //Null out previous cached row values. _dataCache.FlushValues(); // if CommandBehavior == SingleRow we set _noMoreResults to true so that following reads will fail if (IsCommandBehavior(CommandBehavior.SingleRow)) { _noMoreRows = true; // no more rows, set to -1 SetCurrentRowColumnInfo(-1, 0); } else { // move to the next row SetCurrentRowColumnInfo(_row + 1, 0); } return _isRead; } // Called by odbccommand when executed for the first time internal void FirstResult() { Int16 cCols; SQLLEN cRowsAffected; cRowsAffected = GetRowCount(); // get rowcount of the current resultset (if any) CalculateRecordsAffected(cRowsAffected); // update recordsaffected ODBC32.RetCode retcode = FieldCountNoThrow(out cCols); if ((retcode == ODBC32.RetCode.SUCCESS) && (cCols == 0)) { NextResult(); } else { _isValidResult = true; } } public override bool NextResult() { return NextResult(false, false); } private bool NextResult(bool disposing, bool allresults) { // if disposing, loop through all the remaining results and ignore error messages // if allresults, loop through all results and collect all error messages for a single exception // callers are via Close(false, true), Dispose(true, false), NextResult(false,false) Debug.Assert(!disposing || !allresults, "both disposing & allresults are true"); const int MaxConsecutiveFailure = 2000; // see WebData 72126 for why more than 1000 SQLLEN cRowsAffected; Int16 cColsAffected; ODBC32.RetCode retcode, firstRetCode = ODBC32.RetCode.SUCCESS; bool hasMoreResults; bool hasColumns = false; bool singleResult = IsCommandBehavior(CommandBehavior.SingleResult); if (IsClosed) { throw ADP.DataReaderClosed("NextResult"); } _fieldNameLookup = null; if (IsCancelingCommand || _noMoreResults) { return false; } //Blow away the previous cache (since the next result set will have a different shape, //different schema data, and different data. _isRead = false; _hasRows = HasRowsStatus.DontKnow; _fieldNameLookup = null; _metadata = null; _schemaTable = null; int loop = 0; // infinite loop protection, max out after 2000 consecutive failed results OdbcErrorCollection errors = null; // SQLBU 342112 do { _isValidResult = false; retcode = StatementHandle.MoreResults(); hasMoreResults = ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)); if (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO) { Connection.HandleErrorNoThrow(StatementHandle, retcode); } else if (!disposing && (retcode != ODBC32.RetCode.NO_DATA) && (ODBC32.RetCode.SUCCESS != retcode)) { // allow for building comulative error messages. if (null == errors) { firstRetCode = retcode; errors = new OdbcErrorCollection(); } ODBC32.GetDiagErrors(errors, null, StatementHandle, retcode); ++loop; } if (!disposing && hasMoreResults) { loop = 0; cRowsAffected = GetRowCount(); // get rowcount of the current resultset (if any) CalculateRecordsAffected(cRowsAffected); // update recordsaffected if (!singleResult) { // update row- and columncount FieldCountNoThrow(out cColsAffected); hasColumns = (0 != cColsAffected); _isValidResult = hasColumns; } } } while ((!singleResult && hasMoreResults && !hasColumns) // repeat for results with no columns || ((ODBC32.RetCode.NO_DATA != retcode) && allresults && (loop < MaxConsecutiveFailure)) // or process all results until done || (singleResult && hasMoreResults)); // or for any result in singelResult mode if (retcode == ODBC32.RetCode.NO_DATA) { _dataCache = null; _noMoreResults = true; } if (null != errors) { Debug.Assert(!disposing, "errors while disposing"); errors.SetSource(Connection.Driver); OdbcException exception = OdbcException.CreateException(errors, firstRetCode); Connection.ConnectionIsAlive(exception); throw exception; } return (hasMoreResults); } private void BuildMetaDataInfo() { int count = FieldCount; MetaData[] metaInfos = new MetaData[count]; List<string> qrytables; bool needkeyinfo = IsCommandBehavior(CommandBehavior.KeyInfo); bool isKeyColumn; bool isHidden; ODBC32.SQL_NULLABILITY nullable; if (needkeyinfo) qrytables = new List<string>(); else qrytables = null; // Find out all the metadata info, not all of this info will be available in all cases // for (int i = 0; i < count; i++) { metaInfos[i] = new MetaData(); metaInfos[i].ordinal = i; TypeMap typeMap; // for precision and scale we take the SQL_COLUMN_ attributes. // Those attributes are supported by all provider versions. // for size we use the octet length. We can't use column length because there is an incompatibility with the jet driver. // furthermore size needs to be special cased for wchar types // typeMap = TypeMap.FromSqlType((ODBC32.SQL_TYPE)unchecked((int)GetColAttribute(i, ODBC32.SQL_DESC.CONCISE_TYPE, ODBC32.SQL_COLUMN.TYPE, ODBC32.HANDLER.THROW))); if (typeMap._signType == true) { bool sign = (GetColAttribute(i, ODBC32.SQL_DESC.UNSIGNED, ODBC32.SQL_COLUMN.UNSIGNED, ODBC32.HANDLER.THROW).ToInt64() != 0); // sign = true if the column is unsigned typeMap = TypeMap.UpgradeSignedType(typeMap, sign); } metaInfos[i].typemap = typeMap; metaInfos[i].size = GetColAttribute(i, ODBC32.SQL_DESC.OCTET_LENGTH, ODBC32.SQL_COLUMN.LENGTH, ODBC32.HANDLER.IGNORE); // special case the 'n' types // switch (metaInfos[i].typemap._sql_type) { case ODBC32.SQL_TYPE.WCHAR: case ODBC32.SQL_TYPE.WLONGVARCHAR: case ODBC32.SQL_TYPE.WVARCHAR: metaInfos[i].size /= 2; break; } metaInfos[i].precision = (byte)GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_COLUMN.PRECISION, ODBC32.SQL_COLUMN.PRECISION, ODBC32.HANDLER.IGNORE); metaInfos[i].scale = (byte)GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_COLUMN.SCALE, ODBC32.SQL_COLUMN.SCALE, ODBC32.HANDLER.IGNORE); metaInfos[i].isAutoIncrement = GetColAttribute(i, ODBC32.SQL_DESC.AUTO_UNIQUE_VALUE, ODBC32.SQL_COLUMN.AUTO_INCREMENT, ODBC32.HANDLER.IGNORE) == 1; metaInfos[i].isReadOnly = (GetColAttribute(i, ODBC32.SQL_DESC.UPDATABLE, ODBC32.SQL_COLUMN.UPDATABLE, ODBC32.HANDLER.IGNORE) == (Int32)ODBC32.SQL_UPDATABLE.READONLY); nullable = (ODBC32.SQL_NULLABILITY)(int)GetColAttribute(i, ODBC32.SQL_DESC.NULLABLE, ODBC32.SQL_COLUMN.NULLABLE, ODBC32.HANDLER.IGNORE); metaInfos[i].isNullable = (nullable == ODBC32.SQL_NULLABILITY.NULLABLE); switch (metaInfos[i].typemap._sql_type) { case ODBC32.SQL_TYPE.LONGVARCHAR: case ODBC32.SQL_TYPE.WLONGVARCHAR: case ODBC32.SQL_TYPE.LONGVARBINARY: metaInfos[i].isLong = true; break; default: metaInfos[i].isLong = false; break; } if (IsCommandBehavior(CommandBehavior.KeyInfo)) { // Note: Following two attributes are SQL Server specific (hence _SS in the name) // SSS_WARNINGS_OFF if (!Connection.ProviderInfo.NoSqlCASSColumnKey) { isKeyColumn = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_KEY, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE) == 1; if (isKeyColumn) { metaInfos[i].isKeyColumn = isKeyColumn; metaInfos[i].isUnique = true; needkeyinfo = false; } } // SSS_WARNINGS_ON metaInfos[i].baseSchemaName = GetColAttributeStr(i, ODBC32.SQL_DESC.SCHEMA_NAME, ODBC32.SQL_COLUMN.OWNER_NAME, ODBC32.HANDLER.IGNORE); metaInfos[i].baseCatalogName = GetColAttributeStr(i, ODBC32.SQL_DESC.CATALOG_NAME, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE); metaInfos[i].baseTableName = GetColAttributeStr(i, ODBC32.SQL_DESC.BASE_TABLE_NAME, ODBC32.SQL_COLUMN.TABLE_NAME, ODBC32.HANDLER.IGNORE); metaInfos[i].baseColumnName = GetColAttributeStr(i, ODBC32.SQL_DESC.BASE_COLUMN_NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.IGNORE); if (Connection.IsV3Driver) { if ((metaInfos[i].baseTableName == null) || (metaInfos[i].baseTableName.Length == 0)) { // Driver didn't return the necessary information from GetColAttributeStr. // Try GetDescField() metaInfos[i].baseTableName = GetDescFieldStr(i, ODBC32.SQL_DESC.BASE_TABLE_NAME, ODBC32.HANDLER.IGNORE); } if ((metaInfos[i].baseColumnName == null) || (metaInfos[i].baseColumnName.Length == 0)) { // Driver didn't return the necessary information from GetColAttributeStr. // Try GetDescField() metaInfos[i].baseColumnName = GetDescFieldStr(i, ODBC32.SQL_DESC.BASE_COLUMN_NAME, ODBC32.HANDLER.IGNORE); } } if ((metaInfos[i].baseTableName != null) && !(qrytables.Contains(metaInfos[i].baseTableName))) { qrytables.Add(metaInfos[i].baseTableName); } } // If primary key or autoincrement, then must also be unique if (metaInfos[i].isKeyColumn || metaInfos[i].isAutoIncrement) { if (nullable == ODBC32.SQL_NULLABILITY.UNKNOWN) metaInfos[i].isNullable = false; // We can safely assume these are not nullable } } // now loop over the hidden columns (if any) // SSS_WARNINGS_OFF if (!Connection.ProviderInfo.NoSqlCASSColumnKey) { for (int i = count; i < count + _hiddenColumns; i++) { isKeyColumn = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_KEY, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE) == 1; if (isKeyColumn) { isHidden = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_HIDDEN, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE) == 1; if (isHidden) { for (int j = 0; j < count; j++) { metaInfos[j].isKeyColumn = false; // downgrade keycolumn metaInfos[j].isUnique = false; // downgrade uniquecolumn } } } } } // SSS_WARNINGS_ON // Blow away the previous metadata _metadata = metaInfos; // If key info is requested, then we have to make a few more calls to get the // special columns. This may not succeed for all drivers, so ignore errors and // fill in as much as possible. if (IsCommandBehavior(CommandBehavior.KeyInfo)) { if ((qrytables != null) && (qrytables.Count > 0)) { List<string>.Enumerator tablesEnum = qrytables.GetEnumerator(); QualifiedTableName qualifiedTableName = new QualifiedTableName(Connection.QuoteChar(ADP.GetSchemaTable)); while (tablesEnum.MoveNext()) { // Find the primary keys, identity and autincrement columns qualifiedTableName.Table = tablesEnum.Current; if (RetrieveKeyInfo(needkeyinfo, qualifiedTableName, false) <= 0) { RetrieveKeyInfo(needkeyinfo, qualifiedTableName, true); } } } else { // Some drivers ( < 3.x ?) do not provide base table information. In this case try to // find it by parsing the statement QualifiedTableName qualifiedTableName = new QualifiedTableName(Connection.QuoteChar(ADP.GetSchemaTable), GetTableNameFromCommandText()); if (!string.IsNullOrEmpty(qualifiedTableName.Table)) { // fxcop SetBaseTableNames(qualifiedTableName); if (RetrieveKeyInfo(needkeyinfo, qualifiedTableName, false) <= 0) { RetrieveKeyInfo(needkeyinfo, qualifiedTableName, true); } } } } } private DataTable NewSchemaTable() { DataTable schematable = new DataTable("SchemaTable"); schematable.Locale = CultureInfo.InvariantCulture; schematable.MinimumCapacity = this.FieldCount; //Schema Columns DataColumnCollection columns = schematable.Columns; columns.Add(new DataColumn("ColumnName", typeof(System.String))); columns.Add(new DataColumn("ColumnOrdinal", typeof(System.Int32))); // UInt32 columns.Add(new DataColumn("ColumnSize", typeof(System.Int32))); // UInt32 columns.Add(new DataColumn("NumericPrecision", typeof(System.Int16))); // UInt16 columns.Add(new DataColumn("NumericScale", typeof(System.Int16))); columns.Add(new DataColumn("DataType", typeof(System.Object))); columns.Add(new DataColumn("ProviderType", typeof(System.Int32))); columns.Add(new DataColumn("IsLong", typeof(System.Boolean))); columns.Add(new DataColumn("AllowDBNull", typeof(System.Boolean))); columns.Add(new DataColumn("IsReadOnly", typeof(System.Boolean))); columns.Add(new DataColumn("IsRowVersion", typeof(System.Boolean))); columns.Add(new DataColumn("IsUnique", typeof(System.Boolean))); columns.Add(new DataColumn("IsKey", typeof(System.Boolean))); columns.Add(new DataColumn("IsAutoIncrement", typeof(System.Boolean))); columns.Add(new DataColumn("BaseSchemaName", typeof(System.String))); columns.Add(new DataColumn("BaseCatalogName", typeof(System.String))); columns.Add(new DataColumn("BaseTableName", typeof(System.String))); columns.Add(new DataColumn("BaseColumnName", typeof(System.String))); // MDAC Bug 79231 foreach (DataColumn column in columns) { column.ReadOnly = true; } return schematable; } // The default values are already defined in DbSchemaRows (see DbSchemaRows.cs) so there is no need to set any default value // public override DataTable GetSchemaTable() { if (IsClosed) { // MDAC 68331 throw ADP.DataReaderClosed("GetSchemaTable"); // can't use closed connection } if (_noMoreResults) { return null; // no more results } if (null != _schemaTable) { return _schemaTable; // return cached schematable } //Delegate, to have the base class setup the structure DataTable schematable = NewSchemaTable(); if (FieldCount == 0) { return schematable; } if (_metadata == null) { BuildMetaDataInfo(); } DataColumn columnName = schematable.Columns["ColumnName"]; DataColumn columnOrdinal = schematable.Columns["ColumnOrdinal"]; DataColumn columnSize = schematable.Columns["ColumnSize"]; DataColumn numericPrecision = schematable.Columns["NumericPrecision"]; DataColumn numericScale = schematable.Columns["NumericScale"]; DataColumn dataType = schematable.Columns["DataType"]; DataColumn providerType = schematable.Columns["ProviderType"]; DataColumn isLong = schematable.Columns["IsLong"]; DataColumn allowDBNull = schematable.Columns["AllowDBNull"]; DataColumn isReadOnly = schematable.Columns["IsReadOnly"]; DataColumn isRowVersion = schematable.Columns["IsRowVersion"]; DataColumn isUnique = schematable.Columns["IsUnique"]; DataColumn isKey = schematable.Columns["IsKey"]; DataColumn isAutoIncrement = schematable.Columns["IsAutoIncrement"]; DataColumn baseSchemaName = schematable.Columns["BaseSchemaName"]; DataColumn baseCatalogName = schematable.Columns["BaseCatalogName"]; DataColumn baseTableName = schematable.Columns["BaseTableName"]; DataColumn baseColumnName = schematable.Columns["BaseColumnName"]; //Populate the rows (1 row for each column) int count = FieldCount; for (int i = 0; i < count; i++) { DataRow row = schematable.NewRow(); row[columnName] = GetName(i); //ColumnName row[columnOrdinal] = i; //ColumnOrdinal row[columnSize] = unchecked((int)Math.Min(Math.Max(Int32.MinValue, _metadata[i].size.ToInt64()), Int32.MaxValue)); row[numericPrecision] = (Int16)_metadata[i].precision; row[numericScale] = (Int16)_metadata[i].scale; row[dataType] = _metadata[i].typemap._type; //DataType row[providerType] = _metadata[i].typemap._odbcType; // ProviderType row[isLong] = _metadata[i].isLong; // IsLong row[allowDBNull] = _metadata[i].isNullable; //AllowDBNull row[isReadOnly] = _metadata[i].isReadOnly; // IsReadOnly row[isRowVersion] = _metadata[i].isRowVersion; //IsRowVersion row[isUnique] = _metadata[i].isUnique; //IsUnique row[isKey] = _metadata[i].isKeyColumn; // IsKey row[isAutoIncrement] = _metadata[i].isAutoIncrement; //IsAutoIncrement //BaseSchemaName row[baseSchemaName] = _metadata[i].baseSchemaName; //BaseCatalogName row[baseCatalogName] = _metadata[i].baseCatalogName; //BaseTableName row[baseTableName] = _metadata[i].baseTableName; //BaseColumnName row[baseColumnName] = _metadata[i].baseColumnName; schematable.Rows.Add(row); row.AcceptChanges(); } _schemaTable = schematable; return schematable; } internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTableName, bool quoted) { ODBC32.RetCode retcode; string columnname; int ordinal; int keyColumns = 0; IntPtr cbActual = IntPtr.Zero; if (IsClosed || (_cmdWrapper == null)) { return 0; // Can't do anything without a second handle } _cmdWrapper.CreateKeyInfoStatementHandle(); CNativeBuffer buffer = Buffer; bool mustRelease = false; Debug.Assert(buffer.Length >= 264, "Native buffer to small (_buffer.Length < 264)"); RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.DangerousAddRef(ref mustRelease); if (needkeyinfo) { if (!Connection.ProviderInfo.NoSqlPrimaryKeys) { // Get the primary keys retcode = KeyInfoStatementHandle.PrimaryKeys( qualifiedTableName.Catalog, qualifiedTableName.Schema, qualifiedTableName.GetTable(quoted)); if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) { bool noUniqueKey = false; // We are only interested in column name buffer.WriteInt16(0, 0); retcode = KeyInfoStatementHandle.BindColumn2( (short)(ODBC32.SQL_PRIMARYKEYS.COLUMNNAME), // Column Number ODBC32.SQL_C.WCHAR, buffer.PtrOffset(0, 256), (IntPtr)256, buffer.PtrOffset(256, IntPtr.Size).Handle); while (ODBC32.RetCode.SUCCESS == (retcode = KeyInfoStatementHandle.Fetch())) { cbActual = buffer.ReadIntPtr(256); columnname = buffer.PtrToStringUni(0, (int)cbActual / 2/*cch*/); ordinal = this.GetOrdinalFromBaseColName(columnname); if (ordinal != -1) { keyColumns++; _metadata[ordinal].isKeyColumn = true; _metadata[ordinal].isUnique = true; _metadata[ordinal].isNullable = false; _metadata[ordinal].baseTableName = qualifiedTableName.Table; if (_metadata[ordinal].baseColumnName == null) { _metadata[ordinal].baseColumnName = columnname; } } else { noUniqueKey = true; break; // no need to go over the remaining columns anymore } } // // if we got keyinfo from the column we dont even get to here! // // reset isUnique flag if the key(s) are not unique // if (noUniqueKey) { foreach (MetaData metadata in _metadata) { metadata.isKeyColumn = false; } } // Unbind the column retcode = KeyInfoStatementHandle.BindColumn3( (short)(ODBC32.SQL_PRIMARYKEYS.COLUMNNAME), // SQLUSMALLINT ColumnNumber ODBC32.SQL_C.WCHAR, // SQLSMALLINT TargetType buffer.DangerousGetHandle()); // SQLLEN * StrLen_or_Ind } else { if ("IM001" == Command.GetDiagSqlState()) { Connection.ProviderInfo.NoSqlPrimaryKeys = true; } } } if (keyColumns == 0) { // SQLPrimaryKeys did not work. Have to use the slower SQLStatistics to obtain key information KeyInfoStatementHandle.MoreResults(); keyColumns += RetrieveKeyInfoFromStatistics(qualifiedTableName, quoted); } KeyInfoStatementHandle.MoreResults(); } // Get the special columns for version retcode = KeyInfoStatementHandle.SpecialColumns(qualifiedTableName.GetTable(quoted)); if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) { // We are only interested in column name cbActual = IntPtr.Zero; buffer.WriteInt16(0, 0); retcode = KeyInfoStatementHandle.BindColumn2( (short)(ODBC32.SQL_SPECIALCOLUMNSET.COLUMN_NAME), ODBC32.SQL_C.WCHAR, buffer.PtrOffset(0, 256), (IntPtr)256, buffer.PtrOffset(256, IntPtr.Size).Handle); while (ODBC32.RetCode.SUCCESS == (retcode = KeyInfoStatementHandle.Fetch())) { cbActual = buffer.ReadIntPtr(256); columnname = buffer.PtrToStringUni(0, (int)cbActual / 2/*cch*/); ordinal = this.GetOrdinalFromBaseColName(columnname); if (ordinal != -1) { _metadata[ordinal].isRowVersion = true; if (_metadata[ordinal].baseColumnName == null) { _metadata[ordinal].baseColumnName = columnname; } } } // Unbind the column retcode = KeyInfoStatementHandle.BindColumn3( (short)(ODBC32.SQL_SPECIALCOLUMNSET.COLUMN_NAME), ODBC32.SQL_C.WCHAR, buffer.DangerousGetHandle()); retcode = KeyInfoStatementHandle.MoreResults(); } else { // i've seen "DIAG [HY000] [Microsoft][ODBC SQL Server Driver]Connection is busy with results for another hstmt (0) " // how did we get here? SqlServer does not allow a second handle (Keyinfostmt) anyway... // /* string msg = "Unexpected failure of SQLSpecialColumns. Code = " + Command.GetDiagSqlState(); Debug.Assert (false, msg); */ } } finally { if (mustRelease) { buffer.DangerousRelease(); } } return keyColumns; } // Uses SQLStatistics to retrieve key information for a table private int RetrieveKeyInfoFromStatistics(QualifiedTableName qualifiedTableName, bool quoted) { ODBC32.RetCode retcode; String columnname = String.Empty; String indexname = String.Empty; String currentindexname = String.Empty; int[] indexcolumnordinals = new int[16]; int[] pkcolumnordinals = new int[16]; int npkcols = 0; int ncols = 0; // No of cols in the index bool partialcolumnset = false; int ordinal; int indexordinal; IntPtr cbIndexLen = IntPtr.Zero; IntPtr cbColnameLen = IntPtr.Zero; int keyColumns = 0; // devnote: this test is already done by calling method ... // if (IsClosed) return; // protect against dead connection // MDAC Bug 75928 - SQLStatisticsW damages the string passed in // To protect the tablename we need to pass in a copy of that string String tablename1 = String.Copy(qualifiedTableName.GetTable(quoted)); // Select only unique indexes retcode = KeyInfoStatementHandle.Statistics(tablename1); if (retcode != ODBC32.RetCode.SUCCESS) { // We give up at this point return 0; } CNativeBuffer buffer = Buffer; bool mustRelease = false; Debug.Assert(buffer.Length >= 544, "Native buffer to small (_buffer.Length < 544)"); RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.DangerousAddRef(ref mustRelease); const int colnameBufOffset = 0; const int indexBufOffset = 256; const int ordinalBufOffset = 512; const int colnameActualOffset = 520; const int indexActualOffset = 528; const int ordinalActualOffset = 536; HandleRef colnamebuf = buffer.PtrOffset(colnameBufOffset, 256); HandleRef indexbuf = buffer.PtrOffset(indexBufOffset, 256); HandleRef ordinalbuf = buffer.PtrOffset(ordinalBufOffset, 4); IntPtr colnameActual = buffer.PtrOffset(colnameActualOffset, IntPtr.Size).Handle; IntPtr indexActual = buffer.PtrOffset(indexActualOffset, IntPtr.Size).Handle; IntPtr ordinalActual = buffer.PtrOffset(ordinalActualOffset, IntPtr.Size).Handle; //We are interested in index name, column name, and ordinal buffer.WriteInt16(indexBufOffset, 0); retcode = KeyInfoStatementHandle.BindColumn2( (short)(ODBC32.SQL_STATISTICS.INDEXNAME), ODBC32.SQL_C.WCHAR, indexbuf, (IntPtr)256, indexActual); retcode = KeyInfoStatementHandle.BindColumn2( (short)(ODBC32.SQL_STATISTICS.ORDINAL_POSITION), ODBC32.SQL_C.SSHORT, ordinalbuf, (IntPtr)4, ordinalActual); buffer.WriteInt16(ordinalBufOffset, 0); retcode = KeyInfoStatementHandle.BindColumn2( (short)(ODBC32.SQL_STATISTICS.COLUMN_NAME), ODBC32.SQL_C.WCHAR, colnamebuf, (IntPtr)256, colnameActual); // Find the best unique index on the table, use the ones whose columns are // completely covered by the query. while (ODBC32.RetCode.SUCCESS == (retcode = KeyInfoStatementHandle.Fetch())) { cbColnameLen = buffer.ReadIntPtr(colnameActualOffset); cbIndexLen = buffer.ReadIntPtr(indexActualOffset); // If indexname is not returned, skip this row if (0 == buffer.ReadInt16(indexBufOffset)) continue; // Not an index row, get next row. columnname = buffer.PtrToStringUni(colnameBufOffset, (int)cbColnameLen / 2/*cch*/); indexname = buffer.PtrToStringUni(indexBufOffset, (int)cbIndexLen / 2/*cch*/); ordinal = (int)buffer.ReadInt16(ordinalBufOffset); if (SameIndexColumn(currentindexname, indexname, ordinal, ncols)) { // We are still working on the same index if (partialcolumnset) continue; // We don't have all the keys for this index, so we can't use it ordinal = this.GetOrdinalFromBaseColName(columnname, qualifiedTableName.Table); if (ordinal == -1) { partialcolumnset = true; } else { // Add the column to the index column set if (ncols < 16) indexcolumnordinals[ncols++] = ordinal; else // Can't deal with indexes > 16 columns partialcolumnset = true; } } else { // We got a new index, save the previous index information if (!partialcolumnset && (ncols != 0)) { // Choose the unique index with least columns as primary key if ((npkcols == 0) || (npkcols > ncols)) { npkcols = ncols; for (int i = 0; i < ncols; i++) pkcolumnordinals[i] = indexcolumnordinals[i]; } } // Reset the parameters for a new index ncols = 0; currentindexname = indexname; partialcolumnset = false; // Add this column to index ordinal = this.GetOrdinalFromBaseColName(columnname, qualifiedTableName.Table); if (ordinal == -1) { partialcolumnset = true; } else { // Add the column to the index column set indexcolumnordinals[ncols++] = ordinal; } } // Go on to the next column } // Do we have an index? if (!partialcolumnset && (ncols != 0)) { // Choose the unique index with least columns as primary key if ((npkcols == 0) || (npkcols > ncols)) { npkcols = ncols; for (int i = 0; i < ncols; i++) pkcolumnordinals[i] = indexcolumnordinals[i]; } } // Mark the chosen index as primary key if (npkcols != 0) { for (int i = 0; i < npkcols; i++) { indexordinal = pkcolumnordinals[i]; keyColumns++; _metadata[indexordinal].isKeyColumn = true; // should we set isNullable = false? // This makes the QuikTest against Jet fail // // test test test - we don't know if this is nulalble or not so why do we want to set it to a value? _metadata[indexordinal].isNullable = false; _metadata[indexordinal].isUnique = true; if (_metadata[indexordinal].baseTableName == null) { _metadata[indexordinal].baseTableName = qualifiedTableName.Table; } if (_metadata[indexordinal].baseColumnName == null) { _metadata[indexordinal].baseColumnName = columnname; } } } // Unbind the columns _cmdWrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.UNBIND); } finally { if (mustRelease) { buffer.DangerousRelease(); } } return keyColumns; } internal bool SameIndexColumn(String currentindexname, String indexname, int ordinal, int ncols) { if (string.IsNullOrEmpty(currentindexname)) { return false; } if ((currentindexname == indexname) && (ordinal == ncols + 1)) return true; return false; } internal int GetOrdinalFromBaseColName(String columnname) { return GetOrdinalFromBaseColName(columnname, null); } internal int GetOrdinalFromBaseColName(String columnname, String tablename) { if (string.IsNullOrEmpty(columnname)) { return -1; } if (_metadata != null) { int count = FieldCount; for (int i = 0; i < count; i++) { if ((_metadata[i].baseColumnName != null) && (columnname == _metadata[i].baseColumnName)) { if (!string.IsNullOrEmpty(tablename)) { if (tablename == _metadata[i].baseTableName) { return i; } // end if } // end if else { return i; } // end else } } } // We can't find it in base column names, try regular colnames return this.IndexOf(columnname); } // We try parsing the SQL statement to get the table name as a last resort when // the driver doesn't return this information back to us. // // we can't handle multiple tablenames (JOIN) // only the first tablename will be returned internal string GetTableNameFromCommandText() { if (_command == null) { return null; } String localcmdtext = _cmdText; if (string.IsNullOrEmpty(localcmdtext)) { // fxcop return null; } String tablename; int idx; CStringTokenizer tokenstmt = new CStringTokenizer(localcmdtext, Connection.QuoteChar(ADP.GetSchemaTable)[0], Connection.EscapeChar(ADP.GetSchemaTable)); if (tokenstmt.StartsWith("select") == true) { // select command, search for from clause idx = tokenstmt.FindTokenIndex("from"); } else { if ((tokenstmt.StartsWith("insert") == true) || (tokenstmt.StartsWith("update") == true) || (tokenstmt.StartsWith("delete") == true)) { // Get the following word idx = tokenstmt.CurrentPosition; } else idx = -1; } if (idx == -1) return null; // The next token is the table name tablename = tokenstmt.NextToken(); localcmdtext = tokenstmt.NextToken(); if ((localcmdtext.Length > 0) && (localcmdtext[0] == ',')) { return null; // can't handle multiple tables } if ((localcmdtext.Length == 2) && ((localcmdtext[0] == 'a') || (localcmdtext[0] == 'A')) && ((localcmdtext[1] == 's') || (localcmdtext[1] == 'S'))) { // aliased table, skip the alias name localcmdtext = tokenstmt.NextToken(); localcmdtext = tokenstmt.NextToken(); if ((localcmdtext.Length > 0) && (localcmdtext[0] == ',')) { return null; // Multiple tables } } return tablename; } internal void SetBaseTableNames(QualifiedTableName qualifiedTableName) { int count = FieldCount; for (int i = 0; i < count; i++) { if (_metadata[i].baseTableName == null) { _metadata[i].baseTableName = qualifiedTableName.Table; _metadata[i].baseSchemaName = qualifiedTableName.Schema; _metadata[i].baseCatalogName = qualifiedTableName.Catalog; } } return; } internal sealed class QualifiedTableName { private string _catalogName; private string _schemaName; private string _tableName; private string _quotedTableName; private string _quoteChar; internal string Catalog { get { return _catalogName; } } internal string Schema { get { return _schemaName; } } internal string Table { get { return _tableName; } set { _quotedTableName = value; _tableName = UnQuote(value); } } internal string QuotedTable { get { return _quotedTableName; } } internal string GetTable(bool flag) { return (flag ? QuotedTable : Table); } internal QualifiedTableName(string quoteChar) { _quoteChar = quoteChar; } internal QualifiedTableName(string quoteChar, string qualifiedname) { _quoteChar = quoteChar; string[] names = ParseProcedureName(qualifiedname, quoteChar, quoteChar); _catalogName = UnQuote(names[1]); _schemaName = UnQuote(names[2]); _quotedTableName = names[3]; _tableName = UnQuote(names[3]); } private string UnQuote(string str) { if ((str != null) && (str.Length > 0)) { char quoteChar = _quoteChar[0]; if (str[0] == quoteChar) { Debug.Assert(str.Length > 1, "Illegal string, only one char that is a quote"); Debug.Assert(str[str.Length - 1] == quoteChar, "Missing quote at end of string that begins with quote"); if (str.Length > 1 && str[str.Length - 1] == quoteChar) { str = str.Substring(1, str.Length - 2); } } } return str; } // Note: copy-and pasted from internal DbCommandBuilder implementation // Note: Per definition (ODBC reference) the CatalogSeparator comes before and after the // catalog name, the SchemaSeparator is undefined. Does it come between Schema and Table? internal static string[] ParseProcedureName(string name, string quotePrefix, string quoteSuffix) { // Procedure may consist of up to four parts: // 0) Server // 1) Catalog // 2) Schema // 3) ProcedureName // // Parse the string into four parts, allowing the last part to contain '.'s. // If less than four period delimited parts, use the parts from procedure backwards. // const string Separator = "."; string[] qualifiers = new string[4]; if (!string.IsNullOrEmpty(name)) { bool useQuotes = !string.IsNullOrEmpty(quotePrefix) && !string.IsNullOrEmpty(quoteSuffix); int currentPos = 0, parts; for (parts = 0; (parts < qualifiers.Length) && (currentPos < name.Length); ++parts) { int startPos = currentPos; // does the part begin with a quotePrefix? if (useQuotes && (name.IndexOf(quotePrefix, currentPos, quotePrefix.Length, StringComparison.Ordinal) == currentPos)) { currentPos += quotePrefix.Length; // move past the quotePrefix // search for the quoteSuffix (or end of string) while (currentPos < name.Length) { currentPos = name.IndexOf(quoteSuffix, currentPos, StringComparison.Ordinal); if (currentPos < 0) { // error condition, no quoteSuffix currentPos = name.Length; break; } else { currentPos += quoteSuffix.Length; // move past the quoteSuffix // is this a double quoteSuffix? if ((currentPos < name.Length) && (name.IndexOf(quoteSuffix, currentPos, quoteSuffix.Length, StringComparison.Ordinal) == currentPos)) { // a second quoteSuffix, continue search for terminating quoteSuffix currentPos += quoteSuffix.Length; // move past the second quoteSuffix } else { // found the terminating quoteSuffix break; } } } } // search for separator (either no quotePrefix or already past quoteSuffix) if (currentPos < name.Length) { currentPos = name.IndexOf(Separator, currentPos, StringComparison.Ordinal); if ((currentPos < 0) || (parts == qualifiers.Length - 1)) { // last part that can be found currentPos = name.Length; } } qualifiers[parts] = name.Substring(startPos, currentPos - startPos); currentPos += Separator.Length; } // allign the qualifiers if we had less than MaxQualifiers for (int j = qualifiers.Length - 1; 0 <= j; --j) { qualifiers[j] = ((0 < parts) ? qualifiers[--parts] : null); } } return qualifiers; } } private sealed class MetaData { internal int ordinal; internal TypeMap typemap; internal SQLLEN size; internal byte precision; internal byte scale; internal bool isAutoIncrement; internal bool isUnique; internal bool isReadOnly; internal bool isNullable; internal bool isRowVersion; internal bool isLong; internal bool isKeyColumn; internal string baseSchemaName; internal string baseCatalogName; internal string baseTableName; internal string baseColumnName; } } }
42.164894
198
0.486021
[ "MIT" ]
lukas-lansky/corefx
src/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs
126,832
C#
// Copyright (c) Teroneko. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace Teronis.Collections.Generic { public class KeyValuePairEnumeratorWithPairAsCovariant<KeyType, ValueType> : KeyValuePairEnumeratorWithConversionBase<ICovariantKeyValuePair<KeyType, ValueType>, KeyType, ValueType> { public KeyValuePairEnumeratorWithPairAsCovariant(IEnumerator<KeyValuePair<KeyType, ValueType>> enumerator) : base(enumerator) { } protected override ICovariantKeyValuePair<KeyType, ValueType> CreateCurrent(KeyValuePair<KeyType, ValueType> currentPair) => new CovariantKeyValuePair<KeyType, ValueType>(currentPair.Key, currentPair.Value); } }
44.055556
185
0.770492
[ "MIT" ]
teroneko/Teronis.DotNet
src/NetStandard/Collections/Collections/src/Generic/KeyValuePairEnumeratorWithPairAsCovariant.cs
795
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace LoanMelliBank.Migrations { public partial class updatepeople : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "DateOfBirth", table: "People"); migrationBuilder.DropColumn( name: "FatherName", table: "People"); migrationBuilder.DropColumn( name: "FirstName", table: "People"); migrationBuilder.DropColumn( name: "IdentityCode", table: "People"); migrationBuilder.DropColumn( name: "Job", table: "People"); migrationBuilder.DropColumn( name: "LastName", table: "People"); migrationBuilder.DropColumn( name: "Mobile", table: "People"); migrationBuilder.CreateTable( name: "LegalPerson", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), PersonId = table.Column<int>(nullable: false), Name = table.Column<string>(nullable: true), RegistrationCode = table.Column<string>(nullable: true), RegistrationCity = table.Column<string>(nullable: true), RegistratedOn = table.Column<DateTime>(nullable: true), Coding = table.Column<string>(nullable: true), ExpirationDate = table.Column<string>(nullable: true), RegisteredCapital = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_LegalPerson", x => x.Id); table.ForeignKey( name: "FK_LegalPerson_People_PersonId", column: x => x.PersonId, principalTable: "People", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "NaturalPerson", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), PersonId = table.Column<int>(nullable: false), FirstName = table.Column<string>(nullable: true), LastName = table.Column<string>(nullable: true), FatherName = table.Column<string>(nullable: true), DateOfBirth = table.Column<DateTime>(nullable: false), BirthCity = table.Column<string>(nullable: true), Mobile = table.Column<string>(nullable: true), Job = table.Column<string>(nullable: true), IdCardCode = table.Column<string>(nullable: true), IdCardSerialNumber = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_NaturalPerson", x => x.Id); table.ForeignKey( name: "FK_NaturalPerson_People_PersonId", column: x => x.PersonId, principalTable: "People", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "AuthorizedSignatorie", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), PersonId = table.Column<int>(nullable: false), LegalPersonId = table.Column<int>(nullable: false), ExpirationDate = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AuthorizedSignatorie", x => x.Id); table.ForeignKey( name: "FK_AuthorizedSignatorie_LegalPerson_LegalPersonId", column: x => x.LegalPersonId, principalTable: "LegalPerson", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_AuthorizedSignatorie_People_PersonId", column: x => x.PersonId, principalTable: "People", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "BoardOfDirector", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), PersonId = table.Column<int>(nullable: false), LegalPersonId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_BoardOfDirector", x => x.Id); table.ForeignKey( name: "FK_BoardOfDirector_LegalPerson_LegalPersonId", column: x => x.LegalPersonId, principalTable: "LegalPerson", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_BoardOfDirector_People_PersonId", column: x => x.PersonId, principalTable: "People", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_AuthorizedSignatorie_LegalPersonId", table: "AuthorizedSignatorie", column: "LegalPersonId"); migrationBuilder.CreateIndex( name: "IX_AuthorizedSignatorie_PersonId", table: "AuthorizedSignatorie", column: "PersonId"); migrationBuilder.CreateIndex( name: "IX_BoardOfDirector_LegalPersonId", table: "BoardOfDirector", column: "LegalPersonId"); migrationBuilder.CreateIndex( name: "IX_BoardOfDirector_PersonId", table: "BoardOfDirector", column: "PersonId"); migrationBuilder.CreateIndex( name: "IX_LegalPerson_PersonId", table: "LegalPerson", column: "PersonId", unique: true); migrationBuilder.CreateIndex( name: "IX_NaturalPerson_PersonId", table: "NaturalPerson", column: "PersonId", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AuthorizedSignatorie"); migrationBuilder.DropTable( name: "BoardOfDirector"); migrationBuilder.DropTable( name: "NaturalPerson"); migrationBuilder.DropTable( name: "LegalPerson"); migrationBuilder.AddColumn<DateTime>( name: "DateOfBirth", table: "People", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); migrationBuilder.AddColumn<string>( name: "FatherName", table: "People", nullable: true); migrationBuilder.AddColumn<string>( name: "FirstName", table: "People", nullable: true); migrationBuilder.AddColumn<string>( name: "IdentityCode", table: "People", nullable: true); migrationBuilder.AddColumn<string>( name: "Job", table: "People", nullable: true); migrationBuilder.AddColumn<string>( name: "LastName", table: "People", nullable: true); migrationBuilder.AddColumn<string>( name: "Mobile", table: "People", nullable: true); } } }
40.255411
122
0.497365
[ "MIT" ]
EsmaeelZekaee/LoanMelliBank
aspnet-core/src/LoanMelliBank.EntityFrameworkCore/Migrations/13980115193649_update-people.cs
9,301
C#
using System.Collections.Generic; namespace Pds.Contracts.Data.Api.Client.Models { /// <summary> /// ApiResponse. /// </summary> /// <typeparam name="T">Response data type.</typeparam> public class ContractReminders { /// <summary> /// Gets or sets contract reminders. /// </summary> public IEnumerable<ContractReminderItem> Contracts { get; set; } /// <summary> /// Gets or sets paging. /// </summary> public Paging Paging { get; set; } } }
25.52381
72
0.574627
[ "MIT" ]
SkillsFundingAgency/pds-contracts-data-api-client
Pds.Contracts.Data.Api.Client/Models/ContractReminders.cs
538
C#
using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Volo.Abp; using Volo.Abp.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore.Sqlite; using Volo.Abp.Modularity; namespace TelerikBlazorSample.EntityFrameworkCore; [DependsOn( typeof(TelerikBlazorSampleEntityFrameworkCoreModule), typeof(TelerikBlazorSampleTestBaseModule), typeof(AbpEntityFrameworkCoreSqliteModule) )] public class TelerikBlazorSampleEntityFrameworkCoreTestModule : AbpModule { private SqliteConnection _sqliteConnection; public override void ConfigureServices(ServiceConfigurationContext context) { ConfigureInMemorySqlite(context.Services); } private void ConfigureInMemorySqlite(IServiceCollection services) { _sqliteConnection = CreateDatabaseAndGetConnection(); services.Configure<AbpDbContextOptions>(options => { options.Configure(context => { context.DbContextOptions.UseSqlite(_sqliteConnection); }); }); } public override void OnApplicationShutdown(ApplicationShutdownContext context) { _sqliteConnection.Dispose(); } private static SqliteConnection CreateDatabaseAndGetConnection() { var connection = new SqliteConnection("Data Source=:memory:"); connection.Open(); var options = new DbContextOptionsBuilder<TelerikBlazorSampleDbContext>() .UseSqlite(connection) .Options; using (var context = new TelerikBlazorSampleDbContext(options)) { context.GetService<IRelationalDatabaseCreator>().CreateTables(); } return connection; } }
29.806452
82
0.72619
[ "MIT" ]
271943794/abp-samples
TelerikBlazorSample/test/TelerikBlazorSample.EntityFrameworkCore.Tests/EntityFrameworkCore/TelerikBlazorSampleEntityFrameworkCoreTestModule.cs
1,850
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // add using Microsoft.AspNet.Identity; using ZLib.DB; namespace ZIdentitySqlServer { /// <summary> /// Class that implements the key ASP.NET Identity role store iterfaces /// </summary> public class ZRoleStore<TRole> : IQueryableRoleStore<TRole> where TRole : ZRole { private readonly ZRoleTable roleTable; public ZSqlClient MyDB1 { get; private set; } public IQueryable<TRole> Roles { get { throw new NotImplementedException(); } } //public ZRoleStore(string sConnectionString) //{ // new ZRoleStore<TRole>(new ZIdentityDB(sConnectionString)); //} public ZRoleStore(ZSqlClient db1) { MyDB1 = db1; roleTable = new ZRoleTable(db1); } public Task CreateAsync(TRole role) { if (role == null) { throw new ArgumentNullException("role"); } roleTable.Insert(role); return Task.FromResult<object>(null); } public Task DeleteAsync(TRole role) { if (role == null) { throw new ArgumentNullException("role"); } roleTable.Delete(role.Id); return Task.FromResult<Object>(null); } public Task<TRole> FindByIdAsync(string roleId) { TRole result = roleTable.GetRoleById(roleId) as TRole; return Task.FromResult<TRole>(result); } public Task<TRole> FindByNameAsync(string roleName) { TRole result = roleTable.GetRoleByName(roleName) as TRole; return Task.FromResult<TRole>(result); } public Task UpdateAsync(TRole role) { if (role == null) { throw new ArgumentNullException("role"); } roleTable.Update(role); return Task.FromResult<Object>(null); } public void Dispose() { if (MyDB1 != null) { MyDB1.Dispose(); MyDB1 = null; } } } }
23.237624
75
0.525352
[ "MIT" ]
github-honda/VS2019Practice
WebIdentity/ZIdentitySqlServer/ZRoleStore.cs
2,349
C#
// *********************************************************************** // Copyright (c) Charlie Poole and TestCentric Engine contributors. // Licensed under the MIT License. See LICENSE.txt in root directory. // *********************************************************************** using System; using TestCentric.Engine.Extensibility; namespace TestCentric.Engine { /// <summary> /// Enumeration representing the status of a service /// </summary> public enum ServiceStatus { /// <summary>Service was never started or has been stopped</summary> Stopped, /// <summary>Started successfully</summary> Started, /// <summary>Service failed to start and is unavailable</summary> Error } /// <summary> /// The IService interface is implemented by all Services. Although it /// is extensible, it does not reside in the Extensibility namespace /// because it is so widely used by the engine. /// </summary> [TypeExtensionPoint( Description="Provides a service within the engine and possibly externally as well.")] public interface IService { /// <summary> /// The ServiceContext /// </summary> IServiceLocator ServiceContext { get; set; } /// <summary> /// Gets the ServiceStatus of this service /// </summary> ServiceStatus Status { get; } /// <summary> /// Initialize the Service /// </summary> void StartService(); /// <summary> /// Do any cleanup needed before terminating the service /// </summary> void StopService(); } }
31.055556
93
0.560525
[ "MIT" ]
jurczakk/testcentric-gui
src/TestEngine/testcentric.engine.api/IService.cs
1,677
C#
/* * THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text.Json.Serialization; namespace Plotly.Blazor.Traces.ScatterLib.MarkerLib { /// <summary> /// The Gradient class. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")] [JsonConverter(typeof(PlotlyConverter))] [Serializable] public class Gradient : IEquatable<Gradient> { /// <summary> /// Sets the type of gradient used to fill the markers /// </summary> [JsonPropertyName(@"type")] public Plotly.Blazor.Traces.ScatterLib.MarkerLib.GradientLib.TypeEnum? Type { get; set;} /// <summary> /// Sets the type of gradient used to fill the markers /// </summary> [JsonPropertyName(@"type")] [Array] public IList<Plotly.Blazor.Traces.ScatterLib.MarkerLib.GradientLib.TypeEnum?> TypeArray { get; set;} /// <summary> /// Sets the final color of the gradient fill: the center color for radial, /// the right for horizontal, or the bottom for vertical. /// </summary> [JsonPropertyName(@"color")] public object Color { get; set;} /// <summary> /// Sets the final color of the gradient fill: the center color for radial, /// the right for horizontal, or the bottom for vertical. /// </summary> [JsonPropertyName(@"color")] [Array] public IList<object> ColorArray { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for type . /// </summary> [JsonPropertyName(@"typesrc")] public string TypeSrc { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for color . /// </summary> [JsonPropertyName(@"colorsrc")] public string ColorSrc { get; set;} /// <inheritdoc /> public override bool Equals(object obj) { if (!(obj is Gradient other)) return false; return ReferenceEquals(this, obj) || Equals(other); } /// <inheritdoc /> public bool Equals([AllowNull] Gradient other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; return ( Type == other.Type || Type != null && Type.Equals(other.Type) ) && ( Equals(TypeArray, other.TypeArray) || TypeArray != null && other.TypeArray != null && TypeArray.SequenceEqual(other.TypeArray) ) && ( Color == other.Color || Color != null && Color.Equals(other.Color) ) && ( Equals(ColorArray, other.ColorArray) || ColorArray != null && other.ColorArray != null && ColorArray.SequenceEqual(other.ColorArray) ) && ( TypeSrc == other.TypeSrc || TypeSrc != null && TypeSrc.Equals(other.TypeSrc) ) && ( ColorSrc == other.ColorSrc || ColorSrc != null && ColorSrc.Equals(other.ColorSrc) ); } /// <inheritdoc /> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; if (Type != null) hashCode = hashCode * 59 + Type.GetHashCode(); if (TypeArray != null) hashCode = hashCode * 59 + TypeArray.GetHashCode(); if (Color != null) hashCode = hashCode * 59 + Color.GetHashCode(); if (ColorArray != null) hashCode = hashCode * 59 + ColorArray.GetHashCode(); if (TypeSrc != null) hashCode = hashCode * 59 + TypeSrc.GetHashCode(); if (ColorSrc != null) hashCode = hashCode * 59 + ColorSrc.GetHashCode(); return hashCode; } } /// <summary> /// Checks for equality of the left Gradient and the right Gradient. /// </summary> /// <param name="left">Left Gradient.</param> /// <param name="right">Right Gradient.</param> /// <returns>Boolean</returns> public static bool operator == (Gradient left, Gradient right) { return Equals(left, right); } /// <summary> /// Checks for inequality of the left Gradient and the right Gradient. /// </summary> /// <param name="left">Left Gradient.</param> /// <param name="right">Right Gradient.</param> /// <returns>Boolean</returns> public static bool operator != (Gradient left, Gradient right) { return !Equals(left, right); } /// <summary> /// Gets a deep copy of this instance. /// </summary> /// <returns>Gradient</returns> public Gradient DeepClone() { using var ms = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(ms, this); ms.Position = 0; return (Gradient) formatter.Deserialize(ms); } } }
35.552795
109
0.519217
[ "MIT" ]
HansenBerlin/PlanspielWebapp
Plotly.Blazor/Traces/ScatterLib/MarkerLib/Gradient.cs
5,724
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using System.Security.Cryptography; internal static partial class Interop { internal static partial class libcrypto { // Initialization of libcrypto threading support is done in a static constructor. // This enables a project simply to include this file, and any usage of any of // the libcrypto functions will trigger initialization of the threading support. static libcrypto() { if (Interop.libcoreclr.EnsureOpenSslInitialized() != 0) { // Ideally this would be a CryptographicException, but we use // OpenSSL in libraries lower than System.Security.Cryptography. // It's not a big deal, though: this will already be wrapped in a // TypeLoadException, and this failing means something is very // wrong with the system's configuration and any code using // these libraries will be unable to operate correctly. throw new InvalidOperationException(); } // Load the SHA-2 hash algorithms, and anything else not in the default // support set. OPENSSL_add_all_algorithms_conf(); // Ensure that the error message table is loaded. ERR_load_crypto_strings(); } [DllImport(Libraries.LibCrypto)] private static extern void OPENSSL_add_all_algorithms_conf(); } }
41.125
101
0.653495
[ "MIT" ]
bpschoch/corefx
src/Common/src/Interop/Unix/libcrypto/Interop.Initialization.cs
1,645
C#
namespace NServiceBus.Distributor.MSMQ.Profiles { using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Hosting.Profiles; internal class DistributorProfileHandler : IHandleProfile<MSMQDistributor>, IWantTheListOfActiveProfiles { public void ProfileActivated() { if (ActiveProfiles.Contains(typeof(MSMQWorker))) { throw new ConfigurationErrorsException("Distributor profile and Worker profile should not coexist."); } Configure.Instance.RunMSMQDistributor(false); } public IEnumerable<Type> ActiveProfiles { get; set; } } }
31.434783
118
0.650069
[ "Apache-2.0", "MIT" ]
abombss/NServiceBus
src/NServiceBus.Distributor.MSMQ/Profiles/DistributorProfileHandler.cs
703
C#
// ------------------------------------------------------------------------ // ======================================================================== // THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR // ======================================================================== // Template: PageCS.tt using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Net; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Entities=WPAppStudio.Entities; using Ioc=WPAppStudio.Ioc; using IServices=WPAppStudio.Services.Interfaces; using IViewModels=WPAppStudio.ViewModel.Interfaces; using Localization=WPAppStudio.Localization; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using MyToolkit.Paging; using Repositories=WPAppStudio.Repositories; using WPAppStudio; namespace WPAppStudio.View { /// <summary> /// Phone application page for PhotoAlbum_Detail. /// </summary> [CompilerGenerated] [GeneratedCode("Radarc", "4.0")] public partial class PhotoAlbum_Detail : PhoneApplicationPage { /// <summary> /// Initializes the phone application page for PhotoAlbum_Detail and all its components. /// </summary> public PhotoAlbum_Detail() { InitializeComponent(); if (Resources.Contains("PanoramaPhotoAlbum_Detail0AppBar")) PhonePage.SetApplicationBar(this, Resources["PanoramaPhotoAlbum_Detail0AppBar"] as BindableApplicationBar); } private void panoramaPhotoAlbum_Detail_SelectionChanged(object sender, SelectionChangedEventArgs e) { InitializeAppBarpanoramaPhotoAlbum_Detail(PanoramaPhotoAlbum_Detail.SelectedItem as PanoramaItem); } private void InitializeAppBarpanoramaPhotoAlbum_Detail(PanoramaItem panoramaItem) { if (Resources.Contains(panoramaItem.Name + "AppBar")) { PhonePage.SetApplicationBar(this, Resources[panoramaItem.Name + "AppBar"] as BindableApplicationBar); ApplicationBar.IsVisible = true; } else if(ApplicationBar != null) ApplicationBar.IsVisible = false; } /// <summary> /// Called when the page becomes the active page. /// </summary> /// <param name="e">Contains information about the navigation done.</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); string currentId; if (NavigationContext.QueryString.TryGetValue("currentID", out currentId)) { var dataSource = new Ioc.Container().Resolve<Repositories.IPhotoAlbum_PhotoAlbumCollection>(); AddHomeAppBarButton(); var pinnedItem = (await dataSource.GetData()).FirstOrDefault(x => IsPinnedItem(x.Title.ToString(), currentId)); if(pinnedItem==null) MessageBox.Show(Localization.AppResources.PinError); ((IViewModels.IPhotoAlbum_DetailViewModel)DataContext).CurrentPhotoAlbumCollectionSchema = pinnedItem; } } private static bool IsPinnedItem(string itemId, string currentId) { itemId = itemId.Trim(); currentId = HttpUtility.UrlDecode(currentId.Trim()); return itemId.Equals(currentId, StringComparison.InvariantCultureIgnoreCase); } private void AddHomeAppBarButton() { if (ApplicationBar.Buttons.Count >= 4 || ApplicationBar.Buttons.Cast<ApplicationBarIconButton>().Any(button => button.Text == "Home")) return; var homeIcon = new ApplicationBarIconButton() {IconUri = new Uri("/Images/Icons/Light/Home.png", UriKind.Relative), IsEnabled = true, Text = "Home"}; homeIcon.Click += delegate { new Ioc.Container().Resolve<IServices.INavigationService>().NavigateTo<IViewModels.IWhoWeAre_TutorialViewModel>(); while (NavigationService.RemoveBackEntry() != null); }; ApplicationBar.Buttons.Add(homeIcon); } } }
39.914286
152
0.653543
[ "MIT" ]
tejaswisingh/Turboc-for-windows8-WINDOWS-PHONE-APP
WP8App/View/PhotoAlbum_Detail.xaml.cs
4,191
C#
namespace Calculator.Logic { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Evaluate { public static double EvaluateRPN(string rpn) { Stack<double> evaluatorStack = new Stack<double>(); string[] tokens = rpn.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); foreach (var token in tokens) { if (token.Equals("+")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = a + b; evaluatorStack.Push(result); } else if (token.Equals("-")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = a - b; evaluatorStack.Push(result); } else if (token.Equals("/")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = a / b; evaluatorStack.Push(result); } else if (token.Equals("*")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = a * b; evaluatorStack.Push(result); } else if (token.Equals("^")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = Math.Pow(a, b); evaluatorStack.Push(result); } else { double parsedDouble = double.Parse(token); evaluatorStack.Push(parsedDouble); } } return evaluatorStack.Pop(); } public static string EvaluateRPN_StepByStepInfix(string rpn) { StringBuilder sb = new StringBuilder(); sb.AppendLine(Parser.ConvertToInfix(rpn)); Stack<double> evaluatorStack = new Stack<double>(); string[] tokens = rpn.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < tokens.Length; i++) { if (tokens[i].Equals("+")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = a + b; sb.AppendLine($"Add {a} to {b} to get {result}"); evaluatorStack.Push(result); sb.AppendLine(Parser.ConvertToInfix(GeneateCurrentRPN(evaluatorStack, tokens.Skip(i + 1)))); } else if (tokens[i].Equals("-")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = a - b; sb.AppendLine($"Subtract {b} from {a} to get {result}"); evaluatorStack.Push(result); sb.AppendLine(Parser.ConvertToInfix(GeneateCurrentRPN(evaluatorStack, tokens.Skip(i + 1)))); } else if (tokens[i].Equals("/")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = a / b; sb.AppendLine($"Divide {a} by {b} to get {result}"); evaluatorStack.Push(result); sb.AppendLine(Parser.ConvertToInfix(GeneateCurrentRPN(evaluatorStack, tokens.Skip(i + 1)))); } else if (tokens[i].Equals("*")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = a * b; sb.AppendLine($"Multiply {a} by {b} to get {result}"); evaluatorStack.Push(result); sb.AppendLine(Parser.ConvertToInfix(GeneateCurrentRPN(evaluatorStack, tokens.Skip(i + 1)))); } else if (tokens[i].Equals("^")) { double b = evaluatorStack.Pop(); double a = evaluatorStack.Pop(); double result = Math.Pow(a, b); sb.AppendLine($"Raise {a} to the {b} Power to get {result}"); evaluatorStack.Push(result); sb.AppendLine(Parser.ConvertToInfix(GeneateCurrentRPN(evaluatorStack, tokens.Skip(i + 1)))); } else { double parsedDouble = double.Parse(tokens[i]); evaluatorStack.Push(parsedDouble); } } sb.Append(evaluatorStack.Pop()); return sb.ToString(); } public static string GeneateCurrentRPN(Stack<double> evaluatorStack, IEnumerable<string> enumerable) { StringBuilder currentRPN = new StringBuilder(); foreach (var current in evaluatorStack.Reverse()) { currentRPN.Append($"{current} "); } foreach (var current in enumerable) { currentRPN.Append($"{current} "); } return currentRPN.ToString().Trim(); } public static double EvaluateInfix(string infix) { string rpn = Parser.ConvertToRPN(infix); return EvaluateRPN(rpn); } } }
38.355263
112
0.460549
[ "MIT" ]
aceAtRocky/CSC352_Public
Calculator.Logic/Evaluate.cs
5,832
C#
using System.Collections.Generic; using System.Linq; using System.Reflection; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; namespace iSHARE.Api.Swagger { public class GenerateJwsFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { if (!context.ApiDescription.TryGetMethodInfo(out MethodInfo methodInfo)) { return; } if (methodInfo.GetCustomAttributes<SwaggerOperationForPrivateKeyAttribute>().Any()) { if (operation.Parameters == null) { operation.Parameters = new List<IParameter>(); } operation.Parameters.Add(new BodyParameter { In = "body", Name = "RSA private key", Description = "PEM-format RSA private key that will sign the JWS assertion. The key is discarded once the operation has completed. MUST NOT be encrypted. The body of the request MUST start with -----BEGIN RSA PRIVATE KEY----- and end with -----END RSA PRIVATE KEY-----", Required = true }); } } } }
35.444444
290
0.57837
[ "Unlicense" ]
adrianiftode/AuthorizationRegistry
iSHARE.Api/Swagger/GenerateJwsFilter.cs
1,278
C#
using System; using System.Collections.Generic; #nullable disable namespace Lab3.Models { public partial class Color { public string Name { get; set; } public string Code { get; set; } public int? Red { get; set; } public int? Green { get; set; } public int? Blue { get; set; } } }
19.823529
40
0.587537
[ "MIT" ]
Alanomari/ITHSDATABASLab3
Lab3/Models/Color.cs
339
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CodeNav")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CodeNav")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
27.117647
42
0.748373
[ "MIT" ]
nickmcummins/CodeNav
CodeNav.VS2019/Properties/AssemblyInfo.cs
463
C#
// 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 MS.Internal; using MS.Internal.Commands; using MS.Internal.Documents; using MS.Internal.KnownBoxes; using MS.Internal.PresentationFramework; using MS.Internal.Telemetry.PresentationFramework; using MS.Utility; using System; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows.Threading; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Markup; using System.Windows.Shapes; namespace System.Windows.Controls { #region ScrollBarVisibility enum /// <summary> /// ScrollBarVisibilty defines the visibility behavior of a scrollbar. /// </summary> public enum ScrollBarVisibility { /// <summary> /// No scrollbars and no scrolling in this dimension. /// </summary> Disabled = 0, /// <summary> /// The scrollbar should be visible only if there is more content than fits in the viewport. /// </summary> Auto, /// <summary> /// The scrollbar should never be visible. No space should ever be reserved for the scrollbar. /// </summary> Hidden, /// <summary> /// The scrollbar should always be visible. Space should always be reserved for the scrollbar. /// </summary> Visible, // NOTE: if you add or remove any values in this enum, be sure to update ScrollViewer.IsValidScrollBarVisibility() } #endregion /// <summary> /// A ScrollViewer accepts content and provides the logic that allows it to scroll. /// </summary> [DefaultEvent("ScrollChangedEvent")] [Localizability(LocalizationCategory.Ignore)] [TemplatePart(Name = "PART_HorizontalScrollBar", Type = typeof(ScrollBar))] [TemplatePart(Name = "PART_VerticalScrollBar", Type = typeof(ScrollBar))] [TemplatePart(Name = "PART_ScrollContentPresenter", Type = typeof(ScrollContentPresenter))] public class ScrollViewer : ContentControl { //------------------------------------------------------------------- // // Public Methods // //------------------------------------------------------------------- #region Public Methods /// <summary> /// Scroll content by one line to the top. /// </summary> public void LineUp() { EnqueueCommand(Commands.LineUp, 0, null); } /// <summary> /// Scroll content by one line to the bottom. /// </summary> public void LineDown() { EnqueueCommand(Commands.LineDown, 0, null); } /// <summary> /// Scroll content by one line to the left. /// </summary> public void LineLeft() { EnqueueCommand(Commands.LineLeft, 0, null); } /// <summary> /// Scroll content by one line to the right. /// </summary> public void LineRight() { EnqueueCommand(Commands.LineRight, 0, null); } /// <summary> /// Scroll content by one page to the top. /// </summary> public void PageUp() { EnqueueCommand(Commands.PageUp, 0, null); } /// <summary> /// Scroll content by one page to the bottom. /// </summary> public void PageDown() { EnqueueCommand(Commands.PageDown, 0, null); } /// <summary> /// Scroll content by one page to the left. /// </summary> public void PageLeft() { EnqueueCommand(Commands.PageLeft, 0, null); } /// <summary> /// Scroll content by one page to the right. /// </summary> public void PageRight() { EnqueueCommand(Commands.PageRight, 0, null); } /// <summary> /// Horizontally scroll to the beginning of the content. /// </summary> public void ScrollToLeftEnd() { EnqueueCommand(Commands.SetHorizontalOffset, Double.NegativeInfinity, null); } /// <summary> /// Horizontally scroll to the end of the content. /// </summary> public void ScrollToRightEnd() { EnqueueCommand(Commands.SetHorizontalOffset, Double.PositiveInfinity, null); } /// <summary> /// Scroll to Top-Left of the content. /// </summary> public void ScrollToHome() { EnqueueCommand(Commands.SetHorizontalOffset, Double.NegativeInfinity, null); EnqueueCommand(Commands.SetVerticalOffset, Double.NegativeInfinity, null); } /// <summary> /// Scroll to Bottom-Left of the content. /// </summary> public void ScrollToEnd() { EnqueueCommand(Commands.SetHorizontalOffset, Double.NegativeInfinity, null); EnqueueCommand(Commands.SetVerticalOffset, Double.PositiveInfinity, null); } /// <summary> /// Vertically scroll to the beginning of the content. /// </summary> public void ScrollToTop() { EnqueueCommand(Commands.SetVerticalOffset, Double.NegativeInfinity, null); } /// <summary> /// Vertically scroll to the end of the content. /// </summary> public void ScrollToBottom() { EnqueueCommand(Commands.SetVerticalOffset, Double.PositiveInfinity, null); } /// <summary> /// Scroll horizontally to specified offset. Not guaranteed to end up at the specified offset though. /// </summary> public void ScrollToHorizontalOffset(double offset) { double validatedOffset = ScrollContentPresenter.ValidateInputOffset(offset, "offset"); // Queue up the scroll command, which tells the content to scroll. // Will lead to an update of all offsets (both live and deferred). EnqueueCommand(Commands.SetHorizontalOffset, validatedOffset, null); } /// <summary> /// Scroll vertically to specified offset. Not guaranteed to end up at the specified offset though. /// </summary> public void ScrollToVerticalOffset(double offset) { double validatedOffset = ScrollContentPresenter.ValidateInputOffset(offset, "offset"); // Queue up the scroll command, which tells the content to scroll. // Will lead to an update of all offsets (both live and deferred). EnqueueCommand(Commands.SetVerticalOffset, validatedOffset, null); } private void DeferScrollToHorizontalOffset(double offset) { double validatedOffset = ScrollContentPresenter.ValidateInputOffset(offset, "offset"); // Update the offset property but not the deferred (content offset) // property, which will be updated when the drag operation is complete. HorizontalOffset = validatedOffset; } private void DeferScrollToVerticalOffset(double offset) { double validatedOffset = ScrollContentPresenter.ValidateInputOffset(offset, "offset"); // Update the offset property but not the deferred (content offset) // property, which will be updated when the drag operation is complete. VerticalOffset = validatedOffset; } internal void MakeVisible(Visual child, Rect rect) { MakeVisibleParams p = new MakeVisibleParams(child, rect); EnqueueCommand(Commands.MakeVisible, 0, p); } private void EnsureLayoutUpdatedHandler() { if (_layoutUpdatedHandler == null) { _layoutUpdatedHandler = new EventHandler(OnLayoutUpdated); LayoutUpdated += _layoutUpdatedHandler; } InvalidateArrange(); //can be that there is no outstanding need to do layout - make sure it is. } private void ClearLayoutUpdatedHandler() { // If queue is not empty - then we still need that handler to make sure queue is being processed. if ((_layoutUpdatedHandler != null) && (_queue.IsEmpty())) { LayoutUpdated -= _layoutUpdatedHandler; _layoutUpdatedHandler = null; } } /// <summary> /// This function is called by an IScrollInfo attached to this ScrollViewer when any values /// of scrolling properties (Offset, Extent, and ViewportSize) change. The function schedules /// invalidation of other elements like ScrollBars that are dependant on these properties. /// </summary> public void InvalidateScrollInfo() { IScrollInfo isi = this.ScrollInfo; //STRESS 1627654: anybody can call this method even if we don't have ISI... if(isi == null) return; // This is a public API, and is expected to be called by the // IScrollInfo implementation when any of the scrolling properties // change. Sometimes this is done independently (not as a result // of laying out this ScrollViewer) and that means we should re-run // the logic of determining visibility of autoscrollbars, if any. // // However, invalidating measure during arrange is dangerous // because it could lead to layout never settling down. This has // been observed with the layout rounding feature and non-standard // DPIs causing ScrollViewer to never settle on the visibility of // autoscrollbars. // // To guard against this condition, we only allow measure to be // invalidated from arrange once. // // We also don't invalidate measure if we are in the middle of the // measure pass, as the ScrollViewer will already be updating the // visibility of the autoscrollbars. if(!MeasureInProgress && (!ArrangeInProgress || !InvalidatedMeasureFromArrange)) { // // Check if we should remove/add scrollbars. // double extent = ScrollInfo.ExtentWidth; double viewport = ScrollInfo.ViewportWidth; if ( HorizontalScrollBarVisibility == ScrollBarVisibility.Auto && ( ( _scrollVisibilityX == Visibility.Collapsed && DoubleUtil.GreaterThan(extent, viewport)) || ( _scrollVisibilityX == Visibility.Visible && DoubleUtil.LessThanOrClose(extent, viewport)))) { InvalidateMeasure(); } else { extent = ScrollInfo.ExtentHeight; viewport = ScrollInfo.ViewportHeight; if (VerticalScrollBarVisibility == ScrollBarVisibility.Auto && ((_scrollVisibilityY == Visibility.Collapsed && DoubleUtil.GreaterThan(extent, viewport)) || (_scrollVisibilityY == Visibility.Visible && DoubleUtil.LessThanOrClose(extent, viewport)))) { InvalidateMeasure(); } } } // If any scrolling properties have actually changed, fire public events post-layout if ( !DoubleUtil.AreClose(HorizontalOffset, ScrollInfo.HorizontalOffset) || !DoubleUtil.AreClose(VerticalOffset, ScrollInfo.VerticalOffset) || !DoubleUtil.AreClose(ViewportWidth, ScrollInfo.ViewportWidth) || !DoubleUtil.AreClose(ViewportHeight, ScrollInfo.ViewportHeight) || !DoubleUtil.AreClose(ExtentWidth, ScrollInfo.ExtentWidth) || !DoubleUtil.AreClose(ExtentHeight, ScrollInfo.ExtentHeight)) { EnsureLayoutUpdatedHandler(); } } #endregion //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <summary> /// This property indicates whether the Content should handle scrolling if it can. /// A true value indicates Content should be allowed to scroll if it supports IScrollInfo. /// A false value will always use the default physically scrolling handler. /// </summary> public bool CanContentScroll { get { return (bool)GetValue(CanContentScrollProperty); } set { SetValue(CanContentScrollProperty, value); } } /// <summary> /// HorizonalScollbarVisibility is a <see cref="System.Windows.Controls.ScrollBarVisibility" /> that /// determines if a horizontal scrollbar is shown. /// </summary> [Bindable(true), Category("Appearance")] public ScrollBarVisibility HorizontalScrollBarVisibility { get { return (ScrollBarVisibility) GetValue(HorizontalScrollBarVisibilityProperty); } set { SetValue(HorizontalScrollBarVisibilityProperty, value); } } /// <summary> /// VerticalScrollBarVisibility is a <see cref="System.Windows.Controls.ScrollBarVisibility" /> that /// determines if a vertical scrollbar is shown. /// </summary> [Bindable(true), Category("Appearance")] public ScrollBarVisibility VerticalScrollBarVisibility { get { return (ScrollBarVisibility) GetValue(VerticalScrollBarVisibilityProperty); } set { SetValue(VerticalScrollBarVisibilityProperty, value); } } /// <summary> /// ComputedHorizontalScrollBarVisibility contains the ScrollViewer's current calculation as to /// whether or not scrollbars should be displayed. /// </summary> public Visibility ComputedHorizontalScrollBarVisibility { get { return _scrollVisibilityX; } } /// <summary> /// ComputedVerticalScrollBarVisibility contains the ScrollViewer's current calculation as to /// whether or not scrollbars should be displayed. /// </summary> public Visibility ComputedVerticalScrollBarVisibility { get { return _scrollVisibilityY; } } /// <summary> /// Actual HorizontalOffset contains the ScrollViewer's current horizontal offset. /// This is a computed value, derived from viewport/content size and previous scroll commands /// </summary> public double HorizontalOffset { // _xPositionISI is a local cache of GetValue(HorizontalOffsetProperty) // In the future, it could be replaced with the GetValue call. get { return _xPositionISI; } private set { SetValue(HorizontalOffsetPropertyKey, value); } } /// <summary> /// Actual VerticalOffset contains the ScrollViewer's current Vertical offset. /// This is a computed value, derived from viewport/content size and previous scroll commands /// </summary> public double VerticalOffset { // _yPositionISI is a local cache of GetValue(VerticalOffsetProperty) // In the future, it could be replaced with the GetValue call. get { return _yPositionISI; } private set { SetValue(VerticalOffsetPropertyKey, value); } } /// <summary> /// ExtentWidth contains the horizontal size of the scrolled content element. /// </summary> /// <remarks> /// ExtentWidth is only an output property; it can effectively be set by specifying /// <see cref="System.Windows.FrameworkElement.Width" /> on the content element. /// </remarks> [Category("Layout")] public double ExtentWidth { get { return _xExtent; } } /// <summary> /// ExtentHeight contains the vertical size of the scrolled content element. /// </summary> /// <remarks> /// ExtentHeight is only an output property; it can effectively be set by specifying /// <see cref="System.Windows.FrameworkElement.Height" /> on the content element. /// </remarks> [Category("Layout")] public double ExtentHeight { get { return _yExtent; } } /// <summary> /// ScrollableWidth contains the horizontal size of the content element that can be scrolled. /// </summary> public double ScrollableWidth { get { return Math.Max(0.0, ExtentWidth - ViewportWidth); } } /// <summary> /// ScrollableHeight contains the vertical size of the content element that can be scrolled. /// </summary> public double ScrollableHeight { get { return Math.Max(0.0, ExtentHeight - ViewportHeight); } } /// <summary> /// ViewportWidth contains the horizontal size of the scrolling viewport. /// </summary> /// <remarks> /// ExtentWidth is only an output property; it can effectively be set by specifying /// <see cref="System.Windows.FrameworkElement.Width" /> on this element. /// </remarks> [Category("Layout")] public double ViewportWidth { get { return _xSize; } } /// <summary> /// ViewportHeight contains the vertical size of the scrolling viewport. /// </summary> /// <remarks> /// ViewportHeight is only an output property; it can effectively be set by specifying /// <see cref="System.Windows.FrameworkElement.Height" /> on this element. /// </remarks> [Category("Layout")] public double ViewportHeight { get { return _ySize; } } /// <summary> /// DependencyProperty for <see cref="CanContentScroll" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty CanContentScrollProperty = DependencyProperty.RegisterAttached( "CanContentScroll", typeof(bool), typeof(ScrollViewer), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Helper for setting CanContentScroll property. /// </summary> public static void SetCanContentScroll(DependencyObject element, bool canContentScroll) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(CanContentScrollProperty, canContentScroll); } /// <summary> /// Helper for reading CanContentScroll property. /// </summary> public static bool GetCanContentScroll(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((bool)element.GetValue(CanContentScrollProperty)); } /// <summary> /// DependencyProperty for <see cref="HorizontalScrollBarVisibility" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty HorizontalScrollBarVisibilityProperty = DependencyProperty.RegisterAttached( "HorizontalScrollBarVisibility", typeof(ScrollBarVisibility), typeof(ScrollViewer), new FrameworkPropertyMetadata( ScrollBarVisibility.Disabled, FrameworkPropertyMetadataOptions.AffectsMeasure), new ValidateValueCallback(IsValidScrollBarVisibility)); /// <summary> /// Helper for setting HorizontalScrollBarVisibility property. /// </summary> public static void SetHorizontalScrollBarVisibility(DependencyObject element, ScrollBarVisibility horizontalScrollBarVisibility) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(HorizontalScrollBarVisibilityProperty, horizontalScrollBarVisibility); } /// <summary> /// Helper for reading HorizontalScrollBarVisibility property. /// </summary> public static ScrollBarVisibility GetHorizontalScrollBarVisibility(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((ScrollBarVisibility)element.GetValue(HorizontalScrollBarVisibilityProperty)); } /// <summary> /// DependencyProperty for <see cref="VerticalScrollBarVisibility" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty VerticalScrollBarVisibilityProperty = DependencyProperty.RegisterAttached( "VerticalScrollBarVisibility", typeof(ScrollBarVisibility), typeof(ScrollViewer), new FrameworkPropertyMetadata( ScrollBarVisibility.Visible, FrameworkPropertyMetadataOptions.AffectsMeasure), new ValidateValueCallback(IsValidScrollBarVisibility)); /// <summary> /// Helper for setting VerticalScrollBarVisibility property. /// </summary> public static void SetVerticalScrollBarVisibility(DependencyObject element, ScrollBarVisibility verticalScrollBarVisibility) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(VerticalScrollBarVisibilityProperty, verticalScrollBarVisibility); } /// <summary> /// Helper for reading VerticalScrollBarVisibility property. /// </summary> public static ScrollBarVisibility GetVerticalScrollBarVisibility(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((ScrollBarVisibility)element.GetValue(VerticalScrollBarVisibilityProperty)); } /// <summary> /// The key needed set a read-only property. /// </summary> private static readonly DependencyPropertyKey ComputedHorizontalScrollBarVisibilityPropertyKey = DependencyProperty.RegisterReadOnly( "ComputedHorizontalScrollBarVisibility", typeof(Visibility), typeof(ScrollViewer), new FrameworkPropertyMetadata(Visibility.Visible)); /// <summary> /// Dependency property that indicates whether horizontal scrollbars should display. The /// value of this property is computed by ScrollViewer; it can be controlled via the /// <see cref="HorizontalScrollBarVisibilityProperty" /> /// </summary> public static readonly DependencyProperty ComputedHorizontalScrollBarVisibilityProperty = ComputedHorizontalScrollBarVisibilityPropertyKey.DependencyProperty; /// <summary> /// The key needed set a read-only property. /// </summary> private static readonly DependencyPropertyKey ComputedVerticalScrollBarVisibilityPropertyKey = DependencyProperty.RegisterReadOnly( "ComputedVerticalScrollBarVisibility", typeof(Visibility), typeof(ScrollViewer), new FrameworkPropertyMetadata(Visibility.Visible)); /// <summary> /// Dependency property that indicates whether vertical scrollbars should display. The /// value of this property is computed by ScrollViewer; it can be controlled via the /// <see cref="VerticalScrollBarVisibilityProperty" /> /// </summary> public static readonly DependencyProperty ComputedVerticalScrollBarVisibilityProperty = ComputedVerticalScrollBarVisibilityPropertyKey.DependencyProperty; /// <summary> /// Actual VerticalOffset. /// </summary> private static readonly DependencyPropertyKey VerticalOffsetPropertyKey = DependencyProperty.RegisterReadOnly( "VerticalOffset", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="VerticalOffset" /> property. /// </summary> public static readonly DependencyProperty VerticalOffsetProperty = VerticalOffsetPropertyKey.DependencyProperty; /// <summary> /// HorizontalOffset. /// </summary> private static readonly DependencyPropertyKey HorizontalOffsetPropertyKey = DependencyProperty.RegisterReadOnly( "HorizontalOffset", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="HorizontalOffset" /> property. /// </summary> public static readonly DependencyProperty HorizontalOffsetProperty = HorizontalOffsetPropertyKey.DependencyProperty; /// <summary> /// When not doing live scrolling, this is the offset value where the /// content is visually located. /// </summary> private static readonly DependencyPropertyKey ContentVerticalOffsetPropertyKey = DependencyProperty.RegisterReadOnly( "ContentVerticalOffset", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="ContentVerticalOffset" /> property. /// </summary> public static readonly DependencyProperty ContentVerticalOffsetProperty = ContentVerticalOffsetPropertyKey.DependencyProperty; /// <summary> /// When not doing live scrolling, this is the offset value where the /// content is visually located. /// </summary> public double ContentVerticalOffset { get { return (double)GetValue(ContentVerticalOffsetProperty); } private set { SetValue(ContentVerticalOffsetPropertyKey, value); } } /// <summary> /// When not doing live scrolling, this is the offset value where the /// content is visually located. /// </summary> private static readonly DependencyPropertyKey ContentHorizontalOffsetPropertyKey = DependencyProperty.RegisterReadOnly( "ContentHorizontalOffset", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="ContentHorizontalOffset" /> property. /// </summary> public static readonly DependencyProperty ContentHorizontalOffsetProperty = ContentHorizontalOffsetPropertyKey.DependencyProperty; /// <summary> /// When not doing live scrolling, this is the offset value where the /// content is visually located. /// </summary> public double ContentHorizontalOffset { get { return (double)GetValue(ContentHorizontalOffsetProperty); } private set { SetValue(ContentHorizontalOffsetPropertyKey, value); } } /// <summary> /// The key needed set a read-only property. /// </summary> private static readonly DependencyPropertyKey ExtentWidthPropertyKey = DependencyProperty.RegisterReadOnly( "ExtentWidth", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="ExtentWidth" /> property. /// </summary> public static readonly DependencyProperty ExtentWidthProperty = ExtentWidthPropertyKey.DependencyProperty; /// <summary> /// The key needed set a read-only property. /// </summary> private static readonly DependencyPropertyKey ExtentHeightPropertyKey = DependencyProperty.RegisterReadOnly( "ExtentHeight", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="ExtentHeight" /> property. /// </summary> public static readonly DependencyProperty ExtentHeightProperty = ExtentHeightPropertyKey.DependencyProperty; /// <summary> /// The key needed set a read-only property. /// </summary> private static readonly DependencyPropertyKey ScrollableWidthPropertyKey = DependencyProperty.RegisterReadOnly( "ScrollableWidth", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="ScrollableWidth" /> property. /// </summary> public static readonly DependencyProperty ScrollableWidthProperty = ScrollableWidthPropertyKey.DependencyProperty; /// <summary> /// The key needed set a read-only property. /// </summary> private static readonly DependencyPropertyKey ScrollableHeightPropertyKey = DependencyProperty.RegisterReadOnly( "ScrollableHeight", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="ScrollableHeight" /> property. /// </summary> public static readonly DependencyProperty ScrollableHeightProperty = ScrollableHeightPropertyKey.DependencyProperty; /// <summary> /// The key needed set a read-only property. /// </summary> private static readonly DependencyPropertyKey ViewportWidthPropertyKey = DependencyProperty.RegisterReadOnly( "ViewportWidth", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="ViewportWidth" /> property. /// </summary> public static readonly DependencyProperty ViewportWidthProperty = ViewportWidthPropertyKey.DependencyProperty; /// <summary> /// The key needed set a read-only property. /// </summary> internal static readonly DependencyPropertyKey ViewportHeightPropertyKey = DependencyProperty.RegisterReadOnly( "ViewportHeight", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0d)); /// <summary> /// DependencyProperty for <see cref="ViewportHeight" /> property. /// </summary> public static readonly DependencyProperty ViewportHeightProperty = ViewportHeightPropertyKey.DependencyProperty; /// <summary> /// DependencyProperty that indicates whether the ScrollViewer should /// scroll contents immediately during a thumb drag or defer until /// a drag completes. /// </summary> public static readonly DependencyProperty IsDeferredScrollingEnabledProperty = DependencyProperty.RegisterAttached("IsDeferredScrollingEnabled", typeof(bool), typeof(ScrollViewer), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets the value of IsDeferredScrollingEnabled. /// </summary> /// <param name="element">The element on which to query the property.</param> /// <returns>The value of the property.</returns> public static bool GetIsDeferredScrollingEnabled(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return (bool)element.GetValue(IsDeferredScrollingEnabledProperty); } /// <summary> /// Sets the value of IsDeferredScrollingEnabled. /// </summary> /// <param name="element">The element on which to set the property.</param> /// <param name="value">The new value of the property.</param> public static void SetIsDeferredScrollingEnabled(DependencyObject element, bool value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsDeferredScrollingEnabledProperty, BooleanBoxes.Box(value)); } /// <summary> /// Indicates whether the ScrollViewer should scroll contents /// immediately during a thumb drag or defer until a drag completes. /// </summary> public bool IsDeferredScrollingEnabled { get { return (bool)GetValue(IsDeferredScrollingEnabledProperty); } set { SetValue(IsDeferredScrollingEnabledProperty, BooleanBoxes.Box(value)); } } #endregion //------------------------------------------------------------------- // // Public Events (CLR + Avalon) // //------------------------------------------------------------------- #region Public Events /// <summary> /// Event ID that corresponds to a change in scrolling state. /// See ScrollChangeEvent for the corresponding event handler. /// </summary> public static readonly RoutedEvent ScrollChangedEvent = EventManager.RegisterRoutedEvent( "ScrollChanged", RoutingStrategy.Bubble, typeof(ScrollChangedEventHandler), typeof(ScrollViewer)); /// <summary> /// Event handler registration for the event fired when scrolling state changes. /// </summary> [Category("Action")] public event ScrollChangedEventHandler ScrollChanged { add { AddHandler(ScrollChangedEvent, value); } remove { RemoveHandler(ScrollChangedEvent, value); } } #endregion //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods protected override void OnStylusSystemGesture(StylusSystemGestureEventArgs e) { // DevDiv:1139804 // Keep track of seeing a tap gesture so that we can use this information to // make decisions about panning. _seenTapGesture = e.SystemGesture == SystemGesture.Tap; } /// <summary> /// OnScrollChanged is an override called whenever scrolling state changes on this ScrollViewer. /// </summary> /// <remarks> /// OnScrollChanged fires the ScrollChangedEvent. Overriders of this method should call /// base.OnScrollChanged(args) if they want the event to be fired. /// </remarks> /// <param name="e">ScrollChangedEventArgs containing information about the change in scrolling state.</param> protected virtual void OnScrollChanged(ScrollChangedEventArgs e) { // Fire the event. RaiseEvent(e); } /// <summary> /// ScrollViewer always wants to be hit even when transparent so that it gets input such as MouseWheel. /// </summary> protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters) { // Assumptions: // 1. Input comes after layout, so Actual* are valid at this point // 2. The clipping part of scrolling is on the SCP, not SV. Thus, Actual* not taking clipping into // account is okay here, barring psychotic styles. Rect rc = new Rect(0, 0, this.ActualWidth, this.ActualHeight); if (rc.Contains(hitTestParameters.HitPoint)) { return new PointHitTestResult(this, hitTestParameters.HitPoint); } else { return null; } } /// <summary> /// If control has a scrollviewer in its style and has a custom keyboard scrolling behavior when HandlesScrolling should return true. /// Then ScrollViewer will not handle keyboard input and leave it up to the control. /// </summary> protected internal override bool HandlesScrolling { get { return true; } } /// <summary> /// ScrollArea handles keyboard scrolling events. /// ScrollArea handles: Left, Right, Up, Down, PageUp, PageDown, Home, End /// </summary> protected override void OnKeyDown(KeyEventArgs e) { if (e.Handled) return; Control templatedParentControl = TemplatedParent as Control; if (templatedParentControl != null && templatedParentControl.HandlesScrolling) return; // If the ScrollViewer has focus or other that arrow key is pressed // then it only scrolls if (e.OriginalSource == this) { ScrollInDirection(e); } // Focus is on the element within the ScrollViewer else { // If arrow key is pressed if (e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Down) { ScrollContentPresenter viewPort = GetTemplateChild(ScrollContentPresenterTemplateName) as ScrollContentPresenter; // If style changes and ConentSite cannot be found - just scroll and exit if (viewPort == null) { ScrollInDirection(e); return; } FocusNavigationDirection direction = KeyboardNavigation.KeyToTraversalDirection(e.Key); DependencyObject predictedFocus = null; DependencyObject focusedElement = Keyboard.FocusedElement as DependencyObject; bool isFocusWithinViewport = IsInViewport(viewPort, focusedElement); if (isFocusWithinViewport) { // Navigate from current focused element UIElement currentFocusUIElement = focusedElement as UIElement; if (currentFocusUIElement != null) { predictedFocus = currentFocusUIElement.PredictFocus(direction); } else { ContentElement currentFocusContentElement = focusedElement as ContentElement; if (currentFocusContentElement != null) { predictedFocus = currentFocusContentElement.PredictFocus(direction); } else { UIElement3D currentFocusUIElement3D = focusedElement as UIElement3D; if (currentFocusUIElement3D != null) { predictedFocus = currentFocusUIElement3D.PredictFocus(direction); } } } } else { // Navigate from current viewport predictedFocus = viewPort.PredictFocus(direction); } if (predictedFocus == null) { // predictedFocus is null - just scroll ScrollInDirection(e); } else { // Case 1: predictedFocus is entirely in current view port // Action: Set focus to predictedFocus, handle the event and exit if (IsInViewport(viewPort, predictedFocus)) { ((IInputElement)predictedFocus).Focus(); e.Handled = true; } // Case 2: else - predictedFocus is not entirely in the viewport // Scroll in the direction // If predictedFocus is in the new viewport - set focus // handle the event and exit else { ScrollInDirection(e); UpdateLayout(); if (IsInViewport(viewPort, predictedFocus)) { ((IInputElement)predictedFocus).Focus(); } } } } else // If other than arrow Key is down { ScrollInDirection(e); } } } // Returns true only if element is partly visible in the current viewport private bool IsInViewport(ScrollContentPresenter scp, DependencyObject element) { Visual baseRoot = KeyboardNavigation.GetVisualRoot(scp); Visual elementRoot = KeyboardNavigation.GetVisualRoot(element); // If scp and element are not under the same root, find the // parent of root of element and try with it instead and so on. while (baseRoot != elementRoot) { if (elementRoot == null) { return false; } FrameworkElement fe = elementRoot as FrameworkElement; if (fe == null) { return false; } element = fe.Parent; if (element == null) { return false; } elementRoot = KeyboardNavigation.GetVisualRoot(element); } Rect viewPortRect = KeyboardNavigation.GetRectangle(scp); Rect elementRect = KeyboardNavigation.GetRectangle(element); return viewPortRect.IntersectsWith(elementRect); } internal void ScrollInDirection(KeyEventArgs e) { bool fControlDown = ((e.KeyboardDevice.Modifiers & ModifierKeys.Control) != 0); bool fAltDown = ((e.KeyboardDevice.Modifiers & ModifierKeys.Alt) != 0); // We don't handle Alt + Key if (!fAltDown) { bool fInvertForRTL = (FlowDirection == FlowDirection.RightToLeft); switch (e.Key) { case Key.Left: if (fInvertForRTL) LineRight(); else LineLeft(); e.Handled = true; break; case Key.Right: if (fInvertForRTL) LineLeft(); else LineRight(); e.Handled = true; break; case Key.Up: LineUp(); e.Handled = true; break; case Key.Down: LineDown(); e.Handled = true; break; case Key.PageUp: PageUp(); e.Handled = true; break; case Key.PageDown: PageDown(); e.Handled = true; break; case Key.Home: if (fControlDown) ScrollToTop(); else ScrollToLeftEnd(); e.Handled = true; break; case Key.End: if (fControlDown) ScrollToBottom(); else ScrollToRightEnd(); e.Handled = true; break; } } } /// <summary> /// This is the method that responds to the MouseWheel event. /// </summary> /// <param name="e">Event Arguments</param> protected override void OnMouseWheel(MouseWheelEventArgs e) { if (e.Handled) { return; } if (!HandlesMouseWheelScrolling) { return; } if (ScrollInfo != null) { if (e.Delta < 0) { ScrollInfo.MouseWheelDown(); } else { ScrollInfo.MouseWheelUp(); } } e.Handled = true; } /// <summary> /// This is the method that responds to the MouseButtonEvent event. /// </summary> /// <param name="e"></param> protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { if (Focus()) e.Handled = true; base.OnMouseLeftButtonDown(e); } /// <summary> /// Updates DesiredSize of the ScrollViewer. Called by parent UIElement. This is the first pass of layout. /// </summary> /// <param name="constraint">Constraint size is an "upper limit" that the return value should not exceed.</param> /// <returns>The ScrollViewer's desired size.</returns> protected override Size MeasureOverride(Size constraint) { InChildInvalidateMeasure = false; IScrollInfo isi = this.ScrollInfo; int count = this.VisualChildrenCount; UIElement child = (count > 0) ? this.GetVisualChild(0) as UIElement : null; ScrollBarVisibility vsbv = VerticalScrollBarVisibility; ScrollBarVisibility hsbv = HorizontalScrollBarVisibility; Size desiredSize = new Size(); if (child != null) { bool etwTracingEnabled = EventTrace.IsEnabled(EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info); if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientStringBegin, EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info, "SCROLLVIEWER:MeasureOverride"); } try { bool vsbAuto = (vsbv == ScrollBarVisibility.Auto); bool hsbAuto = (hsbv == ScrollBarVisibility.Auto); bool vDisableScroll = (vsbv == ScrollBarVisibility.Disabled); bool hDisableScroll = (hsbv == ScrollBarVisibility.Disabled); Visibility vv = (vsbv == ScrollBarVisibility.Visible) ? Visibility.Visible : Visibility.Collapsed; Visibility hv = (hsbv == ScrollBarVisibility.Visible) ? Visibility.Visible : Visibility.Collapsed; if (_scrollVisibilityY != vv) { _scrollVisibilityY = vv; SetValue(ComputedVerticalScrollBarVisibilityPropertyKey, _scrollVisibilityY); } if (_scrollVisibilityX != hv) { _scrollVisibilityX = hv; SetValue(ComputedHorizontalScrollBarVisibilityPropertyKey, _scrollVisibilityX); } if (isi != null) { isi.CanHorizontallyScroll = !hDisableScroll; isi.CanVerticallyScroll = !vDisableScroll; } try { // Measure our visual tree. InChildMeasurePass1 = true; child.Measure(constraint); } finally { InChildMeasurePass1 = false; } //it could now be here as a result of visual template expansion that happens during Measure isi = this.ScrollInfo; if (isi != null && (hsbAuto || vsbAuto)) { bool makeHorizontalBarVisible = hsbAuto && DoubleUtil.GreaterThan(isi.ExtentWidth, isi.ViewportWidth); bool makeVerticalBarVisible = vsbAuto && DoubleUtil.GreaterThan(isi.ExtentHeight, isi.ViewportHeight); if (makeHorizontalBarVisible) { if (_scrollVisibilityX != Visibility.Visible) { _scrollVisibilityX = Visibility.Visible; SetValue(ComputedHorizontalScrollBarVisibilityPropertyKey, _scrollVisibilityX); } } if (makeVerticalBarVisible) { if (_scrollVisibilityY != Visibility.Visible) { _scrollVisibilityY = Visibility.Visible; SetValue(ComputedVerticalScrollBarVisibilityPropertyKey, _scrollVisibilityY); } } if (makeHorizontalBarVisible || makeVerticalBarVisible) { // Remeasure our visual tree. // Requires this extra invalidation because we need to remeasure Grid which is not neccessarily dirty now // since we only invlaidated scrollbars but we don't have LayoutUpdate loop at our disposal here InChildInvalidateMeasure = true; child.InvalidateMeasure(); try { InChildMeasurePass2 = true; child.Measure(constraint); } finally { InChildMeasurePass2 = false; } } //if both are Auto, then appearance of one scrollbar may causes appearance of another. //If we don't re-check here, we get some part of content covered by auto scrollbar and can never reach to it since //another scrollbar may not appear (in cases when viewport==extent) - bug 1199443 if(hsbAuto && vsbAuto && (makeHorizontalBarVisible != makeVerticalBarVisible)) { bool makeHorizontalBarVisible2 = !makeHorizontalBarVisible && DoubleUtil.GreaterThan(isi.ExtentWidth, isi.ViewportWidth); bool makeVerticalBarVisible2 = !makeVerticalBarVisible && DoubleUtil.GreaterThan(isi.ExtentHeight, isi.ViewportHeight); if(makeHorizontalBarVisible2) { if (_scrollVisibilityX != Visibility.Visible) { _scrollVisibilityX = Visibility.Visible; SetValue(ComputedHorizontalScrollBarVisibilityPropertyKey, _scrollVisibilityX); } } else if (makeVerticalBarVisible2) //only one can be true { if (_scrollVisibilityY != Visibility.Visible) { _scrollVisibilityY = Visibility.Visible; SetValue(ComputedVerticalScrollBarVisibilityPropertyKey, _scrollVisibilityY); } } if (makeHorizontalBarVisible2 || makeVerticalBarVisible2) { // Remeasure our visual tree. // Requires this extra invalidation because we need to remeasure Grid which is not neccessarily dirty now // since we only invlaidated scrollbars but we don't have LayoutUpdate loop at our disposal here InChildInvalidateMeasure = true; child.InvalidateMeasure(); try { InChildMeasurePass3 = true; child.Measure(constraint); } finally { InChildMeasurePass3 = false; } } } } } finally { if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientStringEnd, EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info, "SCROLLVIEWER:MeasureOverride"); } } desiredSize = child.DesiredSize; } if(!ArrangeDirty && InvalidatedMeasureFromArrange) { // If we invalidated measure from a previous arrange pass, but // if after the following measure pass we are not dirty for // arrange, then ArrangeOverride will not get called, and we // need to clean up our state here. InvalidatedMeasureFromArrange = false; } return desiredSize; } protected override Size ArrangeOverride(Size arrangeSize) { bool previouslyInvalidatedMeasureFromArrange = InvalidatedMeasureFromArrange; Size size = base.ArrangeOverride(arrangeSize); if(previouslyInvalidatedMeasureFromArrange) { // If we invalidated measure from a previous arrange pass, // then we are not supposed to invalidate measure this time. Debug.Assert(!MeasureDirty); InvalidatedMeasureFromArrange = false; } else { InvalidatedMeasureFromArrange = MeasureDirty; } return size; } private void BindToTemplatedParent(DependencyProperty property) { if (!HasNonDefaultValue(property)) { Binding binding = new Binding(); binding.RelativeSource = RelativeSource.TemplatedParent; binding.Path = new PropertyPath(property); SetBinding(property, binding); } } /// <summary> /// ScrollViewer binds to the TemplatedParent's attached properties /// if they are not set directly on the ScrollViewer /// </summary> internal override void OnPreApplyTemplate() { base.OnPreApplyTemplate(); if (TemplatedParent != null) { BindToTemplatedParent(HorizontalScrollBarVisibilityProperty); BindToTemplatedParent(VerticalScrollBarVisibilityProperty); BindToTemplatedParent(CanContentScrollProperty); BindToTemplatedParent(IsDeferredScrollingEnabledProperty); BindToTemplatedParent(PanningModeProperty); } } /// <summary> /// Called when the Template's tree has been generated /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); ScrollBar scrollBar = GetTemplateChild(HorizontalScrollBarTemplateName) as ScrollBar; if (scrollBar != null) scrollBar.IsStandalone = false; scrollBar = GetTemplateChild(VerticalScrollBarTemplateName) as ScrollBar; if (scrollBar != null) scrollBar.IsStandalone = false; OnPanningModeChanged(); } #endregion //------------------------------------------------------------------- // // Protected Propeties // //------------------------------------------------------------------- #region Protected Properties /// <summary> /// The ScrollInfo is the source of scrolling properties (Extent, Offset, and ViewportSize) /// for this ScrollViewer and any of its components like scrollbars. /// </summary> protected internal IScrollInfo ScrollInfo { get { return _scrollInfo; } set { _scrollInfo = value; if (_scrollInfo != null) { _scrollInfo.CanHorizontallyScroll = (HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled); _scrollInfo.CanVerticallyScroll = (VerticalScrollBarVisibility != ScrollBarVisibility.Disabled); EnsureQueueProcessing(); } } } #endregion #region Scroll Manipulations /// <summary> /// The mode of manipulation based panning /// </summary> public PanningMode PanningMode { get { return (PanningMode)GetValue(PanningModeProperty); } set { SetValue(PanningModeProperty, value); } } /// <summary> /// Dependency property for PanningMode property /// </summary> public static readonly DependencyProperty PanningModeProperty = DependencyProperty.RegisterAttached( "PanningMode", typeof(PanningMode), typeof(ScrollViewer), new FrameworkPropertyMetadata(PanningMode.None, new PropertyChangedCallback(OnPanningModeChanged))); /// <summary> /// Set method for PanningMode /// </summary> public static void SetPanningMode(DependencyObject element, PanningMode panningMode) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(PanningModeProperty, panningMode); } /// <summary> /// Get method for PanningMode /// </summary> public static PanningMode GetPanningMode(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((PanningMode)element.GetValue(PanningModeProperty)); } /// <summary> /// Property changed callback for PanningMode. /// </summary> private static void OnPanningModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScrollViewer sv = d as ScrollViewer; if (sv != null) { sv.OnPanningModeChanged(); } } /// <summary> /// Method which sets IsManipulationEnabled /// property based on the PanningMode /// </summary> private void OnPanningModeChanged() { if (!HasTemplateGeneratedSubTree) { return; } PanningMode mode = PanningMode; // Call InvalidateProperty for IsManipulationEnabledProperty // to reset previous SetCurrentValueInternal if any. // Then call SetCurrentValueInternal to // set the value of these properties if needed. InvalidateProperty(IsManipulationEnabledProperty); if (mode != PanningMode.None) { SetCurrentValueInternal(IsManipulationEnabledProperty, BooleanBoxes.TrueBox); } } /// <summary> /// The inertial linear deceleration of manipulation based scrolling /// </summary> public double PanningDeceleration { get { return (double)GetValue(PanningDecelerationProperty); } set { SetValue(PanningDecelerationProperty, value); } } /// <summary> /// Dependency property for PanningDeceleration /// </summary> public static readonly DependencyProperty PanningDecelerationProperty = DependencyProperty.RegisterAttached( "PanningDeceleration", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(0.001), new ValidateValueCallback(CheckFiniteNonNegative)); /// <summary> /// Set method for PanningDeceleration property /// </summary> public static void SetPanningDeceleration(DependencyObject element, double value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(PanningDecelerationProperty, value); } /// <summary> /// Get method for PanningDeceleration property. /// </summary> public static double GetPanningDeceleration(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((double)element.GetValue(PanningDecelerationProperty)); } /// <summary> /// The Scroll pixels to panning pixels. /// </summary> public double PanningRatio { get { return (double)GetValue(PanningRatioProperty); } set { SetValue(PanningRatioProperty, value); } } /// <summary> /// Dependency property for PanningRatio. /// </summary> public static readonly DependencyProperty PanningRatioProperty = DependencyProperty.RegisterAttached( "PanningRatio", typeof(double), typeof(ScrollViewer), new FrameworkPropertyMetadata(1d), new ValidateValueCallback(CheckFiniteNonNegative)); /// <summary> /// Set method for PanningRatio property. /// </summary> public static void SetPanningRatio(DependencyObject element, double value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(PanningRatioProperty, value); } /// <summary> /// Get method for PanningRatio property /// </summary> public static double GetPanningRatio(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((double)element.GetValue(PanningRatioProperty)); } private static bool CheckFiniteNonNegative(object value) { double doubleValue = (double)value; return (DoubleUtil.GreaterThanOrClose(doubleValue, 0) && !double.IsInfinity(doubleValue)); } protected override void OnManipulationStarting(ManipulationStartingEventArgs e) { _panningInfo = null; // DevDiv:1139804 // When starting a new manipulation, clear out that we saw a tap _seenTapGesture = false; PanningMode panningMode = PanningMode; if (panningMode != PanningMode.None) { CompleteScrollManipulation = false; ScrollContentPresenter viewport = GetTemplateChild(ScrollContentPresenterTemplateName) as ScrollContentPresenter; if (ShouldManipulateScroll(e, viewport)) { // Set Manipulation mode and container if (panningMode == PanningMode.HorizontalOnly) { e.Mode = ManipulationModes.TranslateX; } else if (panningMode == PanningMode.VerticalOnly) { e.Mode = ManipulationModes.TranslateY; } else { e.Mode = ManipulationModes.Translate; } e.ManipulationContainer = this; // initialize _panningInfo _panningInfo = new PanningInfo() { OriginalHorizontalOffset = HorizontalOffset, OriginalVerticalOffset = VerticalOffset, PanningMode = panningMode }; // Determine pixels per offset value. This is useful when performing non-pixel scrolling. double viewportWidth = ViewportWidth + 1d; // Using +1 to account for last partially visible item in viewport double viewportHeight = ViewportHeight + 1d; // Using +1 to account for last partially visible item in viewport if (viewport != null) { _panningInfo.DeltaPerHorizontalOffet = (DoubleUtil.AreClose(viewportWidth, 0) ? 0 : viewport.ActualWidth / viewportWidth); _panningInfo.DeltaPerVerticalOffset = (DoubleUtil.AreClose(viewportHeight, 0) ? 0 : viewport.ActualHeight / viewportHeight); } else { _panningInfo.DeltaPerHorizontalOffet = (DoubleUtil.AreClose(viewportWidth, 0) ? 0 : ActualWidth / viewportWidth); _panningInfo.DeltaPerVerticalOffset = (DoubleUtil.AreClose(viewportHeight, 0) ? 0 : ActualHeight / viewportHeight); } // Template bind other Scroll Manipulation properties if needed. if (!ManipulationBindingsInitialized) { BindToTemplatedParent(PanningDecelerationProperty); BindToTemplatedParent(PanningRatioProperty); ManipulationBindingsInitialized = true; } } else { e.Cancel(); ForceNextManipulationComplete = false; } e.Handled = true; } } private bool ShouldManipulateScroll(ManipulationStartingEventArgs e, ScrollContentPresenter viewport) { // If the original source is not from the same PresentationSource as of ScrollViewer, // then do not start the manipulation. if (!PresentationSource.UnderSamePresentationSource(e.OriginalSource as DependencyObject, this)) { return false; } if (viewport == null) { // If there is no ScrollContentPresenter, then always start Manipulation return true; } // Dont start the manipulation if any of the manipulator positions // does not lie inside the viewport. GeneralTransform viewportTransform = TransformToDescendant(viewport); double viewportWidth = viewport.ActualWidth; double viewportHeight = viewport.ActualHeight; foreach (IManipulator manipulator in e.Manipulators) { Point manipulatorPosition = viewportTransform.Transform(manipulator.GetPosition(this)); if (DoubleUtil.LessThan(manipulatorPosition.X, 0) || DoubleUtil.LessThan(manipulatorPosition.Y, 0) || DoubleUtil.GreaterThan(manipulatorPosition.X, viewportWidth) || DoubleUtil.GreaterThan(manipulatorPosition.Y, viewportHeight)) { return false; } } return true; } protected override void OnManipulationDelta(ManipulationDeltaEventArgs e) { if (_panningInfo != null) { if (e.IsInertial && CompleteScrollManipulation) { e.Complete(); } else { bool cancelManipulation = false; // DevDiv:1139804 // High precision touch devices can trigger a panning manipulation // due to the low threshold we set for pan initiation. This may be // undesirable since we may enter pan for what the system considers a // tap. Panning should be contingent on a drag gesture as that is the // most consistent with the system at large. So if we have seen a tap // on our main input, we should cancel any panning. if (_seenTapGesture) { e.Cancel(); _panningInfo = null; } else if (_panningInfo.IsPanning) { // Do the scrolling if we already started it. ManipulateScroll(e); } else if (CanStartScrollManipulation(e.CumulativeManipulation.Translation, out cancelManipulation)) { // Check if we can start the scrolling and do accordingly _panningInfo.IsPanning = true; ManipulateScroll(e); } else if (cancelManipulation) { e.Cancel(); _panningInfo = null; } } e.Handled = true; } } private void ManipulateScroll(ManipulationDeltaEventArgs e) { Debug.Assert(_panningInfo != null); PanningMode panningMode = _panningInfo.PanningMode; if (panningMode != PanningMode.VerticalOnly) { // Scroll horizontally unless the mode is VerticalOnly ManipulateScroll(e.DeltaManipulation.Translation.X, e.CumulativeManipulation.Translation.X, true); } if (panningMode != PanningMode.HorizontalOnly) { // Scroll vertically unless the mode is HorizontalOnly ManipulateScroll(e.DeltaManipulation.Translation.Y, e.CumulativeManipulation.Translation.Y, false); } if (e.IsInertial && IsPastInertialLimit()) { e.Complete(); } else { double unusedX = _panningInfo.UnusedTranslation.X; if (!_panningInfo.InHorizontalFeedback && DoubleUtil.LessThan(Math.Abs(unusedX), PanningInfo.PreFeedbackTranslationX)) { unusedX = 0; } _panningInfo.InHorizontalFeedback = (!DoubleUtil.AreClose(unusedX, 0)); double unusedY = _panningInfo.UnusedTranslation.Y; if (!_panningInfo.InVerticalFeedback && DoubleUtil.LessThan(Math.Abs(unusedY), PanningInfo.PreFeedbackTranslationY)) { unusedY = 0; } _panningInfo.InVerticalFeedback = (!DoubleUtil.AreClose(unusedY, 0)); if (_panningInfo.InHorizontalFeedback || _panningInfo.InVerticalFeedback) { // Report boundary feedback if needed e.ReportBoundaryFeedback(new ManipulationDelta(new Vector(unusedX, unusedY), 0.0, new Vector(1.0, 1.0), new Vector())); if (e.IsInertial && _panningInfo.InertiaBoundaryBeginTimestamp == 0) { _panningInfo.InertiaBoundaryBeginTimestamp = Environment.TickCount; } } } } private void ManipulateScroll(double delta, double cumulativeTranslation, bool isHorizontal) { double unused = (isHorizontal ? _panningInfo.UnusedTranslation.X : _panningInfo.UnusedTranslation.Y); double offset = (isHorizontal ? HorizontalOffset : VerticalOffset); double scrollableLength = (isHorizontal ? ScrollableWidth : ScrollableHeight); if (DoubleUtil.AreClose(scrollableLength, 0)) { // If the Scrollable length in this direction is 0, // then we should neither scroll nor report the boundary feedback unused = 0; delta = 0; } else if ((DoubleUtil.GreaterThan(delta, 0) && DoubleUtil.AreClose(offset, 0)) || (DoubleUtil.LessThan(delta, 0) && DoubleUtil.AreClose(offset, scrollableLength))) { // If we are past the boundary and the delta is in the same direction, // then add the delta to the unused vector unused += delta; delta = 0; } else if (DoubleUtil.LessThan(delta, 0) && DoubleUtil.GreaterThan(unused, 0)) { // If we are past the boundary in positive direction // and the delta is in negative direction, // then compensate the delta from unused vector. double newUnused = Math.Max(unused + delta, 0); delta += unused - newUnused; unused = newUnused; } else if (DoubleUtil.GreaterThan(delta, 0) && DoubleUtil.LessThan(unused, 0)) { // If we are past the boundary in negative direction // and the delta is in positive direction, // then compensate the delta from unused vector. double newUnused = Math.Min(unused + delta, 0); delta += unused - newUnused; unused = newUnused; } if (isHorizontal) { if (!DoubleUtil.AreClose(delta, 0)) { // if there is any delta left, then re-evalute the horizontal offset ScrollToHorizontalOffset(_panningInfo.OriginalHorizontalOffset - Math.Round(PanningRatio * cumulativeTranslation / _panningInfo.DeltaPerHorizontalOffet)); } _panningInfo.UnusedTranslation = new Vector(unused, _panningInfo.UnusedTranslation.Y); } else { if (!DoubleUtil.AreClose(delta, 0)) { // if there is any delta left, then re-evalute the vertical offset ScrollToVerticalOffset(_panningInfo.OriginalVerticalOffset - Math.Round(PanningRatio * cumulativeTranslation / _panningInfo.DeltaPerVerticalOffset)); } _panningInfo.UnusedTranslation = new Vector(_panningInfo.UnusedTranslation.X, unused); } } /// <summary> /// Translation due to intertia past the boundary is restricted to a certain limit. /// This method checks if the unused vector falls beyound that limit /// </summary> /// <returns></returns> private bool IsPastInertialLimit() { if (Math.Abs(Environment.TickCount - _panningInfo.InertiaBoundaryBeginTimestamp) < PanningInfo.InertiaBoundryMinimumTicks) { return false; } return (DoubleUtil.GreaterThanOrClose(Math.Abs(_panningInfo.UnusedTranslation.X), PanningInfo.MaxInertiaBoundaryTranslation) || DoubleUtil.GreaterThanOrClose(Math.Abs(_panningInfo.UnusedTranslation.Y), PanningInfo.MaxInertiaBoundaryTranslation)); } /// <summary> /// Scrolling due to manipulation can start only if there is a considerable delta /// in the direction based on the mode. This method makes sure that the delta is /// considerable. /// </summary> private bool CanStartScrollManipulation(Vector translation, out bool cancelManipulation) { Debug.Assert(_panningInfo != null); cancelManipulation = false; PanningMode panningMode = _panningInfo.PanningMode; if (panningMode == PanningMode.None) { cancelManipulation = true; return false; } bool validX = (DoubleUtil.GreaterThan(Math.Abs(translation.X), PanningInfo.PrePanTranslation)); bool validY = (DoubleUtil.GreaterThan(Math.Abs(translation.Y), PanningInfo.PrePanTranslation)); if (((panningMode == PanningMode.Both) && (validX || validY)) || (panningMode == PanningMode.HorizontalOnly && validX) || (panningMode == PanningMode.VerticalOnly && validY)) { return true; } else if (panningMode == PanningMode.HorizontalFirst) { bool biggerX = (DoubleUtil.GreaterThanOrClose(Math.Abs(translation.X), Math.Abs(translation.Y))); if (validX && biggerX) { return true; } else if (validY) { cancelManipulation = true; return false; } } else if (panningMode == PanningMode.VerticalFirst) { bool biggerY = (DoubleUtil.GreaterThanOrClose(Math.Abs(translation.Y), Math.Abs(translation.X))); if (validY && biggerY) { return true; } else if (validX) { cancelManipulation = true; return false; } } return false; } protected override void OnManipulationInertiaStarting(ManipulationInertiaStartingEventArgs e) { if (_panningInfo != null) { if (!_panningInfo.IsPanning && !ForceNextManipulationComplete) { // If the inertia starts and we are not scrolling yet, then cancel the manipulation. e.Cancel(); _panningInfo = null; } else { e.TranslationBehavior.DesiredDeceleration = PanningDeceleration; } e.Handled = true; } } protected override void OnManipulationCompleted(ManipulationCompletedEventArgs e) { if (_panningInfo != null) { if (!(e.IsInertial && CompleteScrollManipulation)) { if (e.IsInertial && !DoubleUtil.AreClose(e.FinalVelocities.LinearVelocity, new Vector()) && !IsPastInertialLimit()) { // if an inertial manipualtion gets completed without its LinearVelocity reaching 0, // then most probably it was forced to complete by other manipulation. // In such case we dont want the next manipulation to ever cancel. ForceNextManipulationComplete = true; } else { if (!e.IsInertial && !_panningInfo.IsPanning && !ForceNextManipulationComplete) { // If we are not scrolling yet and the manipulation gets completed, then cancel the manipulation. e.Cancel(); } ForceNextManipulationComplete = false; } } _panningInfo = null; CompleteScrollManipulation = false; e.Handled = true; } } private class PanningInfo { public PanningMode PanningMode { get; set; } public double OriginalHorizontalOffset { get; set; } public double OriginalVerticalOffset { get; set; } public double DeltaPerHorizontalOffet { get; set; } public double DeltaPerVerticalOffset { get; set; } public bool IsPanning { get; set; } public Vector UnusedTranslation { get; set; } public bool InHorizontalFeedback { get; set; } public bool InVerticalFeedback { get; set; } public int InertiaBoundaryBeginTimestamp { get; set; } public const double PrePanTranslation = 3d; public const double MaxInertiaBoundaryTranslation = 50d; public const double PreFeedbackTranslationX = 8d; public const double PreFeedbackTranslationY = 5d; public const int InertiaBoundryMinimumTicks = 100; } #endregion //------------------------------------------------------------------- // // Internal Propeties // //------------------------------------------------------------------- #region Internal Properties /// <summary> /// Whether or not the ScrollViewer should handle mouse wheel events. This property was /// specifically introduced for TextBoxBase, to prevent mouse wheel scrolling from "breaking" /// if the mouse pointer happens to land on a TextBoxBase with no more content in the direction /// of the scroll, as with a single-line TextBox. In that scenario, ScrollViewer would /// try to scroll the TextBoxBase and not allow the scroll event to bubble up to an outer /// control even though the TextBoxBase doesn't scroll. /// /// This property defaults to true. TextBoxBase sets it to false. /// </summary> internal bool HandlesMouseWheelScrolling { get { return ((_flags & Flags.HandlesMouseWheelScrolling) == Flags.HandlesMouseWheelScrolling); } set { SetFlagValue(Flags.HandlesMouseWheelScrolling, value); } } internal bool InChildInvalidateMeasure { get { return ((_flags & Flags.InChildInvalidateMeasure) == Flags.InChildInvalidateMeasure); } set { SetFlagValue(Flags.InChildInvalidateMeasure, value); } } #endregion Internal Properties //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods private enum Commands { Invalid, LineUp, LineDown, LineLeft, LineRight, PageUp, PageDown, PageLeft, PageRight, SetHorizontalOffset, SetVerticalOffset, MakeVisible, } private struct Command { internal Command(Commands code, double param, MakeVisibleParams mvp) { Code = code; Param = param; MakeVisibleParam = mvp; } internal Commands Code; internal double Param; internal MakeVisibleParams MakeVisibleParam; } private class MakeVisibleParams { internal MakeVisibleParams(Visual child, Rect targetRect) { Child = child; TargetRect = targetRect; } internal Visual Child; internal Rect TargetRect; } // implements ring buffer of commands private struct CommandQueue { private const int _capacity = 32; //returns false if capacity is used up and entry ignored internal void Enqueue(Command command) { if(_lastWritePosition == _lastReadPosition) //buffer is empty { _array = new Command[_capacity]; _lastWritePosition = _lastReadPosition = 0; } if(!OptimizeCommand(command)) //regular insertion, if optimization didn't happen { _lastWritePosition = (_lastWritePosition + 1) % _capacity; if(_lastWritePosition == _lastReadPosition) //buffer is full { // throw away the oldest entry and continue to accumulate fresh input _lastReadPosition = (_lastReadPosition + 1) % _capacity; } _array[_lastWritePosition] = command; } } // this tries to "merge" the incoming command with the accumulated queue // for example, if we get SetHorizontalOffset incoming, all "horizontal" // commands in the queue get removed and replaced with incoming one, // since horizontal position is going to end up at the specified offset anyways. private bool OptimizeCommand(Command command) { if(_lastWritePosition != _lastReadPosition) //buffer has something { if( ( command.Code == Commands.SetHorizontalOffset && _array[_lastWritePosition].Code == Commands.SetHorizontalOffset) || ( command.Code == Commands.SetVerticalOffset && _array[_lastWritePosition].Code == Commands.SetVerticalOffset) || (command.Code == Commands.MakeVisible && _array[_lastWritePosition].Code == Commands.MakeVisible)) { //if the last command was "set offset" or "make visible", simply replace it and //don't insert new command _array[_lastWritePosition].Param = command.Param; _array[_lastWritePosition].MakeVisibleParam = command.MakeVisibleParam; return true; } } return false; } // returns Invalid command if there is no more commands internal Command Fetch() { if(_lastWritePosition == _lastReadPosition) //buffer is empty { return new Command(Commands.Invalid, 0, null); } _lastReadPosition = (_lastReadPosition + 1) % _capacity; //array exists always if writePos != readPos Command command = _array[_lastReadPosition]; _array[_lastReadPosition].MakeVisibleParam = null; //to release the allocated object if(_lastWritePosition == _lastReadPosition) //it was the last command { _array = null; // make GC work. Hopefully the whole queue is processed in Gen0 } return command; } internal bool IsEmpty() { return (_lastWritePosition == _lastReadPosition); } private int _lastWritePosition; private int _lastReadPosition; private Command[] _array; } //returns true if there was a command sent to ISI private bool ExecuteNextCommand() { IScrollInfo isi = ScrollInfo; if(isi == null) return false; Command cmd = _queue.Fetch(); switch(cmd.Code) { case Commands.LineUp: isi.LineUp(); break; case Commands.LineDown: isi.LineDown(); break; case Commands.LineLeft: isi.LineLeft(); break; case Commands.LineRight: isi.LineRight(); break; case Commands.PageUp: isi.PageUp(); break; case Commands.PageDown: isi.PageDown(); break; case Commands.PageLeft: isi.PageLeft(); break; case Commands.PageRight: isi.PageRight(); break; case Commands.SetHorizontalOffset: isi.SetHorizontalOffset(cmd.Param); break; case Commands.SetVerticalOffset: isi.SetVerticalOffset(cmd.Param); break; case Commands.MakeVisible: { Visual child = cmd.MakeVisibleParam.Child; Visual visi = isi as Visual; if ( child != null && visi != null && (visi == child || visi.IsAncestorOf(child)) // bug 1616807. ISI could be removed from visual tree, // but ScrollViewer.ScrollInfo may not reflect this yet. && this.IsAncestorOf(visi) ) { Rect targetRect = cmd.MakeVisibleParam.TargetRect; if(targetRect.IsEmpty) { UIElement uie = child as UIElement; if(uie != null) targetRect = new Rect(uie.RenderSize); else targetRect = new Rect(); //not a good idea to invoke ISI with Empty rect } // (ScrollContentPresenter.MakeVisible can cause an exception when encountering an empty rectangle) // Workaround: // The method throws InvalidOperationException in some scenarios where it should return Rect.Empty. // Do not workaround for derived classes. Rect rcNew; if(isi.GetType() == typeof(System.Windows.Controls.ScrollContentPresenter)) { rcNew = ((System.Windows.Controls.ScrollContentPresenter)isi).MakeVisible(child, targetRect, false); } else { rcNew = isi.MakeVisible(child, targetRect); } if (!rcNew.IsEmpty) { GeneralTransform t = visi.TransformToAncestor(this); rcNew = t.TransformBounds(rcNew); } BringIntoView(rcNew); } } break; case Commands.Invalid: return false; } return true; } private void EnqueueCommand(Commands code, double param, MakeVisibleParams mvp) { _queue.Enqueue(new Command(code, param, mvp)); EnsureQueueProcessing(); } private void EnsureQueueProcessing() { if(!_queue.IsEmpty()) { EnsureLayoutUpdatedHandler(); } } // LayoutUpdated event handler. // 1. executes next queued command, if any // 2. If no commands to execute, updates properties and fires events private void OnLayoutUpdated(object sender, EventArgs e) { // if there was a command, execute it and leave the handler for the next pass if(ExecuteNextCommand()) { InvalidateArrange(); return; } double oldActualHorizontalOffset = HorizontalOffset; double oldActualVerticalOffset = VerticalOffset; double oldViewportWidth = ViewportWidth; double oldViewportHeight = ViewportHeight; double oldExtentWidth = ExtentWidth; double oldExtentHeight = ExtentHeight; double oldScrollableWidth = ScrollableWidth; double oldScrollableHeight = ScrollableHeight; bool changed = false; // // Go through scrolling properties updating values. // if (ScrollInfo != null && !DoubleUtil.AreClose(oldActualHorizontalOffset, ScrollInfo.HorizontalOffset)) { _xPositionISI = ScrollInfo.HorizontalOffset; HorizontalOffset = _xPositionISI; ContentHorizontalOffset = _xPositionISI; changed = true; } if (ScrollInfo != null && !DoubleUtil.AreClose(oldActualVerticalOffset, ScrollInfo.VerticalOffset)) { _yPositionISI = ScrollInfo.VerticalOffset; VerticalOffset = _yPositionISI; ContentVerticalOffset = _yPositionISI; changed = true; } if (ScrollInfo != null && !DoubleUtil.AreClose(oldViewportWidth, ScrollInfo.ViewportWidth)) { _xSize = ScrollInfo.ViewportWidth; SetValue(ViewportWidthPropertyKey, _xSize); changed = true; } if (ScrollInfo != null && !DoubleUtil.AreClose(oldViewportHeight, ScrollInfo.ViewportHeight)) { _ySize = ScrollInfo.ViewportHeight; SetValue(ViewportHeightPropertyKey, _ySize); changed = true; } if (ScrollInfo != null && !DoubleUtil.AreClose(oldExtentWidth, ScrollInfo.ExtentWidth)) { _xExtent = ScrollInfo.ExtentWidth; SetValue(ExtentWidthPropertyKey, _xExtent); changed = true; } if (ScrollInfo != null && !DoubleUtil.AreClose(oldExtentHeight, ScrollInfo.ExtentHeight)) { _yExtent = ScrollInfo.ExtentHeight; SetValue(ExtentHeightPropertyKey, _yExtent); changed = true; } // ScrollableWidth/Height are dependant on Viewport and Extent set above. This check must be done after those. double scrollableWidth = ScrollableWidth; if (!DoubleUtil.AreClose(oldScrollableWidth, ScrollableWidth)) { SetValue(ScrollableWidthPropertyKey, scrollableWidth); changed = true; } double scrollableHeight = ScrollableHeight; if (!DoubleUtil.AreClose(oldScrollableHeight, ScrollableHeight)) { SetValue(ScrollableHeightPropertyKey, scrollableHeight); changed = true; } Debug.Assert(DoubleUtil.GreaterThanOrClose(_xSize, 0.0) && DoubleUtil.GreaterThanOrClose(_ySize, 0.0), "Negative size for scrolling viewport. Bad IScrollInfo implementation."); // // Fire scrolling events. // if(changed) { // Fire ScrollChange event ScrollChangedEventArgs args = new ScrollChangedEventArgs( new Vector(HorizontalOffset, VerticalOffset), new Vector(HorizontalOffset - oldActualHorizontalOffset, VerticalOffset - oldActualVerticalOffset), new Size(ExtentWidth, ExtentHeight), new Vector(ExtentWidth - oldExtentWidth, ExtentHeight - oldExtentHeight), new Size(ViewportWidth, ViewportHeight), new Vector(ViewportWidth - oldViewportWidth, ViewportHeight - oldViewportHeight)); args.RoutedEvent = ScrollChangedEvent; args.Source = this; try { OnScrollChanged(args); // Fire automation events if automation is active. ScrollViewerAutomationPeer peer = UIElementAutomationPeer.FromElement(this) as ScrollViewerAutomationPeer; if(peer != null) { peer.RaiseAutomationEvents(oldExtentWidth, oldExtentHeight, oldViewportWidth, oldViewportHeight, oldActualHorizontalOffset, oldActualVerticalOffset); } } finally { // // Disconnect the layout listener. // ClearLayoutUpdatedHandler(); } } ClearLayoutUpdatedHandler(); } /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new ScrollViewerAutomationPeer(this); } /// <summary> /// OnRequestBringIntoView is called from the event handler ScrollViewer registers for the event. /// The default implementation checks to make sure the visual is a child of the IScrollInfo, and then /// delegates to a method there /// </summary> /// <param name="sender">The instance handling the event.</param> /// <param name="e">RequestBringIntoViewEventArgs indicates the element and region to scroll into view.</param> private static void OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { ScrollViewer sv = sender as ScrollViewer; Visual child = e.TargetObject as Visual; if (child != null) { //the event starts from the elemetn itself, so if it is an SV.BringINtoView we would //get an SV trying to bring into view itself - this does not work obviously //so don't handle if the request is about ourselves, the event will bubble if (child != sv && child.IsDescendantOf(sv)) { e.Handled = true; sv.MakeVisible(child, e.TargetRect); } } else { ContentElement contentElement = e.TargetObject as ContentElement; if (contentElement != null) { // We need to find the containing Visual and the bounding box for this element. IContentHost contentHost = ContentHostHelper.FindContentHost(contentElement); child = contentHost as Visual; if (child != null && child.IsDescendantOf(sv)) { ReadOnlyCollection<Rect> rects = contentHost.GetRectangles(contentElement); if (rects.Count > 0) { e.Handled = true; sv.MakeVisible(child, rects[0]); } } } } } private static void OnScrollCommand(object target, ExecutedRoutedEventArgs args) { if (args.Command == ScrollBar.DeferScrollToHorizontalOffsetCommand) { if (args.Parameter is double) { ((ScrollViewer)target).DeferScrollToHorizontalOffset((double)args.Parameter); } } else if (args.Command == ScrollBar.DeferScrollToVerticalOffsetCommand) { if (args.Parameter is double) { ((ScrollViewer)target).DeferScrollToVerticalOffset((double)args.Parameter); } } else if (args.Command == ScrollBar.LineLeftCommand) { ((ScrollViewer)target).LineLeft(); } else if (args.Command == ScrollBar.LineRightCommand) { ((ScrollViewer)target).LineRight(); } else if (args.Command == ScrollBar.PageLeftCommand) { ((ScrollViewer)target).PageLeft(); } else if (args.Command == ScrollBar.PageRightCommand) { ((ScrollViewer)target).PageRight(); } else if (args.Command == ScrollBar.LineUpCommand) { ((ScrollViewer)target).LineUp(); } else if (args.Command == ScrollBar.LineDownCommand) { ((ScrollViewer)target).LineDown(); } else if ( args.Command == ScrollBar.PageUpCommand || args.Command == ComponentCommands.ScrollPageUp ) { ((ScrollViewer)target).PageUp(); } else if ( args.Command == ScrollBar.PageDownCommand || args.Command == ComponentCommands.ScrollPageDown ) { ((ScrollViewer)target).PageDown(); } else if (args.Command == ScrollBar.ScrollToEndCommand) { ((ScrollViewer)target).ScrollToEnd(); } else if (args.Command == ScrollBar.ScrollToHomeCommand) { ((ScrollViewer)target).ScrollToHome(); } else if (args.Command == ScrollBar.ScrollToLeftEndCommand) { ((ScrollViewer)target).ScrollToLeftEnd(); } else if (args.Command == ScrollBar.ScrollToRightEndCommand) { ((ScrollViewer)target).ScrollToRightEnd(); } else if (args.Command == ScrollBar.ScrollToTopCommand) { ((ScrollViewer)target).ScrollToTop(); } else if (args.Command == ScrollBar.ScrollToBottomCommand) { ((ScrollViewer)target).ScrollToBottom(); } else if (args.Command == ScrollBar.ScrollToHorizontalOffsetCommand) { if (args.Parameter is double) { ((ScrollViewer)target).ScrollToHorizontalOffset((double)args.Parameter); } } else if (args.Command == ScrollBar.ScrollToVerticalOffsetCommand) { if (args.Parameter is double) { ((ScrollViewer)target).ScrollToVerticalOffset((double)args.Parameter); } } ScrollViewer sv = target as ScrollViewer; if (sv != null) { // If any of the ScrollBar scroll commands are raised while // scroll manipulation is in its inertia, then the manipualtion // should be completed. sv.CompleteScrollManipulation = true; } } private static void OnQueryScrollCommand(object target, CanExecuteRoutedEventArgs args) { args.CanExecute = true; // ScrollViewer is capable of execution of the majority of commands. // The only special case is the component commands below. // When scroll viewer is a primitive / part of another control // capable to handle scrolling - scroll viewer leaves it up // to the control to deal with component commands... if ( args.Command == ComponentCommands.ScrollPageUp || args.Command == ComponentCommands.ScrollPageDown ) { ScrollViewer scrollViewer = target as ScrollViewer; Control templatedParentControl = scrollViewer != null ? scrollViewer.TemplatedParent as Control : null; if ( templatedParentControl != null && templatedParentControl.HandlesScrolling ) { args.CanExecute = false; args.ContinueRouting = true; // It is important to handle this event to prevent any // other ScrollViewers in the ancestry from claiming it. args.Handled = true; } } else if ((args.Command == ScrollBar.DeferScrollToHorizontalOffsetCommand) || (args.Command == ScrollBar.DeferScrollToVerticalOffsetCommand)) { // The scroll bar has indicated that a drag operation is in progress. // If deferred scrolling is disabled, then mark the command as // not executable so that the scroll bar will fire the regular scroll // command, and the scroll viewer will do live scrolling. ScrollViewer scrollViewer = target as ScrollViewer; if ((scrollViewer != null) && !scrollViewer.IsDeferredScrollingEnabled) { args.CanExecute = false; // It is important to handle this event to prevent any // other ScrollViewers in the ancestry from claiming it. args.Handled = true; } } } private static void InitializeCommands() { ExecutedRoutedEventHandler executeScrollCommandEventHandler = new ExecutedRoutedEventHandler(OnScrollCommand); CanExecuteRoutedEventHandler canExecuteScrollCommandEventHandler = new CanExecuteRoutedEventHandler(OnQueryScrollCommand); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.LineLeftCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.LineRightCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.PageLeftCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.PageRightCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.LineUpCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.LineDownCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.PageUpCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.PageDownCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.ScrollToLeftEndCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.ScrollToRightEndCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.ScrollToEndCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.ScrollToHomeCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.ScrollToTopCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.ScrollToBottomCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.ScrollToHorizontalOffsetCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.ScrollToVerticalOffsetCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.DeferScrollToHorizontalOffsetCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ScrollBar.DeferScrollToVerticalOffsetCommand, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ComponentCommands.ScrollPageUp, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); CommandHelpers.RegisterCommandHandler(typeof(ScrollViewer), ComponentCommands.ScrollPageDown, executeScrollCommandEventHandler, canExecuteScrollCommandEventHandler); } // Creates the default control template for ScrollViewer. private static ControlTemplate CreateDefaultControlTemplate() { ControlTemplate template = null; // Our default style is a 2x2 grid: // <Grid Columns="*,Auto" Rows="*,Auto"> // Grid // <ColumnDefinition Width="*" /> // <ColumnDefinition Width="Auto" /> // <RowDefinition Height="*" /> // <RowDefinition Height="Auto" /> // <Border> // Cell 1-2, 1-2 // <ScrollContentPresenter /> // </Border> // <VerticalScrollBar /> // Cell 1, 2 // <HorizontalScrollBar /> // Cell 2, 1 // </Grid> FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid), "Grid"); FrameworkElementFactory gridColumn1 = new FrameworkElementFactory(typeof(ColumnDefinition), "ColumnDefinitionOne"); FrameworkElementFactory gridColumn2 = new FrameworkElementFactory(typeof(ColumnDefinition), "ColumnDefinitionTwo"); FrameworkElementFactory gridRow1 = new FrameworkElementFactory(typeof(RowDefinition), "RowDefinitionOne"); FrameworkElementFactory gridRow2 = new FrameworkElementFactory(typeof(RowDefinition), "RowDefinitionTwo"); FrameworkElementFactory vsb = new FrameworkElementFactory(typeof(ScrollBar), VerticalScrollBarTemplateName); FrameworkElementFactory hsb = new FrameworkElementFactory(typeof(ScrollBar), HorizontalScrollBarTemplateName); FrameworkElementFactory content = new FrameworkElementFactory(typeof(ScrollContentPresenter), ScrollContentPresenterTemplateName); FrameworkElementFactory corner = new FrameworkElementFactory(typeof(Rectangle), "Corner"); // Bind Actual HorizontalOffset to HorizontalScrollBar.Value // Bind Actual VerticalOffset to VerticalScrollbar.Value Binding bindingHorizontalOffset = new Binding("HorizontalOffset"); bindingHorizontalOffset.Mode = BindingMode.OneWay; bindingHorizontalOffset.RelativeSource = RelativeSource.TemplatedParent; Binding bindingVerticalOffset = new Binding("VerticalOffset"); bindingVerticalOffset.Mode = BindingMode.OneWay; bindingVerticalOffset.RelativeSource = RelativeSource.TemplatedParent; grid.SetValue(Grid.BackgroundProperty, new TemplateBindingExtension(BackgroundProperty)); grid.AppendChild(gridColumn1); grid.AppendChild(gridColumn2); grid.AppendChild(gridRow1); grid.AppendChild(gridRow2); grid.AppendChild(corner); grid.AppendChild(content); grid.AppendChild(vsb); grid.AppendChild(hsb); gridColumn1.SetValue(ColumnDefinition.WidthProperty, new GridLength(1.0, GridUnitType.Star)); gridColumn2.SetValue(ColumnDefinition.WidthProperty, new GridLength(1.0, GridUnitType.Auto)); gridRow1.SetValue(RowDefinition.HeightProperty, new GridLength(1.0, GridUnitType.Star)); gridRow2.SetValue(RowDefinition.HeightProperty, new GridLength(1.0, GridUnitType.Auto)); content.SetValue(Grid.ColumnProperty, 0); content.SetValue(Grid.RowProperty, 0); content.SetValue(ContentPresenter.MarginProperty, new TemplateBindingExtension(PaddingProperty)); content.SetValue(ContentProperty, new TemplateBindingExtension(ContentProperty)); content.SetValue(ContentTemplateProperty, new TemplateBindingExtension(ContentTemplateProperty)); content.SetValue(CanContentScrollProperty, new TemplateBindingExtension(CanContentScrollProperty)); hsb.SetValue(ScrollBar.OrientationProperty, Orientation.Horizontal); hsb.SetValue(Grid.ColumnProperty, 0); hsb.SetValue(Grid.RowProperty, 1); hsb.SetValue(RangeBase.MinimumProperty, 0.0); hsb.SetValue(RangeBase.MaximumProperty, new TemplateBindingExtension(ScrollableWidthProperty)); hsb.SetValue(ScrollBar.ViewportSizeProperty, new TemplateBindingExtension(ViewportWidthProperty)); hsb.SetBinding(RangeBase.ValueProperty, bindingHorizontalOffset); hsb.SetValue(UIElement.VisibilityProperty, new TemplateBindingExtension(ComputedHorizontalScrollBarVisibilityProperty)); hsb.SetValue(FrameworkElement.CursorProperty, Cursors.Arrow); hsb.SetValue(AutomationProperties.AutomationIdProperty, "HorizontalScrollBar"); vsb.SetValue(Grid.ColumnProperty, 1); vsb.SetValue(Grid.RowProperty, 0); vsb.SetValue(RangeBase.MinimumProperty, 0.0); vsb.SetValue(RangeBase.MaximumProperty, new TemplateBindingExtension(ScrollableHeightProperty)); vsb.SetValue(ScrollBar.ViewportSizeProperty, new TemplateBindingExtension(ViewportHeightProperty)); vsb.SetBinding(RangeBase.ValueProperty, bindingVerticalOffset); vsb.SetValue(UIElement.VisibilityProperty, new TemplateBindingExtension(ComputedVerticalScrollBarVisibilityProperty)); vsb.SetValue(FrameworkElement.CursorProperty, Cursors.Arrow); vsb.SetValue(AutomationProperties.AutomationIdProperty, "VerticalScrollBar"); corner.SetValue(Grid.ColumnProperty, 1); corner.SetValue(Grid.RowProperty, 1); corner.SetResourceReference(Rectangle.FillProperty, SystemColors.ControlBrushKey); template = new ControlTemplate(typeof(ScrollViewer)); template.VisualTree = grid; template.Seal(); return (template); } [Flags] private enum Flags { None = 0x0000, InvalidatedMeasureFromArrange = 0x0001, InChildInvalidateMeasure = 0x0002, HandlesMouseWheelScrolling = 0x0004, ForceNextManipulationComplete = 0x0008, ManipulationBindingsInitialized = 0x0010, CompleteScrollManipulation = 0x0020, InChildMeasurePass1 = 0x0040, InChildMeasurePass2 = 0x0080, InChildMeasurePass3 = 0x00C0, } private void SetFlagValue(Flags flag, bool value) { if (value) { _flags |= flag; } else { _flags &= ~flag; } } private bool InvalidatedMeasureFromArrange { get { return ((_flags & Flags.InvalidatedMeasureFromArrange) == Flags.InvalidatedMeasureFromArrange); } set { SetFlagValue(Flags.InvalidatedMeasureFromArrange, value); } } private bool ForceNextManipulationComplete { get { return ((_flags & Flags.ForceNextManipulationComplete) == Flags.ForceNextManipulationComplete); } set { SetFlagValue(Flags.ForceNextManipulationComplete, value); } } private bool ManipulationBindingsInitialized { get { return ((_flags & Flags.ManipulationBindingsInitialized) == Flags.ManipulationBindingsInitialized); } set { SetFlagValue(Flags.ManipulationBindingsInitialized, value); } } private bool CompleteScrollManipulation { get { return ((_flags & Flags.CompleteScrollManipulation) == Flags.CompleteScrollManipulation); } set { SetFlagValue(Flags.CompleteScrollManipulation, value); } } internal bool InChildMeasurePass1 { get { return ((_flags & Flags.InChildMeasurePass1) == Flags.InChildMeasurePass1); } set { SetFlagValue(Flags.InChildMeasurePass1, value); } } internal bool InChildMeasurePass2 { get { return ((_flags & Flags.InChildMeasurePass2) == Flags.InChildMeasurePass2); } set { SetFlagValue(Flags.InChildMeasurePass2, value); } } internal bool InChildMeasurePass3 { get { return ((_flags & Flags.InChildMeasurePass3) == Flags.InChildMeasurePass3); } set { SetFlagValue(Flags.InChildMeasurePass3, value); } } #endregion //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private Fields // DevDiv:1139804 // Tracks if the current main input to the ScrollViewer result in a Tap gesture private bool _seenTapGesture = false; // Scrolling physical "line" metrics. internal const double _scrollLineDelta = 16.0; // Default physical amount to scroll with one Up/Down/Left/Right key internal const double _mouseWheelDelta = 48.0; // Default physical amount to scroll with one MouseWheel. private const string HorizontalScrollBarTemplateName = "PART_HorizontalScrollBar"; private const string VerticalScrollBarTemplateName = "PART_VerticalScrollBar"; internal const string ScrollContentPresenterTemplateName = "PART_ScrollContentPresenter"; // Property caching private Visibility _scrollVisibilityX; private Visibility _scrollVisibilityY; // Scroll property values - cache of what was computed by ISI private double _xPositionISI; private double _yPositionISI; private double _xExtent; private double _yExtent; private double _xSize; private double _ySize; // Event/infrastructure private EventHandler _layoutUpdatedHandler; private IScrollInfo _scrollInfo; private CommandQueue _queue; private PanningInfo _panningInfo = null; private Flags _flags = Flags.HandlesMouseWheelScrolling; #endregion //------------------------------------------------------------------- // // Static Constructors & Delegates // //------------------------------------------------------------------- #region Static Constructors & Delegates static ScrollViewer() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ScrollViewer), new FrameworkPropertyMetadata(typeof(ScrollViewer))); _dType = DependencyObjectType.FromSystemTypeInternal(typeof(ScrollViewer)); InitializeCommands(); ControlTemplate template = CreateDefaultControlTemplate(); Control.TemplateProperty.OverrideMetadata(typeof(ScrollViewer), new FrameworkPropertyMetadata(template)); IsTabStopProperty.OverrideMetadata(typeof(ScrollViewer), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(ScrollViewer), new FrameworkPropertyMetadata(KeyboardNavigationMode.Local)); EventManager.RegisterClassHandler(typeof(ScrollViewer), RequestBringIntoViewEvent, new RequestBringIntoViewEventHandler(OnRequestBringIntoView)); ControlsTraceLogger.AddControl(TelemetryControls.ScrollViewer); } private static bool IsValidScrollBarVisibility(object o) { ScrollBarVisibility value = (ScrollBarVisibility)o; return (value == ScrollBarVisibility.Disabled || value == ScrollBarVisibility.Auto || value == ScrollBarVisibility.Hidden || value == ScrollBarVisibility.Visible); } // // This property // 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject // 2. This is a performance optimization // internal override int EffectiveValuesInitialSize { get { return 28; } } #endregion #region DTypeThemeStyleKey // Returns the DependencyObjectType for the registered ThemeStyleKey's default // value. Controls will override this method to return approriate types. internal override DependencyObjectType DTypeThemeStyleKey { get { return _dType; } } private static DependencyObjectType _dType; #endregion DTypeThemeStyleKey } }
41.998667
243
0.552954
[ "MIT" ]
56hide/wpf
src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/ScrollViewer.cs
125,996
C#
using System.Diagnostics; namespace DeepSleep { /// <summary> /// /// </summary> [DebuggerDisplay("{ToString()}")] public class MediaHeaderValueWithParameters { /// <summary> /// Initializes a new instance of the <see cref="MediaHeaderValueWithParameters"/> class. /// </summary> /// <param name="value">The value.</param> public MediaHeaderValueWithParameters(string value) { Value = value; MediaValue = value.GetMediaHeaderWithParameters(); } /// <summary>Gets the value.</summary> /// <value>The value.</value> public string Value { get; private set; } /// <summary>Gets the values.</summary> /// <value>The values.</value> protected MediaValueWithParameters MediaValue { get; private set; } } }
28.666667
97
0.587209
[ "MIT" ]
mtnvencenzo/DeepSleep
src/DeepSleep/MediaHeaderValueWithParameters.cs
862
C#
using System; using SharpDX; namespace DXFramework.Util { public static class MathHelper { private const float INV_TWOPI = 1f / MathUtil.TwoPi; /// <summary> /// Returns the revolutions [0..1] between a current- and target position, form a facing angle. /// </summary> /// <param name="position">Current position.</param> /// <param name="target">Target position.</param> /// <param name="facingRadians">Current position facing radians.</param> public static float RevolutionsToTarget(Vector2 position, Vector2 target, Vector2 facingRadians) { return RadiansToTarget(position, target, facingRadians) * INV_TWOPI; } /// <summary> /// Returns the radians between a current- and target position, form a facing angle. /// </summary> /// <param name="position">Current position.</param> /// <param name="target">Target position.</param> /// <param name="facingRadians">Current position facing radians.</param> public static float RadiansToTarget(Vector2 position, Vector2 target, Vector2 facingRadians) { Vector2 rightAngle = Vector2.Zero; rightAngle.X = -facingRadians.Y; rightAngle.Y = facingRadians.X; Vector2 diff = target - position; float dot1; float dot2; Vector2.Dot(ref facingRadians, ref diff, out dot1); Vector2.Dot(ref rightAngle, ref diff, out dot2); return (float)Math.Atan2(dot2, dot1); } /// <summary> /// Warps an angle between 0 and TwoPI (6.28319). /// NOTE: Single-pass. Values below -(2 * TwoPI) or above (2 * TwoPI) will not be correctly warped. /// </summary> /// <param name="radians">Radians to warp.</param> public static float WarpAngle(float radians) { if (radians > MathUtil.TwoPi) { radians -= MathUtil.TwoPi; } else if (radians < 0) { radians += MathUtil.TwoPi; } return radians; } public static float Warp(float value, float min, float max) { while (value > max) { value -= max - min; } while (value < min) { value += max - min; } return value; } public static string RoundString(double value, int decimals = 2) { return Math.Round(value, decimals, MidpointRounding.AwayFromZero).ToString("0.".PadRight(2 + decimals, '0')); } } }
28.525641
112
0.67236
[ "MIT" ]
adamxi/SharpDXFramework
DXFramework/Util/MathHelper.cs
2,227
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using NuGet.Common; namespace NuGet.Configuration { /// <summary> /// Concrete implementation of ISettings to support NuGet Settings /// Wrapper for computed settings from given settings files /// </summary> public class Settings : ISettings { /// <summary> /// Default file name for a settings file is 'NuGet.config' /// Also, the user level setting file at '%APPDATA%\NuGet' always uses this name /// </summary> public static readonly string DefaultSettingsFileName = "NuGet.Config"; /// <summary> /// NuGet config names with casing ordered by precedence. /// </summary> public static readonly string[] OrderedSettingsFileNames = PathUtility.IsFileSystemCaseInsensitive ? new[] { DefaultSettingsFileName } : new[] { "nuget.config", // preferred style "NuGet.config", // Alternative DefaultSettingsFileName // NuGet v2 style }; public static readonly string[] SupportedMachineWideConfigExtension = RuntimeEnvironmentHelper.IsWindows ? new[] { "*.config" } : new[] { "*.Config", "*.config" }; private readonly SettingsFile _settingsHead; private readonly Dictionary<string, VirtualSettingSection> _computedSections; public SettingSection GetSection(string sectionName) { if (_computedSections.TryGetValue(sectionName, out var section)) { return section.Clone() as SettingSection; } return null; } public void AddOrUpdate(string sectionName, SettingItem item) { if (string.IsNullOrEmpty(sectionName)) { throw new ArgumentException(Resources.Argument_Cannot_Be_Null_Or_Empty, nameof(sectionName)); } if (item == null) { throw new ArgumentNullException(nameof(item)); } // Operation is an update if (_computedSections.TryGetValue(sectionName, out var section) && section.Items.Contains(item)) { // An update could not be possible here because the operation might be // in a machine wide config. If so then we want to add the item to // the output config. if (section.Update(item)) { return; } } // Operation is an add var outputSettingsFile = GetOutputSettingFileForSection(sectionName); if (outputSettingsFile == null) { throw new InvalidOperationException(Resources.NoWritteableConfig); } AddOrUpdate(outputSettingsFile, sectionName, item); } internal void AddOrUpdate(SettingsFile settingsFile, string sectionName, SettingItem item) { if (string.IsNullOrEmpty(sectionName)) { throw new ArgumentException(Resources.Argument_Cannot_Be_Null_Or_Empty, nameof(sectionName)); } if (item == null) { throw new ArgumentNullException(nameof(item)); } var currentSettings = Priority.Last(f => f.Equals(settingsFile)); if (settingsFile.IsMachineWide || (currentSettings?.IsMachineWide ?? false)) { throw new InvalidOperationException(Resources.CannotUpdateMachineWide); } if (currentSettings == null) { Priority.First().SetNextFile(settingsFile); } // If it is an update this will take care of it and modify the underlaying object, which is also referenced by _computedSections. settingsFile.AddOrUpdate(sectionName, item); // AddOrUpdate should have created this section, therefore this should always exist. settingsFile.TryGetSection(sectionName, out var settingFileSection); // If it is an add we have to manually add it to the _computedSections. var computedSectionExists = _computedSections.TryGetValue(sectionName, out var section); if (computedSectionExists && !section.Items.Contains(item)) { var existingItem = settingFileSection.Items.First(i => i.Equals(item)); section.Add(existingItem); } else if (!computedSectionExists) { _computedSections.Add(sectionName, new VirtualSettingSection(settingFileSection)); } } public void Remove(string sectionName, SettingItem item) { if (string.IsNullOrEmpty(sectionName)) { throw new ArgumentException(Resources.Argument_Cannot_Be_Null_Or_Empty, nameof(sectionName)); } if (item == null) { throw new ArgumentNullException(nameof(item)); } if (!_computedSections.TryGetValue(sectionName, out var section)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.SectionDoesNotExist, sectionName)); } if (!section.Items.Contains(item)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ItemDoesNotExist, sectionName)); } section.Remove(item); if (section.IsEmpty()) { _computedSections.Remove(sectionName); } } public event EventHandler SettingsChanged = delegate { }; public Settings(string root) : this(new SettingsFile(root)) { } public Settings(string root, string fileName) : this(new SettingsFile(root, fileName)) { } public Settings(string root, string fileName, bool isMachineWide) : this(new SettingsFile(root, fileName, isMachineWide)) { } internal Settings(SettingsFile settingsHead) { _settingsHead = settingsHead; var computedSections = new Dictionary<string, VirtualSettingSection>(); var curr = _settingsHead; while (curr != null) { curr.MergeSectionsInto(computedSections); curr = curr.Next; } _computedSections = computedSections; } private SettingsFile GetOutputSettingFileForSection(string sectionName) { // Search for the furthest from the user that can be written // to that is not clearing the ones before it on the hierarchy var writteableSettingsFiles = Priority.Where(f => !f.IsMachineWide); var clearedSections = writteableSettingsFiles.Select(f => { if(f.TryGetSection(sectionName, out var section)) { return section; } return null; }).Where(s => s != null && s.Items.Contains(new ClearItem())); if (clearedSections.Any()) { return clearedSections.First().Origin; } // if none have a clear tag, default to furthest from the user return writteableSettingsFiles.LastOrDefault(); } /// <summary> /// Enumerates the sequence of <see cref="SettingsFile"/> instances /// ordered from closer to user to further /// </summary> internal IEnumerable<SettingsFile> Priority { get { // explore the linked list, terminating when a duplicate path is found var current = _settingsHead; var found = new List<SettingsFile>(); var paths = new HashSet<string>(); while (current != null && paths.Add(current.ConfigFilePath)) { found.Add(current); current = current.Next; } return found .OrderByDescending(s => s.Priority); } } public void SaveToDisk() { foreach(var settingsFile in Priority) { settingsFile.SaveToDisk(); } SettingsChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Load default settings based on a directory. /// This includes machine wide settings. /// </summary> public static ISettings LoadDefaultSettings(string root) { return LoadSettings( root, configFileName: null, machineWideSettings: new XPlatMachineWideSetting(), loadUserWideSettings: true, useTestingGlobalPath: false); } /// <summary> /// Loads user settings from the NuGet configuration files. The method walks the directory /// tree in <paramref name="root" /> up to its root, and reads each NuGet.config file /// it finds in the directories. It then reads the user specific settings, /// which is file <paramref name="configFileName" /> /// in <paramref name="root" /> if <paramref name="configFileName" /> is not null, /// If <paramref name="configFileName" /> is null, the user specific settings file is /// %AppData%\NuGet\NuGet.config. /// After that, the machine wide settings files are added. /// </summary> /// <remarks> /// For example, if <paramref name="root" /> is c:\dir1\dir2, <paramref name="configFileName" /> /// is "userConfig.file", the files loaded are (in the order that they are loaded): /// c:\dir1\dir2\nuget.config /// c:\dir1\nuget.config /// c:\nuget.config /// c:\dir1\dir2\userConfig.file /// machine wide settings (e.g. c:\programdata\NuGet\Config\*.config) /// </remarks> /// <param name="root"> /// The file system to walk to find configuration files. /// Can be null. /// </param> /// <param name="configFileName">The user specified configuration file.</param> /// <param name="machineWideSettings"> /// The machine wide settings. If it's not null, the /// settings files in the machine wide settings are added after the user specific /// config file. /// </param> /// <returns>The settings object loaded.</returns> public static ISettings LoadDefaultSettings( string root, string configFileName, IMachineWideSettings machineWideSettings) { return LoadSettings( root, configFileName, machineWideSettings, loadUserWideSettings: true, useTestingGlobalPath: false); } /// <summary> /// Loads Specific NuGet.Config file. The method only loads specific config file /// which is file <paramref name="configFileName"/>from <paramref name="root"/>. /// </summary> public static ISettings LoadSpecificSettings(string root, string configFileName) { if (string.IsNullOrEmpty(configFileName)) { throw new ArgumentException(Resources.Argument_Cannot_Be_Null_Or_Empty, nameof(configFileName)); } return LoadSettings( root, configFileName, machineWideSettings: null, loadUserWideSettings: true, useTestingGlobalPath: false); } public static ISettings LoadSettingsGivenConfigPaths(IList<string> configFilePaths) { var settings = new List<SettingsFile>(); if (configFilePaths == null || configFilePaths.Count == 0) { return NullSettings.Instance; } foreach (var configFile in configFilePaths) { var file = new FileInfo(configFile); settings.Add(new SettingsFile(file.DirectoryName, file.Name)); } return LoadSettingsForSpecificConfigs( settings.First().DirectoryPath, settings.First().FileName, validSettingFiles: settings, machineWideSettings: null, loadUserWideSettings: false, useTestingGlobalPath: false); } /// <summary> /// For internal use only /// </summary> internal static ISettings LoadSettings( string root, string configFileName, IMachineWideSettings machineWideSettings, bool loadUserWideSettings, bool useTestingGlobalPath) { // Walk up the tree to find a config file; also look in .nuget subdirectories // If a configFile is passed, don't walk up the tree. Only use that single config file. var validSettingFiles = new List<SettingsFile>(); if (root != null && string.IsNullOrEmpty(configFileName)) { validSettingFiles.AddRange( GetSettingsFilesFullPath(root) .Select(f => ReadSettings(root, f)) .Where(f => f != null)); } return LoadSettingsForSpecificConfigs( root, configFileName, validSettingFiles, machineWideSettings, loadUserWideSettings, useTestingGlobalPath); } /// <summary> /// For internal use only. /// Finds and loads all configuration files within <paramref name="root" />. /// Does not load configuration files outside of <paramref name="root" />. /// </summary> internal static ISettings LoadSettings( DirectoryInfo root, IMachineWideSettings machineWideSettings, bool loadUserWideSettings, bool useTestingGlobalPath) { var validSettingFiles = new List<SettingsFile>(); var comparer = PathUtility.GetStringComparisonBasedOnOS(); var settingsFiles = root.GetFileSystemInfos("*.*", SearchOption.AllDirectories) .OfType<FileInfo>() .OrderByDescending(file => file.FullName.Count(c => c == Path.DirectorySeparatorChar)) .Where(file => OrderedSettingsFileNames.Any(fileName => fileName.Equals(file.Name, comparer))); validSettingFiles.AddRange( settingsFiles .Select(file => ReadSettings(file.DirectoryName, file.FullName)) .Where(file => file != null)); return LoadSettingsForSpecificConfigs( root.FullName, configFileName: null, validSettingFiles, machineWideSettings, loadUserWideSettings, useTestingGlobalPath); } private static ISettings LoadSettingsForSpecificConfigs( string root, string configFileName, List<SettingsFile> validSettingFiles, IMachineWideSettings machineWideSettings, bool loadUserWideSettings, bool useTestingGlobalPath) { if (loadUserWideSettings) { var userSpecific = LoadUserSpecificSettings(root, configFileName, useTestingGlobalPath); if (userSpecific != null) { validSettingFiles.Add(userSpecific); } } if (machineWideSettings != null && machineWideSettings.Settings is Settings mwSettings && string.IsNullOrEmpty(configFileName)) { // Priority gives you the settings file in the order you want to start reading them validSettingFiles.AddRange( mwSettings.Priority.Select( s => new SettingsFile(s.DirectoryPath, s.FileName, s.IsMachineWide))); } if (validSettingFiles?.Any() != true) { // This means we've failed to load all config files and also failed to load or create the one in %AppData% // Work Item 1531: If the config file is malformed and the constructor throws, NuGet fails to load in VS. // Returning a null instance prevents us from silently failing and also from picking up the wrong config return NullSettings.Instance; } SettingsFile.ConnectSettingsFilesLinkedList(validSettingFiles); // Create a settings object with the linked list head. Typically, it's either the config file in %ProgramData%\NuGet\Config, // or the user wide config (%APPDATA%\NuGet\nuget.config) if there are no machine // wide config files. The head file is the one we want to read first, while the user wide config // is the one that we want to write to. // TODO: add UI to allow specifying which one to write to return new Settings(validSettingFiles.Last()); } private static SettingsFile LoadUserSpecificSettings( string root, string configFileName, bool useTestingGlobalPath) { // Path.Combine is performed with root so it should not be null // However, it is legal for it be empty in this method var rootDirectory = root ?? string.Empty; // for the default location, allow case where file does not exist, in which case it'll end // up being created if needed SettingsFile userSpecificSettings = null; if (configFileName == null) { var defaultSettingsFilePath = string.Empty; if (useTestingGlobalPath) { defaultSettingsFilePath = Path.Combine(rootDirectory, "TestingGlobalPath", DefaultSettingsFileName); } else { var userSettingsDir = NuGetEnvironment.GetFolderPath(NuGetFolderPath.UserSettingsDirectory); // If there is no user settings directory, return no settings if (userSettingsDir == null) { return null; } defaultSettingsFilePath = Path.Combine(userSettingsDir, DefaultSettingsFileName); } userSpecificSettings = ReadSettings(rootDirectory, defaultSettingsFilePath); if (File.Exists(defaultSettingsFilePath) && userSpecificSettings.IsEmpty()) { var trackFilePath = Path.Combine(Path.GetDirectoryName(defaultSettingsFilePath), NuGetConstants.AddV3TrackFile); if (!File.Exists(trackFilePath)) { File.Create(trackFilePath).Dispose(); var defaultSource = new SourceItem(NuGetConstants.FeedName, NuGetConstants.V3FeedUrl, protocolVersion: "3"); userSpecificSettings.AddOrUpdate(ConfigurationConstants.PackageSources, defaultSource); userSpecificSettings.SaveToDisk(); } } } else { if (!FileSystemUtility.DoesFileExistIn(rootDirectory, configFileName)) { var message = string.Format(CultureInfo.CurrentCulture, Resources.FileDoesNotExist, Path.Combine(rootDirectory, configFileName)); throw new InvalidOperationException(message); } userSpecificSettings = ReadSettings(rootDirectory, configFileName); } return userSpecificSettings; } /// <summary> /// Loads the machine wide settings. /// </summary> /// <remarks> /// For example, if <paramref name="paths" /> is {"IDE", "Version", "SKU" }, then /// the files loaded are (in the order that they are loaded): /// %programdata%\NuGet\Config\IDE\Version\SKU\*.config /// %programdata%\NuGet\Config\IDE\Version\*.config /// %programdata%\NuGet\Config\IDE\*.config /// %programdata%\NuGet\Config\*.config /// </remarks> /// <param name="root">The file system in which the settings files are read.</param> /// <param name="paths">The additional paths under which to look for settings files.</param> /// <returns>The list of settings read.</returns> public static ISettings LoadMachineWideSettings( string root, params string[] paths) { if (string.IsNullOrEmpty(root)) { throw new ArgumentException("root cannot be null or empty"); } var settingFiles = new List<SettingsFile>(); var combinedPath = Path.Combine(paths); while (true) { // load setting files in directory foreach (var file in FileSystemUtility.GetFilesRelativeToRoot(root, combinedPath, SupportedMachineWideConfigExtension, SearchOption.TopDirectoryOnly)) { var settings = ReadSettings(root, file, isMachineWideSettings: true); if (settings != null) { settingFiles.Add(settings); } } if (combinedPath.Length == 0) { break; } var index = combinedPath.LastIndexOf(Path.DirectorySeparatorChar); if (index < 0) { index = 0; } combinedPath = combinedPath.Substring(0, index); } if (settingFiles.Any()) { SettingsFile.ConnectSettingsFilesLinkedList(settingFiles); return new Settings(settingFiles.Last()); } return NullSettings.Instance; } public static string ApplyEnvironmentTransform(string value) { if (string.IsNullOrEmpty(value)) { return value; } return Environment.ExpandEnvironmentVariables(value); } public static Tuple<string, string> GetFileNameAndItsRoot(string root, string settingsPath) { string fileName = null; string directory = null; if (Path.IsPathRooted(settingsPath)) { fileName = Path.GetFileName(settingsPath); directory = Path.GetDirectoryName(settingsPath); } else if (!FileSystemUtility.IsPathAFile(settingsPath)) { var fullPath = Path.Combine(root ?? string.Empty, settingsPath); fileName = Path.GetFileName(fullPath); directory = Path.GetDirectoryName(fullPath); } else { fileName = settingsPath; directory = root; } return new Tuple<string, string>(fileName, directory); } /// <summary> /// Get a list of all the paths of the settings files used as part of this settings object /// </summary> public IList<string> GetConfigFilePaths() { return Priority.Select(config => Path.GetFullPath(Path.Combine(config.DirectoryPath, config.FileName))).ToList(); } /// <summary> /// Get a list of all the roots of the settings files used as part of this settings object /// </summary> public IList<string> GetConfigRoots() { return Priority.Select(config => config.DirectoryPath).Distinct().ToList(); } internal static string ResolvePathFromOrigin(string originDirectoryPath, string originFilePath, string path) { if (Uri.TryCreate(path, UriKind.Relative, out var _) && !string.IsNullOrEmpty(originDirectoryPath) && !string.IsNullOrEmpty(originFilePath)) { return ResolveRelativePath(originDirectoryPath, originFilePath, path); } return path; } private static string ResolveRelativePath(string originDirectoryPath, string originFilePath, string path) { if (string.IsNullOrEmpty(originDirectoryPath) || string.IsNullOrEmpty(originFilePath)) { return null; } if (string.IsNullOrEmpty(path)) { return path; } return Path.Combine(originDirectoryPath, ResolvePath(Path.GetDirectoryName(originFilePath), path)); } private static string ResolvePath(string configDirectory, string value) { // Three cases for when Path.IsRooted(value) is true: // 1- C:\folder\file // 2- \\share\folder\file // 3- \folder\file // In the first two cases, we want to honor the fully qualified path // In the last case, we want to return X:\folder\file with X: drive where config file is located. // However, Path.Combine(path1, path2) always returns path2 when Path.IsRooted(path2) == true (which is current case) string root; try { root = Path.GetPathRoot(value); } catch (ArgumentException ex) { throw new NuGetConfigurationException( string.Format( CultureInfo.CurrentCulture, Resources.ShowError_ConfigHasInvalidPackageSource, NuGetLogCode.NU1006, value, ex.Message), ex); } // this corresponds to 3rd case if (root != null && root.Length == 1 && (root[0] == Path.DirectorySeparatorChar || value[0] == Path.AltDirectorySeparatorChar)) { return Path.Combine(Path.GetPathRoot(configDirectory), value.Substring(1)); } return Path.Combine(configDirectory, value); } private static SettingsFile ReadSettings(string settingsRoot, string settingsPath, bool isMachineWideSettings = false) { try { var tuple = GetFileNameAndItsRoot(settingsRoot, settingsPath); var filename = tuple.Item1; var root = tuple.Item2; return new SettingsFile(root, filename, isMachineWideSettings); } catch (XmlException) { return null; } } /// <remarks> /// Order is most significant (e.g. applied last) to least significant (applied first) /// ex: /// c:\someLocation\nuget.config /// c:\nuget.config /// </remarks> private static IEnumerable<string> GetSettingsFilesFullPath(string root) { // for dirs obtained by walking up the tree, only consider setting files that already exist. // otherwise we'd end up creating them. foreach (var dir in GetSettingsFilePaths(root)) { var fileName = GetSettingsFileNameFromDir(dir); if (fileName != null) { yield return fileName; } } yield break; } /// <summary> /// Checks for each possible casing of nuget.config in the directory. The first match is /// returned. If there are no nuget.config files null is returned. /// </summary> /// <remarks>For windows <see cref="OrderedSettingsFileNames"/> contains a single casing since /// the file system is case insensitive.</remarks> private static string GetSettingsFileNameFromDir(string directory) { foreach (var nugetConfigCasing in OrderedSettingsFileNames) { var file = Path.Combine(directory, nugetConfigCasing); if (File.Exists(file)) { return file; } } return null; } private static IEnumerable<string> GetSettingsFilePaths(string root) { while (root != null) { yield return root; root = Path.GetDirectoryName(root); } yield break; } } }
38.87963
166
0.562209
[ "Apache-2.0" ]
JetBrains/NuGet.Client
src/NuGet.Core/NuGet.Configuration/Settings/Settings.cs
29,393
C#
namespace _01_03.Student { public enum Speciality { Telecommunications, Marketing, Business, Entrepreneurship, Phisics, Mathematics, Informatics, Law, Philosophy } }
16.1875
28
0.521236
[ "MIT" ]
kaizer04/Telerik-Academy-2013-2014
OOP/Common-Type-System-Homework/01-03. Student/Speciality.cs
261
C#
//========= Copyright 2018, Sam Tague, All rights reserved. =================== // // Collection of useful static methods // //===================Contact Email: Sam@MassGames.co.uk=========================== using UnityEngine; using System.Collections; namespace VRInteraction { public class VRUtils : MonoBehaviour { public static Vector3 ClosestPointOnLine(Vector3 startPoint, Vector3 endPoint, Vector3 tPoint) { Vector3 startPointTotPointVector = tPoint - startPoint; Vector3 startPointToEndPointVector = (endPoint - startPoint).normalized; float d = Vector3.Distance(startPoint, endPoint); float t = Vector3.Dot(startPointToEndPointVector, startPointTotPointVector); if (t <= 0) return startPoint; if (t >= d) return endPoint; Vector3 distanceAlongVector = startPointToEndPointVector * t; Vector3 closestPoint = startPoint + distanceAlongVector; return closestPoint; } public static float TPositionBetweenPoints(Vector3 startPoint, Vector3 endPoint, Vector3 tPoint) { Vector3 startPointTotPointVector = tPoint - startPoint; Vector3 startPointToEndPointVector = (endPoint - startPoint).normalized; float d = Vector3.Distance(startPoint, endPoint); float tDist = Vector3.Distance(startPoint, tPoint); float t = Vector3.Dot(startPointToEndPointVector, startPointTotPointVector); float tPos = tDist / d; if (t <= 0f || tPos <= 0f) return 0f; if (t >= d || tPos >= 1f) return 1f; return tPos; } public static T CopyComponent<T>(T original, GameObject destination) where T : Component { System.Type type = original.GetType(); Component copy = destination.AddComponent(type); System.Reflection.FieldInfo[] fields = type.GetFields(); foreach (System.Reflection.FieldInfo field in fields) { field.SetValue(copy, field.GetValue(original)); } return copy as T; } public static Vector3 GetConeDirection(Vector3 originalDirection, float coneSize) { // random tilt around the up axis Quaternion randomTilt = Quaternion.AngleAxis(Random.Range(0f, coneSize), Vector3.up); // random spin around the forward axis Quaternion randomSpin = Quaternion.AngleAxis(Random.Range(0f, 360f), originalDirection); // tilt then spin Quaternion tiltSpin = (randomSpin * randomTilt); // fire in direction with offset Vector3 coneDirection = (tiltSpin * originalDirection).normalized; return coneDirection; } public static bool PositionWithinCone(Vector3 startPosition, Vector3 direction, Vector3 targetPosition, float coneSize, float distance) { if (Vector3.Distance(startPosition, targetPosition) > distance) return false; float cone = Mathf.Cos(coneSize*Mathf.Deg2Rad); Vector3 heading = (startPosition - targetPosition).normalized; float dot = Vector3.Dot(-direction.normalized, heading); return dot > cone; } public enum BlendMode { Opaque, Cutout, Fade, Transparent } public static void ChangeRenderMode(Material standardShaderMaterial, BlendMode blendMode) { switch (blendMode) { case BlendMode.Opaque: standardShaderMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); standardShaderMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); standardShaderMaterial.SetInt("_ZWrite", 1); standardShaderMaterial.DisableKeyword("_ALPHATEST_ON"); standardShaderMaterial.DisableKeyword("_ALPHABLEND_ON"); standardShaderMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON"); standardShaderMaterial.renderQueue = -1; break; case BlendMode.Cutout: standardShaderMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); standardShaderMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); standardShaderMaterial.SetInt("_ZWrite", 1); standardShaderMaterial.EnableKeyword("_ALPHATEST_ON"); standardShaderMaterial.DisableKeyword("_ALPHABLEND_ON"); standardShaderMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON"); standardShaderMaterial.renderQueue = 2450; break; case BlendMode.Fade: standardShaderMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); standardShaderMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); standardShaderMaterial.SetInt("_ZWrite", 0); standardShaderMaterial.DisableKeyword("_ALPHATEST_ON"); standardShaderMaterial.EnableKeyword("_ALPHABLEND_ON"); standardShaderMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON"); standardShaderMaterial.renderQueue = 3000; break; case BlendMode.Transparent: standardShaderMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); standardShaderMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); standardShaderMaterial.SetInt("_ZWrite", 0); standardShaderMaterial.DisableKeyword("_ALPHATEST_ON"); standardShaderMaterial.DisableKeyword("_ALPHABLEND_ON"); standardShaderMaterial.EnableKeyword("_ALPHAPREMULTIPLY_ON"); standardShaderMaterial.renderQueue = 3000; break; } } ///Transforms position from local space to world space, but you can put the position, rotation and scale of the transform in seperately. ///Useful if it's the position of one transform but the rotation of another. static public Vector3 TransformPoint(Vector3 position, Quaternion rotation, Vector3 scale, Vector3 localPosition) { var localToWorldMatrix = Matrix4x4.TRS(position, rotation, scale); return localToWorldMatrix.MultiplyPoint3x4(localPosition); } ///Transforms position from world space to local space, but you can put the position, rotation and scale of the transform in seperately. ///Useful if it's the position of one transform but the rotation of another. static public Vector3 InverseTransformPoint(Vector3 position, Quaternion rotation, Vector3 scale, Vector3 worldPosition) { var worldToLocalMatrix = Matrix4x4.TRS(position, rotation, scale).inverse; return worldToLocalMatrix.MultiplyPoint3x4(worldPosition); } ///Transforms direction from local space to world space, but you can put the rotation of the transform in directly. ///Useful if you don't want to make the actual gameobject and just want to convert static public Vector3 TransformDirection(Quaternion rotation, Vector3 localDirection) { return rotation * localDirection; } static public LayerMask StringArrayToLayerMask(string[] layers, bool inverted) { if (layers == null || layers.Length == 0) return ~0; LayerMask layerMask = 1 << LayerMask.NameToLayer(layers[0]); for (int i=1 ; i<layers.Length ; i++) { layerMask |= 1 << LayerMask.NameToLayer(layers[i]); } if (inverted) layerMask = ~layerMask; return layerMask; } } }
38.474576
138
0.746843
[ "MIT" ]
Joeyjoe9876/OSRS-VR-Demo
VRInteraction/Scripts/Utils/VRUtils.cs
6,812
C#
using System; using System.Linq; using EfEagerLoad.Common; using EfEagerLoad.Tests.Testing; using EfEagerLoad.Tests.Testing.Model; using Microsoft.EntityFrameworkCore; using Xunit; namespace EfEagerLoad.Tests.Common { public class NavigationTypeExtensionsTests { private static readonly TestDbContext TestingDbContext = new TestDbContext(new DbContextOptionsBuilder<TestDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); [Fact] public void ShouldReturnNavigationClassType_WhenNavigationIsNotCollection() { var navigation = TestingDbContext.Model.FindEntityType(typeof(Book)).GetNavigations() .First(nav => nav.Name == nameof(Book.Publisher)); Assert.Equal(typeof(Publisher), navigation.GetNavigationType()); } [Fact] public void ShouldReturnNavigationCollectionType_WhenNavigationIsCollection() { var navigation = TestingDbContext.Model.FindEntityType(typeof(Author)).GetNavigations() .First(nav => nav.Name == nameof(Author.Books)); Assert.Equal(typeof(Book), navigation.GetNavigationType()); } } }
34.342857
127
0.697171
[ "MIT" ]
jsaret/EfEagerLoad
source/Core/EfEagerLoad.Tests/Common/NavigationTypeExtensionsTests.cs
1,204
C#
// // Copyright 2021 Adam Burton (adz21c@gmail.com) // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // using Periturf.Clients; using Periturf.Configuration; using Periturf.Events; using Periturf.Verify; namespace Periturf.Components { /// <summary> /// Components run on hosts and are the pieces of the environment that the system under test will interact with. /// Configuration can be registered and unregistered with them. /// </summary> public interface IComponent { /// <summary> /// Creates a component specific condition builder. /// </summary> /// <returns></returns> IConditionBuilder CreateConditionBuilder(); /// <summary> /// Creates a component configuration specification. /// </summary> /// <typeparam name="TSpecification">The type of the specification.</typeparam> /// <param name="eventHandlerFactory">The event handler factory.</param> /// <returns></returns> TSpecification CreateConfigurationSpecification<TSpecification>(IEventHandlerFactory eventHandlerFactory) where TSpecification : IConfigurationSpecification; /// <summary> /// Creates a component client. /// </summary> /// <returns></returns> IComponentClient CreateClient(); } }
35.660377
116
0.667725
[ "Apache-2.0" ]
adz21c/Periturf
src/Periturf/Components/IComponent.cs
1,892
C#
// *********************************************************************** // Copyright (c) 2015-2018 Terje Sandstrom // // 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 EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.TestPlatform.TestGeneration; using Microsoft.VisualStudio.TestPlatform.TestGeneration.Data; using Microsoft.VisualStudio.TestPlatform.TestGeneration.Logging; using Microsoft.VisualStudio.TestPlatform.TestGeneration.Model; using VSLangProj80; namespace TestGeneration.Extensions.NUnit { /// <summary> /// A solution manager for NUnit unit tests. /// </summary> public class NUnit2SolutionManager : SolutionManagerBase { private const string NUnitVersion = "2.6.4"; private const string NunitAdapterVersion = "2.2.0"; /// <summary> /// Initializes a new instance of the <see cref="NUnit2SolutionManager"/> class. /// </summary> /// <param name="serviceProvider">The service provider to use to get the interfaces required.</param> /// <param name="naming">The naming object used to decide how projects, classes and methods are named and created.</param> /// <param name="directory">The directory object to use for directory operations.</param> public NUnit2SolutionManager(IServiceProvider serviceProvider, INaming naming, IDirectory directory) : base(serviceProvider, naming, directory) { } /// <summary> /// Performs any preparatory tasks that have to be done after a new unit test project has been created. /// </summary> /// <param name="unitTestProject">The <see cref="Project"/> of the unit test project that has just been created.</param> /// <param name="sourceMethod">The <see cref="CodeFunction2"/> of the source method that is to be unit tested.</param> protected override void OnUnitTestProjectCreated(Project unitTestProject, CodeFunction2 sourceMethod) { if (unitTestProject == null) { throw new ArgumentNullException(nameof(unitTestProject)); } TraceLogger.LogInfo("NUnitSolutionManager.OnUnitTestProjectCreated: Adding reference to NUnit 2 assemblies through nuget."); base.OnUnitTestProjectCreated(unitTestProject, sourceMethod); EnsureNuGetReference(unitTestProject, "NUnit", NUnitVersion); EnsureNuGetReference(unitTestProject, "NUnitTestAdapter", NunitAdapterVersion); var vsp = unitTestProject.Object as VSProject2; var reference = vsp?.References.Find(GlobalConstants.MSTestAssemblyName); if (reference != null) { TraceLogger.LogInfo("NUnitSolutionManager.OnUnitTestProjectCreated: Removing reference to {0}", reference.Name); reference.Remove(); } } } }
48.878049
136
0.679391
[ "MIT" ]
nunit/TestGenerator.Extension
CreateUnitTests.NUnit/NUnit2SolutionManager.cs
4,010
C#
using Microsoft.Extensions.DependencyInjection; using MigrationTools.TestExtensions; namespace MigrationTools.Tests { internal static class ServiceProviderHelper { internal static ServiceProvider GetServicesV2() { var services = new ServiceCollection(); services.AddMigrationToolServicesForUnitTests(); ///////////////////////////////// services.AddMigrationToolServices(); services.AddMigrationToolServicesForClientInMemory(); services.AddMigrationToolServicesForClientFileSystem(); services.AddMigrationToolServicesForClientAzureDevOpsObjectModel(); services.AddMigrationToolServicesForClientAzureDevopsRest(); return services.BuildServiceProvider(); } } }
36.590909
79
0.678261
[ "MIT" ]
CowboyPurest/azure-devops-migration-tools
src/MigrationTools.Integration.Tests/ServiceProviderHelper.cs
807
C#
namespace GearListoon.Models { /// <summary> /// スペシャル武器Model /// </summary> public class SpecialWeaponModel { /// <summary> /// ID /// </summary> public string id; /// <summary> /// 名前 /// </summary> public string name; } }
12.55
34
0.569721
[ "MIT" ]
ShassBeleth/GearListoon
GearListoon/Assets/Scripts/Models/SpecialWeaponModel.cs
271
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpiceApp.Services { public interface IEmailSender { void SendMailkit(string name, string mailTo); Task SendEmailAsync(string email, string subject, string htmlMessage); } }
21.933333
78
0.738602
[ "MIT" ]
MohamedAshraf004/SpiceApp-
SpiceApp/Services/IEmailSender.cs
331
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Commands.Test.Utilities.HDInsight.PowerShellTestAbstraction.Interfaces; using Microsoft.WindowsAzure.Commands.Test.Utilities.HDInsight.Utilities; using Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.DataObjects; namespace Microsoft.WindowsAzure.Commands.Test.HDInsight.CmdLetTests { [TestClass] public class StarttJobsCmdletTests : StartJobsCmdletTestCaseBase { [TestCleanup] public override void TestCleanup() { base.TestCleanup(); } [TestMethod] [TestCategory("CheckIn")] [TestCategory("Integration")] [TestCategory("Jobs")] [TestCategory("Start-AzureHDInsightJob")] public override void ICanCallThe_NewHiveJob_Then_Start_HDInsightJobsCmdlet() { base.ICanCallThe_NewHiveJob_Then_Start_HDInsightJobsCmdlet(); } [TestMethod] [TestCategory("CheckIn")] [TestCategory("Integration")] [TestCategory("Jobs")] [TestCategory("Start-AzureHDInsightJob")] public override void ICanCallThe_NewMapReduceJob_Then_Start_HDInsightJobsCmdlet() { base.ICanCallThe_NewMapReduceJob_Then_Start_HDInsightJobsCmdlet(); } [TestMethod] [TestCategory("CheckIn")] [TestCategory("Integration")] [TestCategory("Jobs")] [TestCategory("Start-AzureHDInsightJob")] public override void ICanCallThe_NewPigJob_Then_Start_HDInsightJobsCmdlet() { base.ICanCallThe_NewPigJob_Then_Start_HDInsightJobsCmdlet(); } [TestMethod] [TestCategory("CheckIn")] [TestCategory("Integration")] [TestCategory("Jobs")] [TestCategory("Start-AzureHDInsightJob")] public override void ICanCallThe_NewSqoopJob_Then_Start_HDInsightJobsCmdlet() { base.ICanCallThe_NewSqoopJob_Then_Start_HDInsightJobsCmdlet(); } [TestMethod] [TestCategory("CheckIn")] [TestCategory("Integration")] [TestCategory("Jobs")] [TestCategory("Start-AzureHDInsightJob")] public override void ICanCallThe_NewStreamingJob_Then_Start_HDInsightJobsCmdlet() { base.ICanCallThe_NewStreamingJob_Then_Start_HDInsightJobsCmdlet(); } [TestMethod] [TestCategory("CheckIn")] [TestCategory("Integration")] [TestCategory("Jobs")] [TestCategory("Start-AzureHDInsightJob")] public override void ICanCallThe_Start_HDInsightJobsCmdlet() { base.ICanCallThe_Start_HDInsightJobsCmdlet(); } //[TestMethod] [TestCategory("CheckIn")] [TestCategory("Integration")] [TestCategory("Jobs")] [TestCategory("Start-AzureHDInsightJob")] public void ICanCallThe_Start_HDInsightJobsCmdlet_WithDebug() { var mapReduceJobDefinition = new AzureHDInsightMapReduceJobDefinition { JobName = "pi estimation jobDetails", ClassName = "pi", JarFile = TestConstants.WabsProtocolSchemeName + "container@hostname/examples.jar" }; using (IRunspace runspace = this.GetPowerShellRunspace()) { string expectedLogMessage = string.Format(CultureInfo.InvariantCulture, "Starting jobDetails '{0}'.", mapReduceJobDefinition.JobName); RunJobInPowershell( runspace, mapReduceJobDefinition, CmdletScenariosTestCaseBase.GetHttpAccessEnabledCluster(), true, expectedLogMessage); } } [TestMethod] [TestCategory("CheckIn")] [TestCategory("Integration")] [TestCategory("Jobs")] [TestCategory("Start-AzureHDInsightJob")] public override void ICanCallThe_Start_HDInsightJobsCmdlet_WithoutName() { base.ICanCallThe_Start_HDInsightJobsCmdlet_WithoutName(); } [TestInitialize] public override void Initialize() { base.Initialize(); } } }
36.785714
151
0.617282
[ "MIT" ]
Andrean/azure-powershell
src/ServiceManagement/HDInsight/Commands.HDInsight.Test/HDInsight/CmdLetTests/StartJobsCmdletTests.cs
5,013
C#
using Ship; using Upgrade; using System.Collections.Generic; using UnityEngine; using SubPhases; using System; namespace UpgradesList.SecondEdition { public class EmperorPalpatine : GenericUpgrade { public EmperorPalpatine() : base() { UpgradeInfo = new UpgradeCardInfo( "Emperor Palpatine", types: new List<UpgradeType>() { UpgradeType.Crew, UpgradeType.Crew }, cost: 11, isLimited: true, addForce: 1, restriction: new FactionRestriction(Faction.Imperial), abilityType: typeof(Abilities.SecondEdition.EmperorPalpatineCrewAbility), seImageNumber: 115 ); Avatar = new AvatarInfo( Faction.Imperial, new Vector2(450, 16) ); } } } namespace Abilities.SecondEdition { public class EmperorPalpatineCrewAbility : GenericAbility { public override void ActivateAbility() { AddDiceModification( HostName, IsAvailable, () => 20, DiceModificationType.Change, 1, new List<DieSide> { DieSide.Focus }, DieSide.Success, isGlobal: true, payAbilityCost: PayAbilityCost ); } public override void DeactivateAbility() { RemoveDiceModification(); } private bool IsAvailable() { GenericShip activeShip = Combat.AttackStep == CombatStep.Attack ? Combat.Attacker : Combat.Defender; return activeShip.Owner == HostShip.Owner && activeShip != HostShip && HostShip.State.Force > 0; } private void PayAbilityCost(Action<bool> callback) { if (HostShip.State.Force > 0) { HostShip.State.SpendForce(1, delegate { callback(true); }); } else { callback(false); } } } }
27.617284
112
0.498435
[ "MIT" ]
simonthezealot/FlyCasual
Assets/Scripts/Model/Content/SecondEdition/Upgrades/Crew/EmperorPalpatine.cs
2,239
C#
using System; namespace Guidelines.Core.Bootstrap { /// <summary> /// Bootstrap foundation class that ensure a bootstrap process occurs only once. /// </summary> public interface IBootstrapper : IDisposable { /// <summary> /// Call to begin bootstrapping. Can only be run once. /// </summary> IBootstrapper Bootstrap(); } }
21.25
81
0.697059
[ "MIT" ]
basicdays/Guidelines
src/Core/Bootstrap/IBootstrapper.cs
342
C#
 namespace Sunny.UI.Demo { partial class FPipe { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.uiPipe3 = new Sunny.UI.UIPipe(); this.uiPipe4 = new Sunny.UI.UIPipe(); this.uiPipe2 = new Sunny.UI.UIPipe(); this.uiPipe7 = new Sunny.UI.UIPipe(); this.uiPipe8 = new Sunny.UI.UIPipe(); this.uiPipe9 = new Sunny.UI.UIPipe(); this.uiPipe10 = new Sunny.UI.UIPipe(); this.uiPipe11 = new Sunny.UI.UIPipe(); this.uiPipe12 = new Sunny.UI.UIPipe(); this.uiPipe1 = new Sunny.UI.UIPipe(); this.uiPipe5 = new Sunny.UI.UIPipe(); this.uiPipe6 = new Sunny.UI.UIPipe(); this.uiPipe13 = new Sunny.UI.UIPipe(); this.uiPipe14 = new Sunny.UI.UIPipe(); this.uiPipe15 = new Sunny.UI.UIPipe(); this.uiPipe16 = new Sunny.UI.UIPipe(); this.uiPipe17 = new Sunny.UI.UIPipe(); this.uiPipe18 = new Sunny.UI.UIPipe(); this.uiValve1 = new Sunny.UI.UIValve(); this.uiPipe19 = new Sunny.UI.UIPipe(); this.uiValve2 = new Sunny.UI.UIValve(); this.uiValve3 = new Sunny.UI.UIValve(); this.uiValve4 = new Sunny.UI.UIValve(); this.uiPipe20 = new Sunny.UI.UIPipe(); this.uiPipe21 = new Sunny.UI.UIPipe(); this.uiPipe22 = new Sunny.UI.UIPipe(); this.SuspendLayout(); // // timer1 // this.timer1.Interval = 200; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // uiPipe3 // this.uiPipe3.Active = true; this.uiPipe3.BackColor = System.Drawing.Color.Transparent; this.uiPipe3.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe3.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128))))); this.uiPipe3.FlowSpeed = 10; this.uiPipe3.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe3.Location = new System.Drawing.Point(196, 194); this.uiPipe3.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe3.Name = "uiPipe3"; this.uiPipe3.Radius = 16; this.uiPipe3.RadiusSides = Sunny.UI.UICornerRadiusSides.RightTop; this.uiPipe3.Size = new System.Drawing.Size(16, 234); this.uiPipe3.Style = Sunny.UI.UIStyle.Custom; this.uiPipe3.StyleCustomMode = true; this.uiPipe3.TabIndex = 9; this.uiPipe3.Text = "uiPipe3"; // // uiPipe4 // this.uiPipe4.Active = true; this.uiPipe4.BackColor = System.Drawing.Color.Transparent; this.uiPipe4.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe4.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128))))); this.uiPipe4.FlowSpeed = 10; this.uiPipe4.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe4.Location = new System.Drawing.Point(34, 63); this.uiPipe4.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe4.Name = "uiPipe4"; this.uiPipe4.Radius = 16; this.uiPipe4.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe4.Size = new System.Drawing.Size(16, 365); this.uiPipe4.Style = Sunny.UI.UIStyle.Custom; this.uiPipe4.StyleCustomMode = true; this.uiPipe4.TabIndex = 8; this.uiPipe4.Text = "uiPipe4"; // // uiPipe2 // this.uiPipe2.Active = true; this.uiPipe2.BackColor = System.Drawing.Color.Transparent; this.uiPipe2.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128))))); this.uiPipe2.FlowSpeed = 10; this.uiPipe2.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe2.Location = new System.Drawing.Point(48, 194); this.uiPipe2.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe2.Name = "uiPipe2"; this.uiPipe2.Radius = 16; this.uiPipe2.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe2.Size = new System.Drawing.Size(73, 16); this.uiPipe2.Style = Sunny.UI.UIStyle.Custom; this.uiPipe2.StyleCustomMode = true; this.uiPipe2.TabIndex = 5; this.uiPipe2.Text = "uiPipe2"; // // uiPipe7 // this.uiPipe7.Active = true; this.uiPipe7.BackColor = System.Drawing.Color.Transparent; this.uiPipe7.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe7.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe7.FlowSpeed = 10; this.uiPipe7.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe7.Location = new System.Drawing.Point(451, 194); this.uiPipe7.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe7.Name = "uiPipe7"; this.uiPipe7.Radius = 16; this.uiPipe7.RadiusSides = ((Sunny.UI.UICornerRadiusSides)((Sunny.UI.UICornerRadiusSides.RightTop | Sunny.UI.UICornerRadiusSides.RightBottom))); this.uiPipe7.Size = new System.Drawing.Size(16, 73); this.uiPipe7.Style = Sunny.UI.UIStyle.Custom; this.uiPipe7.StyleCustomMode = true; this.uiPipe7.TabIndex = 14; this.uiPipe7.Text = "uiPipe7"; // // uiPipe8 // this.uiPipe8.Active = true; this.uiPipe8.BackColor = System.Drawing.Color.Transparent; this.uiPipe8.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe8.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe8.FlowSpeed = 10; this.uiPipe8.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe8.Location = new System.Drawing.Point(289, 175); this.uiPipe8.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe8.Name = "uiPipe8"; this.uiPipe8.Radius = 16; this.uiPipe8.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe8.Size = new System.Drawing.Size(16, 253); this.uiPipe8.Style = Sunny.UI.UIStyle.Custom; this.uiPipe8.StyleCustomMode = true; this.uiPipe8.TabIndex = 13; this.uiPipe8.Text = "uiPipe8"; // // uiPipe9 // this.uiPipe9.Active = true; this.uiPipe9.BackColor = System.Drawing.Color.Transparent; this.uiPipe9.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe9.FlowSpeed = 10; this.uiPipe9.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe9.Location = new System.Drawing.Point(303, 194); this.uiPipe9.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe9.Name = "uiPipe9"; this.uiPipe9.Radius = 16; this.uiPipe9.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe9.Size = new System.Drawing.Size(149, 16); this.uiPipe9.Style = Sunny.UI.UIStyle.Custom; this.uiPipe9.StyleCustomMode = true; this.uiPipe9.TabIndex = 12; this.uiPipe9.Text = "uiPipe9"; // // uiPipe10 // this.uiPipe10.Active = true; this.uiPipe10.BackColor = System.Drawing.Color.Transparent; this.uiPipe10.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe10.FlowDirection = Sunny.UI.UIPipe.UIFlowDirection.Reverse; this.uiPipe10.FlowSpeed = 10; this.uiPipe10.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe10.Location = new System.Drawing.Point(78, 251); this.uiPipe10.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe10.Name = "uiPipe10"; this.uiPipe10.Radius = 16; this.uiPipe10.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe10.Size = new System.Drawing.Size(389, 16); this.uiPipe10.Style = Sunny.UI.UIStyle.Custom; this.uiPipe10.StyleCustomMode = true; this.uiPipe10.TabIndex = 15; this.uiPipe10.Text = "uiPipe10"; // // uiPipe11 // this.uiPipe11.Active = true; this.uiPipe11.BackColor = System.Drawing.Color.Transparent; this.uiPipe11.FlowColor = System.Drawing.Color.SkyBlue; this.uiPipe11.FlowDirection = Sunny.UI.UIPipe.UIFlowDirection.Reverse; this.uiPipe11.FlowSpeed = 10; this.uiPipe11.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe11.Location = new System.Drawing.Point(109, 295); this.uiPipe11.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe11.Name = "uiPipe11"; this.uiPipe11.Radius = 16; this.uiPipe11.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe11.Size = new System.Drawing.Size(612, 16); this.uiPipe11.Style = Sunny.UI.UIStyle.Custom; this.uiPipe11.StyleCustomMode = true; this.uiPipe11.TabIndex = 16; this.uiPipe11.Text = "uiPipe11"; // // uiPipe12 // this.uiPipe12.Active = true; this.uiPipe12.BackColor = System.Drawing.Color.Transparent; this.uiPipe12.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe12.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe12.FlowSpeed = 10; this.uiPipe12.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe12.Location = new System.Drawing.Point(63, 251); this.uiPipe12.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe12.Name = "uiPipe12"; this.uiPipe12.Radius = 16; this.uiPipe12.RadiusSides = Sunny.UI.UICornerRadiusSides.LeftTop; this.uiPipe12.Size = new System.Drawing.Size(16, 114); this.uiPipe12.Style = Sunny.UI.UIStyle.Custom; this.uiPipe12.StyleCustomMode = true; this.uiPipe12.TabIndex = 17; this.uiPipe12.Text = "uiPipe12"; // // uiPipe1 // this.uiPipe1.Active = true; this.uiPipe1.BackColor = System.Drawing.Color.Transparent; this.uiPipe1.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe1.FlowColor = System.Drawing.Color.SkyBlue; this.uiPipe1.FlowSpeed = 10; this.uiPipe1.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe1.Location = new System.Drawing.Point(94, 295); this.uiPipe1.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe1.Name = "uiPipe1"; this.uiPipe1.Radius = 16; this.uiPipe1.RadiusSides = Sunny.UI.UICornerRadiusSides.LeftTop; this.uiPipe1.Size = new System.Drawing.Size(16, 70); this.uiPipe1.Style = Sunny.UI.UIStyle.Custom; this.uiPipe1.StyleCustomMode = true; this.uiPipe1.TabIndex = 18; this.uiPipe1.Text = "uiPipe1"; // // uiPipe5 // this.uiPipe5.Active = true; this.uiPipe5.BackColor = System.Drawing.Color.Transparent; this.uiPipe5.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe5.FlowColor = System.Drawing.Color.SkyBlue; this.uiPipe5.FlowSpeed = 10; this.uiPipe5.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe5.Location = new System.Drawing.Point(716, 175); this.uiPipe5.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe5.Name = "uiPipe5"; this.uiPipe5.Radius = 16; this.uiPipe5.RadiusSides = Sunny.UI.UICornerRadiusSides.RightBottom; this.uiPipe5.Size = new System.Drawing.Size(16, 136); this.uiPipe5.Style = Sunny.UI.UIStyle.Custom; this.uiPipe5.StyleCustomMode = true; this.uiPipe5.TabIndex = 19; this.uiPipe5.Text = "uiPipe5"; // // uiPipe6 // this.uiPipe6.Active = true; this.uiPipe6.BackColor = System.Drawing.Color.Transparent; this.uiPipe6.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe6.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255))))); this.uiPipe6.FlowInterval = 16; this.uiPipe6.FlowSize = 28; this.uiPipe6.FlowSpeed = 12; this.uiPipe6.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe6.Location = new System.Drawing.Point(63, 384); this.uiPipe6.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe6.Name = "uiPipe6"; this.uiPipe6.Radius = 16; this.uiPipe6.RadiusSides = Sunny.UI.UICornerRadiusSides.LeftBottom; this.uiPipe6.RectColor = System.Drawing.Color.DarkGray; this.uiPipe6.Size = new System.Drawing.Size(16, 156); this.uiPipe6.Style = Sunny.UI.UIStyle.Custom; this.uiPipe6.StyleCustomMode = true; this.uiPipe6.TabIndex = 20; this.uiPipe6.Text = "uiPipe6"; // // uiPipe13 // this.uiPipe13.Active = true; this.uiPipe13.BackColor = System.Drawing.Color.Transparent; this.uiPipe13.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255))))); this.uiPipe13.FlowInterval = 16; this.uiPipe13.FlowSize = 28; this.uiPipe13.FlowSpeed = 12; this.uiPipe13.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe13.Location = new System.Drawing.Point(77, 483); this.uiPipe13.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe13.Name = "uiPipe13"; this.uiPipe13.Radius = 16; this.uiPipe13.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe13.RectColor = System.Drawing.Color.DarkGray; this.uiPipe13.Size = new System.Drawing.Size(643, 16); this.uiPipe13.Style = Sunny.UI.UIStyle.Custom; this.uiPipe13.StyleCustomMode = true; this.uiPipe13.TabIndex = 21; this.uiPipe13.Text = "uiPipe13"; // // uiPipe14 // this.uiPipe14.Active = true; this.uiPipe14.BackColor = System.Drawing.Color.Transparent; this.uiPipe14.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255))))); this.uiPipe14.FlowInterval = 16; this.uiPipe14.FlowSize = 28; this.uiPipe14.FlowSpeed = 12; this.uiPipe14.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe14.Location = new System.Drawing.Point(77, 524); this.uiPipe14.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe14.Name = "uiPipe14"; this.uiPipe14.Radius = 16; this.uiPipe14.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe14.RectColor = System.Drawing.Color.DarkGray; this.uiPipe14.Size = new System.Drawing.Size(134, 16); this.uiPipe14.Style = Sunny.UI.UIStyle.Custom; this.uiPipe14.StyleCustomMode = true; this.uiPipe14.TabIndex = 22; this.uiPipe14.Text = "uiPipe14"; // // uiPipe15 // this.uiPipe15.Active = true; this.uiPipe15.BackColor = System.Drawing.Color.Transparent; this.uiPipe15.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe15.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255))))); this.uiPipe15.FlowDirection = Sunny.UI.UIPipe.UIFlowDirection.Reverse; this.uiPipe15.FlowInterval = 16; this.uiPipe15.FlowSize = 28; this.uiPipe15.FlowSpeed = 12; this.uiPipe15.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe15.Location = new System.Drawing.Point(374, 384); this.uiPipe15.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe15.Name = "uiPipe15"; this.uiPipe15.Radius = 16; this.uiPipe15.RadiusSides = Sunny.UI.UICornerRadiusSides.RightBottom; this.uiPipe15.RectColor = System.Drawing.Color.DarkGray; this.uiPipe15.Size = new System.Drawing.Size(16, 156); this.uiPipe15.Style = Sunny.UI.UIStyle.Custom; this.uiPipe15.StyleCustomMode = true; this.uiPipe15.TabIndex = 23; this.uiPipe15.Text = "uiPipe15"; // // uiPipe16 // this.uiPipe16.Active = true; this.uiPipe16.BackColor = System.Drawing.Color.Transparent; this.uiPipe16.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe16.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe16.FlowInterval = 16; this.uiPipe16.FlowSize = 28; this.uiPipe16.FlowSpeed = 12; this.uiPipe16.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe16.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.uiPipe16.Location = new System.Drawing.Point(536, 384); this.uiPipe16.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe16.Name = "uiPipe16"; this.uiPipe16.Radius = 16; this.uiPipe16.RadiusSides = Sunny.UI.UICornerRadiusSides.LeftBottom; this.uiPipe16.RectColor = System.Drawing.Color.DarkGray; this.uiPipe16.Size = new System.Drawing.Size(16, 83); this.uiPipe16.Style = Sunny.UI.UIStyle.Custom; this.uiPipe16.StyleCustomMode = true; this.uiPipe16.TabIndex = 24; this.uiPipe16.Text = "uiPipe16"; // // uiPipe17 // this.uiPipe17.Active = true; this.uiPipe17.BackColor = System.Drawing.Color.Transparent; this.uiPipe17.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe17.FlowInterval = 16; this.uiPipe17.FlowSize = 28; this.uiPipe17.FlowSpeed = 12; this.uiPipe17.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe17.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.uiPipe17.Location = new System.Drawing.Point(551, 451); this.uiPipe17.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe17.Name = "uiPipe17"; this.uiPipe17.Radius = 16; this.uiPipe17.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe17.RectColor = System.Drawing.Color.DarkGray; this.uiPipe17.Size = new System.Drawing.Size(169, 16); this.uiPipe17.Style = Sunny.UI.UIStyle.Custom; this.uiPipe17.StyleCustomMode = true; this.uiPipe17.TabIndex = 25; this.uiPipe17.Text = "uiPipe17"; // // uiPipe18 // this.uiPipe18.Active = true; this.uiPipe18.BackColor = System.Drawing.Color.Transparent; this.uiPipe18.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe18.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe18.FlowInterval = 16; this.uiPipe18.FlowSize = 28; this.uiPipe18.FlowSpeed = 12; this.uiPipe18.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe18.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.uiPipe18.Location = new System.Drawing.Point(716, 451); this.uiPipe18.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe18.Name = "uiPipe18"; this.uiPipe18.Radius = 16; this.uiPipe18.RadiusSides = Sunny.UI.UICornerRadiusSides.RightTop; this.uiPipe18.RectColor = System.Drawing.Color.DarkGray; this.uiPipe18.Size = new System.Drawing.Size(16, 89); this.uiPipe18.Style = Sunny.UI.UIStyle.Custom; this.uiPipe18.StyleCustomMode = true; this.uiPipe18.TabIndex = 26; this.uiPipe18.Text = "uiPipe18"; // // uiValve1 // this.uiValve1.Active = true; this.uiValve1.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiValve1.Location = new System.Drawing.Point(255, 122); this.uiValve1.MinimumSize = new System.Drawing.Size(1, 1); this.uiValve1.Name = "uiValve1"; this.uiValve1.PipeSize = 20; this.uiValve1.Size = new System.Drawing.Size(60, 60); this.uiValve1.TabIndex = 27; this.uiValve1.Text = "uiValve1"; this.uiValve1.ValveColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0))))); this.uiValve1.ActiveChanged += new System.EventHandler(this.uiValve1_ActiveChanged); // // uiPipe19 // this.uiPipe19.Active = true; this.uiPipe19.BackColor = System.Drawing.Color.Transparent; this.uiPipe19.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe19.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.uiPipe19.FlowSpeed = 10; this.uiPipe19.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe19.Location = new System.Drawing.Point(289, 63); this.uiPipe19.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe19.Name = "uiPipe19"; this.uiPipe19.Radius = 16; this.uiPipe19.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe19.Size = new System.Drawing.Size(16, 74); this.uiPipe19.Style = Sunny.UI.UIStyle.Custom; this.uiPipe19.StyleCustomMode = true; this.uiPipe19.TabIndex = 28; this.uiPipe19.Text = "uiPipe19"; // // uiValve2 // this.uiValve2.Active = true; this.uiValve2.Direction = Sunny.UI.UIValve.UIValveDirection.Right; this.uiValve2.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiValve2.Location = new System.Drawing.Point(706, 122); this.uiValve2.MinimumSize = new System.Drawing.Size(1, 1); this.uiValve2.Name = "uiValve2"; this.uiValve2.PipeSize = 20; this.uiValve2.Size = new System.Drawing.Size(60, 60); this.uiValve2.TabIndex = 29; this.uiValve2.Text = "uiValve2"; this.uiValve2.ActiveChanged += new System.EventHandler(this.uiValve2_ActiveChanged); // // uiValve3 // this.uiValve3.Active = true; this.uiValve3.Direction = Sunny.UI.UIValve.UIValveDirection.Top; this.uiValve3.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiValve3.Location = new System.Drawing.Point(94, 160); this.uiValve3.MinimumSize = new System.Drawing.Size(1, 1); this.uiValve3.Name = "uiValve3"; this.uiValve3.PipeSize = 20; this.uiValve3.Size = new System.Drawing.Size(60, 60); this.uiValve3.TabIndex = 30; this.uiValve3.Text = "uiValve3"; this.uiValve3.ValveColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.uiValve3.ActiveChanged += new System.EventHandler(this.uiValve3_ActiveChanged); // // uiValve4 // this.uiValve4.Active = true; this.uiValve4.Direction = Sunny.UI.UIValve.UIValveDirection.Bottom; this.uiValve4.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiValve4.Location = new System.Drawing.Point(186, 514); this.uiValve4.MinimumSize = new System.Drawing.Size(1, 1); this.uiValve4.Name = "uiValve4"; this.uiValve4.PipeSize = 20; this.uiValve4.RectColor = System.Drawing.Color.DarkGray; this.uiValve4.Size = new System.Drawing.Size(60, 60); this.uiValve4.TabIndex = 31; this.uiValve4.Text = "uiValve4"; this.uiValve4.ValveColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255))))); this.uiValve4.ActiveChanged += new System.EventHandler(this.uiValve4_ActiveChanged); // // uiPipe20 // this.uiPipe20.Active = true; this.uiPipe20.BackColor = System.Drawing.Color.Transparent; this.uiPipe20.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128))))); this.uiPipe20.FlowSpeed = 10; this.uiPipe20.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe20.Location = new System.Drawing.Point(124, 194); this.uiPipe20.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe20.Name = "uiPipe20"; this.uiPipe20.Radius = 16; this.uiPipe20.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe20.Size = new System.Drawing.Size(73, 16); this.uiPipe20.Style = Sunny.UI.UIStyle.Custom; this.uiPipe20.StyleCustomMode = true; this.uiPipe20.TabIndex = 32; this.uiPipe20.Text = "uiPipe20"; // // uiPipe21 // this.uiPipe21.Active = true; this.uiPipe21.BackColor = System.Drawing.Color.Transparent; this.uiPipe21.Direction = Sunny.UI.UILine.LineDirection.Vertical; this.uiPipe21.FlowColor = System.Drawing.Color.SkyBlue; this.uiPipe21.FlowSpeed = 10; this.uiPipe21.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe21.Location = new System.Drawing.Point(716, 63); this.uiPipe21.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe21.Name = "uiPipe21"; this.uiPipe21.Radius = 16; this.uiPipe21.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe21.Size = new System.Drawing.Size(16, 74); this.uiPipe21.Style = Sunny.UI.UIStyle.Custom; this.uiPipe21.StyleCustomMode = true; this.uiPipe21.TabIndex = 33; this.uiPipe21.Text = "uiPipe21"; // // uiPipe22 // this.uiPipe22.Active = true; this.uiPipe22.BackColor = System.Drawing.Color.Transparent; this.uiPipe22.FlowColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255))))); this.uiPipe22.FlowInterval = 16; this.uiPipe22.FlowSize = 28; this.uiPipe22.FlowSpeed = 12; this.uiPipe22.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiPipe22.Location = new System.Drawing.Point(242, 524); this.uiPipe22.MinimumSize = new System.Drawing.Size(1, 1); this.uiPipe22.Name = "uiPipe22"; this.uiPipe22.Radius = 16; this.uiPipe22.RadiusSides = Sunny.UI.UICornerRadiusSides.None; this.uiPipe22.RectColor = System.Drawing.Color.DarkGray; this.uiPipe22.Size = new System.Drawing.Size(134, 16); this.uiPipe22.Style = Sunny.UI.UIStyle.Custom; this.uiPipe22.StyleCustomMode = true; this.uiPipe22.TabIndex = 34; this.uiPipe22.Text = "uiPipe22"; // // FPipe // this.AllowShowTitle = true; this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 21F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.ClientSize = new System.Drawing.Size(855, 642); this.Controls.Add(this.uiValve4); this.Controls.Add(this.uiValve2); this.Controls.Add(this.uiPipe21); this.Controls.Add(this.uiPipe3); this.Controls.Add(this.uiValve3); this.Controls.Add(this.uiPipe20); this.Controls.Add(this.uiValve1); this.Controls.Add(this.uiPipe19); this.Controls.Add(this.uiPipe18); this.Controls.Add(this.uiPipe16); this.Controls.Add(this.uiPipe15); this.Controls.Add(this.uiPipe6); this.Controls.Add(this.uiPipe5); this.Controls.Add(this.uiPipe1); this.Controls.Add(this.uiPipe12); this.Controls.Add(this.uiPipe7); this.Controls.Add(this.uiPipe8); this.Controls.Add(this.uiPipe9); this.Controls.Add(this.uiPipe4); this.Controls.Add(this.uiPipe2); this.Controls.Add(this.uiPipe10); this.Controls.Add(this.uiPipe11); this.Controls.Add(this.uiPipe14); this.Controls.Add(this.uiPipe17); this.Controls.Add(this.uiPipe13); this.Controls.Add(this.uiPipe22); this.Name = "FPipe"; this.Padding = new System.Windows.Forms.Padding(0, 35, 0, 0); this.ShowTitle = true; this.Symbol = 61860; this.Text = "Pipe"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Timer timer1; private UIPipe uiPipe2; private UIPipe uiPipe4; private UIPipe uiPipe3; private UIPipe uiPipe7; private UIPipe uiPipe8; private UIPipe uiPipe9; private UIPipe uiPipe10; private UIPipe uiPipe11; private UIPipe uiPipe12; private UIPipe uiPipe1; private UIPipe uiPipe5; private UIPipe uiPipe6; private UIPipe uiPipe13; private UIPipe uiPipe14; private UIPipe uiPipe15; private UIPipe uiPipe16; private UIPipe uiPipe17; private UIPipe uiPipe18; private UIValve uiValve1; private UIPipe uiPipe19; private UIValve uiValve2; private UIValve uiValve3; private UIValve uiValve4; private UIPipe uiPipe20; private UIPipe uiPipe21; private UIPipe uiPipe22; } }
51.368917
156
0.578449
[ "MIT" ]
BillChan226/Visualization-Project-for-Greyout
VisualTool/Industrial/FPipe.designer.cs
33,086
C#
// 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. #nullable enable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Remote.Services; namespace Microsoft.CodeAnalysis.Remote { internal partial class CodeAnalysisService : IRemoteGlobalNotificationDeliveryService { /// <summary> /// Remote API. /// </summary> public void OnGlobalOperationStarted() { RunService(() => { var globalOperationNotificationService = GetGlobalOperationNotificationService(); globalOperationNotificationService?.OnStarted(); }, CancellationToken.None); } /// <summary> /// Remote API. /// </summary> public void OnGlobalOperationStopped(IReadOnlyList<string> operations, bool cancelled) { RunService(() => { var globalOperationNotificationService = GetGlobalOperationNotificationService(); globalOperationNotificationService?.OnStopped(operations, cancelled); }, CancellationToken.None); } private RemoteGlobalOperationNotificationService? GetGlobalOperationNotificationService() => GetWorkspace().Services.GetService<IGlobalOperationNotificationService>() as RemoteGlobalOperationNotificationService; } }
36
133
0.67803
[ "MIT" ]
IanKemp/roslyn
src/Workspaces/Remote/ServiceHub/Services/CodeAnalysis/CodeAnalysisService_GlobalNotifications.cs
1,586
C#
using System; using System.Xml.Serialization; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Call center overflow processing action. /// </summary> [Serializable] [XmlRoot(Namespace = "")] public enum CallCenterOverflowProcessingAction { [XmlEnum(Name = "Busy")] Busy, [XmlEnum(Name = "Transfer")] Transfer, [XmlEnum(Name = "Ringing")] Ringing, } }
21.190476
50
0.6
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/CallCenterOverflowProcessingAction.cs
445
C#
using System; using System.ComponentModel.DataAnnotations; using System.Security.Cryptography; using Zop.Identity; namespace Zop.Domain.Entities { /// <summary> /// 秘钥 /// </summary> [Serializable] public class Secret:Entity<int> { #region 构造函数 /// <summary> /// 初始化 <see cref="ApiSecret"/> /// </summary> public Secret() { Type = SecretTypes.SharedSecret; } /// <summary> /// 初始化 <see cref="ApiSecret"/> /// </summary> /// <param name="value">秘钥</param> /// <param name="type">秘钥类型</param> /// <param name="expiration">过期时间</param> public Secret( string value, string type = SecretTypes.SharedSecret, DateTime? expiration = null) : this(value, type, "", expiration) { } /// <summary> /// 初始化 <see cref="ApiSecret"/> /// </summary> /// <param name="value">秘钥</param> /// <param name="type">秘钥类型</param> /// <param name="description">描述</param> /// <param name="expiration">过期时间</param> public Secret( string value, string type = SecretTypes.SharedSecret, string description="", DateTime? expiration = null) : this() { Description = description; Expiration = expiration; if (type == SecretTypes.SharedSecret) { Value = value.Sha512(); } } #endregion /// <summary> /// 描述 /// </summary> [MaxLength(1000)] public string Description { get; set; } /// <summary> /// 密钥 /// </summary> [MaxLength(10000)] public string Value { get; set; } /// <summary> /// 过期时间 /// </summary> public DateTime? Expiration { get; set; } /// <summary> /// 密钥类型 SecretTypes /// </summary> [MaxLength(250)] public string Type { get; set; } } }
26.519481
128
0.496082
[ "Apache-2.0" ]
aqa510415008/Zop.Identity
src/Zop.Domain/Entities/Secret.cs
2,142
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using System; using System.Diagnostics; using System.IO; using System.Linq; namespace ESTHost.Simulator { class Program { static void Main(string[] args) { // 数据模拟器 CreateHostBuilder(args).Build().Run(); Console.WriteLine("Hello World!"); } public static IHostBuilder CreateHostBuilder(string[] args) { var isService = !(Debugger.IsAttached || args.Contains("--console")); if (isService) { var pathExe = Process.GetCurrentProcess().MainModule.FileName; var pathRoot = Path.GetDirectoryName(pathExe); Directory.SetCurrentDirectory(pathRoot); } var config = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json", true) .Build(); return Host.CreateDefaultBuilder(args) .UseWindowsService(options => { options.ServiceName = "EST.Simulator"; }) .ConfigureAppConfiguration(cif => cif.AddConfiguration(config)) .RegisterLmsServices<SimulatorModule>(); } } }
31.068182
81
0.566935
[ "MIT" ]
easteng/MonitorPlatform
src/services/ESTHost.Simulator/Program.cs
1,379
C#
using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using EasyAbp.NotificationService.EntityFrameworkCore; using EasyAbp.NotificationService.MultiTenancy; using EasyAbp.NotificationService.Web; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.Swagger; using Volo.Abp; using Volo.Abp.Account; using Volo.Abp.Account.Web; using Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic; using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared; using Volo.Abp.AspNetCore.Serilog; using Volo.Abp.AuditLogging.EntityFrameworkCore; using Volo.Abp.Autofac; using Volo.Abp.Data; using Volo.Abp.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore.SqlServer; using Volo.Abp.FeatureManagement; using Volo.Abp.FeatureManagement.EntityFrameworkCore; using Volo.Abp.Identity; using Volo.Abp.Identity.EntityFrameworkCore; using Volo.Abp.Identity.Web; using Volo.Abp.Localization; using Volo.Abp.Modularity; using Volo.Abp.MultiTenancy; using Volo.Abp.PermissionManagement; using Volo.Abp.PermissionManagement.EntityFrameworkCore; using Volo.Abp.PermissionManagement.Identity; using Volo.Abp.SettingManagement.EntityFrameworkCore; using Volo.Abp.TenantManagement; using Volo.Abp.TenantManagement.EntityFrameworkCore; using Volo.Abp.TenantManagement.Web; using Volo.Abp.Threading; using Volo.Abp.VirtualFileSystem; namespace EasyAbp.NotificationService { [DependsOn( typeof(NotificationServiceWebModule), typeof(NotificationServiceApplicationModule), typeof(NotificationServiceEntityFrameworkCoreModule), typeof(AbpAuditLoggingEntityFrameworkCoreModule), typeof(AbpAutofacModule), typeof(AbpAccountWebModule), typeof(AbpAccountApplicationModule), typeof(AbpEntityFrameworkCoreSqlServerModule), typeof(AbpSettingManagementEntityFrameworkCoreModule), typeof(AbpPermissionManagementEntityFrameworkCoreModule), typeof(AbpPermissionManagementApplicationModule), typeof(AbpIdentityWebModule), typeof(AbpIdentityApplicationModule), typeof(AbpIdentityEntityFrameworkCoreModule), typeof(AbpPermissionManagementDomainIdentityModule), typeof(AbpFeatureManagementWebModule), typeof(AbpFeatureManagementApplicationModule), typeof(AbpFeatureManagementEntityFrameworkCoreModule), typeof(AbpTenantManagementWebModule), typeof(AbpTenantManagementApplicationModule), typeof(AbpTenantManagementEntityFrameworkCoreModule), typeof(AbpAspNetCoreMvcUiBasicThemeModule), typeof(AbpAspNetCoreSerilogModule) )] public class NotificationServiceWebUnifiedModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { var hostingEnvironment = context.Services.GetHostingEnvironment(); var configuration = context.Services.GetConfiguration(); Configure<AbpDbContextOptions>(options => { options.UseSqlServer(); }); if (hostingEnvironment.IsDevelopment()) { Configure<AbpVirtualFileSystemOptions>(options => { options.FileSets.ReplaceEmbeddedByPhysical<NotificationServiceDomainSharedModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}EasyAbp.NotificationService.Domain.Shared", Path.DirectorySeparatorChar))); options.FileSets.ReplaceEmbeddedByPhysical<NotificationServiceDomainModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}EasyAbp.NotificationService.Domain", Path.DirectorySeparatorChar))); options.FileSets.ReplaceEmbeddedByPhysical<NotificationServiceApplicationContractsModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}EasyAbp.NotificationService.Application.Contracts", Path.DirectorySeparatorChar))); options.FileSets.ReplaceEmbeddedByPhysical<NotificationServiceApplicationModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}EasyAbp.NotificationService.Application", Path.DirectorySeparatorChar))); options.FileSets.ReplaceEmbeddedByPhysical<NotificationServiceWebModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}EasyAbp.NotificationService.Web", Path.DirectorySeparatorChar))); }); } context.Services.AddSwaggerGen( options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "NotificationService API", Version = "v1" }); options.DocInclusionPredicate((docName, description) => true); options.CustomSchemaIds(type => type.FullName); }); Configure<AbpLocalizationOptions>(options => { options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština")); options.Languages.Add(new LanguageInfo("en", "en", "English")); options.Languages.Add(new LanguageInfo("fr", "fr", "Français")); options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português (Brasil)")); options.Languages.Add(new LanguageInfo("ru", "ru", "Русский")); options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe")); options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文")); options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文")); }); Configure<AbpMultiTenancyOptions>(options => { options.IsEnabled = MultiTenancyConsts.IsEnabled; }); } public override void OnApplicationInitialization(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseErrorPage(); app.UseHsts(); } app.UseHttpsRedirection(); app.UseVirtualFiles(); app.UseRouting(); app.UseAuthentication(); if (MultiTenancyConsts.IsEnabled) { app.UseMultiTenancy(); } app.UseAbpRequestLocalization(); app.UseAuthorization(); app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "Support APP API"); }); app.UseAuditing(); app.UseAbpSerilogEnrichers(); app.UseConfiguredEndpoints(); using (var scope = context.ServiceProvider.CreateScope()) { AsyncHelper.RunSync(async () => { await scope.ServiceProvider .GetRequiredService<IDataSeeder>() .SeedAsync(); }); } } } }
43.753012
273
0.66887
[ "MIT" ]
wagnerhsu/sample-EasyAbp-NotificationService
host/EasyAbp.NotificationService.Web.Unified/NotificationServiceWebUnifiedModule.cs
7,292
C#
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; namespace ScannTechSDK.Enums { [JsonConverter(typeof(StringEnumConverter))] public enum TipoPromocao { [EnumMember(Value = "LLEVA_PAGA")] LevaPaga = 1, [EnumMember(Value = "ADICIONAL_DESCUENTO")] DescontoAdicional = 2, [EnumMember(Value = "ADICIONAL_REGALO")] PresenteAdicional = 3, [EnumMember(Value = "PRECIO_FIJO")] PrecoFixo = 4, [EnumMember(Value = "DESCUENTO_VARIABLE")] DescontoVariado = 5, [EnumMember(Value = "DESCUENTO_FIJO")] DescontoFixo = 6 } }
27.708333
51
0.642105
[ "Apache-2.0" ]
GuimoBear/ScannTechSDK
Enums/TipoPromocao.cs
667
C#
namespace _05.Calculate_Sequence_with_Queue { using System; using System.Collections.Generic; public class Program { public static void Main() { var currentNumber = long.Parse(Console.ReadLine()); var sequenceOfNumbers = new Queue<long>(); var secondSequenceOfNumbers = new Queue<long>(); secondSequenceOfNumbers.Enqueue(currentNumber); while (secondSequenceOfNumbers.Count < 50) { secondSequenceOfNumbers.Enqueue(currentNumber + 1); sequenceOfNumbers.Enqueue(currentNumber + 1); if (secondSequenceOfNumbers.Count < 50) { secondSequenceOfNumbers.Enqueue(2 * currentNumber + 1); sequenceOfNumbers.Enqueue(2 * currentNumber + 1); } if (secondSequenceOfNumbers.Count < 50) { secondSequenceOfNumbers.Enqueue(currentNumber + 2); sequenceOfNumbers.Enqueue(currentNumber + 2); currentNumber = sequenceOfNumbers.Dequeue(); } } Console.WriteLine(string.Join(" ", secondSequenceOfNumbers)); } } }
32.358974
75
0.558637
[ "MIT" ]
anedyalkov/CSharp-Advanced
01.Exercises-Stacks and Queues/05.Calculate Sequence with Queue/05.Calculate Sequence with Queue.cs
1,264
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Windows; using System.Runtime.InteropServices; using System.Net; namespace EpgTimer { public class TVTestCtrlClass { Process process = null; string processType; public bool SetLiveCh(UInt16 ONID, UInt16 TSID, UInt16 SID) { try { if (Settings.Instance.TvTestExe.Length == 0) { MessageBox.Show("TVTest.exeのパスが設定されていません"); return false; } // TVTestのパスが録画用アプリと一致する場合はViewアプリとして扱う bool isView = CommonManager.Instance.NWMode == false && Settings.Instance.NwTvMode == false && string.Compare(IniFileHandler.GetPrivateProfileString("SET", "RecExePath", "", SettingPath.CommonIniPath), Settings.Instance.TvTestExe, true) == 0; OpenTVTest(Settings.Instance.TvTestOpenWait, isView ? "View" : "TvTest"); var cmdTvTest = new CtrlCmdUtil(); cmdTvTest.SetPipeSetting("Global\\" + processType + "_Ctrl_BonConnect_" + process.Id, processType + "_Ctrl_BonPipe_" + process.Id); cmdTvTest.SetConnectTimeOut(1000); if (Settings.Instance.NwTvMode == true) { SetChInfo chInfo = new SetChInfo(); chInfo.useSID = 1; chInfo.useBonCh = 0; chInfo.ONID = ONID; chInfo.TSID = TSID; chInfo.SID = SID; UInt32 nwMode = 0; String nwBonDriver = "BonDriver_UDP.dll"; if (Settings.Instance.NwTvModeUDP == true) { nwMode += 1; } if (Settings.Instance.NwTvModeTCP == true) { nwMode += 2; nwBonDriver = "BonDriver_TCP.dll"; } if (CommonManager.CreateSrvCtrl().SendNwTVMode(nwMode) == ErrCode.CMD_SUCCESS) { if (CommonManager.CreateSrvCtrl().SendNwTVSetCh(chInfo) == ErrCode.CMD_SUCCESS) { String val = ""; for (int i = 0; i < 10; i++) { if (cmdTvTest.SendViewGetBonDrivere(ref val) != ErrCode.CMD_SUCCESS) { System.Threading.Thread.Sleep(1000); continue; } if (String.Compare(val, nwBonDriver, true) != 0) { cmdTvTest.SendViewSetBonDrivere(nwBonDriver); } break; } } } } else { UInt64 key = CommonManager.Create64Key(ONID, TSID, SID); TvTestChChgInfo chInfo = new TvTestChChgInfo(); ErrCode err = CommonManager.CreateSrvCtrl().SendGetChgChTVTest(key, ref chInfo); if (err == ErrCode.CMD_SUCCESS) { String val = ""; for (int i = 0; i < 10; i++) { if (cmdTvTest.SendViewGetBonDrivere(ref val) != ErrCode.CMD_SUCCESS) { System.Threading.Thread.Sleep(1000); continue; } // 識別用IDが設定されたViewアプリは弄らない if (processType == "View") { int id = -1; if (cmdTvTest.SendViewGetID(ref id) != ErrCode.CMD_SUCCESS || id >= 0) { break; } } if (String.Compare(val, chInfo.bonDriver, true) != 0) { if (cmdTvTest.SendViewSetBonDrivere(chInfo.bonDriver) == ErrCode.CMD_SUCCESS) { System.Threading.Thread.Sleep(Settings.Instance.TvTestChgBonWait); cmdTvTest.SendViewSetCh(chInfo.chInfo); } } else { cmdTvTest.SendViewSetCh(chInfo.chInfo); } break; } } else { MessageBox.Show(CommonManager.GetErrCodeText(err) ?? "指定サービスを受信できるBonDriverが設定されていません。"); return false; } } WakeupWindow(process.MainWindowHandle); } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } return true; } public bool StartTimeShift(UInt32 reserveID) { try { if (Settings.Instance.TvTestExe.Length == 0) { MessageBox.Show("TVTest.exeのパスが設定されていません"); return false; } if (CommonManager.Instance.NWMode == false) { if (IniFileHandler.GetPrivateProfileInt("SET", "EnableTCPSrv", 0, SettingPath.TimerSrvIniPath) == 0) { MessageBox.Show("追っかけ再生を行うには、動作設定でネットワーク接続を許可する必要があります。"); return false; } } NWPlayTimeShiftInfo playInfo = new NWPlayTimeShiftInfo(); ErrCode err = CommonManager.CreateSrvCtrl().SendNwTimeShiftOpen(reserveID, ref playInfo); if (err != ErrCode.CMD_SUCCESS) { MessageBox.Show(CommonManager.GetErrCodeText(err) ?? "まだ録画が開始されていません。"); return false; } OpenTVTest(1000, "TvTest"); var cmdTvTest = new CtrlCmdUtil(); cmdTvTest.SetPipeSetting("Global\\TvTest_Ctrl_BonConnect_" + process.Id, "TvTest_Ctrl_BonPipe_" + process.Id); cmdTvTest.SetConnectTimeOut(1000); TVTestStreamingInfo sendInfo = new TVTestStreamingInfo(); sendInfo.enableMode = 1; sendInfo.ctrlID = playInfo.ctrlID; if (CommonManager.Instance.NWMode == false) { sendInfo.serverIP = 0x7F000001; // 原作はここで自ホスト名を取得して解決したアドレスを格納している。(ないとは思うが)不具合があれば戻すこと sendInfo.serverPort = (UInt32)IniFileHandler.GetPrivateProfileInt("SET", "TCPPort", 4510, SettingPath.TimerSrvIniPath); } else { sendInfo.serverIP = 0x7F000001; IPAddress srvIP = CommonManager.Instance.NW.ConnectedIP; if (srvIP != null && srvIP.GetAddressBytes().Length == 4) { byte[] oct = srvIP.GetAddressBytes(); sendInfo.serverIP = (uint)oct[0] << 24 | (uint)oct[1] << 16 | (uint)oct[2] << 8 | oct[3]; } sendInfo.serverPort = CommonManager.Instance.NW.ConnectedPort; } sendInfo.filePath = playInfo.filePath; if (Settings.Instance.NwTvModeUDP == true) { sendInfo.udpSend = 1; } if (Settings.Instance.NwTvModeTCP == true) { sendInfo.tcpSend = 1; } for (int i = 0; i < 10 && cmdTvTest.SendViewSetStreamingInfo(sendInfo) != ErrCode.CMD_SUCCESS; i++) { System.Threading.Thread.Sleep(1000); } WakeupWindow(process.MainWindowHandle); } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } return true; } public bool StartStreamingPlay(String filePath, IPAddress srvIP, UInt32 srvPort) { try { if (Settings.Instance.TvTestExe.Length == 0) { MessageBox.Show("TVTest.exeのパスが設定されていません"); return false; } UInt32 ctrlID = 0; ErrCode err = CommonManager.CreateSrvCtrl().SendNwPlayOpen(filePath, ref ctrlID); if (err != ErrCode.CMD_SUCCESS) { MessageBox.Show(CommonManager.GetErrCodeText(err) ?? "まだ録画が開始されていません。"); return false; } OpenTVTest(Settings.Instance.TvTestOpenWait, "TvTest"); var cmdTvTest = new CtrlCmdUtil(); cmdTvTest.SetPipeSetting("Global\\TvTest_Ctrl_BonConnect_" + process.Id, "TvTest_Ctrl_BonPipe_" + process.Id); cmdTvTest.SetConnectTimeOut(1000); UInt32 ip = 0x7F000001; if (srvIP != null && srvIP.GetAddressBytes().Length == 4) { byte[] oct = srvIP.GetAddressBytes(); ip = (uint)oct[0] << 24 | (uint)oct[1] << 16 | (uint)oct[2] << 8 | oct[3]; } TVTestStreamingInfo sendInfo = new TVTestStreamingInfo(); sendInfo.enableMode = 1; sendInfo.ctrlID = ctrlID; sendInfo.serverIP = ip; sendInfo.serverPort = srvPort; if (Settings.Instance.NwTvModeUDP == true) { sendInfo.udpSend = 1; } if (Settings.Instance.NwTvModeTCP == true) { sendInfo.tcpSend = 1; } for (int i = 0; i < 10 && cmdTvTest.SendViewSetStreamingInfo(sendInfo) != ErrCode.CMD_SUCCESS; i++) { System.Threading.Thread.Sleep(1000); } WakeupWindow(process.MainWindowHandle); } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } return true; } private void OpenTVTest(int openWait, string type) { if (process == null || process.HasExited || processType != type) { processType = type; process = FindTVTestProcess(type); if (process == null) { process = Process.Start(Settings.Instance.TvTestExe, Settings.Instance.TvTestCmd); System.Threading.Thread.Sleep(openWait); } } } private static Process FindTVTestProcess(string type) { foreach (Process p in Process.GetProcesses()) { // 原作と異なりプロセス名ではなく接続待機用イベントの有無で判断するので注意 try { using (System.Threading.EventWaitHandle.OpenExisting( "Global\\" + type + "_Ctrl_BonConnect_" + p.Id, System.Security.AccessControl.EventWaitHandleRights.Synchronize)) { } // 識別用IDが設定されたViewアプリは除外する if (type == "View") { var cmdTvTest = new CtrlCmdUtil(); cmdTvTest.SetPipeSetting("Global\\View_Ctrl_BonConnect_" + p.Id, "View_Ctrl_BonPipe_" + p.Id); cmdTvTest.SetConnectTimeOut(1000); int id = -1; if (cmdTvTest.SendViewGetID(ref id) != ErrCode.CMD_SUCCESS || id >= 0) { continue; } } return p; } catch { } } return null; } public void CloseTVTest() { if (process != null && process.HasExited == false) { var cmdTvTest = new CtrlCmdUtil(); cmdTvTest.SetPipeSetting("Global\\" + processType + "_Ctrl_BonConnect_" + process.Id, processType + "_Ctrl_BonPipe_" + process.Id); cmdTvTest.SetConnectTimeOut(1000); cmdTvTest.SendViewAppClose(); } process = null; if (Settings.Instance.NwTvMode == true) { CommonManager.CreateSrvCtrl().SendNwTVClose(); } } // 外部プロセスのウィンドウを起動する private static void WakeupWindow(IntPtr windowHandle) { if (IsIconic(windowHandle)) { ShowWindowAsync(windowHandle, SW_RESTORE); } // メイン・ウィンドウを最前面に表示する SetForegroundWindow(windowHandle); } // 外部プロセスのメイン・ウィンドウを起動するためのWin32 API [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); // ShowWindowAsync関数のパラメータに渡す定義値 private const int SW_RESTORE = 9; // 画面を元の大きさに戻す } }
41.973913
178
0.440923
[ "MIT" ]
nexus7ici/tkntrec
EpgTimer/EpgTimer/Common/TVTestCtrlClass.cs
15,203
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Zilon.Core.Common; using Zilon.Core.CommonServices.Dices; using Zilon.Core.Graphs; using Zilon.Core.Schemes; using Zilon.Core.Tactics.Spatial; namespace Zilon.Core.MapGenerators.CellularAutomatonStyle { /// <summary> /// Фабрика карты на основе клеточного автомата. /// </summary> public sealed class CellularAutomatonMapFactory : IMapFactory { private const int RETRY_MAX_COUNT = 3; private readonly IDice _dice; /// <summary> /// Конструктор фабрики. /// </summary> /// <param name="dice"> Кость для рандома. </param> public CellularAutomatonMapFactory(IDice dice) { _dice = dice; } private static ISectorMap CreateSectorMap(Matrix<bool> matrix, RegionDraft[] draftRegions, IEnumerable<SectorTransition> transitions) { // Создание графа карты сектора на основе карты клеточного автомата. ISectorMap map = new SectorHexMap(); FillMapRegions(draftRegions, map); MapDraftRegionsToSectorMap(matrix, draftRegions, map); // Размещаем переходы и отмечаем стартовую комнату. // Общее описание: стараемся размещать переходы в самых маленьких комнатах. // Для этого сортируем все комнаты по размеру. // Первую занимаем под старт. // Последующие - это переходы. var regionOrderedBySize = map.Regions.OrderBy(x => x.Nodes.Length).ToArray(); if (regionOrderedBySize.Any()) { CreateTransitionInSmallestRegion(transitions, map, regionOrderedBySize); } return map; } private static void CreateTransitionInSmallestRegion(IEnumerable<SectorTransition> transitions, ISectorMap map, MapRegion[] regionOrderedBySize) { var startRegion = regionOrderedBySize.First(); startRegion.IsStart = true; var transitionArray = transitions.ToArray(); // Пропускаем 1, потому что 1 занять стартом. var trasitionRegionDrafts = regionOrderedBySize.Skip(1).ToArray(); Debug.Assert(trasitionRegionDrafts.Length >= transitionArray.Length, "Должно быть достаточно регионов для размещения всех переходов."); for (var i = 0; i < transitionArray.Length; i++) { var transitionRegion = trasitionRegionDrafts[i]; var transition = transitionArray[i]; var transitionNode = transitionRegion.Nodes.First(); map.Transitions.Add(transitionNode, transition); if (transition.SectorNode == null) { transitionRegion.IsOut = true; } transitionRegion.ExitNodes = (from regionNode in transitionRegion.Nodes where map.Transitions.Keys.Contains(regionNode) select regionNode).ToArray(); } } private static void FillMapRegions(RegionDraft[] draftRegions, ISectorMap map) { var regionIdCounter = 1; foreach (var draftRegion in draftRegions) { var regionNodeList = new List<IGraphNode>(); foreach (var coord in draftRegion.Coords) { var node = new HexNode(coord.X, coord.Y); map.AddNode(node); regionNodeList.Add(node); } var region = new MapRegion(regionIdCounter, regionNodeList.ToArray()); map.Regions.Add(region); regionIdCounter++; } } /// <summary> /// Преобразовывет черновые регионы в узлы реальной карты. /// </summary> private static void MapDraftRegionsToSectorMap(Matrix<bool> matrix, RegionDraft[] draftRegions, ISectorMap map) { var cellMap = matrix.Items; var mapWidth = matrix.Width; var mapHeight = matrix.Height; var regionNodeCoords = draftRegions.SelectMany(x => x.Coords); var hashSet = new HashSet<OffsetCoords>(regionNodeCoords); for (var x = 0; x < mapWidth; x++) { for (var y = 0; y < mapHeight; y++) { if (cellMap[x, y]) { var offsetCoord = new OffsetCoords(x, y); if (!hashSet.Contains(offsetCoord)) { var node = new HexNode(x, y); map.AddNode(node); } } } } } private static IEnumerable<RegionDraft> PostProcess( IEnumerable<IRegionPostProcessor> regionPostProcessors, IEnumerable<RegionDraft> regions) { foreach (var processor in regionPostProcessors) { regions = processor.Process(regions); } return regions; } /// <inheritdoc /> public Task<ISectorMap> CreateAsync(ISectorMapFactoryOptions generationOptions) { if (generationOptions is null) { throw new ArgumentNullException(nameof(generationOptions)); } var transitions = generationOptions.Transitions; var cellularAutomatonOptions = (ISectorCellularAutomataMapFactoryOptionsSubScheme)generationOptions.OptionsSubScheme; if (cellularAutomatonOptions == null) { throw new ArgumentException( $"Для {nameof(generationOptions)} не задано {nameof(ISectorSubScheme.MapGeneratorOptions)} равно null."); } var matrixWidth = cellularAutomatonOptions.MapWidth; var matrixHeight = cellularAutomatonOptions.MapHeight; var fillProbability = cellularAutomatonOptions.ChanceToStartAlive; var cellularAutomatonGenerator = new CellularAutomatonGenerator(_dice); var mapRuleManager = new MapRuleManager(); var rule = new RegionCountRule { Count = transitions.Count() + 1 }; mapRuleManager.AddRule(rule); var regionPostProcessors = new IRegionPostProcessor[] { new SplitToTargetCountRegionPostProcessor(mapRuleManager, _dice) }; for (var retryIndex = 0; retryIndex < RETRY_MAX_COUNT; retryIndex++) { var matrix = new Matrix<bool>(matrixWidth, matrixHeight); var regions = cellularAutomatonGenerator.Generate(ref matrix, fillProbability, 7); try { regions = PostProcess(regionPostProcessors, regions); ClosestRegionConnector.Connect(matrix, regions); var map = CreateSectorMap(matrix, regions.ToArray(), transitions); return Task.FromResult(map); } catch (CellularAutomatonException) { // This means that with the current starting data it is not possible to create a suitable map. // Start the next iteration. } } // If the cycle has ended, then no attempt has ended with a successful map building throw new InvalidOperationException("Failed to create a map within the maximum number of attempts."); } } }
35.825688
125
0.570551
[ "MIT" ]
kreghek/Zilon_Roguelike
Zilon.Core/Zilon.Core/MapGenerators/CellularAutomatonStyle/CellularAutomatonMapFactory.cs
8,272
C#
using System; using System.Collections.Generic; using System.Text; namespace SEDC.Adv.TryBeingFit.Domain { public abstract class Training : BaseEntity, ITraining { public string Title { get; set; } public string Description { get; set; } public int Time { get; set; } public Difficulty Difficulty { get; set; } public int Rating { get; set; } public string CheckRating() { if (Rating == 1) return "Bad"; if (Rating <= 3) return "Okay"; if (Rating > 3) return "Good"; return "Unknown"; } } }
25.75
58
0.566343
[ "MIT" ]
sedc-codecademy/skwd8-06-csharpadv
g7/TryBeingFitApp/SEDC.Adv.TryBeingFit/SEDC.Adv.TryBeingFit.Domain/Core/Entities/Training.cs
620
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Joy.Server.Data; namespace DAL { public class D { public static Db DB = Dbs.Use<DbAccess>("dbportal"); public static SiteCache Cache = new SiteCache { Name = "Root" }; } public class SiteCache { public string Name; public string Value; public readonly List<SiteCache> Children = new List<SiteCache>(); public SiteCache Retrieve(string name) { foreach (SiteCache i in Children) { if (string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)) { return i; } } SiteCache r = new SiteCache(); r.Name = name; Children.Add(r); return r; } } }
19.914286
72
0.678623
[ "MIT" ]
mind0n/hive
Product/Website/Portal/DAL/D.cs
699
C#
using EnTier.DataAccess.EntityFramework; using EnTier.UnitOfWork; using Microsoft.EntityFrameworkCore; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { public static IServiceCollection AddEntityFrameworkUnitOfWork(this IServiceCollection services, DbContext context) { return services.AddSingleton<IUnitOfWork>(new EntityFrameworkUnitOfWork(context)); } } }
32.0625
103
0.762183
[ "MIT" ]
Acidmanic/EnTier
EnTier.DataAccess.EntityFramework/ServiceCollectionExtensions.cs
513
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using StateOfNeo.Data; namespace StateOfNeo.Data.Migrations { [DbContext(typeof(StateOfNeoContext))] [Migration("20181217183132_TotalStats_ForgotenSetOfPropertiesAdded")] partial class TotalStats_ForgotenSetOfPropertiesAdded { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("StateOfNeo.Data.Models.Address", b => { b.Property<string>("PublicAddress") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreatedOn"); b.Property<DateTime>("FirstTransactionOn"); b.Property<DateTime>("LastTransactionOn"); b.Property<int>("TransactionsCount"); b.HasKey("PublicAddress"); b.HasIndex("LastTransactionOn"); b.ToTable("Addresses"); }); modelBuilder.Entity("StateOfNeo.Data.Models.AddressAssetBalance", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AddressPublicAddress"); b.Property<string>("AssetHash"); b.Property<float>("Balance"); b.Property<DateTime>("CreatedOn"); b.Property<int>("TransactionsCount"); b.HasKey("Id"); b.HasIndex("AddressPublicAddress"); b.HasIndex("AssetHash"); b.ToTable("AddressBalances"); }); modelBuilder.Entity("StateOfNeo.Data.Models.AddressInAssetTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AddressPublicAddress"); b.Property<decimal>("Amount") .HasColumnType("decimal(36, 8)"); b.Property<int>("AssetInTransactionId"); b.Property<DateTime>("CreatedOn"); b.HasKey("Id"); b.HasIndex("AddressPublicAddress"); b.HasIndex("AssetInTransactionId"); b.ToTable("AddressesInAssetTransactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.AddressInTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AddressPublicAddress"); b.Property<decimal>("Amount") .HasColumnType("decimal(36, 8)"); b.Property<string>("AssetHash"); b.Property<DateTime>("CreatedOn"); b.Property<long>("DailyStamp"); b.Property<long>("HourlyStamp"); b.Property<long>("MonthlyStamp"); b.Property<long>("Timestamp"); b.Property<string>("TransactionHash"); b.HasKey("Id"); b.HasIndex("AddressPublicAddress"); b.HasIndex("AssetHash"); b.HasIndex("TransactionHash"); b.ToTable("AddressesInTransactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Asset", b => { b.Property<string>("Hash") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreatedOn"); b.Property<long?>("CurrentSupply"); b.Property<int>("Decimals"); b.Property<byte?>("GlobalType"); b.Property<long?>("MaxSupply"); b.Property<string>("Name"); b.Property<string>("Symbol"); b.Property<int>("TransactionsCount"); b.Property<int>("Type"); b.HasKey("Hash"); b.ToTable("Assets"); }); modelBuilder.Entity("StateOfNeo.Data.Models.AssetInTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AssetHash"); b.Property<DateTime>("CreatedOn"); b.Property<long>("Timestamp"); b.Property<string>("TransactionHash"); b.HasKey("Id"); b.HasIndex("AssetHash"); b.HasIndex("TransactionHash"); b.HasIndex("Timestamp", "AssetHash"); b.ToTable("AssetsInTransactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Block", b => { b.Property<string>("Hash") .ValueGeneratedOnAdd(); b.Property<decimal>("ConsensusData") .HasConversion(new ValueConverter<decimal, decimal>(v => default(decimal), v => default(decimal), new ConverterMappingHints(precision: 20, scale: 0))); b.Property<DateTime>("CreatedOn"); b.Property<long>("DailyStamp"); b.Property<int>("Height"); b.Property<long>("HourlyStamp"); b.Property<string>("InvocationScript"); b.Property<long>("MonthlyStamp"); b.Property<string>("NextConsensusNodeAddress"); b.Property<string>("PreviousBlockHash"); b.Property<int>("Size"); b.Property<double>("TimeInSeconds"); b.Property<long>("Timestamp"); b.Property<string>("Validator"); b.Property<string>("VerificationScript"); b.HasKey("Hash"); b.HasIndex("Height"); b.HasIndex("PreviousBlockHash"); b.HasIndex("Timestamp"); b.ToTable("Blocks"); }); modelBuilder.Entity("StateOfNeo.Data.Models.ChartEntry", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal?>("AccumulatedValue"); b.Property<long?>("Count"); b.Property<long>("TimeStamp"); b.Property<int>("Type"); b.Property<int>("UnitOfTime"); b.Property<decimal>("Value") .HasColumnType("decimal(36, 8)"); b.HasKey("Id"); b.ToTable("ChartEntries"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Node", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<long?>("FirstRuntime"); b.Property<string>("FlagUrl"); b.Property<int?>("Height"); b.Property<bool>("IsHttps"); b.Property<long?>("LastAudit"); b.Property<long?>("LatestRuntime"); b.Property<double?>("Latitude"); b.Property<string>("Locale"); b.Property<string>("Location"); b.Property<double?>("Longitude"); b.Property<int?>("MemoryPool"); b.Property<string>("Net"); b.Property<int?>("Peers"); b.Property<string>("Protocol"); b.Property<long>("SecondsOnline"); b.Property<string>("SuccessUrl"); b.Property<int>("Type"); b.Property<string>("Url"); b.Property<string>("Version"); b.HasKey("Id"); b.ToTable("Nodes"); }); modelBuilder.Entity("StateOfNeo.Data.Models.NodeAddress", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Ip"); b.Property<int>("NodeId"); b.Property<long?>("Port"); b.Property<int>("Type"); b.HasKey("Id"); b.HasIndex("NodeId"); b.ToTable("NodeAddresses"); }); modelBuilder.Entity("StateOfNeo.Data.Models.NodeAudit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<long>("DailyStamp"); b.Property<long>("HourlyStamp"); b.Property<int>("Latency"); b.Property<long>("MonthlyStamp"); b.Property<int>("NodeId"); b.Property<decimal>("Peers") .HasColumnType("decimal(36, 8)"); b.Property<long>("Timestamp"); b.HasKey("Id"); b.HasIndex("NodeId"); b.HasIndex("Timestamp"); b.ToTable("NodeAudits"); }); modelBuilder.Entity("StateOfNeo.Data.Models.NodeStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BlockHash"); b.Property<int>("BlockId"); b.Property<DateTime>("CreatedOn"); b.Property<bool>("IsP2pTcpOnline"); b.Property<bool>("IsP2pWsOnline"); b.Property<bool>("IsRpcOnline"); b.Property<int>("NodeId"); b.HasKey("Id"); b.HasIndex("BlockHash"); b.HasIndex("NodeId"); b.ToTable("NodeStatusUpdates"); }); modelBuilder.Entity("StateOfNeo.Data.Models.TotalStats", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("AddressCount"); b.Property<int?>("AssetsCount"); b.Property<int?>("BlockCount"); b.Property<long?>("BlocksSizes"); b.Property<decimal?>("BlocksTimes"); b.Property<decimal?>("ClaimedGas"); b.Property<long?>("Timestamp"); b.Property<long?>("TransactionsCount"); b.HasKey("Id"); b.ToTable("TotalStats"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.EnrollmentTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<string>("PublicKey"); b.Property<int>("TransactionId"); b.HasKey("Id"); b.ToTable("EnrollmentTransactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.InvocationTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<decimal>("Gas") .HasColumnType("decimal(36, 8)"); b.Property<string>("ScriptAsHexString"); b.Property<int>("TransactionId"); b.HasKey("Id"); b.ToTable("InvocationTransactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.MinerTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<long>("Nonce"); b.Property<int>("TransactionId"); b.HasKey("Id"); b.ToTable("MinerTransaction"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.PublishTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Author"); b.Property<string>("CodeVersion"); b.Property<DateTime>("CreatedOn"); b.Property<string>("Description"); b.Property<string>("Email"); b.Property<string>("Name"); b.Property<bool>("NeedStorage"); b.Property<string>("ParameterList"); b.Property<string>("ReturnType"); b.Property<string>("ScriptAsHexString"); b.Property<int>("TransactionId"); b.HasKey("Id"); b.ToTable("PublishTransactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.RegisterTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AdminAddress"); b.Property<decimal>("Amount") .HasColumnType("decimal(36, 8)"); b.Property<byte>("AssetType"); b.Property<DateTime>("CreatedOn"); b.Property<string>("Name"); b.Property<string>("OwnerPublicKey"); b.Property<byte>("Precision"); b.Property<int>("TransactionId"); b.HasKey("Id"); b.ToTable("RegisterTransactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.StateDescriptor", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<string>("Field"); b.Property<string>("KeyAsHexString"); b.Property<int>("TransactionId"); b.Property<byte>("Type"); b.Property<string>("ValueAsHexString"); b.HasKey("Id"); b.HasIndex("TransactionId"); b.ToTable("StateDescriptors"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.StateTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<int>("TransactionId"); b.HasKey("Id"); b.ToTable("StateTransactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.TransactedAsset", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal>("Amount") .HasColumnType("decimal(36, 8)"); b.Property<string>("AssetHash"); b.Property<int>("AssetType"); b.Property<DateTime>("CreatedOn"); b.Property<string>("FromAddressPublicAddress"); b.Property<string>("InGlobalTransactionHash"); b.Property<string>("OutGlobalTransactionHash"); b.Property<string>("ToAddressPublicAddress"); b.Property<string>("TransactionHash"); b.HasKey("Id"); b.HasIndex("AssetHash"); b.HasIndex("FromAddressPublicAddress"); b.HasIndex("InGlobalTransactionHash"); b.HasIndex("OutGlobalTransactionHash"); b.HasIndex("ToAddressPublicAddress"); b.HasIndex("TransactionHash"); b.ToTable("TransactedAssets"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.Transaction", b => { b.Property<string>("Hash") .ValueGeneratedOnAdd(); b.Property<string>("BlockId"); b.Property<DateTime>("CreatedOn"); b.Property<long>("DailyStamp"); b.Property<int?>("EnrollmentTransactionId"); b.Property<long>("HourlyStamp"); b.Property<int?>("InvocationTransactionId"); b.Property<int?>("MinerTransactionId"); b.Property<long>("MonthlyStamp"); b.Property<decimal>("NetworkFee") .HasColumnType("decimal(36, 8)"); b.Property<int?>("PublishTransactionId"); b.Property<int?>("RegisterTransactionId"); b.Property<int>("Size"); b.Property<int?>("StateTransactionId"); b.Property<decimal>("SystemFee") .HasColumnType("decimal(36, 8)"); b.Property<long>("Timestamp"); b.Property<byte>("Type"); b.Property<int>("Version"); b.HasKey("Hash"); b.HasIndex("BlockId"); b.HasIndex("EnrollmentTransactionId") .IsUnique() .HasFilter("[EnrollmentTransactionId] IS NOT NULL"); b.HasIndex("InvocationTransactionId") .IsUnique() .HasFilter("[InvocationTransactionId] IS NOT NULL"); b.HasIndex("MinerTransactionId") .IsUnique() .HasFilter("[MinerTransactionId] IS NOT NULL"); b.HasIndex("PublishTransactionId") .IsUnique() .HasFilter("[PublishTransactionId] IS NOT NULL"); b.HasIndex("RegisterTransactionId") .IsUnique() .HasFilter("[RegisterTransactionId] IS NOT NULL"); b.HasIndex("StateTransactionId") .IsUnique() .HasFilter("[StateTransactionId] IS NOT NULL"); b.HasIndex("Timestamp"); b.HasIndex("Timestamp", "Hash"); b.ToTable("Transactions"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.TransactionAttribute", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<string>("DataAsHexString"); b.Property<string>("TransactionHash"); b.Property<int>("TransactionId"); b.Property<int>("Usage"); b.HasKey("Id"); b.HasIndex("TransactionHash"); b.ToTable("TransactionAttributes"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.TransactionWitness", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Address"); b.Property<DateTime>("CreatedOn"); b.Property<string>("InvocationScriptAsHexString"); b.Property<string>("TransactionHash"); b.Property<int>("TransactionId"); b.Property<string>("VerificationScriptAsHexString"); b.HasKey("Id"); b.HasIndex("TransactionHash"); b.ToTable("TransactionWitnesses"); }); modelBuilder.Entity("StateOfNeo.Data.Models.AddressAssetBalance", b => { b.HasOne("StateOfNeo.Data.Models.Address", "Address") .WithMany("Balances") .HasForeignKey("AddressPublicAddress"); b.HasOne("StateOfNeo.Data.Models.Asset", "Asset") .WithMany("Balances") .HasForeignKey("AssetHash"); }); modelBuilder.Entity("StateOfNeo.Data.Models.AddressInAssetTransaction", b => { b.HasOne("StateOfNeo.Data.Models.Address", "Address") .WithMany("AddressesInAssetTransactions") .HasForeignKey("AddressPublicAddress"); b.HasOne("StateOfNeo.Data.Models.AssetInTransaction", "AssetInTransaction") .WithMany("AddressesInAssetTransactions") .HasForeignKey("AssetInTransactionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("StateOfNeo.Data.Models.AddressInTransaction", b => { b.HasOne("StateOfNeo.Data.Models.Address", "Address") .WithMany("AddressesInTransaction") .HasForeignKey("AddressPublicAddress"); b.HasOne("StateOfNeo.Data.Models.Asset", "Asset") .WithMany("AddressesInTransactions") .HasForeignKey("AssetHash"); b.HasOne("StateOfNeo.Data.Models.Transactions.Transaction", "Transaction") .WithMany("AddressesInTransactions") .HasForeignKey("TransactionHash"); }); modelBuilder.Entity("StateOfNeo.Data.Models.AssetInTransaction", b => { b.HasOne("StateOfNeo.Data.Models.Asset", "Asset") .WithMany("AssetsInTransactions") .HasForeignKey("AssetHash"); b.HasOne("StateOfNeo.Data.Models.Transactions.Transaction", "Transaction") .WithMany("AssetsInTransactions") .HasForeignKey("TransactionHash"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Block", b => { b.HasOne("StateOfNeo.Data.Models.Block", "PreviousBlock") .WithMany() .HasForeignKey("PreviousBlockHash"); }); modelBuilder.Entity("StateOfNeo.Data.Models.NodeAddress", b => { b.HasOne("StateOfNeo.Data.Models.Node", "Node") .WithMany("NodeAddresses") .HasForeignKey("NodeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("StateOfNeo.Data.Models.NodeAudit", b => { b.HasOne("StateOfNeo.Data.Models.Node", "Node") .WithMany("Audits") .HasForeignKey("NodeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("StateOfNeo.Data.Models.NodeStatus", b => { b.HasOne("StateOfNeo.Data.Models.Block", "Block") .WithMany("NodeStatusUpdates") .HasForeignKey("BlockHash"); b.HasOne("StateOfNeo.Data.Models.Node", "Node") .WithMany("NodeStatusUpdates") .HasForeignKey("NodeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.StateDescriptor", b => { b.HasOne("StateOfNeo.Data.Models.Transactions.StateTransaction", "Transaction") .WithMany("Descriptors") .HasForeignKey("TransactionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.TransactedAsset", b => { b.HasOne("StateOfNeo.Data.Models.Asset", "Asset") .WithMany("TransactedAssets") .HasForeignKey("AssetHash"); b.HasOne("StateOfNeo.Data.Models.Address", "FromAddress") .WithMany("OutgoingTransactions") .HasForeignKey("FromAddressPublicAddress"); b.HasOne("StateOfNeo.Data.Models.Transactions.Transaction", "InGlobalTransaction") .WithMany("GlobalIncomingAssets") .HasForeignKey("InGlobalTransactionHash"); b.HasOne("StateOfNeo.Data.Models.Transactions.Transaction", "OutGlobalTransaction") .WithMany("GlobalOutgoingAssets") .HasForeignKey("OutGlobalTransactionHash"); b.HasOne("StateOfNeo.Data.Models.Address", "ToAddress") .WithMany("IncomingTransactions") .HasForeignKey("ToAddressPublicAddress"); b.HasOne("StateOfNeo.Data.Models.Transactions.Transaction", "Transaction") .WithMany("Assets") .HasForeignKey("TransactionHash"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.Transaction", b => { b.HasOne("StateOfNeo.Data.Models.Block", "Block") .WithMany("Transactions") .HasForeignKey("BlockId"); b.HasOne("StateOfNeo.Data.Models.Transactions.EnrollmentTransaction", "EnrollmentTransaction") .WithOne("Transaction") .HasForeignKey("StateOfNeo.Data.Models.Transactions.Transaction", "EnrollmentTransactionId"); b.HasOne("StateOfNeo.Data.Models.Transactions.InvocationTransaction", "InvocationTransaction") .WithOne("Transaction") .HasForeignKey("StateOfNeo.Data.Models.Transactions.Transaction", "InvocationTransactionId"); b.HasOne("StateOfNeo.Data.Models.Transactions.MinerTransaction", "MinerTransaction") .WithOne("Transaction") .HasForeignKey("StateOfNeo.Data.Models.Transactions.Transaction", "MinerTransactionId"); b.HasOne("StateOfNeo.Data.Models.Transactions.PublishTransaction", "PublishTransaction") .WithOne("Transaction") .HasForeignKey("StateOfNeo.Data.Models.Transactions.Transaction", "PublishTransactionId"); b.HasOne("StateOfNeo.Data.Models.Transactions.RegisterTransaction", "RegisterTransaction") .WithOne("Transaction") .HasForeignKey("StateOfNeo.Data.Models.Transactions.Transaction", "RegisterTransactionId"); b.HasOne("StateOfNeo.Data.Models.Transactions.StateTransaction", "StateTransaction") .WithOne("Transaction") .HasForeignKey("StateOfNeo.Data.Models.Transactions.Transaction", "StateTransactionId"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.TransactionAttribute", b => { b.HasOne("StateOfNeo.Data.Models.Transactions.Transaction", "Transaction") .WithMany("Attributes") .HasForeignKey("TransactionHash"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Transactions.TransactionWitness", b => { b.HasOne("StateOfNeo.Data.Models.Transactions.Transaction", "Transaction") .WithMany("Witnesses") .HasForeignKey("TransactionHash"); }); #pragma warning restore 612, 618 } } }
35.53059
175
0.494396
[ "MIT" ]
alienworks/state-of-neo-server
StateOfNeo/StateOfNeo.Data/Migrations/20181217183132_TotalStats_ForgotenSetOfPropertiesAdded.Designer.cs
31,944
C#
 using System.Collections.Generic; namespace Flighter.Core { public enum TextAlign { TopLeft, TopCenter, TopRight, MiddleLeft, MiddleCenter, MiddleRight, BottomLeft, BottomCenter, BottomRight } public enum FontStyle { Normal, Bold, Italic, BoldAndItalic } public enum TextOverflow { Clip, Overflow } public interface IFontHandle { Size PreferredSize(string text, TextStyle style, BoxConstraints constraints); } public struct TextStyle { // TODO: Define all these. public IFontHandle font; public int size; public float lineSpacing; public TextAlign textAlign; public FontStyle fontStyle; public bool wrapLines; public TextOverflow textOverflow; public Color color; /// <summary> /// Create a new <see cref="TextStyle"/> with the values specified. /// Values left null will be copied from this. /// </summary> /// <returns></returns> public TextStyle From( IFontHandle font = null, int? size = null, float? lineSpacing = null, TextAlign? textAlign = null, FontStyle? fontStyle = null, bool? wrapLines = null, TextOverflow? textOverflow = null, Color? color = null) { return new TextStyle { font = font ?? this.font, size = size ?? this.size, lineSpacing = lineSpacing ?? this.lineSpacing, textAlign = textAlign ?? this.textAlign, fontStyle = fontStyle ?? this.fontStyle, wrapLines = wrapLines ?? this.wrapLines, textOverflow = textOverflow ?? this.textOverflow, color = color ?? this.color, }; } public override bool Equals(object obj) { if (!(obj is TextStyle)) { return false; } var style = (TextStyle)obj; return EqualityComparer<IFontHandle>.Default.Equals(font, style.font) && size == style.size && lineSpacing == style.lineSpacing && textAlign == style.textAlign && fontStyle == style.fontStyle && wrapLines == style.wrapLines && textOverflow == style.textOverflow && color == style.color; } public override int GetHashCode() { var hashCode = -1944643188; hashCode = hashCode * -1521134295 + EqualityComparer<IFontHandle>.Default.GetHashCode(font); hashCode = hashCode * -1521134295 + size.GetHashCode(); hashCode = hashCode * -1521134295 + lineSpacing.GetHashCode(); hashCode = hashCode * -1521134295 + textAlign.GetHashCode(); hashCode = hashCode * -1521134295 + fontStyle.GetHashCode(); hashCode = hashCode * -1521134295 + wrapLines.GetHashCode(); hashCode = hashCode * -1521134295 + textOverflow.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<Color>.Default.GetHashCode(color); return hashCode; } public static bool operator ==(TextStyle style1, TextStyle style2) { return style1.Equals(style2); } public static bool operator !=(TextStyle style1, TextStyle style2) { return !(style1 == style2); } } public abstract class TextComponent : Component { public abstract string Data { get; set; } public abstract TextStyle? Style { get; set; } } public struct Color { public float r, g, b, a; public Color(float v, float a = 1) { r = g = b = v; this.a = a; } public Color(float r, float g, float b, float a = 1) { this.r = r; this.g = g; this.b = b; this.a = a; } public override bool Equals(object obj) { if (!(obj is Color)) { return false; } var color = (Color)obj; return r == color.r && g == color.g && b == color.b && a == color.a; } public override int GetHashCode() { var hashCode = -490236692; hashCode = hashCode * -1521134295 + r.GetHashCode(); hashCode = hashCode * -1521134295 + g.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); hashCode = hashCode * -1521134295 + a.GetHashCode(); return hashCode; } public override string ToString() { return "r:" + r + ", g:" + g + ", b:" + b + ", a:" + a; } public static bool operator ==(Color color1, Color color2) { return color1.Equals(color2); } public static bool operator !=(Color color1, Color color2) { return !(color1 == color2); } } public abstract class ColorComponent : Component { public abstract Color Color { get; set; } } public enum BoxFit { /// <summary> /// As big as possible within the box, without distorting. /// </summary> Contain, /// <summary> /// Fill the entire frame, without distorting, cropping edges. /// </summary> Cover, /// <summary> /// Fill the entire frame, distorting. /// </summary> Fill, /// <summary> /// Top and bottom edges will be flush with edges. /// </summary> FitHeight, /// <summary> /// Left and right edges will be flush with edges. /// </summary> FitWidth } public abstract class ImageComponent : Component { public abstract IImageHandle ImageHandle { get; set; } public abstract Color? Color { get; set; } } public abstract class ClipComponent : Component { } }
28.926267
104
0.518719
[ "MIT" ]
After-Ever/Flighter
Flighter/Core/CoreComponents.cs
6,279
C#
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; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// Override the value of a single interval in a forecast /// </summary> [DataContract] public partial class WfmForecastModificationIntervalOffsetValue : IEquatable<WfmForecastModificationIntervalOffsetValue> { /// <summary> /// Initializes a new instance of the <see cref="WfmForecastModificationIntervalOffsetValue" /> class. /// </summary> [JsonConstructorAttribute] protected WfmForecastModificationIntervalOffsetValue() { } /// <summary> /// Initializes a new instance of the <see cref="WfmForecastModificationIntervalOffsetValue" /> class. /// </summary> /// <param name="IntervalIndex">The number of 15 minute intervals past referenceStartDate to which to apply this modification (required).</param> /// <param name="Value">The value to set for the given interval (required).</param> public WfmForecastModificationIntervalOffsetValue(int? IntervalIndex = null, double? Value = null) { this.IntervalIndex = IntervalIndex; this.Value = Value; } /// <summary> /// The number of 15 minute intervals past referenceStartDate to which to apply this modification /// </summary> /// <value>The number of 15 minute intervals past referenceStartDate to which to apply this modification</value> [DataMember(Name="intervalIndex", EmitDefaultValue=false)] public int? IntervalIndex { get; set; } /// <summary> /// The value to set for the given interval /// </summary> /// <value>The value to set for the given interval</value> [DataMember(Name="value", EmitDefaultValue=false)] public double? Value { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class WfmForecastModificationIntervalOffsetValue {\n"); sb.Append(" IntervalIndex: ").Append(IntervalIndex).Append("\n"); sb.Append(" Value: ").Append(Value).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 WfmForecastModificationIntervalOffsetValue); } /// <summary> /// Returns true if WfmForecastModificationIntervalOffsetValue instances are equal /// </summary> /// <param name="other">Instance of WfmForecastModificationIntervalOffsetValue to be compared</param> /// <returns>Boolean</returns> public bool Equals(WfmForecastModificationIntervalOffsetValue other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.IntervalIndex == other.IntervalIndex || this.IntervalIndex != null && this.IntervalIndex.Equals(other.IntervalIndex) ) && ( this.Value == other.Value || this.Value != null && this.Value.Equals(other.Value) ); } /// <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.IntervalIndex != null) hash = hash * 59 + this.IntervalIndex.GetHashCode(); if (this.Value != null) hash = hash * 59 + this.Value.GetHashCode(); return hash; } } } }
34.266234
153
0.559788
[ "MIT" ]
nmusco/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/WfmForecastModificationIntervalOffsetValue.cs
5,277
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using LinqToDB; using LinqToDB.Data; using LinqToDB.DataProvider.MySql; using LinqToDB.DataProvider.SqlServer; using LinqToDB.Expressions; using LinqToDB.Extensions; using LinqToDB.Linq; using LinqToDB.Mapping; namespace Tests.UserTests { public static class DynamicExtensions { private static readonly MethodInfo SetValueMethodInfo = MemberHelper .MethodOf<object>(o => ((IUpdatable<object>)null).Set(null, 0)) .GetGenericMethodDefinition(); private static readonly MethodInfo SetExpressionMethodInfo = MemberHelper .MethodOf<object>(o => ((IUpdatable<object>)null).Set(null, v => v.ToString())) .GetGenericMethodDefinition(); private static readonly MethodInfo InnerJoinMethodInfo = MemberHelper .MethodOf<object>(o => ((IQueryable<object>)null).InnerJoin<object, object, object>(null, null, null)) .GetGenericMethodDefinition(); private static readonly MethodInfo SqlPropertyMethodInfo = typeof(Sql).GetMethod("Property") .GetGenericMethodDefinition(); public enum FieldSource { Propety, Column } public static Func<ParameterExpression, KeyValuePair<string, object>, Expression> GetFieldFunc( FieldSource fieldSource) { switch (fieldSource) { case FieldSource.Propety: return GetPropertyExpression; case FieldSource.Column: return GetColumnExpression; default: throw new ArgumentOutOfRangeException(nameof(fieldSource), fieldSource, null); } } public static IQueryable<T> FilterByValues<T>(this IQueryable<T> source, IEnumerable<KeyValuePair<string, object>> values, Func<ParameterExpression, KeyValuePair<string, object>, Expression> fieldFunc) { var param = Expression.Parameter(typeof(T)); foreach (var pair in values) { var fieldExpression = fieldFunc(param, pair); if (fieldExpression != null) { var equality = Expression.Equal(fieldExpression, Expression.Constant(pair.Value, fieldExpression.Type)); var lambda = Expression.Lambda<Func<T, bool>>(equality, param); source = source.Where(lambda); } } return source; } public static IQueryable<T> FilterByValues<T>(this IQueryable<T> source, IEnumerable<KeyValuePair<string, object>> values, FieldSource fieldSource = FieldSource.Propety) { return FilterByValues(source, values, GetFieldFunc(fieldSource)); } public static IUpdatable<T> SetValues<T>(this IUpdatable<T> source, IEnumerable<KeyValuePair<string, object>> values, Func<ParameterExpression, KeyValuePair<string, object>, Expression> fieldFunc) { var param = Expression.Parameter(typeof(T)); object current = source; foreach (var pair in values) { var fieldExpression = fieldFunc(param, pair); if (fieldExpression != null) { var lambda = Expression.Lambda(fieldExpression, param); var method = SetValueMethodInfo.MakeGenericMethod(typeof(T), fieldExpression.Type); current = method.Invoke(null, new[] { current, lambda, pair.Value }); } } return (IUpdatable<T>)current; } public static IUpdatable<T> SetValues<T>(this IQueryable<T> source, IEnumerable<KeyValuePair<string, object>> values, FieldSource fieldSource = FieldSource.Propety) { return source.AsUpdatable().SetValues(values, fieldSource); } public static IUpdatable<T> SetValues<T>(this IUpdatable<T> source, IEnumerable<KeyValuePair<string, object>> values, FieldSource fieldSource = FieldSource.Propety) { return SetValues(source, values, GetFieldFunc(fieldSource)); } public static IUpdatable<T> SetValues<T>(this IQueryable<T> source, T obj, MappingSchema schema = null) { return source.AsUpdatable().SetValues(obj, schema); } public static IUpdatable<T> SetValues<T>(this IUpdatable<T> source, T obj, MappingSchema schema = null) { schema = schema ?? MappingSchema.Default; var descriptor = schema.GetEntityDescriptor(typeof(T)); var toUpdate = descriptor.Columns.Where(c => !c.SkipOnUpdate); var param = Expression.Parameter(typeof(T)); object current = source; foreach (var c in toUpdate) if (c.MemberAccessor.Getter != null) { var value = c.MemberAccessor.Getter(obj); var memberAccess = Expression.MakeMemberAccess(param, c.MemberInfo); var lambda = Expression.Lambda(memberAccess, param); var method = SetValueMethodInfo.MakeGenericMethod(typeof(T), memberAccess.Type); current = method.Invoke(null, new[] { current, lambda, value }); } return (IUpdatable<T>)current; } public static Expression GetPropertyExpression(ParameterExpression instance, KeyValuePair<string, object> pair) { var propInfo = instance.Type.GetProperty(pair.Key); if (propInfo == null) return null; var propExpression = Expression.MakeMemberAccess(instance, propInfo); return propExpression; } public static Expression GetColumnExpression(ParameterExpression instance, KeyValuePair<string, object> pair) { var valueType = pair.Value != null ? pair.Value.GetType() : typeof(string); var method = SqlPropertyMethodInfo.MakeGenericMethod(valueType); var sqlPropertyCall = Expression.Call(null, method, instance, Expression.Constant(pair.Key, typeof(string))); var memberInfo = MemberHelper.GetMemberInfo(sqlPropertyCall); var memberAccess = Expression.MakeMemberAccess(instance, memberInfo); return memberAccess; } public class JoinHelper<TOuter, TInner> { public TOuter Outer { get; set; } public TInner Inner { get; set; } } private static ITable<T> CreateTempTable<T>(DataConnection dataConnection, string tableName = null) { // temporary solution, will unify Temporary Table creation if (tableName == null) { tableName = "temp_" + dataConnection.MappingSchema.GetEntityDescriptor(typeof(T)).TableName; } if (dataConnection.DataProvider is MySqlDataProvider) return dataConnection.CreateTable<T>(tableName, statementHeader: "CREATE TEMPORARY TABLE {0}"); if (dataConnection.DataProvider is SqlServerDataProvider) { if (!tableName.StartsWith("#")) tableName = tableName + "#"; return dataConnection.CreateTable<T>(tableName); } throw new NotImplementedException( $"CreateTempTable is not implemented for \"{dataConnection.DataProvider.GetType()}\""); } public static int BulkUpdate<T>( this DataConnection dataConnection, IEnumerable<T> items, ITable<T> target, params Expression<Func<T, object>>[] fields ) where T : class { var temp = CreateTempTable<T>(dataConnection); try { temp.BulkCopy(items); return BuildBulkUpdate(dataConnection, target, temp, fields) .Update(); } finally { temp.Drop(); } } public static async Task<int> BulkUpdateAsync<T>( this DataConnection dataConnection, IEnumerable<T> items, ITable<T> target, params Expression<Func<T, object>>[] fields ) where T : class { var temp = CreateTempTable<T>(dataConnection); try { temp.BulkCopy(items); return await BuildBulkUpdate(dataConnection, target, temp, fields) .UpdateAsync(); } finally { await temp.DropAsync(); } } public static IUpdatable<JoinHelper<T, T>> BuildBulkUpdate<T>( DataConnection dataConnection, ITable<T> target, ITable<T> sourceTable, params Expression<Func<T, object>>[] fields ) where T : class { var descriptor = dataConnection.MappingSchema.GetEntityDescriptor(typeof(T)); var members = new List<MemberInfo>(); if (fields.Length == 0) { members.AddRange( descriptor.Columns .Where(c => !c.SkipOnUpdate & !c.IsPrimaryKey & !c.IsIdentity) .Select(c => c.MemberInfo) ); } else { foreach (var field in fields) { var member = MemberHelper.GetMemberInfo(field); if (member == null) throw new LinqToDBException($"Can not retrive member info from lambda function: {field}"); members.Add(member); } } /* Emulating the following calls var join = target.InnerJoin(temporaryTable, (outer, inner) => outer.ID1 == inner.ID1 && outer.ID2 == inner.ID2, (outer, inner) => new DynamicExtensions.JoinHelper<BulkUpdateEntity, BulkUpdateEntity> { Outer = outer, Inner = inner }); var updatable = join.AsUpdatable(); updatable = updatable.Set(pair => pair.Outer.Value1, pair => pair.Inner.Value1); updatable = updatable.Set(pair => pair.Outer.Value2, pair => pair.Inner.Value2); */ var joinMethod = InnerJoinMethodInfo.MakeGenericMethod(typeof(T), typeof(T), typeof(JoinHelper<T, T>)); var outerParam = Expression.Parameter(typeof(T), "outer"); var innerParam = Expression.Parameter(typeof(T), "inner"); Expression cmpExpression = null; foreach (var c in descriptor.Columns.Where(c => c.IsPrimaryKey)) { var equals = Expression.Equal( Expression.MakeMemberAccess(outerParam, c.MemberInfo), Expression.MakeMemberAccess(innerParam, c.MemberInfo) ); cmpExpression = cmpExpression == null ? equals : Expression.AndAlso(cmpExpression, equals); } if (cmpExpression == null) throw new LinqToDBException($"Entity {typeof(T)} does not contain primary key"); var equalityLambda = Expression.Lambda(cmpExpression, outerParam, innerParam); var helperType = typeof(JoinHelper<T, T>); var constructor = helperType.GetConstructor(new Type[0]); var joinHelperOuterPropertyInfo = helperType.GetProperty("Outer"); var joinHelperInnerPropertyInfo = helperType.GetProperty("Inner"); var newExpression = Expression.Lambda( Expression.MemberInit( Expression.New(constructor), Expression.Bind(joinHelperOuterPropertyInfo, outerParam), Expression.Bind(joinHelperInnerPropertyInfo, innerParam) ), outerParam, innerParam); var joinQuery = joinMethod.Invoke(null, new object[] { target.AsQueryable(), sourceTable.AsQueryable(), equalityLambda, newExpression }); object updatable = ((IQueryable<JoinHelper<T, T>>)joinQuery).AsUpdatable(); var helperParam = Expression.Parameter(helperType, "pair"); var outerExpression = Expression.MakeMemberAccess(helperParam, joinHelperOuterPropertyInfo); var innerExpression = Expression.MakeMemberAccess(helperParam, joinHelperInnerPropertyInfo); foreach (var memberInfo in members) { var method = SetExpressionMethodInfo.MakeGenericMethod(helperType, memberInfo.GetMemberType()); var propLambda = Expression.Lambda(Expression.MakeMemberAccess(outerExpression, memberInfo), helperParam); var valueLambda = Expression.Lambda(Expression.MakeMemberAccess(innerExpression, memberInfo), helperParam); updatable = method.Invoke(null, new object[] { updatable, propLambda, valueLambda }); } return (IUpdatable<JoinHelper<T, T>>)updatable; } } }
33.648968
141
0.691155
[ "MIT" ]
ozergurbanov1/linq2db
Tests/Linq/UserTests/DynamicExtensions.cs
11,409
C#
using System; namespace Eqstra.CrossPlatform.API.Areas.HelpPage { /// <summary> /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. /// </summary> public class ImageSample { /// <summary> /// Initializes a new instance of the <see cref="ImageSample"/> class. /// </summary> /// <param name="src">The URL of an image.</param> public ImageSample(string src) { if (src == null) { throw new ArgumentNullException("src"); } Src = src; } public string Src { get; private set; } public override bool Equals(object obj) { ImageSample other = obj as ImageSample; return other != null && Src == other.Src; } public override int GetHashCode() { return Src.GetHashCode(); } public override string ToString() { return Src; } } }
26.02439
130
0.530459
[ "MIT" ]
pithline/FMS
Pithline.FMS.CrossPlatform.API/Areas/HelpPage/SampleGeneration/ImageSample.cs
1,067
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Autofac; using MediatR; using Strive.Core.Interfaces; using Strive.Core.Services; using Strive.Core.Services.Permissions; namespace Strive.Hubs.Core.Services.Middlewares { public static class ServiceInvokerPermissionMiddleware { public static IServiceRequestBuilder<TResponse> RequirePermissions<TResponse>( this IServiceRequestBuilder<TResponse> builder, params PermissionDescriptor<bool>[] requiredPermissions) { return builder.AddMiddleware(context => CheckPermissions(context, requiredPermissions)); } public static IServiceRequestBuilder<TResponse> RequirePermissions<TResponse>( this IServiceRequestBuilder<TResponse> builder, IEnumerable<PermissionDescriptor<bool>> requiredPermissions) { return builder.RequirePermissions(requiredPermissions.ToArray()); } public static async ValueTask<SuccessOrError<Unit>> CheckPermissions(ServiceInvokerContext context, params PermissionDescriptor<bool>[] requiredPermissions) { if (requiredPermissions.Length == 0) return SuccessOrError<Unit>.Succeeded(Unit.Value); var participantPermissions = context.Context.Resolve<IParticipantPermissions>(); var permissions = await participantPermissions.FetchForParticipant(context.Participant); foreach (var permission in requiredPermissions) { var permissionValue = await permissions.GetPermissionValue(permission); if (!permissionValue) return CommonError.PermissionDenied(permission); } return SuccessOrError<Unit>.Succeeded(Unit.Value); } } }
40.977273
120
0.713256
[ "Apache-2.0" ]
Anapher/PaderConference
src/Services/ConferenceManagement/Strive/Hubs/Core/Services/Middlewares/ServiceInvokerPermissionMiddleware.cs
1,803
C#
using HelenSposa.Core.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelenSposa.Entities.Dtos.Product { public class ProductAddDto:IDto { public string Name { get; set; } } }
19.066667
42
0.734266
[ "MIT" ]
omerserdarkose/WeddingStore-Backend
HelenSposa.Entities/Dtos/Product/ProductAddDto.cs
288
C#
using System; using System.Threading.Tasks; using Foundatio.Parsers.LuceneQueries.Extensions; using Foundatio.Parsers.LuceneQueries.Nodes; namespace Foundatio.Parsers.LuceneQueries.Visitors; public class AssignOperationTypeVisitor : ChainableQueryVisitor { public override Task VisitAsync(GroupNode node, IQueryVisitorContext context) { if (String.IsNullOrEmpty(node.Field)) return base.VisitAsync(node, context); if (node.Left is not TermNode leftTerm) { context.AddValidationError($"Aggregations ({node.Field}) must specify a field."); return Task.CompletedTask; } if (String.IsNullOrEmpty(leftTerm.Term)) context.AddValidationError($"Aggregations ({node.Field}) must specify a field."); if (node.Field.StartsWith("@")) return base.VisitAsync(node, context); node.SetOperationType(node.Field); node.Field = leftTerm.Term; node.Boost = leftTerm.Boost; node.Proximity = leftTerm.Proximity; node.Left = null; return base.VisitAsync(node, context); } public override void Visit(TermNode node, IQueryVisitorContext context) { if (String.IsNullOrEmpty(node.Field) && !String.IsNullOrEmpty(node.Term)) { context.AddValidationError($"Aggregations ({node.Term}) must specify a field."); node.SetOperationType(node.Term); return; } if (String.IsNullOrEmpty(node.Term)) context.AddValidationError($"Aggregations ({node.Field}) must specify a field."); if (node.Field != null && node.Field.StartsWith("@")) return; node.SetOperationType(node.Field); node.Field = node.Term; node.Term = null; } } public static class AggregationType { public const string Min = "min"; public const string Max = "max"; public const string Avg = "avg"; public const string Sum = "sum"; public const string Cardinality = "cardinality"; public const string Missing = "missing"; public const string DateHistogram = "date"; public const string Histogram = "histogram"; public const string Percentiles = "percentiles"; public const string GeoHashGrid = "geogrid"; public const string Terms = "terms"; public const string Stats = "stats"; public const string TopHits = "tophits"; public const string ExtendedStats = "exstats"; }
35.911765
93
0.665848
[ "Apache-2.0" ]
exceptionless/Exceptionless.QueryParser
src/Foundatio.Parsers.LuceneQueries/Visitors/AssignOperationTypeVisitor.cs
2,444
C#
/** * Autogenerated by Thrift Compiler (0.11.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; using System.Threading.Tasks; using Thrift; using Thrift.Collections; using Thrift.Protocols; using Thrift.Protocols.Entities; using Thrift.Protocols.Utilities; using Thrift.Transports; using Thrift.Transports.Client; using Thrift.Transports.Server; namespace Ruyi.SDK.PublisherSubscriber { public partial class UserShellEvent : TBase { private UserShellEventType _EventType; /// <summary> /// /// <seealso cref="UserShellEventType"/> /// </summary> public UserShellEventType EventType { get { return _EventType; } set { __isset.EventType = true; this._EventType = value; } } public Isset __isset; public struct Isset { public bool EventType; } public UserShellEvent() { } public async Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken) { iprot.IncrementRecursionDepth(); try { TField field; await iprot.ReadStructBeginAsync(cancellationToken); while (true) { field = await iprot.ReadFieldBeginAsync(cancellationToken); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.I32) { EventType = (UserShellEventType)await iprot.ReadI32Async(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; default: await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); break; } await iprot.ReadFieldEndAsync(cancellationToken); } await iprot.ReadStructEndAsync(cancellationToken); } finally { iprot.DecrementRecursionDepth(); } } public async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken) { oprot.IncrementRecursionDepth(); try { var struc = new TStruct("UserShellEvent"); await oprot.WriteStructBeginAsync(struc, cancellationToken); var field = new TField(); if (__isset.EventType) { field.Name = "EventType"; field.Type = TType.I32; field.ID = 1; await oprot.WriteFieldBeginAsync(field, cancellationToken); await oprot.WriteI32Async((int)EventType, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } await oprot.WriteFieldStopAsync(cancellationToken); await oprot.WriteStructEndAsync(cancellationToken); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { var sb = new StringBuilder("UserShellEvent("); bool __first = true; if (__isset.EventType) { if(!__first) { sb.Append(", "); } __first = false; sb.Append("EventType: "); sb.Append(EventType); } sb.Append(")"); return sb.ToString(); } } }
23.726027
92
0.596709
[ "MIT" ]
c04x/sdk
SDK.Gen.ServiceAsync/Generated/Ruyi/SDK/PublisherSubscriber/UserShellEvent.cs
3,464
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.Neptune; using Amazon.Neptune.Model; namespace Amazon.PowerShell.Cmdlets.NPT { /// <summary> /// Modify a setting for a DB cluster. You can change one or more database configuration /// parameters by specifying these parameters and the new values in the request. /// </summary> [Cmdlet("Edit", "NPTDBCluster", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("Amazon.Neptune.Model.DBCluster")] [AWSCmdlet("Calls the Amazon Neptune ModifyDBCluster API operation.", Operation = new[] {"ModifyDBCluster"}, SelectReturnType = typeof(Amazon.Neptune.Model.ModifyDBClusterResponse))] [AWSCmdletOutput("Amazon.Neptune.Model.DBCluster or Amazon.Neptune.Model.ModifyDBClusterResponse", "This cmdlet returns an Amazon.Neptune.Model.DBCluster object.", "The service call response (type Amazon.Neptune.Model.ModifyDBClusterResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class EditNPTDBClusterCmdlet : AmazonNeptuneClientCmdlet, IExecutor { #region Parameter ApplyImmediately /// <summary> /// <para> /// <para>A value that specifies whether the modifications in this request and any pending modifications /// are asynchronously applied as soon as possible, regardless of the <code>PreferredMaintenanceWindow</code> /// setting for the DB cluster. If this parameter is set to <code>false</code>, changes /// to the DB cluster are applied during the next maintenance window.</para><para>The <code>ApplyImmediately</code> parameter only affects the <code>NewDBClusterIdentifier</code> /// and <code>MasterUserPassword</code> values. If you set the <code>ApplyImmediately</code> /// parameter value to false, then changes to the <code>NewDBClusterIdentifier</code> /// and <code>MasterUserPassword</code> values are applied during the next maintenance /// window. All other changes are applied immediately, regardless of the value of the /// <code>ApplyImmediately</code> parameter.</para><para>Default: <code>false</code></para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? ApplyImmediately { get; set; } #endregion #region Parameter BackupRetentionPeriod /// <summary> /// <para> /// <para>The number of days for which automated backups are retained. You must specify a minimum /// value of 1.</para><para>Default: 1</para><para>Constraints:</para><ul><li><para>Must be a value from 1 to 35</para></li></ul> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Int32? BackupRetentionPeriod { get; set; } #endregion #region Parameter DBClusterIdentifier /// <summary> /// <para> /// <para>The DB cluster identifier for the cluster being modified. This parameter is not case-sensitive.</para><para>Constraints:</para><ul><li><para>Must match the identifier of an existing DBCluster.</para></li></ul> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String DBClusterIdentifier { get; set; } #endregion #region Parameter DBClusterParameterGroupName /// <summary> /// <para> /// <para>The name of the DB cluster parameter group to use for the DB cluster.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String DBClusterParameterGroupName { get; set; } #endregion #region Parameter DeletionProtection /// <summary> /// <para> /// <para>A value that indicates whether the DB cluster has deletion protection enabled. The /// database can't be deleted when deletion protection is enabled. By default, deletion /// protection is disabled.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? DeletionProtection { get; set; } #endregion #region Parameter CloudwatchLogsExportConfiguration_DisableLogType /// <summary> /// <para> /// <para>The list of log types to disable.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("CloudwatchLogsExportConfiguration_DisableLogTypes")] public System.String[] CloudwatchLogsExportConfiguration_DisableLogType { get; set; } #endregion #region Parameter EnableIAMDatabaseAuthentication /// <summary> /// <para> /// <para>True to enable mapping of AWS Identity and Access Management (IAM) accounts to database /// accounts, and otherwise false.</para><para>Default: <code>false</code></para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? EnableIAMDatabaseAuthentication { get; set; } #endregion #region Parameter CloudwatchLogsExportConfiguration_EnableLogType /// <summary> /// <para> /// <para>The list of log types to enable.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("CloudwatchLogsExportConfiguration_EnableLogTypes")] public System.String[] CloudwatchLogsExportConfiguration_EnableLogType { get; set; } #endregion #region Parameter EngineVersion /// <summary> /// <para> /// <para>The version number of the database engine. Currently, setting this parameter has no /// effect. To upgrade your database engine to the most recent release, use the <a>ApplyPendingMaintenanceAction</a> /// API.</para><para>For a list of valid engine versions, see <a>CreateDBInstance</a>, or call <a>DescribeDBEngineVersions</a>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String EngineVersion { get; set; } #endregion #region Parameter MasterUserPassword /// <summary> /// <para> /// <para>The new password for the master database user. This password can contain any printable /// ASCII character except "/", """, or "@".</para><para>Constraints: Must contain from 8 to 41 characters.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String MasterUserPassword { get; set; } #endregion #region Parameter NewDBClusterIdentifier /// <summary> /// <para> /// <para>The new DB cluster identifier for the DB cluster when renaming a DB cluster. This /// value is stored as a lowercase string.</para><para>Constraints:</para><ul><li><para>Must contain from 1 to 63 letters, numbers, or hyphens</para></li><li><para>The first character must be a letter</para></li><li><para>Cannot end with a hyphen or contain two consecutive hyphens</para></li></ul><para>Example: <code>my-cluster2</code></para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String NewDBClusterIdentifier { get; set; } #endregion #region Parameter OptionGroupName /// <summary> /// <para> /// <para><i>(Not supported by Neptune)</i></para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String OptionGroupName { get; set; } #endregion #region Parameter Port /// <summary> /// <para> /// <para>The port number on which the DB cluster accepts connections.</para><para>Constraints: Value must be <code>1150-65535</code></para><para>Default: The same port as the original DB cluster.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Int32? Port { get; set; } #endregion #region Parameter PreferredBackupWindow /// <summary> /// <para> /// <para>The daily time range during which automated backups are created if automated backups /// are enabled, using the <code>BackupRetentionPeriod</code> parameter.</para><para>The default is a 30-minute window selected at random from an 8-hour block of time /// for each AWS Region.</para><para>Constraints:</para><ul><li><para>Must be in the format <code>hh24:mi-hh24:mi</code>.</para></li><li><para>Must be in Universal Coordinated Time (UTC).</para></li><li><para>Must not conflict with the preferred maintenance window.</para></li><li><para>Must be at least 30 minutes.</para></li></ul> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String PreferredBackupWindow { get; set; } #endregion #region Parameter PreferredMaintenanceWindow /// <summary> /// <para> /// <para>The weekly time range during which system maintenance can occur, in Universal Coordinated /// Time (UTC).</para><para>Format: <code>ddd:hh24:mi-ddd:hh24:mi</code></para><para>The default is a 30-minute window selected at random from an 8-hour block of time /// for each AWS Region, occurring on a random day of the week.</para><para>Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun.</para><para>Constraints: Minimum 30-minute window.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String PreferredMaintenanceWindow { get; set; } #endregion #region Parameter VpcSecurityGroupId /// <summary> /// <para> /// <para>A list of VPC security groups that the DB cluster will belong to.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("VpcSecurityGroupIds")] public System.String[] VpcSecurityGroupId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'DBCluster'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Neptune.Model.ModifyDBClusterResponse). /// Specifying the name of a property of type Amazon.Neptune.Model.ModifyDBClusterResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "DBCluster"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the DBClusterIdentifier parameter. /// The -PassThru parameter is deprecated, use -Select '^DBClusterIdentifier' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^DBClusterIdentifier' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.DBClusterIdentifier), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Edit-NPTDBCluster (ModifyDBCluster)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.Neptune.Model.ModifyDBClusterResponse, EditNPTDBClusterCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.DBClusterIdentifier; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.ApplyImmediately = this.ApplyImmediately; context.BackupRetentionPeriod = this.BackupRetentionPeriod; if (this.CloudwatchLogsExportConfiguration_DisableLogType != null) { context.CloudwatchLogsExportConfiguration_DisableLogType = new List<System.String>(this.CloudwatchLogsExportConfiguration_DisableLogType); } if (this.CloudwatchLogsExportConfiguration_EnableLogType != null) { context.CloudwatchLogsExportConfiguration_EnableLogType = new List<System.String>(this.CloudwatchLogsExportConfiguration_EnableLogType); } context.DBClusterIdentifier = this.DBClusterIdentifier; #if MODULAR if (this.DBClusterIdentifier == null && ParameterWasBound(nameof(this.DBClusterIdentifier))) { WriteWarning("You are passing $null as a value for parameter DBClusterIdentifier which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.DBClusterParameterGroupName = this.DBClusterParameterGroupName; context.DeletionProtection = this.DeletionProtection; context.EnableIAMDatabaseAuthentication = this.EnableIAMDatabaseAuthentication; context.EngineVersion = this.EngineVersion; context.MasterUserPassword = this.MasterUserPassword; context.NewDBClusterIdentifier = this.NewDBClusterIdentifier; context.OptionGroupName = this.OptionGroupName; context.Port = this.Port; context.PreferredBackupWindow = this.PreferredBackupWindow; context.PreferredMaintenanceWindow = this.PreferredMaintenanceWindow; if (this.VpcSecurityGroupId != null) { context.VpcSecurityGroupId = new List<System.String>(this.VpcSecurityGroupId); } // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.Neptune.Model.ModifyDBClusterRequest(); if (cmdletContext.ApplyImmediately != null) { request.ApplyImmediately = cmdletContext.ApplyImmediately.Value; } if (cmdletContext.BackupRetentionPeriod != null) { request.BackupRetentionPeriod = cmdletContext.BackupRetentionPeriod.Value; } // populate CloudwatchLogsExportConfiguration var requestCloudwatchLogsExportConfigurationIsNull = true; request.CloudwatchLogsExportConfiguration = new Amazon.Neptune.Model.CloudwatchLogsExportConfiguration(); List<System.String> requestCloudwatchLogsExportConfiguration_cloudwatchLogsExportConfiguration_DisableLogType = null; if (cmdletContext.CloudwatchLogsExportConfiguration_DisableLogType != null) { requestCloudwatchLogsExportConfiguration_cloudwatchLogsExportConfiguration_DisableLogType = cmdletContext.CloudwatchLogsExportConfiguration_DisableLogType; } if (requestCloudwatchLogsExportConfiguration_cloudwatchLogsExportConfiguration_DisableLogType != null) { request.CloudwatchLogsExportConfiguration.DisableLogTypes = requestCloudwatchLogsExportConfiguration_cloudwatchLogsExportConfiguration_DisableLogType; requestCloudwatchLogsExportConfigurationIsNull = false; } List<System.String> requestCloudwatchLogsExportConfiguration_cloudwatchLogsExportConfiguration_EnableLogType = null; if (cmdletContext.CloudwatchLogsExportConfiguration_EnableLogType != null) { requestCloudwatchLogsExportConfiguration_cloudwatchLogsExportConfiguration_EnableLogType = cmdletContext.CloudwatchLogsExportConfiguration_EnableLogType; } if (requestCloudwatchLogsExportConfiguration_cloudwatchLogsExportConfiguration_EnableLogType != null) { request.CloudwatchLogsExportConfiguration.EnableLogTypes = requestCloudwatchLogsExportConfiguration_cloudwatchLogsExportConfiguration_EnableLogType; requestCloudwatchLogsExportConfigurationIsNull = false; } // determine if request.CloudwatchLogsExportConfiguration should be set to null if (requestCloudwatchLogsExportConfigurationIsNull) { request.CloudwatchLogsExportConfiguration = null; } if (cmdletContext.DBClusterIdentifier != null) { request.DBClusterIdentifier = cmdletContext.DBClusterIdentifier; } if (cmdletContext.DBClusterParameterGroupName != null) { request.DBClusterParameterGroupName = cmdletContext.DBClusterParameterGroupName; } if (cmdletContext.DeletionProtection != null) { request.DeletionProtection = cmdletContext.DeletionProtection.Value; } if (cmdletContext.EnableIAMDatabaseAuthentication != null) { request.EnableIAMDatabaseAuthentication = cmdletContext.EnableIAMDatabaseAuthentication.Value; } if (cmdletContext.EngineVersion != null) { request.EngineVersion = cmdletContext.EngineVersion; } if (cmdletContext.MasterUserPassword != null) { request.MasterUserPassword = cmdletContext.MasterUserPassword; } if (cmdletContext.NewDBClusterIdentifier != null) { request.NewDBClusterIdentifier = cmdletContext.NewDBClusterIdentifier; } if (cmdletContext.OptionGroupName != null) { request.OptionGroupName = cmdletContext.OptionGroupName; } if (cmdletContext.Port != null) { request.Port = cmdletContext.Port.Value; } if (cmdletContext.PreferredBackupWindow != null) { request.PreferredBackupWindow = cmdletContext.PreferredBackupWindow; } if (cmdletContext.PreferredMaintenanceWindow != null) { request.PreferredMaintenanceWindow = cmdletContext.PreferredMaintenanceWindow; } if (cmdletContext.VpcSecurityGroupId != null) { request.VpcSecurityGroupIds = cmdletContext.VpcSecurityGroupId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.Neptune.Model.ModifyDBClusterResponse CallAWSServiceOperation(IAmazonNeptune client, Amazon.Neptune.Model.ModifyDBClusterRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Neptune", "ModifyDBCluster"); try { #if DESKTOP return client.ModifyDBCluster(request); #elif CORECLR return client.ModifyDBClusterAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.Boolean? ApplyImmediately { get; set; } public System.Int32? BackupRetentionPeriod { get; set; } public List<System.String> CloudwatchLogsExportConfiguration_DisableLogType { get; set; } public List<System.String> CloudwatchLogsExportConfiguration_EnableLogType { get; set; } public System.String DBClusterIdentifier { get; set; } public System.String DBClusterParameterGroupName { get; set; } public System.Boolean? DeletionProtection { get; set; } public System.Boolean? EnableIAMDatabaseAuthentication { get; set; } public System.String EngineVersion { get; set; } public System.String MasterUserPassword { get; set; } public System.String NewDBClusterIdentifier { get; set; } public System.String OptionGroupName { get; set; } public System.Int32? Port { get; set; } public System.String PreferredBackupWindow { get; set; } public System.String PreferredMaintenanceWindow { get; set; } public List<System.String> VpcSecurityGroupId { get; set; } public System.Func<Amazon.Neptune.Model.ModifyDBClusterResponse, EditNPTDBClusterCmdlet, object> Select { get; set; } = (response, cmdlet) => response.DBCluster; } } }
51.737255
352
0.639771
[ "Apache-2.0" ]
JekzVadaria/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/Neptune/Basic/Edit-NPTDBCluster-Cmdlet.cs
26,386
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using WebPushDemo.Models; namespace WebPushDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDbContext<WebPushDemoContext>(options => options.UseSqlite("Data Source=Data/WebPushDb.db")); services.AddSingleton<IConfiguration>(Configuration); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); if (Configuration.GetSection("VapidKeys")["PublicKey"].Length == 0 || Configuration.GetSection("VapidKeys")["PrivateKey"].Length == 0) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=WebPush}/{action=GenerateKeys}/{id?}"); }); return; } app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Devices}/{action=Index}/{id?}"); }); } } }
30.542857
146
0.567353
[ "MIT" ]
TupaNegreiros/WebPushDemo
WebPushDemo/Startup.cs
2,140
C#
using System; namespace FW { [Serializable] public class Watermark { } }
9
26
0.6
[ "MIT" ]
seonghwan-dev/UnityForensicsWatermark
Assets/Scripts/Watermark.cs
90
C#
namespace Amazon.IonDotnet.Internals { internal interface ISymbolTableProvider { ISymbolTable GetSystemTable(); } }
17.125
43
0.70073
[ "Apache-2.0" ]
Armanbqt/ion-dotnet
Amazon.IonDotnet/Internals/ISymbolTableProvider.cs
139
C#
using System.Collections.Generic; using System.Linq; using System.Diagnostics; using System; using System.IO; using MultimodalEmotionDetection; namespace EDARecognition { public class EDARecognitionComponent : IAffectRecognitionComponent { private OpenSignalsSocket Socket { get; set; } public const float AVERAGE_SCL = 1.801015f; public const float STD_SCL = 0.509811f; public float SkinConductanceLevel { get; private set; } public float SkinConductanceResponse { get; private set; } public float SCLMinBaseline { get; private set; } public float SCLMaxBaseline { get; private set; } public float SCRMinBaseline { get; private set; } public float SCRMaxBaseline { get; private set; } public float StandardSCL { get { return (this.SkinConductanceLevel - this.SCLMinBaseline) / (this.SCLMaxBaseline - this.SCLMinBaseline); } } public float StandardSCR { get { return this.SkinConductanceResponse / this.SCRMaxBaseline; } } public float SCL_ZScore { get { return (this.SkinConductanceLevel - AVERAGE_SCL) / STD_SCL; } } public float SCR_ZScore { get { return this.SCRSamples.MovingZScore; } } public float SCL_MovingAverage { get { return this.SCLSamples.MovingAverage; } } public float SCR_MovingAverage { get { return this.SCRSamples.MovingAverage; } } public float Arousal { get { return this.SCL_ZScore * 0.2f + 0.5f; } } public bool Connected { get { return this.Socket.SocketReady; } } public bool IsRecordingBaseline { get { return this.baselineWatch.IsRunning; } } public bool LogActive { get; set; } public string Name { get { return "EDARecognition"; } } private StreamWriter logWriter; private Stopwatch baselineWatch; private long baselineRecordingWindow; private List<float> SCLMinBaselineSamples; private List<float> SCLMaxBaselineSamples; private List<float> SCRMinBaselineSamples; private List<float> SCRMaxBaselineSamples; private bool minBaseline; private MovingSampleSet SCLSamples; private MovingSampleSet SCRSamples; public EDARecognitionComponent() { this.Socket = new OpenSignalsSocket(this); this.SCLSamples = new MovingSampleSet(600); this.SCRSamples = new MovingSampleSet(30); this.baselineWatch = new Stopwatch(); } public void RecordMinBaseline(long timeInSeconds) { this.SCLMinBaselineSamples = new List<float>(); this.SCRMinBaselineSamples = new List<float>(); this.baselineWatch.Restart(); this.baselineRecordingWindow = timeInSeconds; this.minBaseline = true; } public void RecordMaxBaseline(long timeInSeconds) { this.SCLMaxBaselineSamples = new List<float>(); this.SCRMaxBaselineSamples = new List<float>(); this.baselineWatch.Restart(); this.baselineRecordingWindow = timeInSeconds; this.minBaseline = false; } public void ActivateLogging(string logFile) { this.LogActive = true; this.logWriter = File.CreateText("logs/" + logFile + ".txt"); this.logWriter.WriteLine("Time\tSCLValue\tSCLStandardizedValue\tSCLZ-Score\tSCLMovingAverage\tSCRValue\tSCRStandardizedValue\tSCRZ-Score\tSCRMovingAverage"); } private void Log() { if(this.logWriter != null) { this.logWriter.WriteLine(DateTime.Now + "\t" + this.SkinConductanceLevel + "\t" + this.StandardSCL + "\t" + this.SCL_ZScore + "\t" + this.SCL_MovingAverage + "\t" + this.SkinConductanceResponse + "\t" + this.StandardSCR + "\t" + this.SCR_ZScore + "\t" + this.SCR_MovingAverage); this.logWriter.Flush(); } } public void SetSkinConductanceLevel(float tonicLevel) { var logOfTonicLevel = (float)Math.Log(tonicLevel); this.SCLSamples.AddSample(logOfTonicLevel); this.SkinConductanceLevel = logOfTonicLevel; if (this.baselineWatch.IsRunning) { if(this.baselineWatch.Elapsed.Seconds > this.baselineRecordingWindow) { this.SetBaselineLevels(this.minBaseline); } else { if (this.minBaseline) { this.SCLMinBaselineSamples.Add(logOfTonicLevel); } else { this.SCLMaxBaselineSamples.Add(logOfTonicLevel); } } } if(this.LogActive) { this.Log(); } } public void SetSkinConductanceRate(float phasicRate) { this.SCRSamples.AddSample(phasicRate); this.SkinConductanceResponse = phasicRate; if (this.baselineWatch.IsRunning) { if (this.baselineWatch.Elapsed.Seconds > this.baselineRecordingWindow) { this.SetBaselineLevels(this.minBaseline); } else { if(this.minBaseline) { this.SCRMinBaselineSamples.Add(phasicRate); } else { this.SCRMaxBaselineSamples.Add(phasicRate); } } } } private void SetBaselineLevels(bool minBaseline) { this.baselineWatch.Stop(); if(minBaseline) { if (this.SCLMinBaselineSamples.Count > 0) { this.SCLMinBaseline = this.SCLMinBaselineSamples.Average(); } else this.SCLMinBaseline = 0; if (this.SCRMinBaselineSamples.Count > 0) { this.SCRMinBaseline = this.SCRMinBaselineSamples.Average(); } else this.SCRMinBaseline = 0; } else { if (this.SCLMaxBaselineSamples.Count > 0) { this.SCLMaxBaseline = this.SCLMaxBaselineSamples.Average(); } else this.SCLMaxBaseline = 0; if (this.SCRMaxBaselineSamples.Count > 0) { this.SCRMaxBaseline = this.SCRMaxBaselineSamples.Max(); } else this.SCRMaxBaseline = 0; } } public IEnumerable<AffectiveInformation> GetSample() { var arousal = this.Arousal; if(arousal > 1) { arousal = 1; } else if (arousal < 0) { arousal = 0; } return new List<AffectiveInformation> { new AffectiveInformation { Name = "arousal", Score = arousal } }; } public IEnumerable<string> GetRecognizedAffectiveVariables() { return new List<string> { "arousal" }; } } }
33.325991
171
0.54382
[ "Apache-2.0" ]
GAIPS-INESC-ID/FAtiMA-Toolk
AffectRecognition/AffectRecognitionComponents/EDARecognition/EDARecognitionComponent.cs
7,567
C#
using System.ComponentModel.DataAnnotations; using Abp.Auditing; using Abp.Authorization.Users; using Abp.AutoMapper; using Abp.Runtime.Validation; using MediaShare.Authorization.Users; namespace MediaShare.Users.Dto { [AutoMapTo(typeof(User))] public class CreateUserDto : IShouldNormalize { [Required] [StringLength(AbpUserBase.MaxUserNameLength)] public string UserName { get; set; } [Required] [StringLength(AbpUserBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpUserBase.MaxSurnameLength)] public string Surname { get; set; } [Required] [EmailAddress] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string EmailAddress { get; set; } public bool IsActive { get; set; } public string[] RoleNames { get; set; } [Required] [StringLength(AbpUserBase.MaxPlainPasswordLength)] [DisableAuditing] public string Password { get; set; } public void Normalize() { if (RoleNames == null) { RoleNames = new string[0]; } } } }
25.25
58
0.617162
[ "MIT" ]
tigeryzx/MediaShare
aspnet-core/src/MediaShare.Application/Users/Dto/CreateUserDto.cs
1,212
C#
namespace System.Workflow.Activities { using System; using System.Text; using System.Reflection; using System.Collections; using System.CodeDom; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Drawing.Drawing2D; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Collections.ObjectModel; #region StateFinalizationDesigner [ActivityDesignerTheme(typeof(StateFinalizationDesignerTheme))] internal sealed class StateFinalizationDesigner : System.Workflow.Activities.SequenceDesigner { #region Properties and Methods public override bool CanBeParentedTo(CompositeActivityDesigner parentActivityDesigner) { if (parentActivityDesigner == null) throw new ArgumentNullException("parentActivityDesigner"); if (!(parentActivityDesigner.Activity is StateActivity)) return false; return base.CanBeParentedTo(parentActivityDesigner); } protected override void DoDefaultAction() { base.DoDefaultAction(); EnsureVisible(); } public override bool CanExpandCollapse { get { return false; } } public override bool CanInsertActivities(HitTestInfo insertLocation, ReadOnlyCollection<Activity> activitiesToInsert) { foreach (Activity activity in activitiesToInsert) { if (activity is IEventActivity) return false; } return base.CanInsertActivities(insertLocation, activitiesToInsert); } #endregion } #endregion #region StateFinalizationDesignerTheme internal sealed class StateFinalizationDesignerTheme : CompositeDesignerTheme { public StateFinalizationDesignerTheme(WorkflowTheme theme) : base(theme) { this.ShowDropShadow = false; this.ConnectorStartCap = LineAnchor.None; this.ConnectorEndCap = LineAnchor.ArrowAnchor; this.ForeColor = Color.FromArgb(0xFF, 0x80, 0x00, 0x00); this.BorderColor = Color.FromArgb(0xFF, 0xE0, 0xE0, 0xE0); this.BorderStyle = DashStyle.Dash; this.BackColorStart = Color.FromArgb(0x00, 0x00, 0x00, 0x00); this.BackColorEnd = Color.FromArgb(0x00, 0x00, 0x00, 0x00); } } #endregion }
32.43038
125
0.645199
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/WF/Activities/Designers/StateFinalizationDesigner.cs
2,562
C#
using System; using System.Text; namespace LinqToDB.DataProvider.Access { using Mapping; using SqlQuery; using System.Data.Linq; public class AccessMappingSchema : MappingSchema { public AccessMappingSchema() : this(ProviderName.Access) { } protected AccessMappingSchema(string configuration) : base(configuration) { SetDataType(typeof(DateTime), DataType.DateTime); SetDataType(typeof(DateTime?), DataType.DateTime); SetValueToSqlConverter(typeof(bool), (sb,dt,v) => sb.Append(v)); SetValueToSqlConverter(typeof(Guid), (sb,dt,v) => sb.Append("'").Append(((Guid)v).ToString("B")).Append("'")); SetValueToSqlConverter(typeof(DateTime), (sb,dt,v) => ConvertDateTimeToSql(sb, (DateTime)v)); SetDataType(typeof(string), new SqlDataType(DataType.NVarChar, typeof(string), 255)); SetValueToSqlConverter(typeof(string), (sb,dt,v) => ConvertStringToSql (sb, v.ToString()!)); SetValueToSqlConverter(typeof(char), (sb,dt,v) => ConvertCharToSql (sb, (char)v)); SetValueToSqlConverter(typeof(byte[]), (sb,dt,v) => ConvertBinaryToSql (sb, (byte[])v)); SetValueToSqlConverter(typeof(Binary), (sb,dt,v) => ConvertBinaryToSql (sb, ((Binary)v).ToArray())); } static void ConvertBinaryToSql(StringBuilder stringBuilder, byte[] value) { stringBuilder.Append("0x"); foreach (var b in value) stringBuilder.Append(b.ToString("X2")); } static void AppendConversion(StringBuilder stringBuilder, int value) { stringBuilder .Append("chr(") .Append(value) .Append(")") ; } static void ConvertStringToSql(StringBuilder stringBuilder, string value) { DataTools.ConvertStringToSql(stringBuilder, "+", null, AppendConversion, value, null); } static void ConvertCharToSql(StringBuilder stringBuilder, char value) { DataTools.ConvertCharToSql(stringBuilder, "'", AppendConversion, value); } static void ConvertDateTimeToSql(StringBuilder stringBuilder, DateTime value) { var format = value.Hour == 0 && value.Minute == 0 && value.Second == 0 ? "#{0:yyyy-MM-dd}#" : "#{0:yyyy-MM-dd HH:mm:ss}#"; stringBuilder.AppendFormat(format, value); } internal static readonly AccessMappingSchema Instance = new AccessMappingSchema(); public class OleDbMappingSchema : MappingSchema { public OleDbMappingSchema() : base(ProviderName.Access, Instance) { } } public class ODBCMappingSchema : MappingSchema { public ODBCMappingSchema() : base(ProviderName.AccessOdbc, Instance) { } } } }
29.943182
118
0.67666
[ "MIT" ]
Corey-M/linq2db
Source/LinqToDB/DataProvider/Access/AccessMappingSchema.cs
2,550
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Mvc.ModelBinding { /// <summary> /// A context that contains information specific to the current request and the action whose parameters /// are being model bound. /// </summary> public class OperationBindingContext { /// <summary> /// Represents if there has been a body bound model found during the current model binding process. /// </summary> public BodyBindingState BodyBindingState { get; set; } = BodyBindingState.NotBodyBased; /// <summary> /// Gets or sets the <see cref="HttpContext"/> for the current request. /// </summary> public HttpContext HttpContext { get; set; } /// <summary> /// Gets unaltered value provider collection. /// Value providers can be filtered by specific model binders. /// </summary> public IValueProvider ValueProvider { get; set; } /// <summary> /// Gets or sets the <see cref="IModelBinder"/> associated with this context. /// </summary> public IModelBinder ModelBinder { get; set; } /// <summary> /// Gets or sets the <see cref="IModelMetadataProvider"/> associated with this context. /// </summary> public IModelMetadataProvider MetadataProvider { get; set; } /// <summary> /// Gets or sets the <see cref="IModelValidatorProvider"/> instance used for model validation with this /// context. /// </summary> public IModelValidatorProvider ValidatorProvider { get; set; } } }
38.212766
111
0.640312
[ "Apache-2.0" ]
moljac/Mvc
src/Microsoft.AspNet.Mvc.ModelBinding/OperationBindingContext.cs
1,796
C#
using System; using UnityEditor; /* tpr #if ENABLE_VR && ENABLE_VR_MODULE using UnityEngine.XR; #endif */ namespace UnityEngine.Rendering { /// <summary> /// XRGraphics insulates SRP from API changes across platforms, Editor versions, and as XR transitions into XR SDK /// </summary> [Serializable] public class XRGraphics { /// <summary> /// Stereo Rendering Modes. /// </summary> public enum StereoRenderingMode { /// <summary>Multi Pass.</summary> MultiPass = 0, /// <summary>Single Pass.</summary> SinglePass, /// <summary>Single Pass Instanced.</summary> SinglePassInstanced, /// <summary>Single Pass Multi View.</summary> SinglePassMultiView }; /// <summary> /// Eye texture resolution scale. /// </summary> public static float eyeTextureResolutionScale { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return XRSettings.eyeTextureResolutionScale; #endif */ return 1.0f; } set { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE XRSettings.eyeTextureResolutionScale = value; #endif */ } } /// <summary> /// Render viewport scale. /// </summary> public static float renderViewportScale { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return XRSettings.renderViewportScale; #endif */ return 1.0f; } } /// <summary> /// Try enable. /// </summary> #if UNITY_EDITOR // TryEnable gets updated before "play" is pressed- we use this for updating GUI only. public static bool tryEnable { get { #if UNITY_2020_1_OR_NEWER return false; #else return UnityEditorInternal.VR.VREditor.GetVREnabledOnTargetGroup(BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); #endif } } #endif /// <summary> /// SRP should use this to safely determine whether XR is enabled at runtime. /// </summary> public static bool enabled { get { #if ENABLE_VR && ENABLE_VR_MODULE /* tpr return XRSettings.enabled; */ #else return false; #endif } } /// <summary> /// Returns true if the XR device is active. /// </summary> public static bool isDeviceActive { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return XRSettings.isDeviceActive; #endif */ return false; } } /// <summary> /// Name of the loaded XR device. /// </summary> public static string loadedDeviceName { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return XRSettings.loadedDeviceName; #endif */ return "No XR device loaded"; } } /// <summary> /// List of supported XR devices. /// </summary> public static string[] supportedDevices { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return XRSettings.supportedDevices; #endif */ return new string[1]; } } /// <summary> /// Stereo rendering mode. /// </summary> public static StereoRenderingMode stereoRenderingMode { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return (StereoRenderingMode)XRSettings.stereoRenderingMode; #endif */ return StereoRenderingMode.SinglePass; } } /// <summary> /// Eye texture descriptor. /// </summary> public static RenderTextureDescriptor eyeTextureDesc { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return XRSettings.eyeTextureDesc; #endif */ return new RenderTextureDescriptor(0, 0); } } /// <summary> /// Eye texture width. /// </summary> public static int eyeTextureWidth { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return XRSettings.eyeTextureWidth; #endif */ return 0; } } /// <summary> /// Eye texture height. /// </summary> public static int eyeTextureHeight { get { /* tpr #if ENABLE_VR && ENABLE_VR_MODULE if (enabled) return XRSettings.eyeTextureHeight; #endif */ return 0; } } } }
22.982759
159
0.485559
[ "MIT" ]
turesnake/tpr_Unity_Render_Pipeline_LearningNotes
11.0/Core_and_URP_11.0/rp.core.11.0/Runtime/Common/XRGraphics.cs
5,332
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using MvcPlayground.Helpers; namespace MvcPlayground.Models { [TypeConverter(typeof(PascalCaseWordSplittingEnumConverter))] public enum Color { Red, Green, Blue, BrightRed, BrightGreen, BrightBlue, } public class Person { [Display(Name = "Favorite fruit", Order = 200)] [AutoComplete("AutocompleteTextBox", "Autocomplete")] public string Fruit { get; set; } [Display(Name = "Fullname", Order = 100)] public string Name { get; set; } [Display(Order = 300)] [DataType("Date")] public DateTime Birthdate { get; set; } // [UIHint("EnumDropdown")] // public Color FavoriteColor { get; set; } } }
24.157895
65
0.617647
[ "Apache-2.0" ]
Guzzter/MvcPlayground
MvcPlayground/Models/Person.cs
920
C#
namespace Shared.Group_008 { using Xunit; public class Benchmark038Tests { [Fact] public void Test_001() { } [Fact] public void Test_002() { } [Fact] public void Test_003() { } [Fact] public void Test_004() { } [Fact] public void Test_005() { } [Fact] public void Test_006() { } [Fact] public void Test_007() { } [Fact] public void Test_008() { } [Fact] public void Test_009() { } [Fact] public void Test_010() { } [Fact] public void Test_011() { } [Fact] public void Test_012() { } [Fact] public void Test_013() { } [Fact] public void Test_014() { } [Fact] public void Test_015() { } [Fact] public void Test_016() { } [Fact] public void Test_017() { } [Fact] public void Test_018() { } [Fact] public void Test_019() { } [Fact] public void Test_020() { } [Fact] public void Test_021() { } [Fact] public void Test_022() { } [Fact] public void Test_023() { } [Fact] public void Test_024() { } [Fact] public void Test_025() { } [Fact] public void Test_026() { } [Fact] public void Test_027() { } [Fact] public void Test_028() { } [Fact] public void Test_029() { } [Fact] public void Test_030() { } [Fact] public void Test_031() { } [Fact] public void Test_032() { } [Fact] public void Test_033() { } [Fact] public void Test_034() { } [Fact] public void Test_035() { } [Fact] public void Test_036() { } [Fact] public void Test_037() { } [Fact] public void Test_038() { } [Fact] public void Test_039() { } [Fact] public void Test_040() { } [Fact] public void Test_041() { } [Fact] public void Test_042() { } [Fact] public void Test_043() { } [Fact] public void Test_044() { } [Fact] public void Test_045() { } [Fact] public void Test_046() { } [Fact] public void Test_047() { } [Fact] public void Test_048() { } [Fact] public void Test_049() { } [Fact] public void Test_050() { } } }
37.220339
41
0.529144
[ "MIT" ]
chan18/fixie.benchmark
src/Shared/Group_008/Benchmark038Tests.cs
2,196
C#
using System; using System.Collections.Generic; namespace AoC.Y2017.Days { internal class TuringState { public string Name { get; set; } public (int Zero, int One) NextSlotOffset { get; set; } public (string Zero, string One) NextState { get; set; } public (int Zero, int One) WriteValue { get; set; } public TuringState(List<string> configuration) { Name = configuration[0].Replace(":", "").Split(' ')[2]; WriteValue = GetNumberValues(configuration[2], configuration[6], 4); NextSlotOffset = GetSlotValues(configuration[3], configuration[7], 6); NextState = GetValues(configuration[4], configuration[8], 4); } public (int, int, string) GetValues(int current) => current == 0 ? (WriteValue.Zero, NextSlotOffset.Zero, NextState.Zero) : (WriteValue.One, NextSlotOffset.One, NextState.One); private (int, int) GetNumberValues(string zero, string one, int position) { var (zeroValue, oneValue) = GetValues(zero, one, position); return (int.Parse(zeroValue), int.Parse(oneValue)); } private (int, int) GetSlotValues(string zero, string one, int position) { var (zeroValue, oneValue) = GetValues(zero, one, position); return (zeroValue == "left" ? -1 : 1, oneValue == "left" ? -1 : 1); } private (string, string) GetValues(string zero, string one, int position) => (zero.Replace(".", "").Split(' ', StringSplitOptions.RemoveEmptyEntries)[position], one.Replace(".", "").Split(' ', StringSplitOptions.RemoveEmptyEntries)[position]); } }
41.609756
184
0.606096
[ "MIT" ]
EwoutIO/AdventOfCode
AoC.Y2017/Day25/TuringState.cs
1,708
C#
using System; using System.Collections.Generic; using System.Text; namespace RT.Cryptography { public class CipherService { private ICipherFactory _factory = null; private Dictionary<CipherContext, ICipher> _ciphers = new Dictionary<CipherContext, ICipher>(); public bool EnableEncryption { get; set; } = true; public CipherService(ICipherFactory factory) { _factory = factory; } public void GenerateCipher(CipherContext context) { if (!_ciphers.ContainsKey(context)) _ciphers.Add(context, _factory.CreateNew(context)); else _ciphers[context] = _factory.CreateNew(context); } public void GenerateCipher(CipherContext context, byte[] publicKey) { if (!_ciphers.ContainsKey(context)) _ciphers.Add(context, _factory.CreateNew(context, publicKey)); else _ciphers[context] = _factory.CreateNew(context, publicKey); } public void GenerateCipher(RsaKeyPair rsaKeyPair) { var context = CipherContext.RSA_AUTH; if (!_ciphers.ContainsKey(context)) _ciphers.Add(context, _factory.CreateNew(rsaKeyPair)); else _ciphers[context] = _factory.CreateNew(rsaKeyPair); } public void SetCipher(CipherContext context, ICipher cipher) { if (!_ciphers.ContainsKey(context)) _ciphers.Add(context, cipher); else _ciphers[context] = cipher; } public bool HasKey(CipherContext context) { return _ciphers.TryGetValue(context, out var value) && value != null; } public byte[] GetPublicKey(CipherContext context) { var cipher = _ciphers[context]; if (cipher == null) throw new KeyNotFoundException($"The CipherContext {context} does not have a cipher associated with it."); return cipher.GetPublicKey(); } public bool Encrypt(CipherContext context, byte[] input, out byte[] cipher, out byte[] hash) { cipher = null; hash = null; if (!EnableEncryption || !_ciphers.TryGetValue(context, out var c) || c == null) return false; return c.Encrypt(input, out cipher, out hash); } public bool Decrypt(byte[] input, byte[] hash, out byte[] plain) { var cipherContext = (CipherContext)(hash[3] >> 5); return Decrypt(cipherContext, input, hash, out plain); } public bool Decrypt(CipherContext context, byte[] input, byte[] hash, out byte[] plain) { if (!_ciphers.TryGetValue(context, out var cipher) || cipher == null) throw new KeyNotFoundException($"The CipherContext {context} does not have a cipher associated with it."); return cipher.Decrypt(input, hash, out plain); } } }
33.380435
122
0.585477
[ "MIT" ]
Horizon-Private-Server/horizon-server
RT.Cryptography/CipherService.cs
3,073
C#
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(Angular103.Startup))] namespace Angular103 { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
18
60
0.648148
[ "Apache-2.0" ]
Kiandr/Angular
Practice/Angular100/Angular103/Angular103/Startup.cs
272
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Docomb.WebCore.Configurations { public static class UiConfig { public const string UrlPathPrefix = "_admin"; public static bool HasAdmin { get; private set; } = false; public static void SetHasAdmin(bool value) => HasAdmin = value; public static bool HasReader { get; private set; } = false; public static void SetHasReader(bool value) => HasReader = value; } }
23.045455
67
0.74359
[ "MIT" ]
MatMiler/Docomb
WebCore/Configurations/UiConfig.cs
509
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConnectAndJoinRandom.cs" company="Exit Games GmbH"> // Part of: Photon Unity Utilities, // </copyright> // <summary> // Simple component to call ConnectUsingSettings and to get into a PUN room easily. // </summary> // <remarks> // A custom inspector provides a button to connect in PlayMode, should AutoConnect be false. // </remarks> // <author>developer@exitgames.com</author> // -------------------------------------------------------------------------------------------------------------------- //#if UNITY_EDITOR //using UnityEditor; //#endif using UnityEngine; //using Photon.Pun; using Photon.Realtime; namespace Photon.Pun.UtilityScripts { /// <summary>Simple component to call ConnectUsingSettings and to get into a PUN room easily.</summary> /// <remarks>A custom inspector provides a button to connect in PlayMode, should AutoConnect be false.</remarks> public class ConnectAndJoinRandom : MonoBehaviourPunCallbacks { /// <summary>Connect automatically? If false you can set this to true later on or call ConnectUsingSettings in your own scripts.</summary> public bool AutoConnect = true; /// <summary>Used as PhotonNetwork.GameVersion.</summary> public byte Version = 1; public void Start() { if (this.AutoConnect) { this.ConnectNow(); } } public void ConnectNow() { Debug.Log("ConnectAndJoinRandom.ConnectNow() will now call: PhotonNetwork.ConnectUsingSettings()."); PhotonNetwork.ConnectUsingSettings(); PhotonNetwork.GameVersion = this.Version + "." + SceneManagerHelper.ActiveSceneBuildIndex; } // below, we implement some callbacks of the Photon Realtime API. // Being a MonoBehaviourPunCallbacks means, we can override the few methods which are needed here. public override void OnConnectedToMaster() { Debug.Log("OnConnectedToMaster() was called by PUN. This client is now connected to Master Server in region [" + PhotonNetwork.CloudRegion + "] and can join a room. Calling: PhotonNetwork.JoinRandomRoom();"); PhotonNetwork.JoinRandomRoom(); } public override void OnJoinedLobby() { Debug.Log("OnJoinedLobby(). This client is now connected to Relay in region [" + PhotonNetwork.CloudRegion + "]. This script now calls: PhotonNetwork.JoinRandomRoom();"); PhotonNetwork.JoinRandomRoom(); } public override void OnJoinRandomFailed(short returnCode, string message) { Debug.Log("OnJoinRandomFailed() was called by PUN. No random room available in region [" + PhotonNetwork.CloudRegion + "], so we create one. Calling: PhotonNetwork.CreateRoom(null, new RoomOptions() {maxPlayers = 4}, null);"); PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = 4 }, null); } // the following methods are implemented to give you some context. re-implement them as needed. public override void OnDisconnected(DisconnectCause cause) { Debug.Log("OnDisconnected(" + cause + ")"); } public override void OnJoinedRoom() { Debug.Log("OnJoinedRoom() called by PUN. Now this client is in a room in region [" + PhotonNetwork.CloudRegion + "]. Game is now running."); } } //#if UNITY_EDITOR //[CanEditMultipleObjects] //[CustomEditor(typeof(ConnectAndJoinRandom), true)] //public class ConnectAndJoinRandomInspector : Editor //{ // void OnEnable() { EditorApplication.update += Update; } // void OnDisable() { EditorApplication.update -= Update; } // bool isConnectedCache = false; // void Update() // { // if (this.isConnectedCache != PhotonNetwork.IsConnected) // { // this.Repaint(); // } // } // public override void OnInspectorGUI() // { // this.isConnectedCache = !PhotonNetwork.IsConnected; // this.DrawDefaultInspector(); // Draw the normal inspector // if (Application.isPlaying && !PhotonNetwork.IsConnected) // { // if (GUILayout.Button("Connect")) // { // ((ConnectAndJoinRandom)this.target).ConnectNow(); // } // } // } //} //#endif }
39.040323
239
0.565379
[ "MIT" ]
mjimenez98/tank-warfare-online
Assets/Resources/Photon/PhotonUnityNetworking/UtilityScripts/Prototyping/ConnectAndJoinRandom.cs
4,841
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class XLuaCSObjectWrapXLuaCSObjectWrapDCETModelFrame_ClickMapWrapWrapWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapDCETModelFrame_ClickMapWrapWrap); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { XLua.CSObjectWrap.XLuaCSObjectWrapDCETModelFrame_ClickMapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapDCETModelFrame_ClickMapWrapWrap(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapDCETModelFrame_ClickMapWrapWrap constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m___Register_xlua_st_(RealStatePtr L) { try { { System.IntPtr _L = LuaAPI.lua_touserdata(L, 1); XLua.CSObjectWrap.XLuaCSObjectWrapDCETModelFrame_ClickMapWrapWrap.__Register( _L ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } }
24.881818
153
0.579467
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapDCETModelFrame_ClickMapWrapWrapWrap.cs
2,739
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Bonsai.Windows.Input { [Description("Produces a sequence of events whenever a keyboard key is released.")] public class KeyUp : Source<Keys> { [Description("The target keys to be observed.")] public Keys Filter { get; set; } public override IObservable<Keys> Generate() { return InterceptKeys.Instance.KeyUp .Where(key => Filter == Keys.None || key == Filter); } } }
27.56
88
0.642961
[ "MIT" ]
aalmada/bonsai
Bonsai.Windows.Input/KeyUp.cs
691
C#
/* * 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 ec2-2014-09-01.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.EC2.Model { /// <summary> /// Container for the parameters to the DeleteVpcPeeringConnection operation. /// Deletes a VPC peering connection. Either the owner of the requester VPC or the owner /// of the peer VPC can delete the VPC peering connection if it's in the <code>active</code> /// state. The owner of the requester VPC can delete a VPC peering connection in the <code>pending-acceptance</code> /// state. /// </summary> public partial class DeleteVpcPeeringConnectionRequest : AmazonEC2Request { private string _vpcPeeringConnectionId; /// <summary> /// Gets and sets the property VpcPeeringConnectionId. /// <para> /// The ID of the VPC peering connection. /// </para> /// </summary> public string VpcPeeringConnectionId { get { return this._vpcPeeringConnectionId; } set { this._vpcPeeringConnectionId = value; } } // Check to see if VpcPeeringConnectionId property is set internal bool IsSetVpcPeeringConnectionId() { return this._vpcPeeringConnectionId != null; } } }
34.3
120
0.683673
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet35/Amazon.EC2/Model/DeleteVpcPeeringConnectionRequest.cs
2,058
C#
using UnityEngine; using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_Color32 : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { UnityEngine.Color32 o; System.Byte a1; checkType(l,2,out a1); System.Byte a2; checkType(l,3,out a2); System.Byte a3; checkType(l,4,out a3); System.Byte a4; checkType(l,5,out a4); o=new UnityEngine.Color32(a1,a2,a3,a4); pushValue(l,o); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Lerp_s(IntPtr l) { try { UnityEngine.Color32 a1; checkType(l,1,out a1); UnityEngine.Color32 a2; checkType(l,2,out a2); System.Single a3; checkType(l,3,out a3); var ret=UnityEngine.Color32.Lerp(a1,a2,a3); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_r(IntPtr l) { try { UnityEngine.Color32 self; checkType(l,1,out self); pushValue(l,self.r); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_r(IntPtr l) { try { UnityEngine.Color32 self; checkType(l,1,out self); System.Byte v; checkType(l,2,out v); self.r=v; setBack(l,self); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_g(IntPtr l) { try { UnityEngine.Color32 self; checkType(l,1,out self); pushValue(l,self.g); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_g(IntPtr l) { try { UnityEngine.Color32 self; checkType(l,1,out self); System.Byte v; checkType(l,2,out v); self.g=v; setBack(l,self); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_b(IntPtr l) { try { UnityEngine.Color32 self; checkType(l,1,out self); pushValue(l,self.b); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_b(IntPtr l) { try { UnityEngine.Color32 self; checkType(l,1,out self); System.Byte v; checkType(l,2,out v); self.b=v; setBack(l,self); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_a(IntPtr l) { try { UnityEngine.Color32 self; checkType(l,1,out self); pushValue(l,self.a); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_a(IntPtr l) { try { UnityEngine.Color32 self; checkType(l,1,out self); System.Byte v; checkType(l,2,out v); self.a=v; setBack(l,self); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.Color32"); addMember(l,Lerp_s); addMember(l,"r",get_r,set_r,true); addMember(l,"g",get_g,set_g,true); addMember(l,"b",get_b,set_b,true); addMember(l,"a",get_a,set_a,true); createTypeMetatable(l,constructor, typeof(UnityEngine.Color32),typeof(System.ValueType)); } }
22.313953
91
0.671704
[ "MIT" ]
LunaFramework/Luna
luna/Assets/LuaObject/Unity/Lua_UnityEngine_Color32.cs
3,840
C#
/* * 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 ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for FailedQueuedPurchaseDeletion Object /// </summary> public class FailedQueuedPurchaseDeletionUnmarshaller : IUnmarshaller<FailedQueuedPurchaseDeletion, XmlUnmarshallerContext>, IUnmarshaller<FailedQueuedPurchaseDeletion, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public FailedQueuedPurchaseDeletion Unmarshall(XmlUnmarshallerContext context) { FailedQueuedPurchaseDeletion unmarshalledObject = new FailedQueuedPurchaseDeletion(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("error", targetDepth)) { var unmarshaller = DeleteQueuedReservedInstancesErrorUnmarshaller.Instance; unmarshalledObject.Error = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("reservedInstancesId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ReservedInstancesId = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <returns></returns> public FailedQueuedPurchaseDeletion Unmarshall(JsonUnmarshallerContext context) { return null; } private static FailedQueuedPurchaseDeletionUnmarshaller _instance = new FailedQueuedPurchaseDeletionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static FailedQueuedPurchaseDeletionUnmarshaller Instance { get { return _instance; } } } }
36.543689
197
0.61796
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/FailedQueuedPurchaseDeletionUnmarshaller.cs
3,764
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Rest; using Serilog; using Serilog.Sinks.SystemConsole.Themes; using System.Threading.Tasks; namespace Yarp.ReverseProxy.Kubernetes.Controller { public static class Program { public static async Task Main(string[] args) { using var serilog = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.Console(theme: AnsiConsoleTheme.Code) .CreateLogger(); ServiceClientTracing.IsEnabled = true; await Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddSerilog(serilog, dispose: false); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .Build() .RunAsync().ConfigureAwait(false); } } }
29.585366
64
0.583677
[ "MIT" ]
BennyM/reverse-proxy
src/ReverseProxy.Kubernetes.Controller/Program.cs
1,213
C#
/* * Copyright 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 greengrass-2017-06-07.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Greengrass.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Greengrass.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateGroup operation /// </summary> public class CreateGroupResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateGroupResponse response = new CreateGroupResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Arn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Arn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CreationTimestamp", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.CreationTimestamp = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Id", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Id = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LastUpdatedTimestamp", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.LastUpdatedTimestamp = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LatestVersion", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.LatestVersion = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LatestVersionArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.LatestVersionArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Name = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonGreengrassException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static CreateGroupResponseUnmarshaller _instance = new CreateGroupResponseUnmarshaller(); internal static CreateGroupResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateGroupResponseUnmarshaller Instance { get { return _instance; } } } }
39.945205
194
0.588992
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Greengrass/Generated/Model/Internal/MarshallTransformations/CreateGroupResponseUnmarshaller.cs
5,832
C#
using Cirrious.CrossCore; using Cirrious.CrossCore.IoC; using Cirrious.MvvmCross.ViewModels; using Test.NewCore.ViewModels; namespace Test.NewCore { public class App : MvxApplication { public App() { CreatableTypes() .EndingWith("Service") .AsInterfaces() .RegisterAsLazySingleton(); // Mvx.RegisterSingleton<IMvxAppStart>(new MvxAppStart<TestViewModel>()); RegisterAppStart<ViewModels.TestViewModel>(); } } }
25.727273
86
0.575972
[ "MIT" ]
ehuna/MvvmCross.Test.Uwp
Test.NewCore/App.cs
568
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200301 { /// <summary> /// Service End point policy resource. /// </summary> [AzureNativeResourceType("azure-native:network/v20200301:ServiceEndpointPolicy")] public partial class ServiceEndpointPolicy : Pulumi.CustomResource { /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The provisioning state of the service endpoint policy resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The resource GUID property of the service endpoint policy resource. /// </summary> [Output("resourceGuid")] public Output<string> ResourceGuid { get; private set; } = null!; /// <summary> /// A collection of service endpoint policy definitions of the service endpoint policy. /// </summary> [Output("serviceEndpointPolicyDefinitions")] public Output<ImmutableArray<Outputs.ServiceEndpointPolicyDefinitionResponse>> ServiceEndpointPolicyDefinitions { get; private set; } = null!; /// <summary> /// A collection of references to subnets. /// </summary> [Output("subnets")] public Output<ImmutableArray<Outputs.SubnetResponse>> Subnets { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a ServiceEndpointPolicy resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ServiceEndpointPolicy(string name, ServiceEndpointPolicyArgs args, CustomResourceOptions? options = null) : base("azure-native:network/v20200301:ServiceEndpointPolicy", name, args ?? new ServiceEndpointPolicyArgs(), MakeResourceOptions(options, "")) { } private ServiceEndpointPolicy(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:network/v20200301:ServiceEndpointPolicy", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20180701:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20180801:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20181001:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20181101:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20181201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20190201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20190401:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20190601:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20190701:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20190801:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20190901:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20191101:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20191201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20200401:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20200501:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20200601:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20200701:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20200801:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-native:network/v20201101:ServiceEndpointPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:ServiceEndpointPolicy"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ServiceEndpointPolicy resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ServiceEndpointPolicy Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ServiceEndpointPolicy(name, id, options); } } public sealed class ServiceEndpointPolicyArgs : Pulumi.ResourceArgs { /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("serviceEndpointPolicyDefinitions")] private InputList<Inputs.ServiceEndpointPolicyDefinitionArgs>? _serviceEndpointPolicyDefinitions; /// <summary> /// A collection of service endpoint policy definitions of the service endpoint policy. /// </summary> public InputList<Inputs.ServiceEndpointPolicyDefinitionArgs> ServiceEndpointPolicyDefinitions { get => _serviceEndpointPolicyDefinitions ?? (_serviceEndpointPolicyDefinitions = new InputList<Inputs.ServiceEndpointPolicyDefinitionArgs>()); set => _serviceEndpointPolicyDefinitions = value; } /// <summary> /// The name of the service endpoint policy. /// </summary> [Input("serviceEndpointPolicyName")] public Input<string>? ServiceEndpointPolicyName { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public ServiceEndpointPolicyArgs() { } } }
50.602804
155
0.620556
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/Network/V20200301/ServiceEndpointPolicy.cs
10,829
C#
//---------------------------------------------------------------------------------- // <copyright file="DelegateComparer.cs" company="Prakrishta Technologies"> // Copyright (c) 2019 Prakrishta Technologies. All rights reserved. // </copyright> // <author>Arul Sengottaiyan</author> // <date>3/3/2019</date> // <summary>The delegate comparer class</summary> //----------------------------------------------------------------------------------- namespace Prakrishta.Infrastructure.Helper { using System; using System.Collections.Generic; /// <summary> /// The delegate comparer class /// </summary> /// <typeparam name="T">The generic type parameter</typeparam> public sealed class DelegateComparer<T> : IEqualityComparer<T> { #region |Private fields| /// <summary> /// Holds equal func /// </summary> private readonly Func<T, T, bool> equals; /// <summary> /// Holds get hash code func /// </summary> private readonly Func<T, int> getHashCode; #endregion #region |Constructor| /// <summary> /// Initializes a new instance of <see cref="DelegateComparer<T>"/> class /// </summary> /// <param name="equals">The equals filter func</param> /// <param name="getHashCode">The gethascode func</param> public DelegateComparer(Func<T, T, bool> equals, Func<T, int> getHashCode) { this.equals = equals ?? throw new ArgumentNullException(nameof(equals)); this.getHashCode = getHashCode ?? throw new ArgumentNullException(nameof(getHashCode)); } #endregion #region |Interface Implementation| /// <inheritdoc /> public bool Equals(T x, T y) { return this.equals(x, y); } /// <inheritdoc /> public int GetHashCode(T obj) { if (this.getHashCode != null) { return this.getHashCode(obj); } else { return obj.GetHashCode(); } } #endregion } }
31.647059
99
0.521375
[ "MIT" ]
sarul84/Prakrishta.Infrastructure
Prakrishta.Infrastructure/Helper/DelegateComparer.cs
2,154
C#
/** * (C) Copyright IBM Corp. 2018, 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using Newtonsoft.Json; namespace IBM.Watson.Assistant.V1.Model { /// <summary> /// DialogNodeOutputGeneric. /// </summary> public class DialogNodeOutputGeneric { /// <summary> /// The type of response returned by the dialog node. The specified response type must be supported by the /// client application or channel. /// /// **Note:** The **search_skill** response type is available only for Plus and Premium users, and is used only /// by the v2 runtime API. /// </summary> public class ResponseTypeValue { /// <summary> /// Constant TEXT for text /// </summary> public const string TEXT = "text"; /// <summary> /// Constant PAUSE for pause /// </summary> public const string PAUSE = "pause"; /// <summary> /// Constant IMAGE for image /// </summary> public const string IMAGE = "image"; /// <summary> /// Constant OPTION for option /// </summary> public const string OPTION = "option"; /// <summary> /// Constant CONNECT_TO_AGENT for connect_to_agent /// </summary> public const string CONNECT_TO_AGENT = "connect_to_agent"; /// <summary> /// Constant SEARCH_SKILL for search_skill /// </summary> public const string SEARCH_SKILL = "search_skill"; } /// <summary> /// How a response is selected from the list, if more than one response is specified. Valid only when /// **response_type**=`text`. /// </summary> public class SelectionPolicyValue { /// <summary> /// Constant SEQUENTIAL for sequential /// </summary> public const string SEQUENTIAL = "sequential"; /// <summary> /// Constant RANDOM for random /// </summary> public const string RANDOM = "random"; /// <summary> /// Constant MULTILINE for multiline /// </summary> public const string MULTILINE = "multiline"; } /// <summary> /// The preferred type of control to display, if supported by the channel. Valid only when /// **response_type**=`option`. /// </summary> public class PreferenceValue { /// <summary> /// Constant DROPDOWN for dropdown /// </summary> public const string DROPDOWN = "dropdown"; /// <summary> /// Constant BUTTON for button /// </summary> public const string BUTTON = "button"; } /// <summary> /// The type of the search query. Required when **response_type**=`search_skill`. /// </summary> public class QueryTypeValue { /// <summary> /// Constant NATURAL_LANGUAGE for natural_language /// </summary> public const string NATURAL_LANGUAGE = "natural_language"; /// <summary> /// Constant DISCOVERY_QUERY_LANGUAGE for discovery_query_language /// </summary> public const string DISCOVERY_QUERY_LANGUAGE = "discovery_query_language"; } /// <summary> /// The type of response returned by the dialog node. The specified response type must be supported by the /// client application or channel. /// /// **Note:** The **search_skill** response type is available only for Plus and Premium users, and is used only /// by the v2 runtime API. /// Constants for possible values can be found using DialogNodeOutputGeneric.ResponseTypeValue /// </summary> [JsonProperty("response_type", NullValueHandling = NullValueHandling.Ignore)] public string ResponseType { get; set; } /// <summary> /// How a response is selected from the list, if more than one response is specified. Valid only when /// **response_type**=`text`. /// Constants for possible values can be found using DialogNodeOutputGeneric.SelectionPolicyValue /// </summary> [JsonProperty("selection_policy", NullValueHandling = NullValueHandling.Ignore)] public string SelectionPolicy { get; set; } /// <summary> /// The preferred type of control to display, if supported by the channel. Valid only when /// **response_type**=`option`. /// Constants for possible values can be found using DialogNodeOutputGeneric.PreferenceValue /// </summary> [JsonProperty("preference", NullValueHandling = NullValueHandling.Ignore)] public string Preference { get; set; } /// <summary> /// The type of the search query. Required when **response_type**=`search_skill`. /// Constants for possible values can be found using DialogNodeOutputGeneric.QueryTypeValue /// </summary> [JsonProperty("query_type", NullValueHandling = NullValueHandling.Ignore)] public string QueryType { get; set; } /// <summary> /// A list of one or more objects defining text responses. Required when **response_type**=`text`. /// </summary> [JsonProperty("values", NullValueHandling = NullValueHandling.Ignore)] public List<DialogNodeOutputTextValuesElement> Values { get; set; } /// <summary> /// The delimiter to use as a separator between responses when `selection_policy`=`multiline`. /// </summary> [JsonProperty("delimiter", NullValueHandling = NullValueHandling.Ignore)] public string Delimiter { get; set; } /// <summary> /// How long to pause, in milliseconds. The valid values are from 0 to 10000. Valid only when /// **response_type**=`pause`. /// </summary> [JsonProperty("time", NullValueHandling = NullValueHandling.Ignore)] public long? Time { get; set; } /// <summary> /// Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this /// event. Valid only when **response_type**=`pause`. /// </summary> [JsonProperty("typing", NullValueHandling = NullValueHandling.Ignore)] public bool? Typing { get; set; } /// <summary> /// The URL of the image. Required when **response_type**=`image`. /// </summary> [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)] public string Source { get; set; } /// <summary> /// An optional title to show before the response. Valid only when **response_type**=`image` or `option`. /// </summary> [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)] public string Title { get; set; } /// <summary> /// An optional description to show with the response. Valid only when **response_type**=`image` or `option`. /// </summary> [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] public string Description { get; set; } /// <summary> /// An array of objects describing the options from which the user can choose. You can include up to 20 options. /// Required when **response_type**=`option`. /// </summary> [JsonProperty("options", NullValueHandling = NullValueHandling.Ignore)] public List<DialogNodeOutputOptionsElement> Options { get; set; } /// <summary> /// An optional message to be sent to the human agent who will be taking over the conversation. Valid only when /// **reponse_type**=`connect_to_agent`. /// </summary> [JsonProperty("message_to_human_agent", NullValueHandling = NullValueHandling.Ignore)] public string MessageToHumanAgent { get; set; } /// <summary> /// The text of the search query. This can be either a natural-language query or a query that uses the Discovery /// query language syntax, depending on the value of the **query_type** property. For more information, see the /// [Discovery service /// documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). Required when /// **response_type**=`search_skill`. /// </summary> [JsonProperty("query", NullValueHandling = NullValueHandling.Ignore)] public string Query { get; set; } /// <summary> /// An optional filter that narrows the set of documents to be searched. For more information, see the /// [Discovery service documentation]([Discovery service /// documentation](`https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). /// </summary> [JsonProperty("filter", NullValueHandling = NullValueHandling.Ignore)] public string Filter { get; set; } /// <summary> /// The version of the Discovery service API to use for the query. /// </summary> [JsonProperty("discovery_version", NullValueHandling = NullValueHandling.Ignore)] public string DiscoveryVersion { get; set; } } }
45.613636
127
0.606776
[ "Apache-2.0" ]
oscillator25/IBM-Watson-Unity-SDK_v3.1.0
Scripts/Services/Assistant/V1/Model/DialogNodeOutputGeneric.cs
10,035
C#
using CsvHelper.Configuration; namespace BenchmarksDriver { public class CsvResult { public string Class { get; set; } public string Method { get; set; } public string Params { get; set; } public double Mean { get; set; } public double Error { get; set; } public double StdDev { get; set; } public double OperationsPerSecond { get; set; } public double Allocated { get; set; } } public sealed class CsvResultMap : ClassMap<CsvResult> { public CsvResultMap() { Map(m => m.Method).Name("Method"); Map(m => m.Params).Name("Params").Optional(); Map(m => m.Mean).Name("Mean [us]").Default(0); Map(m => m.Error).Name("Error [us]").Default(0); Map(m => m.StdDev).Name("StdDev [us]").Default(0); Map(m => m.OperationsPerSecond).Name("Op/s").Default(0); Map(m => m.Allocated).Name("Allocated Memory/Op [KB]").Default(0); } } }
32.806452
78
0.551622
[ "Apache-2.0" ]
Dmitry-Matveev/Benchmarks
src/BenchmarksDriver/CsvResult.cs
1,019
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using EvitiContact.ContactModel; namespace NRepository.RazorPages.Pages.CT { public class DetailsModel : PageModel { private readonly EvitiContact.ContactModel.ContactModelDbContext _context; public DetailsModel(EvitiContact.ContactModel.ContactModelDbContext context) { _context = context; } public ContactType ContactType { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } ContactType = await _context.ContactType.FirstOrDefaultAsync(m => m.ID == id); if (ContactType == null) { return NotFound(); } return Page(); } } }
25.3
90
0.620553
[ "MIT" ]
irperez/RepositoryPattern
NRepository/NRepository.RazorPages/Pages/CT/Details.cshtml.cs
1,014
C#
using System; using MaxStack.Classes; using static System.Console; namespace MaxStack { class Program { static void Main(string[] args) { // creates a new stack with 3 elements Stack newStack = new Stack(new Node(100)); newStack.Push(new Node(390)); newStack.Push(new Node(251)); // tests the get stack WriteLine("Creating new stack with numbers: 251, 390, 100"); WriteLine("Finding max, should be 390.\n Max: " + newStack.GetMax()); } } }
25.590909
81
0.57016
[ "MIT" ]
jimmyn123/Data-Structures-and-Algorithms
Challenges/MaxStack/MaxStack/Program.cs
565
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Training20200901.Algorithms; using Training20200901.Collections; using Training20200901.Extensions; using Training20200901.Numerics; using Training20200901.Questions; namespace Training20200901.Questions { public class QuestionB : AtCoderQuestionBase { public override IEnumerable<object> Solve(TextReader inputStream) { throw new NotImplementedException(); } } }
25
73
0.773333
[ "MIT" ]
terry-u16/AtCoder
Training20200901/Training20200901/Training20200901/Questions/QuestionB.cs
602
C#
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using Castle.Core.Resource; using Castle.MicroKernel; using Castle.MicroKernel.SubSystems.Resource; using Castle.Windsor; namespace Rhino.Commons.Binsor { public class BinsorResourceInstaller: BinsorScriptInstaller<BinsorResourceInstaller> { private readonly string uri; public BinsorResourceInstaller(string uri) { this.uri = uri; } protected override AbstractConfigurationRunner InstallInto(IWindsorContainer container) { var system = (IResourceSubSystem) container.Kernel.GetSubSystem(SubSystemConstants.ResourceKey); var resource = system.CreateResource(uri); var Uri = new CustomUri(uri); return BooReader.Read(container, Uri, GenerationOptions, GetName(), EnvironmentName); } protected string GetName() { return "Binsor" + Guid.NewGuid(); } } }
41.129032
108
0.732941
[ "BSD-3-Clause" ]
cneuwirt/rhino-commons
Rhino.Commons.Binsor/Installer/BinsorResourceInstaller.cs
2,550
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 4.0.2 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace NWN.Native.API { public class SWIGTYPE_p_CExoAliasListInternal { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal SWIGTYPE_p_CExoAliasListInternal(global::System.IntPtr cPtr, bool futureUse) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } protected SWIGTYPE_p_CExoAliasListInternal() { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SWIGTYPE_p_CExoAliasListInternal obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } /*@SWIG:/__w/NWN.Native/NWN.Native/nwnx/Plugins/SWIG/SWIG_DotNET/API_NWNXLib.i,25,SWIG_DOTNET_EXTENSIONS@*/ public global::System.IntPtr Pointer { get { return swigCPtr.Handle; } } public static unsafe implicit operator void*(SWIGTYPE_p_CExoAliasListInternal self) { return (void*)self.swigCPtr.Handle; } public static unsafe SWIGTYPE_p_CExoAliasListInternal FromPointer(void* pointer, bool memoryOwn = false) { return pointer != null ? new SWIGTYPE_p_CExoAliasListInternal((global::System.IntPtr)pointer, memoryOwn) : null; } public static SWIGTYPE_p_CExoAliasListInternal FromPointer(global::System.IntPtr pointer, bool memoryOwn = false) { return pointer != global::System.IntPtr.Zero ? new SWIGTYPE_p_CExoAliasListInternal(pointer, memoryOwn) : null; } public bool Equals(SWIGTYPE_p_CExoAliasListInternal other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return Pointer.Equals(other.Pointer); } public override bool Equals(object obj) { return ReferenceEquals(this, obj) || obj is SWIGTYPE_p_CExoAliasListInternal other && Equals(other); } public override int GetHashCode() { return swigCPtr.Handle.GetHashCode(); } public static bool operator ==(SWIGTYPE_p_CExoAliasListInternal left, SWIGTYPE_p_CExoAliasListInternal right) { return Equals(left, right); } public static bool operator !=(SWIGTYPE_p_CExoAliasListInternal left, SWIGTYPE_p_CExoAliasListInternal right) { return !Equals(left, right); } /*@SWIG@*/} }
35.855263
129
0.70422
[ "MIT" ]
Jorteck/NWN.Native
src/main/API/SWIGTYPE_p_CExoAliasListInternal.cs
2,725
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using NativoPlusStudio.AuthToken.Ficoso.Extensions; using NativoPlusStudio.AuthToken.Core.Interfaces; using FicosoLib; namespace NativoPlusStudio.AuthToken.FicosoTests { public abstract class BaseConfiguration { public static IServiceProvider serviceProvider; public static IConfiguration configuration; public BaseConfiguration() { configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile($"{AppContext.BaseDirectory}/appsettings.json", optional: false, reloadOnChange: true) .Build(); var services = new ServiceCollection(); //services.AddFicosoAuthTokenProvider((options, builder) => //{ // options.AddFicosoOptions( // protectedResource: configuration["FicosoOptions:ProtectedResourceName"], // accessTokenEndpoint: configuration["FicosoOptions:AccessTokenEndpoint"], // clientId: configuration["FicosoOptions:ClientId"], // clientSecret: configuration["FicosoOptions:ClientSecret"], // grantType: configuration["FicosoOptions:GrantType"], // userName: configuration["FicosoOptions:UserName"], // password: configuration["FicosoOptions:Password"], // scope: configuration["FicosoOptions:Scope"], // url: configuration["FicosoOptions:Url"], // includeEncryptedTokenInResponse: true // ); //}); //services.AddHttpClient<FCSHttpClient>(async (provider, client) => //{ // client.BaseAddress = new Uri(configuration["FicosoOptions:Url"]); // var token = await provider.GetService<IAuthTokenGenerator>().GetTokenAsync(protectedResource: configuration["FicosoOptions:ProtectedResourceName"]); // client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(scheme: "Bearer", parameter: token.Token); //}) //.AddRefreshFicosoTokenPolicyWithJitteredBackoff(protectedResourceName: configuration["FicosoOptions:ProtectedResourceName"], initialDelayInSeconds: 1, retryCount: 2) //.AddRefreshFicosoTokenPolicyWithConstantBackoff(protectedResourceName: configuration["FicosoOptions:ProtectedResourceName"], initialDelayInSeconds: 1, retryCount: 2) //.AddRefreshFicosoTokenPolicyWithExponentialBackoff(protectedResourceName: configuration["FicosoOptions:ProtectedResourceName"], initialDelayInSeconds: 1, retryCount: 2) //.AddRefreshFicosoTokenPolicyWithLinearBackoff(protectedResourceName: configuration["FicosoOptions:ProtectedResourceName"], initialDelayInSeconds: 1, retryCount: 2) //.AddRefreshFicosoTokenPolicyWithRetry(protectedResourceName: configuration["FicosoOptions:ProtectedResourceName"], retryCount: 2) ; serviceProvider = services.BuildServiceProvider(); } } }
52.968254
182
0.685945
[ "MIT" ]
nativoplus/NativoPlusStudio.AuthToken.Ficoso
NativoPlusStudio.AuthToken.FicosoTests/BaseConfiguration.cs
3,339
C#
using System; namespace FontAwesome { /// <summary> /// The unicode values for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Unicode { /// <summary> /// fa-galactic-republic unicode value ("\uf50c"). /// <para/> /// This icon supports the following styles: Brands /// <para/> /// See https://fontawesome.com/icons/galactic-republic /// </summary> public const string GalacticRepublic = "\uf50c"; } /// <summary> /// The Css values for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Css { /// <summary> /// GalacticRepublic unicode value ("fa-galactic-republic"). /// <para/> /// This icon supports the following styles: Brands /// <para/> /// See https://fontawesome.com/icons/galactic-republic /// </summary> public const string GalacticRepublic = "fa-galactic-republic"; } /// <summary> /// The Icon names for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Icon { /// <summary> /// fa-galactic-republic unicode value ("\uf50c"). /// <para/> /// This icon supports the following styles: Brands /// <para/> /// See https://fontawesome.com/icons/galactic-republic /// </summary> public const string GalacticRepublic = "GalacticRepublic"; } }
35.52459
154
0.604984
[ "MIT" ]
michaelswells/FontAwesomeAttribute
FontAwesome/FontAwesome.GalacticRepublic.cs
2,167
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20191101.Outputs { [OutputType] public sealed class MatchVariableResponse { /// <summary> /// The selector of match variable. /// </summary> public readonly string? Selector; /// <summary> /// Match Variable. /// </summary> public readonly string VariableName; [OutputConstructor] private MatchVariableResponse( string? selector, string variableName) { Selector = selector; VariableName = variableName; } } }
25.277778
81
0.623077
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20191101/Outputs/MatchVariableResponse.cs
910
C#
/** * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Worklight; namespace StepUpWin10 { public class PinCodeChallengeHandler : Worklight.SecurityCheckChallengeHandler { public JObject challengeAnswer { get; set; } public override string SecurityCheck { get; set; } private bool authSuccess = false; private bool shouldsubmitchallenge = false; private bool shouldsubmitfailure = false; private string Realm; public static ManualResetEvent waitForPincode = new ManualResetEvent(false); public PinCodeChallengeHandler(String securityCheck) { Realm = securityCheck; } public override JObject GetChallengeAnswer() { return this.challengeAnswer; } public override void HandleChallenge(Object challenge) { waitForPincode.Reset(); MainPage._this.showPinChallenge(challenge); shouldsubmitchallenge = true; waitForPincode.WaitOne(); } public override bool ShouldCancel() { return shouldsubmitfailure; } public override bool ShouldSubmitChallengeAnswer() { return this.shouldsubmitchallenge; } public void SetShouldSubmitChallenge(bool shouldsubmitchallenge) { this.shouldsubmitchallenge = shouldsubmitchallenge; } public void SetSubmitFailure(bool shouldsubmitfailure) { this.shouldsubmitfailure = shouldsubmitfailure; } public override void HandleFailure(JObject error) { Debug.WriteLine("Error"); } public override void HandleSuccess(JObject identity) { Debug.WriteLine("Success"); } public override void SubmitChallengeAnswer(object answer) { challengeAnswer = (JObject)answer; } public async Task logout(String SecurityCheck) { WorklightResponse response = await WorklightClient.CreateInstance().AuthorizationManager.Logout(SecurityCheck); } } }
27.862385
124
0.634178
[ "Apache-2.0" ]
MobileFirst-Platform-Developer-Center/StepUpWin10
StepUpWin10/PinCodeChallengeHandler.cs
3,037
C#
//---------------------------------------------------------------------------------------------------------- // X-PostProcessing Library // Copyright (C) 2020 QianMo. All rights reserved. // Licensed under the MIT License // you may not use this file except in compliance with the License.You may obtain a copy of the License at // http://opensource.org/licenses/MIT //---------------------------------------------------------------------------------------------------------- using System; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.PostProcessing; namespace XPostProcessing { [Serializable] [PostProcess(typeof(PixelizeSectorRenderer), PostProcessEvent.BeforeStack, "X-PostProcessing/Pixelize/PixelizeSector")] public class PixelizeSector : PostProcessEffectSettings { [Range(0.01f, 1.0f)] public FloatParameter pixelSize = new FloatParameter { value = 0.8f }; [Range(0.01f, 1.0f)] public FloatParameter circleRadius = new FloatParameter { value = 0.8f }; [Range(0.2f, 5.0f), Tooltip("Pixel interval X")] public FloatParameter pixelIntervalX = new FloatParameter { value = 1f }; [Range(0.2f, 5.0f), Tooltip("Pixel interval Y")] public FloatParameter pixelIntervalY = new FloatParameter { value = 1f }; [ColorUsageAttribute(true, true, 0f, 20f, 0.125f, 3f)] public ColorParameter BackgroundColor = new ColorParameter { value = new Color(0.0f, 0.0f, 0.0f) }; } public sealed class PixelizeSectorRenderer : PostProcessEffectRenderer<PixelizeSector> { private const string PROFILER_TAG = "X-PixelizeSector"; private Shader shader; public override void Init() { shader = Shader.Find("Hidden/X-PostProcessing/PixelizeSector"); } public override void Release() { base.Release(); } static class ShaderIDs { internal static readonly int Params = Shader.PropertyToID("_Params"); internal static readonly int Params2 = Shader.PropertyToID("_Params2"); } public override void Render(PostProcessRenderContext context) { CommandBuffer cmd = context.command; PropertySheet sheet = context.propertySheets.Get(shader); cmd.BeginSample(PROFILER_TAG); float size = (1.01f - settings.pixelSize) * 300f; Vector4 parameters = new Vector4(size, ((context.screenWidth * 2 / context.screenHeight) * size / Mathf.Sqrt(3f)), settings.circleRadius, 0f); sheet.properties.SetVector(ShaderIDs.Params, parameters); sheet.properties.SetVector(ShaderIDs.Params2, new Vector2(settings.pixelIntervalX, settings.pixelIntervalY)); sheet.properties.SetColor("_BackgroundColor", settings.BackgroundColor); cmd.BlitFullscreenTriangle(context.source, context.destination, sheet, 0); cmd.EndSample(PROFILER_TAG); } } }
40.783784
154
0.622598
[ "MIT" ]
flycodes/X-PostProcessing-Library
Assets/X-PostProcessing/Effects/PixelizeSector/PixelizeSector.cs
3,020
C#
using System; using System.Net; using FubuCore; using FubuMVC.Core; using FubuMVC.Core.Behaviors; using Shouldly; using NUnit.Framework; namespace FubuMVC.Tests.Behaviors { [TestFixture] public class InterceptExceptionBehaviorTester { [Test] public void should_invoke_inside_behavior() { var insideBehavior = new DoNothingBehavior(); var cut = new TestInterceptExceptionBehavior<ArgumentException> { InsideBehavior = insideBehavior }; cut.Invoke(); insideBehavior.Invoked.ShouldBeTrue(); } [Test] public void when_no_exception_is_thrown_none_should_be_handled() { var insideBehavior = new DoNothingBehavior(); var cut = new TestInterceptExceptionBehavior<ArgumentException> { InsideBehavior = insideBehavior }; cut.Invoke(); cut.HandledException.ShouldBeNull(); } [Test] public void invoke_should_throw_an_exception_when_no_inside_behavior_is_set() { var interceptExceptionBehavior = new TestInterceptExceptionBehavior<ArgumentException>(); Exception<FubuAssertionException>.ShouldBeThrownBy(interceptExceptionBehavior.Invoke); } [Test] public void when_matching_exception_is_thrown_by_inside_behavior_it_should_be_handled() { var cut = new TestInterceptExceptionBehavior<ArgumentException> { InsideBehavior = new ThrowingBehavior<ArgumentException>() }; cut.Invoke(); cut.HandledException.ShouldBeOfType<ArgumentException>(); } [Test] public void when_exception_should_not_be_handled_the_handle_method_should_not_be_invoked() { var cut = new TestInterceptExceptionBehavior<ArgumentException> { InsideBehavior = new ThrowingBehavior<ArgumentException>() }; cut.SetShouldHandle(false); Exception<ArgumentException>.ShouldBeThrownBy(cut.Invoke); cut.HandledException.ShouldBeNull(); } [Test] public void when_non_matching_exception_is_thrown_should_handled_should_not_be_invoked() { var cut = new TestInterceptExceptionBehavior<ArgumentException> { InsideBehavior = new ThrowingBehavior<WebException>() }; cut.SetShouldHandle(false); Exception<WebException>.ShouldBeThrownBy(cut.Invoke); cut.HandledException.ShouldBeNull(); } } public class TestInterceptExceptionBehavior<T> : InterceptExceptionBehavior<T> where T : Exception { private bool shouldHandle = true; public T HandledException { get; private set; } public void SetShouldHandle(bool value) { shouldHandle = value; } public override bool ShouldHandle(T exception) { return shouldHandle; } public override void Handle(T exception) { HandledException = exception; } } public class ThrowingBehavior<T> : IActionBehavior where T : Exception, new() { public void Invoke() { throw new T(); } public void InvokePartial() { throw new T(); } } public class DoNothingBehavior : IActionBehavior { public bool Invoked { get; set; } public void Invoke() { Invoked = true; } public void InvokePartial() { Invoked = true; } } }
22.465278
99
0.699536
[ "Apache-2.0" ]
JohnnyKapps/fubumvc
src/FubuMVC.Tests/Behaviors/InterceptExceptionBehaviorTester.cs
3,237
C#
/* * 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 es-2015-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Elasticsearch.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Elasticsearch.Model.Internal.MarshallTransformations { /// <summary> /// CreatePackage Request Marshaller /// </summary> public class CreatePackageRequestMarshaller : IMarshaller<IRequest, CreatePackageRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreatePackageRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreatePackageRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Elasticsearch"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-01-01"; request.HttpMethod = "POST"; request.ResourcePath = "/2015-01-01/packages"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetPackageDescription()) { context.Writer.WritePropertyName("PackageDescription"); context.Writer.Write(publicRequest.PackageDescription); } if(publicRequest.IsSetPackageName()) { context.Writer.WritePropertyName("PackageName"); context.Writer.Write(publicRequest.PackageName); } if(publicRequest.IsSetPackageSource()) { context.Writer.WritePropertyName("PackageSource"); context.Writer.WriteObjectStart(); var marshaller = PackageSourceMarshaller.Instance; marshaller.Marshall(publicRequest.PackageSource, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetPackageType()) { context.Writer.WritePropertyName("PackageType"); context.Writer.Write(publicRequest.PackageType); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreatePackageRequestMarshaller _instance = new CreatePackageRequestMarshaller(); internal static CreatePackageRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreatePackageRequestMarshaller Instance { get { return _instance; } } } }
35.555556
141
0.610491
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Elasticsearch/Generated/Model/Internal/MarshallTransformations/CreatePackageRequestMarshaller.cs
4,480
C#
using System; using System.Collections; using Network; using LibCore; using CoreUtils; namespace Polestar_PM.OpsEngine { public class PredictedInfoManager { NodeTree model; Node timeNode; Node predictedMarketInfoNode; public PredictedInfoManager(NodeTree model) { this.model = model; timeNode = model.GetNamedNode("CurrentTime"); timeNode.AttributesChanged += new Network.Node.AttributesChangedEventHandler (timeNode_AttributesChanged); predictedMarketInfoNode = model.GetNamedNode("predicted_market_info"); } public void Dispose() { timeNode.AttributesChanged -= new Network.Node.AttributesChangedEventHandler(timeNode_AttributesChanged); } private void timeNode_AttributesChanged(Node sender, ArrayList attrs) { foreach (AttributeValuePair avp in attrs) { if (avp.Attribute == "seconds") { int displaytime = predictedMarketInfoNode.GetIntAttribute("displaytime",0); if (displaytime > 0) { displaytime--; predictedMarketInfoNode.SetAttribute("displaytime", CONVERT.ToStr(displaytime)); } else { bool display = predictedMarketInfoNode.GetBooleanAttribute("displaytext", false); if (display) { predictedMarketInfoNode.SetAttribute("displaytext", "false"); } } } } } } }
23.927273
109
0.718845
[ "MIT-0" ]
business-sims-toolkit/business-sims-toolkit
dev/products/eboards/pm/Polestar_PM/Polestar_PM.OpsEngine/PredictedInfoManager.cs
1,316
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CuttingRoom { /// <summary> /// A container for holding the logic required to select groups within a layer narrative object. /// </summary> public partial class LayerSelectionDecisionPoint : DecisionPoint { /// <summary> /// A container for the layer selection method definition. /// </summary> [Serializable] public class LayerSelectionMethodNameContainer : MethodNameContainer { } /// <summary> /// The layer selection method definition for this instance of the decision point. /// </summary> [HelpBox("Built in Layer Selection Methods:\n\n• All - Selects all candidates for processing.\n• Random - Selects randomly and returns selected candidates for processing.", HelpBoxMessageType.Info)] public LayerSelectionMethodNameContainer layerSelectionMethodNameContainer = null; /// <summary> /// Initialisation. /// </summary> private new void Awake() { layerSelectionMethodNameContainer.methodClass = typeof(LayerSelectionDecisionPoint).AssemblyQualifiedName; layerSelectionMethodNameContainer.Init(); base.Awake(); } /// <summary> /// Processing loop. /// </summary> /// <param name="onSelected"></param> /// <param name="sequencer"></param> /// <returns></returns> public IEnumerator Process(OnSelectedCallback onSelected, Sequencer sequencer, Sequencer.SequencerLayer sequencerLayer, LayerNarrativeObject layerNarrativeObject) { #if UNITY_EDITOR if (candidates.Count > 0 && !layerSelectionMethodNameContainer.Initialised) { Debug.LogWarning("Layer Selection decision point has candidates but no assigned Layer Selection Method. No selection will be made."); } #endif // If ready to select some layers... if (layerSelectionMethodNameContainer.Initialised) { // ...and some layers are available to be selected. if (candidates.Count > 0) { yield return StartCoroutine(layerSelectionMethodNameContainer.methodInfo.Name, new object[] { this, onSelected, sequencer, sequencerLayer, layerNarrativeObject }); } } } } }
33.375
200
0.738296
[ "Apache-2.0" ]
Digital-Creativity-Labs/CuttingRoom
Assets/Scripts/DecisionPoints/LayerSelectionDecisionPoint.cs
2,142
C#
// // Copyright (C) Microsoft. All rights reserved. // using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.PowerShell.Utility.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Utility\Group-Object command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class GroupObject : PSActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public GroupObject() { this.DisplayName = "Group-Object"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Utility\\Group-Object"; } } // Arguments /// <summary> /// Provides access to the NoElement parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> NoElement { get; set; } /// <summary> /// Provides access to the AsHashTable parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> AsHashTable { get; set; } /// <summary> /// Provides access to the AsString parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> AsString { get; set; } /// <summary> /// Provides access to the InputObject parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.PSObject> InputObject { get; set; } /// <summary> /// Provides access to the Property parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Object[]> Property { get; set; } /// <summary> /// Provides access to the Culture parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Culture { get; set; } /// <summary> /// Provides access to the CaseSensitive parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> CaseSensitive { get; set; } // Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if(NoElement.Expression != null) { targetCommand.AddParameter("NoElement", NoElement.Get(context)); } if(AsHashTable.Expression != null) { targetCommand.AddParameter("AsHashTable", AsHashTable.Get(context)); } if(AsString.Expression != null) { targetCommand.AddParameter("AsString", AsString.Get(context)); } if(InputObject.Expression != null) { targetCommand.AddParameter("InputObject", InputObject.Get(context)); } if(Property.Expression != null) { targetCommand.AddParameter("Property", Property.Get(context)); } if(Culture.Expression != null) { targetCommand.AddParameter("Culture", Culture.Get(context)); } if(CaseSensitive.Expression != null) { targetCommand.AddParameter("CaseSensitive", CaseSensitive.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
35.118881
130
0.620669
[ "Apache-2.0", "MIT" ]
JM2K69/PowerShell
src/Microsoft.PowerShell.Utility.Activities/Generated/GroupObjectActivity.cs
5,022
C#
using UnityEngine; public class TimeManager : Singleton<TimeManager> { public float SlowRate = 0.2f; public float SlowMoSpeed = 2f; public bool IsTimeFrozen = false; [HideInInspector] public bool IsTimeSlowTime = false; [HideInInspector] public bool IsPause = false; void Update() { if (IsPause == true) return; Time.timeScale += SlowMoSpeed * Time.unscaledDeltaTime; Time.timeScale = Mathf.Clamp01 (Time.timeScale); Time.fixedDeltaTime = Time.timeScale * 0.02f; } public void SlowTime() { Time.timeScale = SlowRate; } public void SlowTime(float SlowDownRate) { Time.timeScale = SlowDownRate; } public void FreezeTime() { IsTimeFrozen = true; IsPause = true; Time.timeScale = 0f; } public void UnFreezeTime() { IsTimeFrozen = false; IsPause = false; Time.timeScale = 1f; } }
17.744681
57
0.702638
[ "MIT" ]
CaptainJeoy/A-Combined-Shoot-Em-Up-and-Quiz-Mobile-Game
HannahsNumber/Assets/Scripts/TimeManager.cs
836
C#
#if MIGRATION namespace System.Windows.Automation.Peers #else namespace Windows.UI.Xaml.Automation.Peers #endif { public enum AutomationControlType { // // Summary: // A button control. Button = 0, // // Summary: // A calendar control, such as a date picker. Calendar = 1, // // Summary: // A check box control. CheckBox = 2, // // Summary: // A combo box control. ComboBox = 3, // // Summary: // An edit control, such as a text box. Edit = 4, // // Summary: // A hyperlink control. Hyperlink = 5, // // Summary: // An image control. Image = 6, // // Summary: // A list item control, which is a child item of a list control. ListItem = 7, // // Summary: // A list control, such as a list box. List = 8, // // Summary: // A menu control, such as a top-level menu in an application window. Menu = 9, // // Summary: // A menu bar control, which generally contains a set of top-level menus. MenuBar = 10, // // Summary: // A menu item control. MenuItem = 11, // // Summary: // A progress bar control, which visually indicates the progress of a lengthy operation. ProgressBar = 12, // // Summary: // A radio button control, which is a selection mechanism allowing exactly one selected // item in a group. RadioButton = 13, // // Summary: // A scroll bar control, such as a scroll bar in an application window. ScrollBar = 14, // // Summary: // A slider control. Slider = 15, // // Summary: // A spinner control. Spinner = 16, // // Summary: // A status bar control. StatusBar = 17, // // Summary: // A tab control. Tab = 18, // // Summary: // A tab item control, which represents a page of a tab control. TabItem = 19, // // Summary: // An edit control, such as a text box or rich text box. Text = 20, // // Summary: // A toolbar, such as the control that contains a set of command buttons in an application // window. ToolBar = 21, // // Summary: // A tooltip control, an informational window that appears as a result of moving // the pointer over a control or sometimes when tabbing to a control using the keyboard. ToolTip = 22, // // Summary: // A tree control. Tree = 23, // // Summary: // A node in a tree control. TreeItem = 24, // // Summary: // A control that is not one of the defined control types. Custom = 25, // // Summary: // A group control, which acts as a container for other controls. Group = 26, // // Summary: // The control in a scrollbar that can be dragged to a different position. Thumb = 27, // // Summary: // A data grid control. DataGrid = 28, // // Summary: // A data item control. DataItem = 29, // // Summary: // A document control. Document = 30, // // Summary: // A split button, which is a button that performs a default action and can also // expand to a list of other possible actions. SplitButton = 31, // // Summary: // A window frame, which contains child objects. Window = 32, // // Summary: // A pane control. Pane = 33, // // Summary: // A header control, which is a container for the labels of rows and columns of // information. Header = 34, // // Summary: // A header item, which is the label for a row or column of information. HeaderItem = 35, // // Summary: // A table. Table = 36, // // Summary: // The caption bar on a window. TitleBar = 37, // // Summary: // A separator, which creates a visual division in controls such as menus and toolbars. Separator = 38 } }
22.151163
96
0.586614
[ "MIT" ]
Barjonp/OpenSilver
src/Runtime/Runtime/System.Windows.Automation.Peers/WORKINPROGRESS/AutomationControlType.cs
3,810
C#