context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Text; using System.Reflection.Metadata; #if SRM using System.Reflection.Internal; using BitArithmeticUtilities = System.Reflection.Internal.BitArithmetic; #else using System; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; #endif #if SRM namespace System.Reflection.Metadata.Ecma335 #else namespace Roslyn.Reflection.Metadata.Ecma335 #endif { #if SRM public #endif sealed partial class MetadataBuilder { // #US heap private readonly Dictionary<string, int> _userStrings = new Dictionary<string, int>(); private readonly BlobBuilder _userStringWriter = new BlobBuilder(1024); private readonly int _userStringHeapStartOffset; // #String heap private Dictionary<string, StringHandle> _strings = new Dictionary<string, StringHandle>(128); private int[] _stringIndexToResolvedOffsetMap; private BlobBuilder _stringWriter; private readonly int _stringHeapStartOffset; // #Blob heap private readonly Dictionary<ImmutableArray<byte>, BlobHandle> _blobs = new Dictionary<ImmutableArray<byte>, BlobHandle>(ByteSequenceComparer.Instance); private readonly int _blobHeapStartOffset; private int _blobHeapSize; // #GUID heap private readonly Dictionary<Guid, GuidHandle> _guids = new Dictionary<Guid, GuidHandle>(); private readonly BlobBuilder _guidWriter = new BlobBuilder(16); // full metadata has just a single guid private bool _streamsAreComplete; public MetadataBuilder( int userStringHeapStartOffset = 0, int stringHeapStartOffset = 0, int blobHeapStartOffset = 0, int guidHeapStartOffset = 0) { // Add zero-th entry to all heaps, even in EnC delta. // We don't want generation-relative handles to ever be IsNil. // In both full and delta metadata all nil heap handles should have zero value. // There should be no blob handle that references the 0 byte added at the // beginning of the delta blob. _userStringWriter.WriteByte(0); _blobs.Add(ImmutableArray<byte>.Empty, default(BlobHandle)); _blobHeapSize = 1; // When EnC delta is applied #US, #String and #Blob heaps are appended. // Thus indices of strings and blobs added to this generation are offset // by the sum of respective heap sizes of all previous generations. _userStringHeapStartOffset = userStringHeapStartOffset; _stringHeapStartOffset = stringHeapStartOffset; _blobHeapStartOffset = blobHeapStartOffset; // Unlike other heaps, #Guid heap in EnC delta is zero-padded. _guidWriter.WriteBytes(0, guidHeapStartOffset); } public BlobHandle GetBlob(BlobBuilder builder) { // TODO: avoid making a copy if the blob exists in the index return GetBlob(builder.ToImmutableArray()); } public BlobHandle GetBlob(ImmutableArray<byte> blob) { BlobHandle index; if (!_blobs.TryGetValue(blob, out index)) { Debug.Assert(!_streamsAreComplete); index = MetadataTokens.BlobHandle(_blobHeapSize); _blobs.Add(blob, index); _blobHeapSize += BlobWriterImpl.GetCompressedIntegerSize(blob.Length) + blob.Length; } return index; } public BlobHandle GetConstantBlob(object value) { string str = value as string; if (str != null) { return this.GetBlob(str); } var writer = new BlobBuilder(); writer.WriteConstant(value); return this.GetBlob(writer); } public BlobHandle GetBlob(string str) { byte[] byteArray = new byte[str.Length * 2]; int i = 0; foreach (char ch in str) { byteArray[i++] = (byte)(ch & 0xFF); byteArray[i++] = (byte)(ch >> 8); } return this.GetBlob(ImmutableArray.Create(byteArray)); } public BlobHandle GetBlobUtf8(string str) { return GetBlob(ImmutableArray.Create(Encoding.UTF8.GetBytes(str))); } public GuidHandle GetGuid(Guid guid) { if (guid == Guid.Empty) { return default(GuidHandle); } GuidHandle result; if (_guids.TryGetValue(guid, out result)) { return result; } result = GetNextGuid(); _guids.Add(guid, result); _guidWriter.WriteBytes(guid.ToByteArray()); return result; } public GuidHandle ReserveGuid(out Blob reservedBlob) { var handle = GetNextGuid(); reservedBlob = _guidWriter.ReserveBytes(16); return handle; } private GuidHandle GetNextGuid() { Debug.Assert(!_streamsAreComplete); // The only GUIDs that are serialized are MVID, EncId, and EncBaseId in the // Module table. Each of those GUID offsets are relative to the local heap, // even for deltas, so there's no need for a GetGuidStreamPosition() method // to offset the positions by the size of the original heap in delta metadata. // Unlike #Blob, #String and #US streams delta #GUID stream is padded to the // size of the previous generation #GUID stream before new GUIDs are added. // Metadata Spec: // The Guid heap is an array of GUIDs, each 16 bytes wide. // Its first element is numbered 1, its second 2, and so on. return MetadataTokens.GuidHandle((_guidWriter.Count >> 4) + 1); } public StringHandle GetString(string str) { StringHandle index; if (str.Length == 0) { index = default(StringHandle); } else if (!_strings.TryGetValue(str, out index)) { Debug.Assert(!_streamsAreComplete); index = MetadataTokens.StringHandle(_strings.Count + 1); // idx 0 is reserved for empty string _strings.Add(str, index); } return index; } public int GetHeapOffset(StringHandle handle) { return _stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(handle)]; } public int GetHeapOffset(BlobHandle handle) { int offset = MetadataTokens.GetHeapOffset(handle); return (offset == 0) ? 0 : _blobHeapStartOffset + offset; } public int GetHeapOffset(GuidHandle handle) { return MetadataTokens.GetHeapOffset(handle); } public int GetHeapOffset(UserStringHandle handle) { return MetadataTokens.GetHeapOffset(handle); } public UserStringHandle GetUserString(string str) { int index; if (!_userStrings.TryGetValue(str, out index)) { Debug.Assert(!_streamsAreComplete); index = _userStringWriter.Position + _userStringHeapStartOffset; _userStrings.Add(str, index); _userStringWriter.WriteCompressedInteger(str.Length * 2 + 1); _userStringWriter.WriteUTF16(str); // Write out a trailing byte indicating if the string is really quite simple byte stringKind = 0; foreach (char ch in str) { if (ch >= 0x7F) { stringKind = 1; } else { switch ((int)ch) { case 0x1: case 0x2: case 0x3: case 0x4: case 0x5: case 0x6: case 0x7: case 0x8: case 0xE: case 0xF: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case 0x27: case 0x2D: stringKind = 1; break; default: continue; } } break; } _userStringWriter.WriteByte(stringKind); } return MetadataTokens.UserStringHandle(index); } internal void CompleteHeaps() { Debug.Assert(!_streamsAreComplete); _streamsAreComplete = true; SerializeStringHeap(); } public ImmutableArray<int> GetHeapSizes() { var heapSizes = new int[MetadataTokens.HeapCount]; heapSizes[(int)HeapIndex.UserString] = _userStringWriter.Count; heapSizes[(int)HeapIndex.String] = _stringWriter.Count; heapSizes[(int)HeapIndex.Blob] = _blobHeapSize; heapSizes[(int)HeapIndex.Guid] = _guidWriter.Count; return ImmutableArray.CreateRange(heapSizes); } /// <summary> /// Fills in stringIndexMap with data from stringIndex and write to stringWriter. /// Releases stringIndex as the stringTable is sealed after this point. /// </summary> private void SerializeStringHeap() { // Sort by suffix and remove stringIndex var sorted = new List<KeyValuePair<string, StringHandle>>(_strings); sorted.Sort(new SuffixSort()); _strings = null; _stringWriter = new BlobBuilder(1024); // Create VirtIdx to Idx map and add entry for empty string _stringIndexToResolvedOffsetMap = new int[sorted.Count + 1]; _stringIndexToResolvedOffsetMap[0] = 0; _stringWriter.WriteByte(0); // Find strings that can be folded string prev = string.Empty; foreach (KeyValuePair<string, StringHandle> entry in sorted) { int position = _stringHeapStartOffset + _stringWriter.Position; // It is important to use ordinal comparison otherwise we'll use the current culture! if (prev.EndsWith(entry.Key, StringComparison.Ordinal) && !BlobUtilities.IsLowSurrogateChar(entry.Key[0])) { // Map over the tail of prev string. Watch for null-terminator of prev string. _stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(entry.Value)] = position - (BlobUtilities.GetUTF8ByteCount(entry.Key) + 1); } else { _stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(entry.Value)] = position; _stringWriter.WriteUTF8(entry.Key, allowUnpairedSurrogates: false); _stringWriter.WriteByte(0); } prev = entry.Key; } } /// <summary> /// Sorts strings such that a string is followed immediately by all strings /// that are a suffix of it. /// </summary> private class SuffixSort : IComparer<KeyValuePair<string, StringHandle>> { public int Compare(KeyValuePair<string, StringHandle> xPair, KeyValuePair<string, StringHandle> yPair) { string x = xPair.Key; string y = yPair.Key; for (int i = x.Length - 1, j = y.Length - 1; i >= 0 & j >= 0; i--, j--) { if (x[i] < y[j]) { return -1; } if (x[i] > y[j]) { return +1; } } return y.Length.CompareTo(x.Length); } } public void WriteHeapsTo(BlobBuilder writer) { WriteAligned(_stringWriter, writer); WriteAligned(_userStringWriter, writer); WriteAligned(_guidWriter, writer); WriteAlignedBlobHeap(writer); } private void WriteAlignedBlobHeap(BlobBuilder builder) { int alignment = BitArithmeticUtilities.Align(_blobHeapSize, 4) - _blobHeapSize; var writer = new BlobWriter(builder.ReserveBytes(_blobHeapSize + alignment)); // Perf consideration: With large heap the following loop may cause a lot of cache misses // since the order of entries in _blobs dictionary depends on the hash of the array values, // which is not correlated to the heap index. If we observe such issue we should order // the entries by heap position before running this loop. foreach (var entry in _blobs) { int heapOffset = MetadataTokens.GetHeapOffset(entry.Value); var blob = entry.Key; writer.Offset = heapOffset; writer.WriteCompressedInteger(blob.Length); writer.WriteBytes(blob); } writer.Offset = _blobHeapSize; writer.WriteBytes(0, alignment); } private static void WriteAligned(BlobBuilder source, BlobBuilder target) { int length = source.Count; target.LinkSuffix(source); target.WriteBytes(0, BitArithmeticUtilities.Align(length, 4) - length); } } }
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.Configuration; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Frapid.NPoco; using Serilog; namespace Frapid.Config.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "config.email_queue". /// </summary> public class EmailQueue : DbAccess, IEmailQueueRepository { /// <summary> /// The schema of this table. Returns literal "config". /// </summary> public override string _ObjectNamespace => "config"; /// <summary> /// The schema unqualified name of this table. Returns literal "email_queue". /// </summary> public override string _ObjectName => "email_queue"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "config.email_queue". /// </summary> /// <returns>Returns the number of rows of the table "config.email_queue".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"EmailQueue\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM config.email_queue;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.email_queue" to return all instances of the "EmailQueue" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "EmailQueue" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.EmailQueue> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"EmailQueue\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue ORDER BY queue_id;"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.email_queue" to return all instances of the "EmailQueue" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "EmailQueue" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"EmailQueue\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue ORDER BY queue_id;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.email_queue" with a where filter on the column "queue_id" to return a single instance of the "EmailQueue" class. /// </summary> /// <param name="queueId">The column "queue_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "EmailQueue" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.EmailQueue Get(long queueId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"EmailQueue\" filtered by \"QueueId\" with value {QueueId} was denied to the user with Login ID {_LoginId}", queueId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue WHERE queue_id=@0;"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql, queueId).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "config.email_queue". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "EmailQueue" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.EmailQueue GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"EmailQueue\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue ORDER BY queue_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "config.email_queue" sorted by queueId. /// </summary> /// <param name="queueId">The column "queue_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "EmailQueue" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.EmailQueue GetPrevious(long queueId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"EmailQueue\" by \"QueueId\" with value {QueueId} was denied to the user with Login ID {_LoginId}", queueId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue WHERE queue_id < @0 ORDER BY queue_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql, queueId).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "config.email_queue" sorted by queueId. /// </summary> /// <param name="queueId">The column "queue_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "EmailQueue" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.EmailQueue GetNext(long queueId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"EmailQueue\" by \"QueueId\" with value {QueueId} was denied to the user with Login ID {_LoginId}", queueId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue WHERE queue_id > @0 ORDER BY queue_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql, queueId).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "config.email_queue". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "EmailQueue" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.EmailQueue GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"EmailQueue\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue ORDER BY queue_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "config.email_queue" with a where filter on the column "queue_id" to return a multiple instances of the "EmailQueue" class. /// </summary> /// <param name="queueIds">Array of column "queue_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "EmailQueue" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.EmailQueue> Get(long[] queueIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"EmailQueue\" was denied to the user with Login ID {LoginId}. queueIds: {queueIds}.", this._LoginId, queueIds); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue WHERE queue_id IN (@0);"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql, queueIds); } /// <summary> /// Custom fields are user defined form elements for config.email_queue. /// </summary> /// <returns>Returns an enumerable custom field collection for the table config.email_queue</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"EmailQueue\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='config.email_queue' ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql); } sql = "SELECT * from config.get_custom_field_definition('config.email_queue'::text, @0::text) ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of config.email_queue. /// </summary> /// <returns>Returns an enumerable name and value collection for the table config.email_queue</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"EmailQueue\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT queue_id AS key, from_name as value FROM config.email_queue;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of EmailQueue class on the database table "config.email_queue". /// </summary> /// <param name="emailQueue">The instance of "EmailQueue" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic emailQueue, List<Frapid.DataAccess.Models.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } object primaryKeyValue = emailQueue.queue_id; if (Cast.To<long>(primaryKeyValue) > 0) { this.Update(emailQueue, Cast.To<long>(primaryKeyValue)); } else { primaryKeyValue = this.Add(emailQueue); } string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM config.custom_field_setup " + "WHERE form_name=config.get_custom_field_form_name('config.email_queue')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT config.get_custom_field_setup_id_by_table_name('config.email_queue', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of EmailQueue class on the database table "config.email_queue". /// </summary> /// <param name="emailQueue">The instance of "EmailQueue" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic emailQueue) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"EmailQueue\" was denied to the user with Login ID {LoginId}. {EmailQueue}", this._LoginId, emailQueue); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, emailQueue, "config.email_queue", "queue_id"); } /// <summary> /// Inserts or updates multiple instances of EmailQueue class on the database table "config.email_queue"; /// </summary> /// <param name="emailQueues">List of "EmailQueue" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> emailQueues) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"EmailQueue\" was denied to the user with Login ID {LoginId}. {emailQueues}", this._LoginId, emailQueues); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (ITransaction transaction = db.GetTransaction()) { foreach (dynamic emailQueue in emailQueues) { line++; object primaryKeyValue = emailQueue.queue_id; if (Cast.To<long>(primaryKeyValue) > 0) { result.Add(emailQueue.queue_id); db.Update("config.email_queue", "queue_id", emailQueue, emailQueue.queue_id); } else { result.Add(db.Insert("config.email_queue", "queue_id", emailQueue)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDbErrorResource(ex); throw new DataAccessException(errorMessage, ex); } errorMessage += ex.Message; throw new DataAccessException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new DataAccessException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "config.email_queue" with an instance of "EmailQueue" class against the primary key value. /// </summary> /// <param name="emailQueue">The instance of "EmailQueue" class to update.</param> /// <param name="queueId">The value of the column "queue_id" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic emailQueue, long queueId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"EmailQueue\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {EmailQueue}", queueId, this._LoginId, emailQueue); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, emailQueue, queueId, "config.email_queue", "queue_id"); } /// <summary> /// Deletes the row of the table "config.email_queue" against the primary key value. /// </summary> /// <param name="queueId">The value of the column "queue_id" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(long queueId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"EmailQueue\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", queueId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM config.email_queue WHERE queue_id=@0;"; Factory.NonQuery(this._Catalog, sql, queueId); } /// <summary> /// Performs a select statement on table "config.email_queue" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "EmailQueue" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.EmailQueue> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"EmailQueue\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.email_queue ORDER BY queue_id LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "config.email_queue" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "EmailQueue" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.EmailQueue> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"EmailQueue\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM config.email_queue ORDER BY queue_id LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='config.email_queue' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "config.email_queue". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "EmailQueue" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"EmailQueue\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.email_queue WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.EmailQueue(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.email_queue" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "EmailQueue" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.EmailQueue> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"EmailQueue\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.email_queue WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.EmailQueue(), filters); sql.OrderBy("queue_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "config.email_queue". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "EmailQueue" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"EmailQueue\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.email_queue WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.EmailQueue(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.email_queue" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "EmailQueue" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.EmailQueue> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"EmailQueue\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.email_queue WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.EmailQueue(), filters); sql.OrderBy("queue_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.EmailQueue>(this._Catalog, sql); } } }
using System; using System.ComponentModel; using System.Data.Linq; using System.Linq; using System.Data.Linq.Mapping; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using System.Runtime.Serialization; using System.Reflection; using Dg.Deblazer; using Dg.Deblazer.Validation; using Dg.Deblazer.CodeAnnotation; using Dg.Deblazer.Api; using Dg.Deblazer.Visitors; using Dg.Deblazer.Cache; using Dg.Deblazer.SqlGeneration; using Deblazer.WideWorldImporter.DbLayer.Queries; using Deblazer.WideWorldImporter.DbLayer.Wrappers; using Dg.Deblazer.Read; namespace Deblazer.WideWorldImporter.DbLayer { public partial class Warehouse_StockItemHolding : DbEntity, IId { private DbValue<System.Int32> _StockItemID = new DbValue<System.Int32>(); private DbValue<System.Int32> _QuantityOnHand = new DbValue<System.Int32>(); private DbValue<System.String> _BinLocation = new DbValue<System.String>(); private DbValue<System.Int32> _LastStocktakeQuantity = new DbValue<System.Int32>(); private DbValue<System.Decimal> _LastCostPrice = new DbValue<System.Decimal>(); private DbValue<System.Int32> _ReorderLevel = new DbValue<System.Int32>(); private DbValue<System.Int32> _TargetStockLevel = new DbValue<System.Int32>(); private DbValue<System.Int32> _LastEditedBy = new DbValue<System.Int32>(); private DbValue<System.DateTime> _LastEditedWhen = new DbValue<System.DateTime>(); private IDbEntityRef<Application_People> _Application_People; private IDbEntityRef<Warehouse_StockItem> _Warehouse_StockItem; public int Id => StockItemID; long ILongId.Id => StockItemID; [Validate] public System.Int32 StockItemID { get { return _StockItemID.Entity; } set { _StockItemID.Entity = value; } } [Validate] public System.Int32 QuantityOnHand { get { return _QuantityOnHand.Entity; } set { _QuantityOnHand.Entity = value; } } [StringColumn(20, false)] [Validate] public System.String BinLocation { get { return _BinLocation.Entity; } set { _BinLocation.Entity = value; } } [Validate] public System.Int32 LastStocktakeQuantity { get { return _LastStocktakeQuantity.Entity; } set { _LastStocktakeQuantity.Entity = value; } } [Validate] public System.Decimal LastCostPrice { get { return _LastCostPrice.Entity; } set { _LastCostPrice.Entity = value; } } [Validate] public System.Int32 ReorderLevel { get { return _ReorderLevel.Entity; } set { _ReorderLevel.Entity = value; } } [Validate] public System.Int32 TargetStockLevel { get { return _TargetStockLevel.Entity; } set { _TargetStockLevel.Entity = value; } } [Validate] public System.Int32 LastEditedBy { get { return _LastEditedBy.Entity; } set { _LastEditedBy.Entity = value; } } [StringColumn(7, false)] [Validate] public System.DateTime LastEditedWhen { get { return _LastEditedWhen.Entity; } set { _LastEditedWhen.Entity = value; } } [Validate] public Application_People Application_People { get { Action<Application_People> beforeRightsCheckAction = e => e.Warehouse_StockItemHoldings.Add(this); if (_Application_People != null) { return _Application_People.GetEntity(beforeRightsCheckAction); } _Application_People = GetDbEntityRef(true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, beforeRightsCheckAction); return (Application_People != null) ? _Application_People.GetEntity(beforeRightsCheckAction) : null; } set { if (_Application_People == null) { _Application_People = new DbEntityRef<Application_People>(_db, true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, _lazyLoadChildren, _getChildrenFromCache); } AssignDbEntity<Application_People, Warehouse_StockItemHolding>(value, value == null ? new long ? [0] : new long ? []{(long ? )value.PersonID}, _Application_People, new long ? []{_LastEditedBy.Entity}, new Action<long ? >[]{x => LastEditedBy = (int ? )x ?? default (int)}, x => x.Warehouse_StockItemHoldings, null, LastEditedByChanged); } } void LastEditedByChanged(object sender, EventArgs eventArgs) { if (sender is Application_People) _LastEditedBy.Entity = (int)((Application_People)sender).Id; } [Validate] public Warehouse_StockItem Warehouse_StockItem { get { Action<Warehouse_StockItem> beforeRightsCheckAction = e => e.Warehouse_StockItemHolding = this; if (_Warehouse_StockItem != null) { return _Warehouse_StockItem.GetEntity(beforeRightsCheckAction); } _Warehouse_StockItem = GetDbEntityRef(true, new[]{"[StockItemID]"}, new Func<long ? >[]{() => _StockItemID.Entity}, beforeRightsCheckAction); return (Warehouse_StockItem != null) ? _Warehouse_StockItem.GetEntity(beforeRightsCheckAction) : null; } set { if (_Warehouse_StockItem == null) { _Warehouse_StockItem = new DbEntityRef<Warehouse_StockItem>(_db, true, new[]{"[StockItemID]"}, new Func<long ? >[]{() => _StockItemID.Entity}, _lazyLoadChildren, _getChildrenFromCache); } AssignDbEntity<Warehouse_StockItem, Warehouse_StockItemHolding>(value, value == null ? new long ? [0] : new long ? []{(long ? )value.StockItemID}, _Warehouse_StockItem, new long ? []{_StockItemID.Entity}, new Action<long ? >[]{x => StockItemID = (int ? )x ?? default (int)}, null, (x, y) => x.Warehouse_StockItemHolding = y, StockItemIDChanged); } } void StockItemIDChanged(object sender, EventArgs eventArgs) { if (sender is Warehouse_StockItem) _StockItemID.Entity = (int)((Warehouse_StockItem)sender).Id; } protected override void ModifyInternalState(FillVisitor visitor) { SendIdChanging(); _StockItemID.Load(visitor.GetInt32()); SendIdChanged(); _QuantityOnHand.Load(visitor.GetInt32()); _BinLocation.Load(visitor.GetValue<System.String>()); _LastStocktakeQuantity.Load(visitor.GetInt32()); _LastCostPrice.Load(visitor.GetDecimal()); _ReorderLevel.Load(visitor.GetInt32()); _TargetStockLevel.Load(visitor.GetInt32()); _LastEditedBy.Load(visitor.GetInt32()); _LastEditedWhen.Load(visitor.GetDateTime()); this._db = visitor.Db; isLoaded = true; } protected sealed override void CheckProperties(IUpdateVisitor visitor) { _StockItemID.Welcome(visitor, "StockItemID", "Int NOT NULL", false); _QuantityOnHand.Welcome(visitor, "QuantityOnHand", "Int NOT NULL", false); _BinLocation.Welcome(visitor, "BinLocation", "NVarChar(20) NOT NULL", false); _LastStocktakeQuantity.Welcome(visitor, "LastStocktakeQuantity", "Int NOT NULL", false); _LastCostPrice.Welcome(visitor, "LastCostPrice", "Decimal(18,2) NOT NULL", false); _ReorderLevel.Welcome(visitor, "ReorderLevel", "Int NOT NULL", false); _TargetStockLevel.Welcome(visitor, "TargetStockLevel", "Int NOT NULL", false); _LastEditedBy.Welcome(visitor, "LastEditedBy", "Int NOT NULL", false); _LastEditedWhen.Welcome(visitor, "LastEditedWhen", "DateTime2(7) NOT NULL", false); } protected override void HandleChildren(DbEntityVisitorBase visitor) { visitor.ProcessAssociation(this, _Application_People); visitor.ProcessAssociation(this, _Warehouse_StockItem); } } public static class Db_Warehouse_StockItemHoldingQueryGetterExtensions { public static Warehouse_StockItemHoldingTableQuery<Warehouse_StockItemHolding> Warehouse_StockItemHoldings(this IDb db) { var query = new Warehouse_StockItemHoldingTableQuery<Warehouse_StockItemHolding>(db as IDb); return query; } } } namespace Deblazer.WideWorldImporter.DbLayer.Queries { public class Warehouse_StockItemHoldingQuery<K, T> : Query<K, T, Warehouse_StockItemHolding, Warehouse_StockItemHoldingWrapper, Warehouse_StockItemHoldingQuery<K, T>> where K : QueryBase where T : DbEntity, ILongId { public Warehouse_StockItemHoldingQuery(IDb db): base (db) { } protected sealed override Warehouse_StockItemHoldingWrapper GetWrapper() { return Warehouse_StockItemHoldingWrapper.Instance; } public Application_PeopleQuery<Warehouse_StockItemHoldingQuery<K, T>, T> JoinApplication_People(JoinType joinType = JoinType.Inner, bool preloadEntities = false) { var joinedQuery = new Application_PeopleQuery<Warehouse_StockItemHoldingQuery<K, T>, T>(Db); return Join(joinedQuery, string.Concat(joinType.GetJoinString(), " [Application].[People] AS {1} {0} ON", "{2}.[LastEditedBy] = {1}.[PersonID]"), o => ((Warehouse_StockItemHolding)o)?.Application_People, (e, fv, ppe) => { var child = (Application_People)ppe(QueryHelpers.Fill<Application_People>(null, fv)); if (e != null) { ((Warehouse_StockItemHolding)e).Application_People = child; } return child; } , typeof (Application_People), preloadEntities); } public Warehouse_StockItemQuery<Warehouse_StockItemHoldingQuery<K, T>, T> JoinWarehouse_StockItem(JoinType joinType = JoinType.Inner, bool preloadEntities = false) { var joinedQuery = new Warehouse_StockItemQuery<Warehouse_StockItemHoldingQuery<K, T>, T>(Db); return Join(joinedQuery, string.Concat(joinType.GetJoinString(), " [Warehouse].[StockItems] AS {1} {0} ON", "{2}.[StockItemID] = {1}.[StockItemID]"), o => ((Warehouse_StockItemHolding)o)?.Warehouse_StockItem, (e, fv, ppe) => { var child = (Warehouse_StockItem)ppe(QueryHelpers.Fill<Warehouse_StockItem>(null, fv)); if (e != null) { ((Warehouse_StockItemHolding)e).Warehouse_StockItem = child; } return child; } , typeof (Warehouse_StockItem), preloadEntities); } } public class Warehouse_StockItemHoldingTableQuery<T> : Warehouse_StockItemHoldingQuery<Warehouse_StockItemHoldingTableQuery<T>, T> where T : DbEntity, ILongId { public Warehouse_StockItemHoldingTableQuery(IDb db): base (db) { } } } namespace Deblazer.WideWorldImporter.DbLayer.Helpers { public class Warehouse_StockItemHoldingHelper : QueryHelper<Warehouse_StockItemHolding>, IHelper<Warehouse_StockItemHolding> { string[] columnsInSelectStatement = new[]{"{0}.StockItemID", "{0}.QuantityOnHand", "{0}.BinLocation", "{0}.LastStocktakeQuantity", "{0}.LastCostPrice", "{0}.ReorderLevel", "{0}.TargetStockLevel", "{0}.LastEditedBy", "{0}.LastEditedWhen"}; public sealed override string[] ColumnsInSelectStatement => columnsInSelectStatement; string[] columnsInInsertStatement = new[]{"{0}.StockItemID", "{0}.QuantityOnHand", "{0}.BinLocation", "{0}.LastStocktakeQuantity", "{0}.LastCostPrice", "{0}.ReorderLevel", "{0}.TargetStockLevel", "{0}.LastEditedBy", "{0}.LastEditedWhen"}; public sealed override string[] ColumnsInInsertStatement => columnsInInsertStatement; private static readonly string createTempTableCommand = "CREATE TABLE #Warehouse_StockItemHolding ([StockItemID] Int NOT NULL,[QuantityOnHand] Int NOT NULL,[BinLocation] NVarChar(20) NOT NULL,[LastStocktakeQuantity] Int NOT NULL,[LastCostPrice] Decimal(18,2) NOT NULL,[ReorderLevel] Int NOT NULL,[TargetStockLevel] Int NOT NULL,[LastEditedBy] Int NOT NULL,[LastEditedWhen] DateTime2(7) NOT NULL, [RowIndexForSqlBulkCopy] INT NOT NULL)"; public sealed override string CreateTempTableCommand => createTempTableCommand; public sealed override string FullTableName => "[Warehouse].[StockItemHoldings]"; public sealed override bool IsForeignKeyTo(Type other) { return false; } private const string insertCommand = "INSERT INTO [Warehouse].[StockItemHoldings] ([{TableName = \"Warehouse].[StockItemHoldings\";}].[StockItemID], [{TableName = \"Warehouse].[StockItemHoldings\";}].[QuantityOnHand], [{TableName = \"Warehouse].[StockItemHoldings\";}].[BinLocation], [{TableName = \"Warehouse].[StockItemHoldings\";}].[LastStocktakeQuantity], [{TableName = \"Warehouse].[StockItemHoldings\";}].[LastCostPrice], [{TableName = \"Warehouse].[StockItemHoldings\";}].[ReorderLevel], [{TableName = \"Warehouse].[StockItemHoldings\";}].[TargetStockLevel], [{TableName = \"Warehouse].[StockItemHoldings\";}].[LastEditedBy], [{TableName = \"Warehouse].[StockItemHoldings\";}].[LastEditedWhen]) VALUES ([@StockItemID],[@QuantityOnHand],[@BinLocation],[@LastStocktakeQuantity],[@LastCostPrice],[@ReorderLevel],[@TargetStockLevel],[@LastEditedBy],[@LastEditedWhen]); SELECT SCOPE_IDENTITY()"; public sealed override void FillInsertCommand(SqlCommand sqlCommand, Warehouse_StockItemHolding _Warehouse_StockItemHolding) { sqlCommand.CommandText = insertCommand; sqlCommand.Parameters.AddWithValue("@StockItemID", _Warehouse_StockItemHolding.StockItemID); sqlCommand.Parameters.AddWithValue("@QuantityOnHand", _Warehouse_StockItemHolding.QuantityOnHand); sqlCommand.Parameters.AddWithValue("@BinLocation", _Warehouse_StockItemHolding.BinLocation ?? (object)DBNull.Value); sqlCommand.Parameters.AddWithValue("@LastStocktakeQuantity", _Warehouse_StockItemHolding.LastStocktakeQuantity); sqlCommand.Parameters.AddWithValue("@LastCostPrice", _Warehouse_StockItemHolding.LastCostPrice); sqlCommand.Parameters.AddWithValue("@ReorderLevel", _Warehouse_StockItemHolding.ReorderLevel); sqlCommand.Parameters.AddWithValue("@TargetStockLevel", _Warehouse_StockItemHolding.TargetStockLevel); sqlCommand.Parameters.AddWithValue("@LastEditedBy", _Warehouse_StockItemHolding.LastEditedBy); sqlCommand.Parameters.AddWithValue("@LastEditedWhen", _Warehouse_StockItemHolding.LastEditedWhen); } public sealed override void ExecuteInsertCommand(SqlCommand sqlCommand, Warehouse_StockItemHolding _Warehouse_StockItemHolding) { using (var sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess)) { sqlDataReader.Read(); _Warehouse_StockItemHolding.StockItemID = Convert.ToInt32(sqlDataReader.GetValue(0)); } } private static Warehouse_StockItemHoldingWrapper _wrapper = Warehouse_StockItemHoldingWrapper.Instance; public QueryWrapper Wrapper { get { return _wrapper; } } } } namespace Deblazer.WideWorldImporter.DbLayer.Wrappers { public class Warehouse_StockItemHoldingWrapper : QueryWrapper<Warehouse_StockItemHolding> { public readonly QueryElMemberId<Application_People> LastEditedBy = new QueryElMemberId<Application_People>("LastEditedBy"); public readonly QueryElMemberStruct<System.Int32> QuantityOnHand = new QueryElMemberStruct<System.Int32>("QuantityOnHand"); public readonly QueryElMember<System.String> BinLocation = new QueryElMember<System.String>("BinLocation"); public readonly QueryElMemberStruct<System.Int32> LastStocktakeQuantity = new QueryElMemberStruct<System.Int32>("LastStocktakeQuantity"); public readonly QueryElMemberStruct<System.Decimal> LastCostPrice = new QueryElMemberStruct<System.Decimal>("LastCostPrice"); public readonly QueryElMemberStruct<System.Int32> ReorderLevel = new QueryElMemberStruct<System.Int32>("ReorderLevel"); public readonly QueryElMemberStruct<System.Int32> TargetStockLevel = new QueryElMemberStruct<System.Int32>("TargetStockLevel"); public readonly QueryElMemberStruct<System.DateTime> LastEditedWhen = new QueryElMemberStruct<System.DateTime>("LastEditedWhen"); public static readonly Warehouse_StockItemHoldingWrapper Instance = new Warehouse_StockItemHoldingWrapper(); private Warehouse_StockItemHoldingWrapper(): base ("[Warehouse].[StockItemHoldings]", "Warehouse_StockItemHolding") { } } }
/** * Copyright 2015-2016 GetSocial B.V. * * 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.ObjectModel; using System.Collections.Generic; namespace GetSocialSdk.Core { /// <summary> /// Describes the current user. /// </summary> public class CurrentUser { /// <summary> /// Get social user identity conflict resolution strategy. /// </summary> public enum AddIdentityConflictResolutionStrategy { /// <summary> /// Current user is used and the new identity won't be added since it already belongs to the remote user /// </summary> Current = 1, /// <summary> /// Remote user that contains added identity /// </summary> Remote = 2 } /// <summary> /// Possible results of adding user identity /// </summary> public enum AddIdentityResult { /// <summary> /// Identity was successfully added without a conflict /// </summary> SuccessfullyAddedIdentity = 1, /// <summary> /// Current user is kept and the new identity won't be added since it already belongs to the remote user /// </summary> ConflictWasResolvedWithCurrent = 2, /// <summary> /// Current user is replaced with remote user /// </summary> ConflictWasResolvedWithRemote = 3 } /// <summary> /// Delefate of the method that will be invoked when adding the identity to the user if the identity already belongs to another user /// /// Based on the received current and remote user information you can prompt user to decide or decide yourself. /// To finalize the callback you MUST ALWAYS call <code>resolveConflictAction</code> passing the resolution strategy you chose. /// </summary> public delegate void OnAddIdentityConflictDelegate( User currentUser,User remoteUser,Action<AddIdentityConflictResolutionStrategy> resolveConflictAction); private readonly IGetSocialNativeBridge nativeBridge; internal CurrentUser(IGetSocialNativeBridge nativeBridge) { this.nativeBridge = nativeBridge; } /// <summary> /// Unique Identifier of the user. /// </summary> public string Guid { get { return nativeBridge.UserGuid; } } /// <summary> /// Display name of the user. /// </summary> public string DisplayName { get { return nativeBridge.UserDisplayName; } } /// <summary> /// Sets a new display name for the user /// </summary> /// <param name="displayName">New display name of the user.</param> /// <param name="onSuccess">On success callback.</param> /// <param name="onFailure">On failure callback.</param> public void SetDisplayName(string displayName, Action onSuccess, Action<string> onFailure) { Check.Argument.IsStrNotNullOrEmpty(displayName, "displayName", "Display name can not be null or empty"); Check.Argument.IsNotNull(onSuccess, "onSuccess", "Success callback cannot be null"); Check.Argument.IsNotNull(onFailure, "onFailure", "Failure callback cannot be null"); nativeBridge.SetDisplayName(displayName, onSuccess, onFailure); } /// <summary> /// The Url of the Avatar of the user. <code>null</code> if no avatar Url is available. /// </summary> public string AvatarUrl { get { return nativeBridge.UserAvatarUrl; } } /// <summary> /// Sets a new avatar url for the user. /// </summary> /// <param name="avatarUrl">New avatar url for the user</param> /// <param name="onSuccess">On success callback.</param> /// <param name="onFailure">On failure callback.</param> public void SetAvatarUrl(string avatarUrl, Action onSuccess, Action<string> onFailure) { Check.Argument.IsStrNotNullOrEmpty(avatarUrl, "avatarUrl", "Avatar url name can not be null or empty"); Check.Argument.IsNotNull(onSuccess, "onSuccess", "Success callback cannot be null"); Check.Argument.IsNotNull(onFailure, "onFailure", "Failure callback cannot be null"); nativeBridge.SetAvatarUrl(avatarUrl, onSuccess, onFailure); } /// <summary> /// Indicates if the user has at least one identity available /// </summary> /// <value><code>true</code> if user does not have any identities; otherwise, <code>false</code>.</value> public bool IsAnonymous { get { return nativeBridge.IsUserAnonymous; } } /// <summary> /// Identities of the user /// </summary> public ReadOnlyCollection<string> Identities { get { return Array.AsReadOnly(nativeBridge.UserIdentities); } } /// <summary> /// Determines whether the user has identity for the specified provider. /// </summary> /// <returns><code>true</code> if this instance has identity for the specified provider; otherwise, <code>false</code>.</returns> public bool HasIdentityForProvider(string provider) { Check.Argument.IsStrNotNullOrEmpty(provider, "provider", "Provider can not be null or empty"); return nativeBridge.UserHasIdentityForProvider(provider); } /// <summary> /// Gets the user id for the specified provider. /// </summary> /// <returns>The user id for provider, null if user doesn't have the specified provider present</returns> public string GetIdForProvider(string provider) { Check.Argument.IsStrNotNullOrEmpty(provider, "provider", "Provider can not be null or empty"); return HasIdentityForProvider(provider) ? nativeBridge.GetUserIdForProvider(provider) : null; } /// <summary> /// Adds identity to the current user. /// /// If the identity you are trying to add already belongs to another user it will invoke <code>onConflict</code> callback passing /// information about current user, remote user the identity you are trying to add already belongs to, and action to finalize the callback. /// /// If you implement <code>onConflict</code> callback you MUST ALWAYS call finalize action pasing your conflict resolution strategy as a parameter. /// If you do not provide <code>onConflict</code> callback SDK will substitute the current user with the user identity already belongs to. /// /// After the finalized action is called you are guaranteed to receive either <code>onComplete</code> or <code>onFailure</code> callback. /// </summary> /// <param name="identity">Identity info to be added</param> /// <param name="onComplete">Invoked when adding identity is completed. The result describing how it completed will be passed as parameter <see cref="AddIdentityResult"/></param> /// <param name="onFailure">Invoked when adding identity failed</param> /// /// <param name="onConflict"> /// Invoked when the identity already belongs to another user and the conflict needs to be resolved. /// </param> public void AddUserIdentity(UserIdentity identity, Action<AddIdentityResult> onComplete, Action<string> onFailure, CurrentUser.OnAddIdentityConflictDelegate onConflict = null) { Check.Argument.IsNotNull(identity, "identity", "Identity cannot be null"); Check.Argument.IsNotNull(onComplete, "onComplete", "Complete callback cannot be null"); Check.Argument.IsNotNull(onFailure, "onFailure", "Failure callback cannot be null"); nativeBridge.AddUserIdentity(identity.Serialize().ToString(), onComplete, onFailure, onConflict); } /// <summary> /// Removes User identity for the specified provider. /// </summary> /// <param name="providerId">Id of the provider.</param> /// <param name="onSuccess">On success callback.</param> /// <param name="onFailure">On failure callback. Error message is passed as a parameter.</param> public void RemoveUserIdentity(string providerId, Action onSuccess, Action<string> onFailure) { Check.Argument.IsStrNotNullOrEmpty(providerId, "providerId", "Provider id can not be null or empty"); Check.Argument.IsNotNull(onSuccess, "onSuccess", "Success callback cannot be null"); Check.Argument.IsNotNull(onFailure, "onFailure", "Failure callback cannot be null"); nativeBridge.RemoveUserIdentity(providerId, onSuccess, onFailure); } /// <summary> /// Resets the current user and generates a new anonymous user. /// </summary> /// <param name="onSuccess">On success callback.</param> /// <param name="onFailure">On failure callback. Error message is passed as a parameter.</param> public void Reset(Action onSuccess, Action<string> onFailure) { Check.Argument.IsNotNull(onSuccess, "onSuccess", "Success callback cannot be null"); Check.Argument.IsNotNull(onFailure, "onFailure", "Failure callback cannot be null"); nativeBridge.ResetUser(onSuccess, onFailure); } #region social_graph_API /// <summary> /// Adds specified user to list of users who the current user is following /// </summary> /// <param name="user">User to follow.</param> /// <param name="onSuccess">On success callback.</param> /// <param name="onFailure">On failure callback. Error message is passed as a parameter.</param> public void FollowUser(User user, Action onSuccess, Action<string> onFailure) { nativeBridge.FollowUser(user.Guid, onSuccess, onFailure); } /// <summary> /// Adds user with specified userId and provider to list of users who the current user is following /// </summary> /// <param name="provider">Provider Id.</param> /// <param name="userId">User id on provider</param> /// <param name="onSuccess">On success callback.</param> /// <param name="onFailure">On failure callback. Error message is passed as a parameter.</param> public void FollowUser(string provider, string userId, Action onSuccess, Action<string> onFailure) { nativeBridge.FollowUser(provider, userId, onSuccess, onFailure); } /// <summary> /// Removes specified user from the list of users who the current user is following /// </summary> /// <param name="user">User to unfollow.</param> /// <param name="onSuccess">On success callback.</param> /// <param name="onFailure">On failure callback. Error message is passed as a parameter.</param> public void UnfollowUser(User user, Action onSuccess, Action<string> onFailure) { nativeBridge.UnfollowUser(user.Guid, onSuccess, onFailure); } /// <summary> /// Removes user with specified userId and provider from the list of users who the current user is following /// </summary> /// <param name="provider">Provider Id.</param> /// <param name="userId">User id on provider</param> /// <param name="onSuccess">On success callback.</param> /// <param name="onFailure">On failure callback. Error message is passed as a parameter.</param> public void UnfollowUser(string provider, string userId, Action onSuccess, Action<string> onFailure) { nativeBridge.UnfollowUser(provider, userId, onSuccess, onFailure); } /// <summary> /// Gets the list of users that current user is following. /// </summary> /// <param name="offset">Offset from which users will be retrieved.</param> /// <param name="count">Number of users to retireve.</param> /// <param name="onSuccess">On success. List of retrieved users is passed as a parameter.</param> /// <param name="onFailure">On failure callback. Error message is passed as a parameter.</param> public void GetFollowing(int offset, int count, Action<List<User>> onSuccess, Action<string> onFailure) { nativeBridge.GetFollowing(offset, count, onSuccess, onFailure); } /// <summary> /// Gets the list of users that are following current user. /// </summary> /// <param name="offset">Offset from which users will be retrieved.</param> /// <param name="count">Number of users to retireve.</param> /// <param name="onSuccess">On success. List of retrieved users is passed as a parameter.</param> /// <param name="onFailure">On failure callback. Error message is passed as a parameter.</param> public void GetFollowers(int offset, int count, Action<List<User>> onSuccess, Action<string> onFailure) { nativeBridge.GetFollowers(offset, count, onSuccess, onFailure); } #endregion } }
using Lucene.Net.Util; using NUnit.Framework; using System; using System.Globalization; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Expressions.JS { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestJavascriptFunction : LuceneTestCase { private static double DELTA = 0.0000001; private void AssertEvaluatesTo(string expression, double expected) { Expression evaluator = JavascriptCompiler.Compile(expression); double actual = evaluator.Evaluate(0, null); Assert.AreEqual(expected, actual, DELTA); } [Test] public virtual void TestAbsMethod() { AssertEvaluatesTo("abs(0)", 0); AssertEvaluatesTo("abs(119)", 119); AssertEvaluatesTo("abs(119)", 119); AssertEvaluatesTo("abs(1)", 1); AssertEvaluatesTo("abs(-1)", 1); } [Test] public virtual void TestAcosMethod() { AssertEvaluatesTo("acos(-1)", Math.PI); AssertEvaluatesTo("acos(-0.8660254)", Math.PI * 5 / 6); AssertEvaluatesTo("acos(-0.7071068)", Math.PI * 3 / 4); AssertEvaluatesTo("acos(-0.5)", Math.PI * 2 / 3); AssertEvaluatesTo("acos(0)", Math.PI / 2); AssertEvaluatesTo("acos(0.5)", Math.PI / 3); AssertEvaluatesTo("acos(0.7071068)", Math.PI / 4); AssertEvaluatesTo("acos(0.8660254)", Math.PI / 6); AssertEvaluatesTo("acos(1)", 0); } [Test] public virtual void TestAcoshMethod() { AssertEvaluatesTo("acosh(1)", 0); AssertEvaluatesTo("acosh(2.5)", 1.5667992369724109); AssertEvaluatesTo("acosh(1234567.89)", 14.719378760739708); } [Test] public virtual void TestAsinMethod() { AssertEvaluatesTo("asin(-1)", -Math.PI / 2); AssertEvaluatesTo("asin(-0.8660254)", -Math.PI / 3); AssertEvaluatesTo("asin(-0.7071068)", -Math.PI / 4); AssertEvaluatesTo("asin(-0.5)", -Math.PI / 6); AssertEvaluatesTo("asin(0)", 0); AssertEvaluatesTo("asin(0.5)", Math.PI / 6); AssertEvaluatesTo("asin(0.7071068)", Math.PI / 4); AssertEvaluatesTo("asin(0.8660254)", Math.PI / 3); AssertEvaluatesTo("asin(1)", Math.PI / 2); } [Test] public virtual void TestAsinhMethod() { AssertEvaluatesTo("asinh(-1234567.89)", -14.719378760740035); AssertEvaluatesTo("asinh(-2.5)", -1.6472311463710958); AssertEvaluatesTo("asinh(-1)", -0.8813735870195429); AssertEvaluatesTo("asinh(0)", 0); AssertEvaluatesTo("asinh(1)", 0.8813735870195429); AssertEvaluatesTo("asinh(2.5)", 1.6472311463710958); AssertEvaluatesTo("asinh(1234567.89)", 14.719378760740035); } [Test] public virtual void TestAtanMethod() { AssertEvaluatesTo("atan(-1.732050808)", -Math.PI / 3); AssertEvaluatesTo("atan(-1)", -Math.PI / 4); AssertEvaluatesTo("atan(-0.577350269)", -Math.PI / 6); AssertEvaluatesTo("atan(0)", 0); AssertEvaluatesTo("atan(0.577350269)", Math.PI / 6); AssertEvaluatesTo("atan(1)", Math.PI / 4); AssertEvaluatesTo("atan(1.732050808)", Math.PI / 3); } [Test] public virtual void TestAtan2Method() { AssertEvaluatesTo("atan2(+0,+0)", +0.0); AssertEvaluatesTo("atan2(+0,-0)", +Math.PI); AssertEvaluatesTo("atan2(-0,+0)", -0.0); AssertEvaluatesTo("atan2(-0,-0)", -Math.PI); AssertEvaluatesTo("atan2(2,2)", Math.PI / 4); AssertEvaluatesTo("atan2(-2,2)", -Math.PI / 4); AssertEvaluatesTo("atan2(2,-2)", Math.PI * 3 / 4); AssertEvaluatesTo("atan2(-2,-2)", -Math.PI * 3 / 4); } [Test] public virtual void TestAtanhMethod() { AssertEvaluatesTo("atanh(-1)", double.NegativeInfinity); AssertEvaluatesTo("atanh(-0.5)", -0.5493061443340549); AssertEvaluatesTo("atanh(0)", 0); AssertEvaluatesTo("atanh(0.5)", 0.5493061443340549); AssertEvaluatesTo("atanh(1)", double.PositiveInfinity); } [Test] public virtual void TestCeilMethod() { AssertEvaluatesTo("ceil(0)", 0); AssertEvaluatesTo("ceil(0.1)", 1); AssertEvaluatesTo("ceil(0.9)", 1); AssertEvaluatesTo("ceil(25.2)", 26); AssertEvaluatesTo("ceil(-0.1)", 0); AssertEvaluatesTo("ceil(-0.9)", 0); AssertEvaluatesTo("ceil(-1.1)", -1); } [Test] public virtual void TestCosMethod() { //AssertEvaluatesTo("cos(0)", 1); //AssertEvaluatesTo("cos(" + Math.PI / 2 + ")", 0); //AssertEvaluatesTo("cos(" + -Math.PI / 2 + ")", 0); //AssertEvaluatesTo("cos(" + Math.PI / 4 + ")", 0.7071068); //AssertEvaluatesTo("cos(" + -Math.PI / 4 + ")", 0.7071068); //AssertEvaluatesTo("cos(" + Math.PI * 2 / 3 + ")", -0.5); //AssertEvaluatesTo("cos(" + -Math.PI * 2 / 3 + ")", -0.5); //AssertEvaluatesTo("cos(" + Math.PI / 6 + ")", 0.8660254); //AssertEvaluatesTo("cos(" + -Math.PI / 6 + ")", 0.8660254); // LUCENENET specific - need to apply invariant culture to the string concatenation // to ensure the numeric formatting is correct, otherwise it may look like the wrong number of parameters AssertEvaluatesTo("cos(0)", 1); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "cos({0})", Math.PI / 2), 0); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "cos({0})", -Math.PI / 2), 0); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "cos({0})", Math.PI / 4), 0.7071068); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "cos({0})", -Math.PI / 4), 0.7071068); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "cos({0})", Math.PI * 2 / 3), -0.5); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "cos({0})", -Math.PI * 2 / 3), -0.5); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "cos({0})", Math.PI / 6), 0.8660254); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "cos({0})", -Math.PI / 6), 0.8660254); } [Test] public virtual void TestCoshMethod() { AssertEvaluatesTo("cosh(0)", 1); AssertEvaluatesTo("cosh(-1)", 1.5430806348152437); AssertEvaluatesTo("cosh(1)", 1.5430806348152437); AssertEvaluatesTo("cosh(-0.5)", 1.1276259652063807); AssertEvaluatesTo("cosh(0.5)", 1.1276259652063807); AssertEvaluatesTo("cosh(-12.3456789)", 114982.09728671524); AssertEvaluatesTo("cosh(12.3456789)", 114982.09728671524); } [Test] public virtual void TestExpMethod() { AssertEvaluatesTo("exp(0)", 1); AssertEvaluatesTo("exp(-1)", 0.36787944117); AssertEvaluatesTo("exp(1)", 2.71828182846); AssertEvaluatesTo("exp(-0.5)", 0.60653065971); AssertEvaluatesTo("exp(0.5)", 1.6487212707); AssertEvaluatesTo("exp(-12.3456789)", 0.0000043485); AssertEvaluatesTo("exp(12.3456789)", 229964.194569); } [Test] public virtual void TestFloorMethod() { AssertEvaluatesTo("floor(0)", 0); AssertEvaluatesTo("floor(0.1)", 0); AssertEvaluatesTo("floor(0.9)", 0); AssertEvaluatesTo("floor(25.2)", 25); AssertEvaluatesTo("floor(-0.1)", -1); AssertEvaluatesTo("floor(-0.9)", -1); AssertEvaluatesTo("floor(-1.1)", -2); } [Test] public virtual void TestHaversinMethod() { AssertEvaluatesTo("haversin(40.7143528,-74.0059731,40.759011,-73.9844722)", 5.284299568309 ); } [Test] public virtual void TestLnMethod() { AssertEvaluatesTo("ln(0)", double.NegativeInfinity); // LUCENENET specific - need to apply invariant culture to the string concatenation // to ensure the numeric formatting is correct, otherwise it may look like the wrong number of parameters AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "ln({0})", Math.E), 1); AssertEvaluatesTo("ln(-1)", double.NaN); AssertEvaluatesTo("ln(1)", 0); AssertEvaluatesTo("ln(0.5)", -0.69314718056); AssertEvaluatesTo("ln(12.3456789)", 2.51330611521); } [Test] public virtual void TestLog10Method() { AssertEvaluatesTo("log10(0)", double.NegativeInfinity); AssertEvaluatesTo("log10(1)", 0); AssertEvaluatesTo("log10(-1)", double.NaN); AssertEvaluatesTo("log10(0.5)", -0.3010299956639812); AssertEvaluatesTo("log10(12.3456789)", 1.0915149771692705); } [Test] public virtual void TestLognMethod() { AssertEvaluatesTo("logn(2, 0)", double.NegativeInfinity); AssertEvaluatesTo("logn(2, 1)", 0); AssertEvaluatesTo("logn(2, -1)", double.NaN); AssertEvaluatesTo("logn(2, 0.5)", -1); AssertEvaluatesTo("logn(2, 12.3456789)", 3.6259342686489378); AssertEvaluatesTo("logn(2.5, 0)", double.NegativeInfinity); AssertEvaluatesTo("logn(2.5, 1)", 0); AssertEvaluatesTo("logn(2.5, -1)", double.NaN); AssertEvaluatesTo("logn(2.5, 0.5)", -0.75647079736603); AssertEvaluatesTo("logn(2.5, 12.3456789)", 2.7429133874016745); } [Test] public virtual void TestMaxMethod() { AssertEvaluatesTo("max(0, 0)", 0); AssertEvaluatesTo("max(1, 0)", 1); AssertEvaluatesTo("max(0, -1)", 0); AssertEvaluatesTo("max(-1, 0)", 0); AssertEvaluatesTo("max(25, 23)", 25); } [Test] public virtual void TestMinMethod() { AssertEvaluatesTo("min(0, 0)", 0); AssertEvaluatesTo("min(1, 0)", 0); AssertEvaluatesTo("min(0, -1)", -1); AssertEvaluatesTo("min(-1, 0)", -1); AssertEvaluatesTo("min(25, 23)", 23); } [Test] public virtual void TestPowMethod() { AssertEvaluatesTo("pow(0, 0)", 1); AssertEvaluatesTo("pow(0.1, 2)", 0.01); AssertEvaluatesTo("pow(0.9, -1)", 1.1111111111111112); AssertEvaluatesTo("pow(2.2, -2.5)", 0.13929749224447147); AssertEvaluatesTo("pow(5, 3)", 125); AssertEvaluatesTo("pow(-0.9, 5)", -0.59049); AssertEvaluatesTo("pow(-1.1, 2)", 1.21); } [Test] public virtual void TestSinMethod() { //AssertEvaluatesTo("sin(0)", 0); //AssertEvaluatesTo("sin(" + Math.PI / 2 + ")", 1); //AssertEvaluatesTo("sin(" + -Math.PI / 2 + ")", -1); //AssertEvaluatesTo("sin(" + Math.PI / 4 + ")", 0.7071068); //AssertEvaluatesTo("sin(" + -Math.PI / 4 + ")", -0.7071068); //AssertEvaluatesTo("sin(" + Math.PI * 2 / 3 + ")", 0.8660254); //AssertEvaluatesTo("sin(" + -Math.PI * 2 / 3 + ")", -0.8660254); //AssertEvaluatesTo("sin(" + Math.PI / 6 + ")", 0.5); //AssertEvaluatesTo("sin(" + -Math.PI / 6 + ")", -0.5); // LUCENENET specific - need to apply invariant culture to the string concatenation // to ensure the numeric formatting is correct, otherwise it may look like the wrong number of parameters AssertEvaluatesTo("sin(0)", 0); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "sin({0})", Math.PI / 2), 1); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "sin({0})", -Math.PI / 2), - 1); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "sin({0})", Math.PI / 4), 0.7071068); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "sin({0})", -Math.PI / 4), -0.7071068); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "sin({0})", Math.PI * 2 / 3), 0.8660254); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "sin({0})", -Math.PI * 2 / 3), - 0.8660254); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "sin({0})", Math.PI / 6), 0.5); AssertEvaluatesTo(string.Format(CultureInfo.InvariantCulture, "sin({0})", -Math.PI / 6), -0.5); } [Test] public virtual void TestSinhMethod() { AssertEvaluatesTo("sinh(0)", 0); AssertEvaluatesTo("sinh(-1)", -1.1752011936438014); AssertEvaluatesTo("sinh(1)", 1.1752011936438014); AssertEvaluatesTo("sinh(-0.5)", -0.52109530549); AssertEvaluatesTo("sinh(0.5)", 0.52109530549); AssertEvaluatesTo("sinh(-12.3456789)", -114982.09728236674); AssertEvaluatesTo("sinh(12.3456789)", 114982.09728236674); } [Test] public virtual void TestSqrtMethod() { AssertEvaluatesTo("sqrt(0)", 0); AssertEvaluatesTo("sqrt(-1)", double.NaN); AssertEvaluatesTo("sqrt(0.49)", 0.7); AssertEvaluatesTo("sqrt(49)", 7); } [Test] public virtual void TestTanMethod() { AssertEvaluatesTo("tan(0)", 0); AssertEvaluatesTo("tan(-1)", -1.55740772465); AssertEvaluatesTo("tan(1)", 1.55740772465); AssertEvaluatesTo("tan(-0.5)", -0.54630248984); AssertEvaluatesTo("tan(0.5)", 0.54630248984); AssertEvaluatesTo("tan(-1.3)", -3.60210244797); AssertEvaluatesTo("tan(1.3)", 3.60210244797); } [Test] public virtual void TestTanhMethod() { AssertEvaluatesTo("tanh(0)", 0); AssertEvaluatesTo("tanh(-1)", -0.76159415595); AssertEvaluatesTo("tanh(1)", 0.76159415595); AssertEvaluatesTo("tanh(-0.5)", -0.46211715726); AssertEvaluatesTo("tanh(0.5)", 0.46211715726); AssertEvaluatesTo("tanh(-12.3456789)", -0.99999999996); AssertEvaluatesTo("tanh(12.3456789)", 0.99999999996); } } }
//------------------------------------------------------------------------------ // <copyright file=QueryOutputWriter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; namespace System.Xml { /// <summary> /// This writer wraps an XmlWriter that was not build using the XmlRawWriter architecture (such as XmlTextWriter or a custom XmlWriter) /// for use in the XslCompilerTransform. Depending on the Xsl stylesheet output settings (which gets transfered to this writer via the /// internal properties of XmlWriterSettings) this writer will inserts additional lexical information into the resulting Xml 1.0 document: /// /// 1. CData sections /// 2. DocType declaration /// 3. Standalone attribute /// /// It also calls WriteStateDocument if standalone="yes" and/or a DocType declaration is written out in order to enforce document conformance /// checking. /// </summary> internal class QueryOutputWriterV1 : XmlWriter { private XmlWriter wrapped; private bool inCDataSection; private Dictionary<XmlQualifiedName, XmlQualifiedName> lookupCDataElems; private BitStack bitsCData; private XmlQualifiedName qnameCData; private bool outputDocType, inAttr; private string systemId, publicId; private XmlStandalone standalone; public QueryOutputWriterV1(XmlWriter writer, XmlWriterSettings settings) { this.wrapped = writer; this.systemId = settings.DocTypeSystem; this.publicId = settings.DocTypePublic; if (settings.OutputMethod == XmlOutputMethod.Xml) { bool documentConformance = false; // Xml output method shouldn't output doc-type-decl if system ID is not defined (even if public ID is) // Only check for well-formed document if output method is xml if (this.systemId != null) { documentConformance = true; this.outputDocType = true; } // Check for well-formed document if standalone="yes" in an auto-generated xml declaration if (settings.Standalone == XmlStandalone.Yes) { documentConformance = true; this.standalone = settings.Standalone; } if (documentConformance) { if (settings.Standalone == XmlStandalone.Yes) { this.wrapped.WriteStartDocument(true); } else { this.wrapped.WriteStartDocument(); } } if (settings.CDataSectionElements != null && settings.CDataSectionElements.Count > 0) { this.bitsCData = new BitStack(); this.lookupCDataElems = new Dictionary<XmlQualifiedName, XmlQualifiedName>(); this.qnameCData = new XmlQualifiedName(); // Add each element name to the lookup table foreach (XmlQualifiedName name in settings.CDataSectionElements) { this.lookupCDataElems[name] = null; } this.bitsCData.PushBit(false); } } else if (settings.OutputMethod == XmlOutputMethod.Html) { // Html output method should output doc-type-decl if system ID or public ID is defined if (this.systemId != null || this.publicId != null) this.outputDocType = true; } } //----------------------------------------------- // XmlWriter interface //----------------------------------------------- public override WriteState WriteState { get { return this.wrapped.WriteState; } } public override void WriteStartDocument() { this.wrapped.WriteStartDocument(); } public override void WriteStartDocument(bool standalone) { this.wrapped.WriteStartDocument(standalone); } public override void WriteEndDocument() { this.wrapped.WriteEndDocument(); } /// <summary> /// Suppress this explicit call to WriteDocType if information was provided by XmlWriterSettings. /// </summary> public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (this.publicId == null && this.systemId == null) { Debug.Assert(!this.outputDocType); this.wrapped.WriteDocType(name, pubid, sysid, subset); } } /// <summary> /// Output doc-type-decl on the first element, and determine whether this element is a /// CData section element. /// </summary> public override void WriteStartElement(string prefix, string localName, string ns) { EndCDataSection(); // Output doc-type declaration immediately before first element is output if (this.outputDocType) { WriteState ws = this.wrapped.WriteState; if (ws == WriteState.Start || ws == WriteState.Prolog) { this.wrapped.WriteDocType( prefix.Length != 0 ? prefix + ":" + localName : localName, this.publicId, this.systemId, null ); } this.outputDocType = false; } this.wrapped.WriteStartElement(prefix, localName, ns); if (this.lookupCDataElems != null) { // Determine whether this element is a CData section element this.qnameCData.Init(localName, ns); this.bitsCData.PushBit(this.lookupCDataElems.ContainsKey(this.qnameCData)); } } public override void WriteEndElement() { EndCDataSection(); this.wrapped.WriteEndElement(); if (this.lookupCDataElems != null) this.bitsCData.PopBit(); } public override void WriteFullEndElement() { EndCDataSection(); this.wrapped.WriteFullEndElement(); if (this.lookupCDataElems != null) this.bitsCData.PopBit(); } public override void WriteStartAttribute(string prefix, string localName, string ns) { this.inAttr = true; this.wrapped.WriteStartAttribute(prefix, localName, ns); } public override void WriteEndAttribute() { this.inAttr = false; this.wrapped.WriteEndAttribute(); } public override void WriteCData(string text) { this.wrapped.WriteCData(text); } public override void WriteComment(string text) { EndCDataSection(); this.wrapped.WriteComment(text); } public override void WriteProcessingInstruction(string name, string text) { EndCDataSection(); this.wrapped.WriteProcessingInstruction(name, text); } public override void WriteWhitespace(string ws) { if (!this.inAttr && (this.inCDataSection || StartCDataSection())) this.wrapped.WriteCData(ws); else this.wrapped.WriteWhitespace(ws); } public override void WriteString(string text) { if (!this.inAttr && (this.inCDataSection || StartCDataSection())) this.wrapped.WriteCData(text); else this.wrapped.WriteString(text); } public override void WriteChars(char[] buffer, int index, int count) { if (!this.inAttr && (this.inCDataSection || StartCDataSection())) this.wrapped.WriteCData(new string(buffer, index, count)); else this.wrapped.WriteChars(buffer, index, count); } public override void WriteBase64(byte[] buffer, int index, int count) { if (!this.inAttr && (this.inCDataSection || StartCDataSection())) this.wrapped.WriteBase64(buffer, index, count); else this.wrapped.WriteBase64(buffer, index, count); } public override void WriteEntityRef(string name) { EndCDataSection(); this.wrapped.WriteEntityRef(name); } public override void WriteCharEntity(char ch) { EndCDataSection(); this.wrapped.WriteCharEntity(ch); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { EndCDataSection(); this.wrapped.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteRaw(char[] buffer, int index, int count) { if (!this.inAttr && (this.inCDataSection || StartCDataSection())) this.wrapped.WriteCData(new string(buffer, index, count)); else this.wrapped.WriteRaw(buffer, index, count); } public override void WriteRaw(string data) { if (!this.inAttr && (this.inCDataSection || StartCDataSection())) this.wrapped.WriteCData(data); else this.wrapped.WriteRaw(data); } public override void Close() { this.wrapped.Close(); } public override void Flush() { this.wrapped.Flush(); } public override string LookupPrefix(string ns) { return this.wrapped.LookupPrefix(ns); } //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// Write CData text if element is a CData element. Return true if text should be written /// within a CData section. /// </summary> private bool StartCDataSection() { Debug.Assert(!this.inCDataSection); if (this.lookupCDataElems != null && this.bitsCData.PeekBit()) { this.inCDataSection = true; return true; } return false; } /// <summary> /// No longer write CData text. /// </summary> private void EndCDataSection() { this.inCDataSection = false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.CoreFunctionLibrary { /// <summary> /// Core Function Library - Node Set Functions /// </summary> public static partial class NodeSetFunctionsTests { /// <summary> /// Expected: Selects the last element child of the context node. /// child::*[last()] /// </summary> [Fact] public static void NodeSetFunctionsTest221() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"child::*[last()]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child5", Name = "Child5", HasNameTable = true, Value = "Last" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the second last element child of the context node. /// child::*[last() - 1] /// </summary> [Fact] public static void NodeSetFunctionsTest222() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"child::*[last() - 1]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child4", Name = "Child4", HasNameTable = true, Value = "Fourth" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the last attribute node of the context node. /// attribute::*[last()] /// </summary> [Fact] public static void NodeSetFunctionsTest223() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"attribute::*[last()]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "Attr5", Name = "Attr5", HasNameTable = true, Value = "Last" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the second last attribute node of the context node. /// attribute::*[last() - 1] /// </summary> [Fact] public static void NodeSetFunctionsTest224() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"attribute::*[last() - 1]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "Attr4", Name = "Attr4", HasNameTable = true, Value = "Fourth" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the last element child of the context node. /// child::*[position() = last()] /// </summary> [Fact] public static void NodeSetFunctionsTest225() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"child::*[position() = last()]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child5", Name = "Child5", HasNameTable = true, Value = "Last" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[position() = last()] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest226() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child5"; var testExpression = @"*[position() = last()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// *[position() = last()] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest227() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child4"; var testExpression = @"*[position() = last()]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() = last()] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest228() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr5"; var testExpression = @"@*[position() = last()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// @*[position() = last()] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest229() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr4"; var testExpression = @"@*[position() = last()]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[last() = 1] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest2210() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test2/Child1"; var testExpression = @"*[last() = 1]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[last() = 1] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest2211() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child1"; var testExpression = @"*[last() = 1]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// child::*[position() = 2] /// </summary> [Fact] public static void NodeSetFunctionsTest2212() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"child::*[position() = 2]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child2", Name = "Child2", HasNameTable = true, Value = "Second" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd attribute of the context node. /// attribute::*[position() = 2] /// </summary> [Fact] public static void NodeSetFunctionsTest2213() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"attribute::*[position() = 2]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "Attr2", Name = "Attr2", HasNameTable = true, Value = "Second" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// child::*[2] /// </summary> [Fact] public static void NodeSetFunctionsTest2214() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"child::*[2]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child2", Name = "Child2", HasNameTable = true, Value = "Second" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd attribute of the context node. /// attribute::*[2] /// </summary> [Fact] public static void NodeSetFunctionsTest2215() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"attribute::*[2]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "Attr2", Name = "Attr2", HasNameTable = true, Value = "Second" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all element children of the context node except the first two. /// child::*[position() > 2] /// </summary> [Fact] public static void NodeSetFunctionsTest2216() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"child::*[position() > 2]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child3", Name = "Child3", HasNameTable = true, Value = "Third" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child4", Name = "Child4", HasNameTable = true, Value = "Fourth" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child5", Name = "Child5", HasNameTable = true, Value = "Last" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all element children of the context node. /// child::*[position()] /// </summary> [Fact] public static void NodeSetFunctionsTest2217() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"child::*[position()]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child1", Name = "Child1", HasNameTable = true, Value = "First" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child2", Name = "Child2", HasNameTable = true, Value = "Second" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child3", Name = "Child3", HasNameTable = true, Value = "Third" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child4", Name = "Child4", HasNameTable = true, Value = "Fourth" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Child5", Name = "Child5", HasNameTable = true, Value = "Last" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[position() = 2] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest2218() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child2"; var testExpression = @"*[position() = 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// *[position() = 2] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest2219() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"*[position() = 2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() = 2] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest2220() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr2"; var testExpression = @"@*[position() = 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() = 2] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest2221() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr3"; var testExpression = @"@*[position() = 2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// *[2] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest2222() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child2"; var testExpression = @"*[2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// *[2] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest2223() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"*[2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// @*[2] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest2224() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr2"; var testExpression = @"@*[2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// @*[2] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest2225() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr1"; var testExpression = @"@*[2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[position() > 2] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest2226() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"*[position() > 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// *[position() > 2] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest2227() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child2"; var testExpression = @"*[position() > 2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() > 2] (Matches = true) /// </summary> [Fact] public static void NodeSetFunctionsTest2228() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr3"; var testExpression = @"@*[position() > 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() > 2] (Matches = false) /// </summary> [Fact] public static void NodeSetFunctionsTest2229() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr2"; var testExpression = @"@*[position() > 2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Number of attribute nodes. /// count(attribute::*) /// </summary> [Fact] public static void NodeSetFunctionsTest2230() { var xml = "xp005.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"count(attribute::*)"; var expected = 5d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Number of attribute nodes. /// count(descendant::para) /// </summary> [Fact] public static void NodeSetFunctionsTest2231() { var xml = "xp005.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"count(descendant::Child3)"; var expected = 1d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Namespace URI of the context node. /// namespace-uri() (element node) /// </summary> [Fact] public static void NodeSetFunctionsTest2235() { var xml = "xp008.xml"; var startingNodePath = "/Doc/ns:elem"; var testExpression = @"namespace-uri()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"uri:this is a test"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: Namespace URI of the context node. /// namespace-uri() (attribute node) /// </summary> [Fact] public static void NodeSetFunctionsTest2236() { var xml = "xp008.xml"; var startingNodePath = "/Doc/ns:elem/@ns:attr"; var testExpression = @"namespace-uri()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"uri:this is a test"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: Namespace URI of the first child node of the context node. /// namespace-uri(child::*) /// </summary> [Fact] public static void NodeSetFunctionsTest2237() { var xml = "xp008.xml"; var startingNodePath = "/Doc"; var testExpression = @"namespace-uri(child::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"uri:this is a test"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: Namespace URI of the first attribute node of the context node. /// namespace-uri(attribute::*) /// </summary> [Fact] public static void NodeSetFunctionsTest2238() { var xml = "xp008.xml"; var startingNodePath = "/Doc/ns:elem"; var testExpression = @"namespace-uri(attribute::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"uri:this is a test"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: QName of the context node. /// name() (with prefix, element node) /// </summary> [Fact] public static void NodeSetFunctionsTest2241() { var xml = "xp008.xml"; var startingNodePath = "/Doc/ns:elem"; var testExpression = @"name()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"ns:elem"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: QName of the context node. /// name() (with prefix, attribute node) /// </summary> [Fact] public static void NodeSetFunctionsTest2242() { var xml = "xp008.xml"; var startingNodePath = "/Doc/ns:elem/@ns:attr"; var testExpression = @"name()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"ns:attr"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: QName of the first child node of the context node. /// name(child::*) /// </summary> [Fact] public static void NodeSetFunctionsTest2243() { var xml = "xp008.xml"; var startingNodePath = "/Doc"; var testExpression = @"name(child::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"ns:elem"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: QName of the first attribute node of the context node. /// name(attribute::*) /// </summary> [Fact] public static void NodeSetFunctionsTest2244() { var xml = "xp008.xml"; var startingNodePath = "/child::*/child::*"; var testExpression = @"name(attribute::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"ns:attr"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: QName of the context node. /// local-name() (with prefix, element node) /// </summary> [Fact] public static void NodeSetFunctionsTest2247() { var xml = "xp008.xml"; var startingNodePath = "/Doc/ns:elem"; var testExpression = @"local-name()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"elem"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: QName of the context node. /// local-name() (with prefix, attribute node) /// </summary> [Fact] public static void NodeSetFunctionsTest2248() { var xml = "xp008.xml"; var startingNodePath = "/Doc/ns:elem/@ns:attr"; var testExpression = @"local-name()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"attr"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: Local part of the expanded-name of the first child node of the context node. /// local-name(child::*) /// </summary> [Fact] public static void NodeSetFunctionsTest2249() { var xml = "xp008.xml"; var startingNodePath = "/Doc"; var testExpression = @"local-name(child::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"elem"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: QName of the first attribute node of the context node. /// local-name(attribute::*) /// </summary> [Fact] public static void NodeSetFunctionsTest2250() { var xml = "xp008.xml"; var startingNodePath = "/Doc/ns:elem"; var testExpression = @"local-name(attribute::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "uri:this is a test"); var expected = @"attr"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } #if FEATURE_XML_XPATH_ID /// <summary> /// Data file has no DTD, so no element has an ID, expected empty node-set /// id("1") /// </summary> [Fact] public static void NodeSetFunctionsTest2267() { var xml = "id4.xml"; var testExpression = @"id(""1"")"; var expected = new XPathResult(0); ; Utils.XPathNodesetTest(xml, testExpression, expected); } #endif /// <summary> /// Expected: empty namespace uri /// namespace-uri() (namespace node) /// </summary> [Fact] public static void NodeSetFunctionsTest2294() { var xml = "name2.xml"; var startingNodePath = "/ns:store/ns:booksection/namespace::NSbook"; var testExpression = @"namespace-uri()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: empty namespace uri /// namespace-uri() (namespace node = xml) /// </summary> [Fact] public static void NodeSetFunctionsTest2295() { var xml = "name2.xml"; var startingNodePath = "/ns:store/namespace::*[1]"; var testExpression = @"namespace-uri()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: empty namespace uri /// namespace-uri() (namespace node = default ns) /// </summary> [Fact] public static void NodeSetFunctionsTest2296() { var xml = "name2.xml"; var startingNodePath = "/ns:store/namespace::*[2]"; var testExpression = @"namespace-uri()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: empty namespace uri /// namespace-uri() (namespace node) /// </summary> [Fact] public static void NodeSetFunctionsTest2297() { var xml = "name2.xml"; var testExpression = @"namespace-uri(ns:store/ns:booksection/namespace::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager); } /// <summary> /// Expected: empty namespace uri /// name() (namespace node) /// </summary> [Fact] public static void NodeSetFunctionsTest2298() { var xml = "name2.xml"; var startingNodePath = "/ns:store/ns:booksection/namespace::NSbook"; var testExpression = @"name()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"NSbook"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: empty namespace uri /// name() (namespace node = xml) /// </summary> [Fact] public static void NodeSetFunctionsTest2299() { var xml = "name2.xml"; var startingNodePath = "/ns:store/namespace::*[1]"; var testExpression = @"name()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: empty namespace uri /// name() (namespace node = default ns) /// </summary> [Fact] public static void NodeSetFunctionsTest22100() { var xml = "name2.xml"; var startingNodePath = "/ns:store/namespace::*[1]"; var testExpression = @"name()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @""; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: empty namespace uri /// name() (namespace node) /// </summary> [Fact] public static void NodeSetFunctionsTest22101() { var xml = "name2.xml"; var testExpression = @"name(ns:store/ns:booksection/namespace::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"NSbook"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Drawing; using System.Drawing.Imaging; namespace Extensions { /// <summary> /// known mime type categories /// </summary> public enum MimeTypeCategoryType : int { Application, Audio, Image, Video, Unknown } /// <summary> /// interface for mime type /// </summary> public interface IMimeType { MimeTypeCategoryType Category { get; } string Name { get; } string FriendlyName { get; } byte[] Signature { get; } string[] Extensions { get; } } /// <summary> /// /// </summary> public sealed class MimeType : IMimeType { private static readonly IDictionary<string, IMimeType> mimeTypeMap = new Dictionary<string, IMimeType>( StringComparer.OrdinalIgnoreCase ) { { "binary", new MimeType( MimeTypeCategoryType.Application, "application/octet-stream", "Binary", null, string.Empty ) }, { "doc", new MimeType( MimeTypeCategoryType.Application, "application/msword", "Word Document", new byte[] { 208, 207, 17, 224, 161, 177, 26, 225 }, ".doc" ) }, { "docx", new MimeType( MimeTypeCategoryType.Application, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Word 2007 Document", new byte[] { 80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33, 0 }, ".docx" ) }, { "exe", new MimeType( MimeTypeCategoryType.Application, "application/x-msdownload", "MS Executable", new byte[] { 77, 90, 144, 0, 3, 0, 0, 0, 4, 0, 0, 0, 255, 255, 0, 0 }, ".exe" ) }, { "dll", new MimeType( MimeTypeCategoryType.Application, "application/x-msdownload", "Dynamic Link Library", new byte[] { 77, 90, 144, 0, 3, 0, 0, 0, 4, 0, 0, 0, 255, 255, 0, 0 }, ".dll" ) }, { "ogx", new MimeType( MimeTypeCategoryType.Application, "application/ogg", "OGG", new byte[] { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, ".ogx" ) }, { "pdf", new MimeType( MimeTypeCategoryType.Application, "application/pdf", "PDF Documents", new byte[] { 37, 80, 68, 70, 45, 49, 46 }, ".pdf" ) }, { "rar", new MimeType( MimeTypeCategoryType.Application, "application/x-rar-compressed", "RAR Archive", new byte[] { 82, 97, 114, 33, 26, 7, 0 }, ".rar" ) }, { "swf", new MimeType( MimeTypeCategoryType.Application, "application/x-shockwave-flash", "Shockwave Flash", new byte[] { 70, 87, 83 }, ".swf" ) }, { "torrent", new MimeType( MimeTypeCategoryType.Application, "application/x-bittorrent", "Bit Torrent", new byte[] { 100, 56, 58, 97, 110, 110, 111, 117, 110, 99, 101 }, ".torrent" ) }, { "ttf", new MimeType( MimeTypeCategoryType.Application, "application/x-font-ttf", "True Type Font", new byte[] { 0, 1, 0, 0, 0 }, ".ttf" ) }, { "zip", new MimeType( MimeTypeCategoryType.Application, "application/x-zip-compressed", "ZIP Archive", new byte[] { 80, 75, 3, 4, 10 }, ".zip" ) }, { "png", new MimeType( MimeTypeCategoryType.Image, "image/png", "PNG Image", new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 }, ".png" ) }, { "jpg", new MimeType( MimeTypeCategoryType.Image, "image/jpeg", "JPG Image", new byte[] { 255, 216, 255 }, new string[] { ".jpeg", ".jpg" } ) }, { "gif", new MimeType( MimeTypeCategoryType.Image, "image/gif", "GIF Image", new byte[] { 71, 73, 70, 56 }, ".gif" ) }, { "bmp", new MimeType( MimeTypeCategoryType.Image, "image/bmp", "Bitmap Image", new byte[] { 66, 77 }, ".bmp" ) }, { "ico", new MimeType( MimeTypeCategoryType.Image, "image/x-icon", "Icon", new byte[] { 0, 0, 1, 0 }, ".ico" ) }, { "tiff", new MimeType( MimeTypeCategoryType.Image, "image/tiff", "TIFF Image", new byte[] { 73, 73, 42, 0 }, ".tiff" ) }, { "mp3", new MimeType( MimeTypeCategoryType.Audio, "audio/", "MP3", new byte[] { 255, 251, 48 }, ".mp3" ) }, { "oga", new MimeType( MimeTypeCategoryType.Audio, "audio/ogg", "OGA", new byte[] { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, ".oga" ) }, { "wav", new MimeType( MimeTypeCategoryType.Audio, "audio/x-wav", "WAV", new byte[] { 82, 73, 70, 70 }, ".wav" ) }, { "wma", new MimeType( MimeTypeCategoryType.Audio, "audio/x-ms-wma", "WMA", new byte[] { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 }, "wma" ) }, { "ogg", new MimeType( MimeTypeCategoryType.Video, "video/ogg", "OGG", new byte[] { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, ".ogg" ) }, { "avi", new MimeType( MimeTypeCategoryType.Video, "video/x-msvideo", "AVI", new byte[] { 82, 73, 70, 70 }, ".avi" ) }, { "wmv", new MimeType( MimeTypeCategoryType.Video, "video/x-ms-wmv", "WMV", new byte[] { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 }, ".wmv" ) }, { "unknown", new MimeType( MimeTypeCategoryType.Unknown, "unknown", "Unknown type", null, string.Empty ) } }; public MimeType( string name, string friendlyName, byte[] signature, string extension ) : this( MimeTypeCategoryType.Unknown, name, friendlyName, signature, new string[] { extension } ) { } public MimeType( MimeTypeCategoryType category, string name, string friendlyName, byte[] signature, string extension ) : this( category, name, friendlyName, signature, new string[] { extension } ) { } public MimeType( string name, string friendlyName, byte[] signature, string[] extensions ) : this( MimeTypeCategoryType.Unknown, name, friendlyName, signature, extensions ) { } public MimeType( MimeTypeCategoryType category, string name, string friendlyName, byte[] signature, string[] extensions ) { this.category = category; this.name = name; this.friendlyName = friendlyName; this.signature = signature; this.extensions = extensions; } #region IMimeType Members private MimeTypeCategoryType category; public MimeTypeCategoryType Category { get { return this.category; } } private string name; public string Name { get { return this.name; } } private string friendlyName; public string FriendlyName { get { return this.friendlyName; } } private byte[] signature; public byte[] Signature { get { return this.signature; } } private string[] extensions; public string[] Extensions { get { return this.extensions; } } #endregion /// <summary> /// /// </summary> /// <param name="extension"></param> /// <returns></returns> // TODO: change to more efficient (non-LINQ) method public static IMimeType GetMimeTypeFromExt( string extension ) { var mimeType = mimeTypeMap.Values .FirstOrDefault( mt => mt.Extensions != null && mt.Extensions.SingleOrDefault( e => e.Equals( extension, StringComparison.OrdinalIgnoreCase ) ) != null ); return ( mimeType == null ) ? mimeTypeMap[ "unknown" ] : mimeType; } /// <summary> /// check an array of bytes against image decoders to determine mime type /// </summary> /// <param name="data"></param> /// <returns></returns> // TODO: change to more efficient (non-LINQ) method public static IMimeType GetImageMimeType( byte[] data ) { Guid id = Guid.Empty; using ( MemoryStream stream = new MemoryStream( data, 0, data.Length ) ) { try { Image img = Image.FromStream( stream, true ); id = img.RawFormat.Guid; foreach ( ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders() ) { if ( codec.FormatID.Equals( id ) ) { return mimeTypeMap.Values.Single( mt => mt.Name.Equals( codec.MimeType, StringComparison.OrdinalIgnoreCase ) ); } } } catch { } } return mimeTypeMap[ "unknown" ]; } /// <summary> /// compares the provided byte array to known mime type byte signatures and extension, if provided, to find the mime type /// </summary> /// <param name="data"></param> /// <param name="extension"></param> /// <returns></returns> // TODO: change to more efficient (non-LINQ) method public static IMimeType GetMimeType( byte[] data, string extension = null ) { IMimeType mimeType = null; var mimeTypes = mimeTypeMap.Values .Where( mt => mt.Signature != null && mt.Signature.SequenceEqual( data.Take(mt.Signature.Length) ) ); // if more than one, with the same signature, are found, try to compare by extension if ( mimeTypes.Count() > 1 && string.IsNullOrWhiteSpace( extension ) == false ) { mimeTypes = mimeTypes.Where( mt => mt.Extensions.SingleOrDefault( e => e.Equals( extension, StringComparison.OrdinalIgnoreCase ) ) != null ); } else if ( mimeTypes.Count() == 0 && string.IsNullOrWhiteSpace( extension ) == false ) { // try the extension return GetMimeTypeFromExt( extension ); } // null or the first found // TODO: return all found mimeTypes? mimeType = mimeTypes.FirstOrDefault(); return ( mimeType == null ) ? mimeTypeMap[ "binary" ] : mimeType; } } }
using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Threading; using Dapper; using MySql.Data.MySqlClient; using NExpect; using NUnit.Framework; using PeanutButter.TempDb.MySql.Base; using PeanutButter.Utils; using static NExpect.Expectations; using static PeanutButter.Utils.PyLike; using static PeanutButter.RandomGenerators.RandomValueGen; // ReSharper disable MemberCanBePrivate.Global // ReSharper disable AccessToDisposedClosure namespace PeanutButter.TempDb.MySql.Data.Tests { [TestFixture] [Parallelizable(ParallelScope.None)] public class TestTempDbMySqlData { [Test] public void ShouldImplement_ITempDB() { // Arrange var sut = typeof(TempDBMySql); // Pre-Assert // Act Expect(sut).To.Implement<ITempDB>(); // Assert } [Test] public void ShouldBeDisposable() { // Arrange var sut = typeof(TempDBMySql); // Pre-Assert // Act Expect(sut).To.Implement<IDisposable>(); // Assert } [TestFixture] public class WhenProvidedPathToMySqlD { [TestCaseSource(nameof(MySqlPathFinders))] public void Construction_ShouldCreateSchemaAndSwitchToIt( string mysqld) { // Arrange var expectedId = GetRandomInt(); var expectedName = GetRandomAlphaNumericString(5); // Pre-Assert // Act using var db = Create(mysqld); var util = new MySqlConnectionStringUtil(db.ConnectionString); Expect(util.Database).Not.To.Be.Null.Or.Empty(); using (var connection = db.OpenConnection()) using (var command = connection.CreateCommand()) { command.CommandText = new[] { "create table cows (id int, name varchar(128));", $"insert into cows (id, name) values ({expectedId}, '{expectedName}');" }.JoinWith("\n"); command.ExecuteNonQuery(); } using (var connection = db.OpenConnection()) using (var command = connection.CreateCommand()) { command.CommandText = "select id, name from cows;"; using (var reader = command.ExecuteReader()) { Expect(reader.HasRows).To.Be.True(); Expect(reader.Read()).To.Be.True(); Expect(reader["id"]).To.Equal(expectedId); Expect(reader["name"]).To.Equal(expectedName); Expect(reader.Read()).To.Be.False(); // Assert } } } [Test] [TestCaseSource(nameof(MySqlPathFinders))] public void ShouldBeAbleToSwitch( string mysqld) { using var sut = Create(mysqld); // Arrange var expected = GetRandomAlphaString(5, 10); // Pre-assert var builder = new MySqlConnectionStringUtil(sut.ConnectionString); Expect(builder.Database).To.Equal("tempdb"); // Act sut.SwitchToSchema(expected); // Assert builder = new MySqlConnectionStringUtil(sut.ConnectionString); Expect(builder.Database).To.Equal(expected); } [Test] [TestCaseSource(nameof(MySqlPathFinders))] public void ShouldBeAbleToSwitchBackAndForthWithoutLoss( string mysqld) { using var sut = Create(mysqld); // Arrange var schema1 = "create table cows (id int, name varchar(100)); insert into cows (id, name) values (1, 'Daisy');"; var schema2 = "create table bovines (id int, name varchar(100)); insert into bovines (id, name) values (42, 'Douglas');"; var schema2Name = GetRandomAlphaString(4); Execute(sut, schema1); // Pre-assert var inSchema1 = Query(sut, "select * from cows;"); Expect(inSchema1).To.Contain.Exactly(1).Item(); Expect(inSchema1[0]["id"]).To.Equal(1); Expect(inSchema1[0]["name"]).To.Equal("Daisy"); // Act sut.SwitchToSchema(schema2Name); Expect(() => Query(sut, "select * from cows;")) .To.Throw() .With.Property(o => o.GetType().Name) .Containing("MySqlException"); Execute(sut, schema2); var results = Query(sut, "select * from bovines;"); // Assert Expect(results).To.Contain.Exactly(1).Item(); Expect(results[0]["id"]).To.Equal(42); Expect(results[0]["name"]).To.Equal("Douglas"); sut.SwitchToSchema("tempdb"); var testAgain = Query(sut, "select * from cows;"); Expect(testAgain).To.Contain.Exactly(1).Item(); Expect(testAgain[0]).To.Deep.Equal(inSchema1[0]); } [TestCaseSource(nameof(MySqlPathFinders))] public void ShouldBeAbleToCreateATable_InsertData_QueryData( string mysqld) { using var sut = Create(mysqld); // Arrange // Act using (var connection = sut.OpenConnection()) using (var command = connection.CreateCommand()) { command.CommandText = new[] { "create schema moocakes;", "use moocakes;", "create table `users` (id int, name varchar(100));", "insert into `users` (id, name) values (1, 'Daisy the cow');" }.JoinWith("\n"); command.ExecuteNonQuery(); } using (var connection = sut.OpenConnection()) { // Assert var users = connection.Query<User>( "use moocakes; select * from users where id > @id; ", new { id = 0 }); Expect(users).To.Contain.Only(1).Matched.By(u => u.Id == 1 && u.Name == "Daisy the cow"); } } public static string[] MySqlPathFinders() { // add mysql installs at the following folders // to test, eg 5.6 vs 5.7 & effect of spaces in the path return new[] { null, // will try to seek out the mysql installation "C:\\apps\\mysql-5.7\\bin\\mysqld.exe", "C:\\apps\\mysql-5.6\\bin\\mysqld.exe", "C:\\apps\\MySQL Server 5.7\\bin\\mysqld.exe", "C:\\apps\\mysql-server-8\\bin\\mysqld.exe" }.Where(p => { if (p == null) { return true; } var exists = Directory.Exists(p) || File.Exists(p); if (!exists) { Console.WriteLine( $"WARN: specific test path for mysql not found: {p}" ); } return exists; }) .ToArray(); } } [TestFixture] public class WhenInstalledAsWindowsService { [Test] public void ShouldBeAbleToStartNewInstance() { // Arrange Expect(() => { using var db = Create(); using (db.OpenConnection()) { // Act // Assert } }).Not.To.Throw(); } [SetUp] public void Setup() { var mysqlServices = ServiceController.GetServices().Where(s => s.DisplayName.ToLower().Contains("mysql")); if (!mysqlServices.Any()) { Assert.Ignore( "Test only works when there is at least one mysql service installed and that service has 'mysql' in the name (case-insensitive)" ); } } } [TestFixture] public class Cleanup { [Test] public void ShouldCleanUpResourcesWhenDisposed() { // Arrange using var tempFolder = new AutoTempFolder(); using (new AutoResetter<string>(() => { var original = TempDbHints.PreferredBasePath; TempDbHints.PreferredBasePath = tempFolder.Path; return original; }, original => { TempDbHints.PreferredBasePath = original; })) { // Act using (new TempDBMySql()) { } // Assert var entries = Directory.EnumerateDirectories(tempFolder.Path); Expect(entries).To.Be.Empty(); } } } [TestFixture] [Explicit("relies on machine-specific setup")] public class FindingInPath { [Test] public void ShouldBeAbleToFindInPath_WhenIsInPath() { // Arrange Expect(() => { using var db = Create(); using (db.OpenConnection()) { // Act // Assert } }).Not.To.Throw(); } private string _envPath; [SetUp] public void Setup() { if (Platform.IsUnixy) { // allow this test to be run on a unixy platform where // mysqld is actually in the path return; } _envPath = Environment.GetEnvironmentVariable("PATH"); if (_envPath == null) { throw new InvalidOperationException("How can you have no PATH variable?"); } var modified = $"C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin;{_envPath}"; Environment.SetEnvironmentVariable("PATH", modified); } [TearDown] public void TearDown() { Environment.SetEnvironmentVariable("PATH", _envPath); } } [TestFixture] public class LoggingProcessStartup { [Test] public void ShouldLogProcessStartupInfoToFileInDataDir() { // Arrange var expected = GetRandomString(5); Environment.SetEnvironmentVariable("LOG_PROCESS_STARTUP_TEST", expected); // Act using var db = new TempDBMySql(); var logFile = Path.Combine(db.DataDir, "startup-info.log"); // Assert Expect(logFile) .To.Exist(); var contents = File.ReadAllLines(logFile); Expect(contents) .To.Contain.Exactly(1) .Matched.By(s => s.StartsWith("CLI:") && s.Contains("mysqld.exe")); Expect(contents) .To.Contain.Exactly(1) .Matched.By(s => s.StartsWith("Environment")); Expect(contents) .To.Contain.Exactly(1) .Matched.By(s => { var trimmed = s.Trim(); return trimmed.StartsWith("LOG_PROCESS_STARTUP_TEST") && trimmed.EndsWith(expected); }); } [SetUp] public void Setup() { var mysqlServices = ServiceController.GetServices().Where(s => s.DisplayName.ToLower().Contains("mysql")); if (!mysqlServices.Any()) { Assert.Ignore( "Test only works when there is at least one mysql service installed and that service has 'mysql' in the name (case-insensitive)" ); } } } [TestFixture] public class Reset { [Test] public void ShouldResetConnections() { // Arrange using var db = new TempDBMySql(); using var conn1 = db.OpenConnection(); using var cmd1 = conn1.CreateCommand(); cmd1.CommandText = "select * from information_schema.TABLES limit 1"; using var reader1 = cmd1.ExecuteReader(); Expect(reader1.HasRows) .To.Be.True(); // Act Expect(() => db.CloseAllConnections()) .Not.To.Throw(); using var conn2 = db.OpenConnection(); using var cmd2 = conn2.CreateCommand(); cmd2.CommandText = "select * from information_schema.TABLES limit 1"; using var reader2 = cmd2.ExecuteReader(); // Assert Expect(reader2.HasRows) .To.Be.True(); } } [TestFixture] public class StayingAlive { [Test] [Explicit("flaky since allowing longer to test connect at startup")] public void ShouldResurrectADerpedServerWhilstNotDisposed() { // Arrange using var db = new TempDBMySql( new TempDbMySqlServerSettings() { Options = { MaxTimeToConnectAtStartInSeconds = 0 } }); // Act using (var conn = db.OpenConnection()) { using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"create schema moo_cakes;"; cmd.ExecuteNonQuery(); db.SwitchToSchema("moo_cakes"); } } using (var conn = db.OpenConnection()) using (var cmd = conn.CreateCommand()) { cmd.CommandText = "create table cows (id int, name text);"; cmd.ExecuteNonQuery(); cmd.CommandText = "insert into cows (id, name) values (1, 'daisy');"; cmd.ExecuteNonQuery(); } var originalId = db.ServerProcessId.Value; var process = Process.GetProcessById(db.ServerProcessId.Value); process.Kill(); var reconnected = false; var maxWait = DateTime.Now.AddMilliseconds( TempDBMySql.PROCESS_POLL_INTERVAL * 50 ); while (DateTime.Now < maxWait) { try { using var conn2 = db.OpenConnection(); using var cmd2 = conn2.CreateCommand(); cmd2.CommandText = "select * from moo_cakes.cows;"; using (var reader = cmd2.ExecuteReader()) { Expect(reader.Read()) .To.Be.True(); } reconnected = true; break; } catch { Console.Error.WriteLine("-- mysql process not yet resurrected --"); /* suppressed */ } Thread.Sleep(50); } // Assert Expect(reconnected) .To.Be.True( "Should have been able to reconnect to mysql server" ); var resurrectedPid = db.ServerProcessId.Value; Expect(resurrectedPid) .To.Be.Greater.Than(0); Expect(() => Process.GetProcessById(originalId)) .To.Throw<ArgumentException>() .With.Message.Containing( "not running", "Server should be dead after disposal"); } } [TestFixture] public class PortHint { [TestFixture] public class ConfiguredFromApi { [Test] public void ShouldListenOnHintedPortWhenAvailable() { // Arrange var port = PortFinder.FindOpenPort(); using var db = new TempDBMySql(CreateForPort(port)); // Act var configuredPort = GrokPortFrom(db.ConnectionString); // Assert Expect(configuredPort) .To.Equal(port); } [Test] public void ShouldIncrementPortWhenHintedPortIsNotAvailable() { // Arrange if (Environment.GetEnvironmentVariable("TEMPDB_PORT_HINT") is null) { Assert.Ignore("Requires TEMPDB_PORT_HINT env var to be set"); } var port = PortFinder.FindOpenPort(); while (PortFinder.PortIsInUse(port + 1)) { port = PortFinder.FindOpenPort(); } using var outer = new TempDBMySql(CreateForPort(port)); using var inner = new TempDBMySql(CreateForPort(port)); // Act var outerPort = GrokPortFrom(outer.ConnectionString); var innerPort = GrokPortFrom(inner.ConnectionString); // Assert Expect(outerPort).To.Equal(port); Expect(innerPort).To.Equal(port + 1); } } [TestFixture] public class ConfiguredFromEnvironment { [Test] public void ShouldListenOnHintedPortWhenAvailable() { // Arrange var port = PortFinder.FindOpenPort(); using (new AutoResetter<string>( () => SetPortHintEnvVar(port), RestorePortHintEnvVar)) { var settings = new TempDbMySqlServerSettings() { Options = { EnableVerboseLogging = true } }; using (var db = new TempDBMySql(settings)) { // Act var configuredPort = GrokPortFrom(db.ConnectionString); // Assert Expect(configuredPort) .To.Equal(port); } } } private void RestorePortHintEnvVar(string prior) { Environment.SetEnvironmentVariable( TempDbMySqlServerSettings.EnvironmentVariables.PORT_HINT, prior ); } private string SetPortHintEnvVar(int port) { var existing = Environment.GetEnvironmentVariable( TempDbMySqlServerSettings.EnvironmentVariables.PORT_HINT ); Environment.SetEnvironmentVariable( TempDbMySqlServerSettings.EnvironmentVariables.PORT_HINT, port.ToString() ); return existing; } } private static TempDbMySqlServerSettings CreateForPort(int port) { return new TempDbMySqlServerSettings() { Options = { PortHint = port } }; } private static int GrokPortFrom(string connectionString) { // can't use MySqlConnectionStringBuilder because // of a conflict between Connector and .Data return connectionString .Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries) .First(part => part.StartsWith("port", StringComparison.OrdinalIgnoreCase)) .Split('=') .Skip(1) .Select(int.Parse) .First(); } } [TestFixture] public class SharingSchemaBetweenNamedInstances { [Test] public void ShouldBeAbleToQueryDumpedSchema() { // Arrange using var outer = new TempDBMySql(SCHEMA); // Act var dumped = outer.DumpSchema(); using var inner = new TempDBMySql(dumped); var result = InsertAnimal(inner, "moo-cow"); // Assert Expect(result).To.Be.Greater.Than(0); } [Test] [Explicit("WIP: requires a cross-platform, reliable method of IPC ...")] public void SimpleSchemaSharing() { // Arrange var name = GetRandomString(10, 20); var settings = TempDbMySqlServerSettingsBuilder.Create() .WithName(name) .Build(); using (new TempDBMySql( settings, SCHEMA)) { using (var inner = new TempDBMySql(settings)) { // Act var result = InsertAnimal(inner, "cow"); Expect(result).To.Be.Greater.Than(0); } } } private const string SCHEMA = "create table animals (id int primary key auto_increment, name text);"; private int InsertAnimal( ITempDB db, string name) { using var conn = db.OpenConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = $"insert into animals (name) values ('{name}'); select LAST_INSERT_ID() as id;"; return int.Parse(cmd.ExecuteScalar()?.ToString() ?? "0"); } } [TestFixture] public class HandlingPortConflicts { [Test] public void ShouldReconfigurePortOnConflict_QuickStart() { // because sometimes a port is taken after it was tested for // viability :/ // Arrange // Act using var db1 = new TempDbMySqlWithDeterministicPort(); using var db2 = new TempDbMySqlWithDeterministicPort(); using var conn1 = db1.OpenConnection(); using var conn2 = db2.OpenConnection(); // Assert Expect(conn1.State) .To.Equal(ConnectionState.Open); Expect(conn2.State) .To.Equal(ConnectionState.Open); Expect(db1.Port) .Not.To.Equal(db2.Port); } [Test] public void ShouldReconfigurePortOnConflict_SlowerStart() { // because sometimes a port is taken after it was tested for // viability :/ // Arrange // Act using var db1 = new TempDbMySqlWithDeterministicPort(); // with a slower start, the conflict may be with an existing // tempdb (or other) mysql instance, so the connect test // will appear to work -- hence the `IsMyInstance` check too // -> so we ensure that we can connect to the first instance using var conn1 = db1.OpenConnection(); using var db2 = new TempDbMySqlWithDeterministicPort(); using var conn2 = db2.OpenConnection(); // Assert Expect(conn1.State) .To.Equal(ConnectionState.Open); Expect(conn2.State) .To.Equal(ConnectionState.Open); Expect(db1.Port) .Not.To.Equal(db2.Port); } public class TempDbMySqlWithDeterministicPort : TempDBMySql { public const int STARTING_PORT = 21000; private int _lastAttempt = 0; protected override int FindRandomOpenPort() { return _lastAttempt > 0 ? (++_lastAttempt) : (_lastAttempt = STARTING_PORT); } } } [TestFixture] public class AutomaticDisposal { // perhaps the creator forgets to dispose // -> perhaps the creator is TempDb.Runner and the caller // of that dies before it can dispose! [Test] public void ShouldAutomaticallyDisposeAfterMaxLifetimeHasExpired() { // Arrange using var db = Create(inactivityTimeout: TimeSpan.FromSeconds(2)); // Act Expect(() => { using var conn = db.OpenConnection(); }).Not.To.Throw(); Thread.Sleep(3000); Expect(() => { using var conn = db.OpenConnection(); }).To.Throw() .With.Property(e => new { Type = e.GetType().Name, IsConnectionError = e.Message.ToLowerInvariant().Contains("unable to connect") }).Deep.Equal.To( new { Type = "MySqlException", IsConnectionError = true }); // Assert } [Test] [Retry(3)] public void ConnectionUseShouldExtendLifetime() { // Arrange var inactivitySeconds = 1; using var db = Create(inactivityTimeout: TimeSpan.FromSeconds(inactivitySeconds)); var disposed = false; db.Disposed += (o, e) => disposed = true; // Act for (var i = 0; i < 5; i++) { Expect(() => { using var conn = db.OpenConnection(); Thread.Sleep(500); }).Not.To.Throw(); } var timeout = DateTime.Now.AddSeconds(10); var stillConnected = true; while (DateTime.Now < timeout && stillConnected) { stillConnected = db.TryFetchCurrentConnectionCount() > 0; if (stillConnected) { Thread.Sleep(100); } } if (stillConnected) { Assert.Fail("Still appear to have connections?!"); } while (DateTime.Now < timeout && !disposed) { Thread.Sleep(100); } // Assert Expect(disposed) .To.Be.True(); Expect(() => { using var conn = db.OpenConnection(); }).To.Throw() .With.Property(e => new { Type = e.GetType().Name, IsConnectionError = e.Message.ToLowerInvariant().Contains("unable to connect") }).Deep.Equal.To( new { Type = "MySqlException", IsConnectionError = true }); } [Test] [Timeout(45000)] public void AbsoluteLifespanShouldOverrideConnectionActivity() { // Arrange using var db = Create( inactivityTimeout: TimeSpan.FromSeconds(1), absoluteLifespan: TimeSpan.FromSeconds(3) ); var connections = 0; // Act Expect(() => { while (true) { using var conn = db.OpenConnection(); connections++; Thread.Sleep(300); } // ReSharper disable once FunctionNeverReturns }).To.Throw() .With.Property(e => new { Type = e.GetType().Name, IsConnectionError = e.Message.ToLowerInvariant().Contains("unable to connect") }).Deep.Equal.To( new { Type = "MySqlException", IsConnectionError = true }); // Assert Expect(connections) .To.Be.Greater.Than(3); } } [TestFixture] public class CreatingUsers { [Test] public void ShouldBeAbleToCreateTheUserAndConnectWithThoseCredentials() { // Arrange using var db = Create(); var user = "testuser"; var password = "testuser"; var schema = "guest_schema"; db.CreateSchemaIfNotExists(schema); // Act db.CreateUser(user, password, schema); // Assert var builder = new MySqlConnectionStringBuilder(db.ConnectionString) { UserID = user, Password = password, Database = schema }; var connectionString = builder.ToString(); using var connection = new MySqlConnection(connectionString); Expect(() => connection.Open()) .Not.To.Throw(); } } private static void Execute( ITempDB tempDb, string sql) { using var conn = tempDb.OpenConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.ExecuteNonQuery(); } private static Dictionary<string, object>[] Query( ITempDB tempDb, string sql ) { using var conn = tempDb.OpenConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = sql; var result = new List<Dictionary<string, object>>(); using var reader = cmd.ExecuteReader(); while (reader.Read()) { var row = new Dictionary<string, object>(); Range(reader.FieldCount) .ForEach(i => row[reader.GetName(i)] = reader[i]); result.Add(row); } return result.ToArray(); } private static TempDBMySql Create( string pathToMySql = null, TimeSpan? inactivityTimeout = null, TimeSpan? absoluteLifespan = null) { return new TempDBMySql( new TempDbMySqlServerSettings() { Options = { PathToMySqlD = pathToMySql, ForceFindMySqlInPath = true, LogAction = Console.WriteLine, InactivityTimeout = inactivityTimeout, AbsoluteLifespan = absoluteLifespan, EnableVerboseLogging = true } }); } public class User { public int Id { get; set; } public string Name { get; set; } } } public class MySqlConnectionStringUtil { public string Database { get; } public MySqlConnectionStringUtil( string connectionString) { Database = connectionString .Split(';') .Select(p => p.Trim()) .FirstOrDefault(p => p.StartsWith("DATABASE", StringComparison.OrdinalIgnoreCase)) ?.Split('=') ?.Last(); } } }
using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media.Animation; using System.Windows.Threading; using Avalon.Windows.Internal.Utility; using Avalon.Windows.Utility; namespace Avalon.Windows.Controls { /// <summary> /// Provides a modal dialog that uses inline <see cref="UIElement"/>s /// instead of a top-level window. /// </summary> public class InlineModalDialog : HeaderedContentControl { #region Fields private bool _isOpen; private DispatcherFrame _dispatcherFrame; #endregion #region Constructors /// <summary> /// Initializes the <see cref="InlineModalDialog"/> class. /// </summary> static InlineModalDialog() { DefaultStyleKeyProperty.OverrideMetadata(typeof(InlineModalDialog), new FrameworkPropertyMetadata(typeof(InlineModalDialog))); IsTabStopProperty.OverrideMetadata(typeof(InlineModalDialog), new FrameworkPropertyMetadata(false.Box())); CommandManager.RegisterClassCommandBinding(typeof(InlineModalDialog), new CommandBinding(CloseCommand, (sender, args) => ((InlineModalDialog)sender).HandleCloseCommand(args))); } /// <summary> /// Initializes a new instance of the <see cref="InlineModalDialog"/> class. /// </summary> public InlineModalDialog() { KeyboardNavigation.SetTabNavigation(this, KeyboardNavigationMode.Local); KeyboardNavigation.SetDirectionalNavigation(this, KeyboardNavigationMode.Local); Loaded += OnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { Loaded -= OnLoaded; Focus(); } #endregion #region Properties /// <summary> /// Identifies the <see cref="DialogIntroAnimation"/> dependency property. /// </summary> public static readonly DependencyProperty DialogIntroAnimationProperty = DependencyProperty.Register("DialogIntroAnimation", typeof(Storyboard), typeof(InlineModalDialog)); /// <summary> /// Gets or sets the animation that runs when this dialog is shown. /// </summary> public Storyboard DialogIntroAnimation { get { return (Storyboard)GetValue(DialogIntroAnimationProperty); } set { SetValue(DialogIntroAnimationProperty, value); } } /// <summary> /// Identifies the <see cref="DialogOutroAnimation"/> dependency property. /// </summary> public static readonly DependencyProperty DialogOutroAnimationProperty = DependencyProperty.Register("DialogOutroAnimation", typeof(Storyboard), typeof(InlineModalDialog)); /// <summary> /// Gets or sets the animation that runs when this dialog is closed. /// </summary> public Storyboard DialogOutroAnimation { get { return (Storyboard)GetValue(DialogOutroAnimationProperty); } set { SetValue(DialogOutroAnimationProperty, value); } } /// <summary> /// Gets or sets a value indicating whether to show the blurrer. /// </summary> /// <value><c>true</c> if the blurrer is shown; otherwise, <c>false</c>.</value> public bool ShowBlurrer { get { return (bool)GetValue(ShowBlurrerProperty); } set { SetValue(ShowBlurrerProperty, value); } } /// <summary> /// Identifies the <see cref="ShowBlurrer"/> dependency property. /// </summary> public static readonly DependencyProperty ShowBlurrerProperty = DependencyProperty.Register("ShowBlurrer", typeof(bool), typeof(InlineModalDialog), new UIPropertyMetadata(true)); /// <summary> /// Gets or sets the owner. /// <remarks> /// This value is used to retrieve the corresponding <see cref="InlineModalDecorator"/>. /// </remarks> /// </summary> /// <value>The owner.</value> public DependencyObject Owner { get { return (DependencyObject)GetValue(OwnerProperty); } set { SetValue(OwnerProperty, value); } } /// <summary> /// Identifies the <see cref="Owner"/> dependency property. /// </summary> public static readonly DependencyProperty OwnerProperty = DependencyProperty.Register("Owner", typeof(DependencyObject), typeof(InlineModalDialog), new FrameworkPropertyMetadata()); private static InlineModalDecorator GetModalDecorator(DependencyObject obj) { return (InlineModalDecorator)obj.GetValue(ModalDecoratorProperty); } internal static void SetModalDecorator(DependencyObject obj, InlineModalDecorator value) { obj.SetValue(ModalDecoratorProperty, value); } internal static void ClearModalDecorator(DependencyObject obj) { obj.ClearValue(ModalDecoratorProperty); } private static readonly DependencyProperty ModalDecoratorProperty = DependencyProperty.RegisterAttached("ModalDecorator", typeof(InlineModalDecorator), typeof(InlineModalDialog), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior)); /// <summary> /// Gets or sets the dialog result. /// </summary> /// <value>The dialog result.</value> public bool? DialogResult { get; set; } #endregion #region Commands /// <summary> /// Identifies the <c>Close</c> routed command, which can be used to close the dialog. /// </summary> public static readonly RoutedCommand CloseCommand = new RoutedCommand("Close", typeof(InlineModalDialog)); #endregion #region Routed Events /// <summary> /// Identifies the <see cref="E:Opened"/> routed event. /// </summary> public static readonly RoutedEvent OpenedEvent = EventManager.RegisterRoutedEvent("Opened", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(InlineModalDialog)); /// <summary> /// Fires when the dialog is opened. /// </summary> public event RoutedEventHandler Opened { add { AddHandler(OpenedEvent, value); } remove { RemoveHandler(OpenedEvent, value); } } /// <summary> /// Raises the <see cref="Opened"/> routed event. /// </summary> protected virtual void OnOpened() { RaiseEvent(new RoutedEventArgs(OpenedEvent)); } /// <summary> /// Identifies the <see cref="E:Closed"/> routed event. /// </summary> public static readonly RoutedEvent ClosedEvent = EventManager.RegisterRoutedEvent("Closed", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(InlineModalDialog)); /// <summary> /// Fires when the dialog closes. /// </summary> public event RoutedEventHandler Closed { add { AddHandler(ClosedEvent, value); } remove { RemoveHandler(ClosedEvent, value); } } /// <summary> /// Raises the <see cref="Closed"/> routed event. /// </summary> protected virtual void OnClosed() { RaiseEvent(new RoutedEventArgs(ClosedEvent)); } /// <summary> /// Identifies the <see cref="E:Closing"/> routed event. /// </summary> public static readonly RoutedEvent ClosingEvent = EventManager.RegisterRoutedEvent("Closing", RoutingStrategy.Bubble, typeof(CancelRoutedEventHandler), typeof(InlineModalDialog)); /// <summary> /// Fires when the dialog is about to close. /// </summary> public event CancelRoutedEventHandler Closing { add { AddHandler(ClosingEvent, value); } remove { RemoveHandler(ClosingEvent, value); } } /// <summary> /// Raises the <see cref="Closing"/> routed event. /// </summary> /// <param name="args"></param> protected virtual void OnClosing(CancelRoutedEventArgs args) { RaiseEvent(args); } #endregion #region Public Methods /// <summary> /// Shows the modal dialog. /// </summary> public void Show() { ValidateOwner(); InlineModalDecorator panel = GetModalDecorator(Owner); if (panel == null) return; panel.AddModal(this, ShowBlurrer); if (Animator.IsAnimationEnabled) { Storyboard dialogAnim = DialogIntroAnimation; if (dialogAnim != null) { if (dialogAnim.IsFrozen) { dialogAnim = dialogAnim.Clone(); } dialogAnim.AttachCompletedEventHandler(OnOpenAnimationCompleted); dialogAnim.Begin(this); } } else { OpenCompleted(); } _dispatcherFrame = new DispatcherFrame(); Dispatcher.PushFrame(_dispatcherFrame); _isOpen = false; } /// <summary> /// Closes the modal dialog. /// </summary> public void Close() { if (!_isOpen) return; ValidateOwner(); InlineModalDecorator panel = GetModalDecorator(Owner); if (panel == null) return; var cancelArgs = new CancelRoutedEventArgs(ClosingEvent); OnClosing(cancelArgs); if (cancelArgs.Cancel) return; if (Animator.IsAnimationEnabled) { Storyboard dialogAnim = DialogOutroAnimation; if (dialogAnim != null) { if (dialogAnim.IsFrozen) { dialogAnim = dialogAnim.Clone(); } // Add a handler so we know when the dialog can be closed. dialogAnim.AttachCompletedEventHandler(OnCloseAnimationCompleted); dialogAnim.Begin(this); } } else { CloseDialog(panel); } } /// <summary> /// Attempts to close the front-most dialog of the provided owner. /// </summary> /// <param name="owner"></param> public static void CloseCurrent(DependencyObject owner) { InlineModalDecorator panel = GetModalDecorator(owner); if (panel == null) return; var current = panel.TopmostModal as InlineModalDialog; if (current != null) { current.Close(); } } #endregion #region Private Methods private void ValidateOwner() { if (Owner == null) { throw new InvalidOperationException("Owner must be set."); } } /// <summary> /// Handler for the close command. /// </summary> /// <param name="e"></param> private void HandleCloseCommand(ExecutedRoutedEventArgs e) { if (DialogResult == null) { var source = e.OriginalSource as Button; if (source != null) { if (source.IsDefault) { DialogResult = true; } else if (source.IsCancel) { DialogResult = false; } } } e.Handled = true; Close(); } private void OnOpenAnimationCompleted(object sender, EventArgs e) { OpenCompleted(); } private void OpenCompleted() { _isOpen = true; OnOpened(); } /// <summary> /// Handler for the window close animation completion, this delays /// actually closing the window until all outro animations have completed. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnCloseAnimationCompleted(object sender, EventArgs e) { InlineModalDecorator panel = GetModalDecorator(Owner); Debug.Assert(panel != null); CloseDialog(panel); } private void CloseDialog(InlineModalDecorator panel) { panel.RemoveModal(this, ShowBlurrer); OnClosed(); var topMost = panel.TopmostModal; if (topMost != null) { topMost.Focus(); } if (_dispatcherFrame != null) { _dispatcherFrame.Continue = false; _dispatcherFrame = null; } _isOpen = false; } #endregion } }
// JPEGator .NET Compact Framework Library. // Copyright (C) 2005-2009, Aleh Dzenisiuk. All Rights Reserved. // http://dzenisiuk.info/jpegator/ // // When redistributing JPEGator source code the above copyright notice and // this messages should be left intact. In case changes are made by you in // this source code it should be clearly indicated in the beginning of each // changed file. using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Reflection; namespace JPEGator { /// <summary> /// Contains some helper functions for working with JPEG files/streams /// and standard <see cref="System.Drawing.Bitmap"/> class: ones that allow /// creating of thumbnail bitmaps from JPEG files, /// loading JPEGs using minimum amount of memory, /// and saving bitmaps. /// </summary> /// /// <threadsafety static="true" instance="false"/> public class BitmapUtils { /// <overloads> /// <summary> /// Saves a <see cref="System.Drawing.Bitmap"/> to some JPEG file or stream. /// </summary> /// <example> /// Here is the bitmap saving code from the <b>JPEGPad</b> example, which /// you can find in <b>\examples</b> folder. /// <code lang="Visual Basic"> /// /// ' Quality of saved JPEG picture /// Private Const JPEGQuality As Integer = 85 /// /// Private Sub SaveMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveMenuItem.Click /// Dim result As DialogResult = SaveFileDialog.ShowDialog() /// If result = DialogResult.OK Then /// JPEGator.BitmapUtils.SaveBitmap(Image, SaveFileDialog.FileName, JPEGQuality) /// End If /// End Sub /// </code> /// </example> /// </overloads> /// /// <summary> /// Compresses a <see cref="System.Drawing.Bitmap"/> to some JPEG file on disk /// with given quality settings. /// </summary> /// /// <param name="bitmap">A <see cref="System.Drawing.Bitmap"/> that needs to be saved as JPEG file.</param> /// <param name="fileName">A name of the file to save this bitmap into.</param> /// <param name="quality">JPEG quality settings. Should be from the range [0; 100].</param> public static void SaveBitmap(System.Drawing.Bitmap bitmap, string fileName, int quality) { System.IO.Stream s = System.IO.File.OpenWrite(fileName); try { SaveBitmap(bitmap, s, quality); } finally { s.Close(); } } #if NETCF1 private static void GetBitmapInternals( System.Drawing.Bitmap bitmap, out IntPtr newBitmapHandle, out IntPtr dcHandle, out IntPtr bitmapBitsPtr) { // Get its internal .NETCF's handle IntPtr how = Image.GetHowFromImage(bitmap); // Reference this handle and obtaining pointer to Bitmap instance data IntPtr ptr = NSLHandle_Reference(0x11, how); // Obtaining pointer to bitmap information structure IntPtr objPtr = (IntPtr)Marshal.ReadInt32(ptr); // Handle to device context where bitmap is selected dcHandle = (IntPtr)Marshal.ReadInt32(objPtr, 1 * 4); // Describe our bits BITMAPINFO bm = new BITMAPINFO(); bm.Size = Marshal.SizeOf(bm); bm.Width = bitmap.Width; bm.Height = -bitmap.Height; bm.Planes = 1; bm.BitCount = 24; // Try to create DIB section from our bits newBitmapHandle = CreateDIBSection(dcHandle, ref bm, 0, out bitmapBitsPtr, IntPtr.Zero, 0); // If it appears that there is not enough memory then try to collect some // garbage and then allocate bitmap again if (newBitmapHandle == IntPtr.Zero) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); newBitmapHandle = CreateDIBSection(dcHandle, ref bm, 0, out bitmapBitsPtr, IntPtr.Zero, 0); } } #endif #if NETCF1 private static bool checkedLockBits; private static ConstructorInfo bitmapConstructor; private static MethodInfo lockBitsMethod; private static MethodInfo unlockBitsMethod; private static PropertyInfo scan0Property; private static PropertyInfo strideProperty; private static object readOnly; private static object writeOnly; private static object format24bppRgb; private static bool HasLockBits() { if (!checkedLockBits) { Type bitmapType = typeof(System.Drawing.Bitmap); lockBitsMethod = bitmapType.GetMethod("LockBits"); if (lockBitsMethod != null) { bitmapConstructor = bitmapType.GetConstructor( new Type[] { Type.GetType("System.Int32"), Type.GetType("System.Int32"), Type.GetType("System.Drawing.Imaging.PixelFormat, System.Drawing"), } ); unlockBitsMethod = bitmapType.GetMethod("UnlockBits"); Type bitmapDataType = Type.GetType("System.Drawing.Imaging.BitmapData, System.Drawing"); scan0Property = bitmapDataType.GetProperty("Scan0"); strideProperty = bitmapDataType.GetProperty("Stride"); Type imageLockModeType = Type.GetType("System.Drawing.Imaging.ImageLockMode, System.Drawing"); readOnly = Enum.ToObject(imageLockModeType, (int)0x00000001); // ImageLockMode.ReadOnly writeOnly = Enum.ToObject(imageLockModeType, (int)0x00000002); // ImageLockMode.WriteOnly format24bppRgb = Enum.ToObject(Type.GetType("System.Drawing.Imaging.PixelFormat, System.Drawing"), (int)0x00021808); // PixelFormat.Format24bppRgb } checkedLockBits = true; } return lockBitsMethod != null; } #endif /// <summary> /// Compresses a <see cref="System.Drawing.Bitmap"/> to some JPEG stream /// with given quality settings. /// </summary> /// /// <param name="bitmap">A <see cref="System.Drawing.Bitmap"/> that needs to be saved as JPEG file.</param> /// <param name="stream">Stream where output JPEG bytes should be written to.</param> /// <param name="quality">JPEG quality settings. Should be from the range [0; 100].</param> /// /// <remarks> /// <note>As this functions has not opened the stream, it will not close it either.</note> /// </remarks> public static void SaveBitmap(System.Drawing.Bitmap bitmap, System.IO.Stream stream, int quality) { #if NETCF1 if (!HasLockBits()) { IntPtr newBitmapHandle, dcHandle, bitmapBitsPtr; GetBitmapInternals(bitmap, out newBitmapHandle, out dcHandle, out bitmapBitsPtr); if (newBitmapHandle != IntPtr.Zero) { try { // // Converting our 24 bit bitmap to device-compatible one // IntPtr dc = CreateCompatibleDC(dcHandle); if (dc != IntPtr.Zero) { try { // Select and copy image from System.Drawing.Bitmap DC into our bitmap IntPtr prevBitmap = SelectObject(dc, newBitmapHandle); BitBlt(dc, 0, 0, bitmap.Width, bitmap.Height, dcHandle, 0, 0, 0x00CC0020 /* SRCCOPY */); SelectObject(dc, prevBitmap); } finally { DeleteDC(dc); } } else throw new OutOfMemoryException("Unable to create a temporary device context"); // // Compress image to JPEG // using (JPEGator.Compress c = new JPEGator.Compress(bitmap.Width, bitmap.Height)) { int offset = 0; int bitmapLineSize = (bitmap.Width * 3 + 3) & ~3; c.Start(stream, quality, JPEGator.ColorSpace.YCbCr); for (int i = 0; i < bitmap.Height; i++) { c.WriteScanline(bitmapBitsPtr, offset); offset += bitmapLineSize; } } } finally { DeleteObject(newBitmapHandle); } } else throw new OutOfMemoryException("Unable to create a temporary bitmap"); } else { object bits = lockBitsMethod.Invoke( bitmap, new object[] { new Rectangle(0, 0, bitmap.Width, bitmap.Height), readOnly, format24bppRgb } ); IntPtr scan0 = (IntPtr)scan0Property.GetValue(bits, null); int stride = (int)strideProperty.GetValue(bits, null); using (JPEGator.Compress c = new JPEGator.Compress(bitmap.Width, bitmap.Height)) { int offset = 0; c.Start(stream, quality, JPEGator.ColorSpace.YCbCr); for (int i = 0; i < bitmap.Height; i++) { c.WriteScanline(scan0, offset); offset += stride; } } unlockBitsMethod.Invoke(bitmap, new object[] { bits }); } #elif NETCF2 BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); using (JPEGator.Compress c = new JPEGator.Compress(bitmap.Width, bitmap.Height)) { int offset = 0; c.Start(stream, quality, JPEGator.ColorSpace.YCbCr); for (int i = 0; i < bitmap.Height; i++) { c.WriteScanline(bits.Scan0, offset); offset += bits.Stride; } } bitmap.UnlockBits(bits); #else #error Framework is not supported or NETCF1/2 flag is not defined #endif } /// <summary> /// Creates a <see cref="System.Drawing.Bitmap" /> from an array of bytes in BGR24 format. /// </summary> /// /// <param name="bitmapBits">An array of raw BGR24 data with strides aligned to the 4 bytes boundary.</param> /// <param name="offset">An offset to a first byte of image in <paramref name="bitmapBits"/> array.</param> /// <param name="width">A width of the image described by this buffer.</param> /// <param name="height">A height of the image described by this buffer.</param> /// /// <remarks> /// <para> /// Bitmap in <paramref name="bitmapBits"/> array should have standard DIB (BMP) format: /// </para> /// <code> /// B G R B G R ... B G R [padding] /// B G R B G R ... B G R [padding] /// .... /// </code> /// <para> /// Upper line of bitmap goes first, every line is padded with some amount of bytes, /// so count of bytes that every line takes is a multiple of 4. /// I.e. a length of <paramref name="bitmapBits"/> array should be at least /// <c>((width * 3 + 3) &amp; ~3) * height</c>. /// </para> /// </remarks> public static System.Drawing.Bitmap BitmapFromBGR24(byte[] bitmapBits, int offset, int width, int height) { int length = ((width * 3 + 3) & ~3) * height; if (bitmapBits.Length < offset + length) throw new ArgumentOutOfRangeException("Bitmap buffer is too small"); // Creating temporary bitmap System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height); #if NETCF1 if (!HasLockBits()) { IntPtr newBitmapHandle, dcHandle, bitmapBitsPtr; GetBitmapInternals(bitmap, out newBitmapHandle, out dcHandle, out bitmapBitsPtr); if (newBitmapHandle != IntPtr.Zero) { // // Converting our 24 bit bitmap into a device-compatible one // IntPtr dc = CreateCompatibleDC(dcHandle); if (dc != IntPtr.Zero) { // Copy our bits to created DIB section Marshal.Copy(bitmapBits, offset, bitmapBitsPtr, length); // Select and copy our bitmap IntPtr prevBitmap = SelectObject(dc, newBitmapHandle); BitBlt(dcHandle, 0, 0, width, height, dc, 0, 0, 0x00CC0020 /* SRCCOPY */); SelectObject(dc, prevBitmap); DeleteDC(dc); } DeleteObject(newBitmapHandle); } else throw new OutOfMemoryException("There is not enough memory for temporary bitmap"); } else { object data = lockBitsMethod.Invoke( bitmap, new object[] { new Rectangle(0, 0, width, height), writeOnly, format24bppRgb } ); IntPtr ptr = (IntPtr)scan0Property.GetValue(data, null); Marshal.Copy(bitmapBits, offset, ptr, length); unlockBitsMethod.Invoke(bitmap, new object[] { data }); } #elif NETCF2 BitmapData data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); Marshal.Copy(bitmapBits, offset, data.Scan0, length); bitmap.UnlockBits(data); #else #error Framework is not supported or NETCF1/2 flag is not defined #endif return bitmap; } /// <summary> /// Copies content of the <see cref="System.Drawing.Bitmap" /> instance into an array of bytes in BGR24 format. /// </summary> /// /// <param name="bitmap">A source bitmap to copy content from.</param> /// <param name="bitmapBits">A destination array of raw BGR24 data with strides aligned to the 4 bytes boundary.</param> /// <param name="offset">An offset to the first byte of image in <paramref name="bitmapBits"/> array.</param> /// /// <remarks> /// <para> /// Bitmap in <paramref name="bitmapBits"/> array will have standard DIB (BMP) format: /// </para> /// <code> /// B G R B G R ... B G R [padding] /// B G R B G R ... B G R [padding] /// .... /// </code> /// <para> /// Upper line of bitmap goes first, every line is padded with some amount of bytes, /// so count of bytes that every line takes is a multiple of 4. /// I.e. a length of <paramref name="bitmapBits"/> array should be at least /// <c>((width * 3 + 3) &amp; ~3) * height</c>. /// </para> /// </remarks> public static void BGR24FromBitmap(System.Drawing.Bitmap bitmap, byte[] bitmapBits, int offset) { int length = ((bitmap.Width * 3 + 3) & ~3) * bitmap.Height; if (bitmapBits.Length < offset + length) throw new ArgumentOutOfRangeException("Bitmap buffer is too small"); #if NETCF1 if (!HasLockBits()) { IntPtr newBitmapHandle, dcHandle, bitmapBitsPtr; GetBitmapInternals(bitmap, out newBitmapHandle, out dcHandle, out bitmapBitsPtr); if (newBitmapHandle != IntPtr.Zero) { try { // // Converting our 24 bit bitmap into a device-compatible one // IntPtr dc = CreateCompatibleDC(dcHandle); if (dc != IntPtr.Zero) { try { // Select and copy our bitmap IntPtr prevBitmap = SelectObject(dc, newBitmapHandle); BitBlt(dc, 0, 0, bitmap.Width, bitmap.Height, dcHandle, 0, 0, 0x00CC0020 /* SRCCOPY */); SelectObject(dc, prevBitmap); } finally { DeleteDC(dc); } Marshal.Copy(bitmapBitsPtr, bitmapBits, offset, length); } } finally { DeleteObject(newBitmapHandle); } } else throw new OutOfMemoryException("There is not enough memory for temporary bitmap"); } else { object data = lockBitsMethod.Invoke( bitmap, new object[] { new Rectangle(0, 0, bitmap.Width, bitmap.Height), readOnly, format24bppRgb } ); IntPtr ptr = (IntPtr)scan0Property.GetValue(data, null); Marshal.Copy(ptr, bitmapBits, offset, length); unlockBitsMethod.Invoke(bitmap, new object[] { data }); } #elif NETCF2 BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); Marshal.Copy(data.Scan0, bitmapBits, offset, length); bitmap.UnlockBits(data); #else #error Framework is not supported or NETCF1/2 flag is not defined #endif } /// <overloads> /// /// <summary> /// Loads a large JPEG image from a file or a stream and returns it as a /// <see cref="System.Drawing.Bitmap"/>. See remarks on why this function can /// be handy despite is has analogues in .NETCF. /// </summary> /// /// <remarks> /// Standard constructor of <see cref="System.Drawing.Bitmap"/> class (both file and stream versions) /// always loads the file into memory before decoding it (not sure about .NETCF 2.0 however), while /// <c>LoadBitmap</c> function always reads an image content directly from /// file/stream and uses only reasonable amount of memory (order of image width, i.e. the whole file /// is not loaded, amount of bytes used does not depend on image height, only does on its width.) /// </remarks> /// /// <example> /// For complete example see <b>JPEGPad</b> sample from <b>\examples</b> folder. /// <code lang="Visual Basic"> /// /// ' Offer user to select some JPEG file /// Dim Result As DialogResult = OpenFileDialog.ShowDialog() /// /// ' Load the file if user selected some file and have not cancelled the dialog /// If Result = DialogResult.OK Then /// /// Try /// Cursor.Current = Cursors.WaitCursor /// /// ' Cleanup previously loaded image /// If Not IsNothing(Image) Then /// PictureBox.Image = Nothing /// Image.Dispose() /// Image = Nothing /// PictureBox.Enabled = False /// PictureBox.Size = New Size(0, 0) /// End If /// /// Try /// ' Load bitmap without any scaling using the JPEGator /// Image = JPEGator.BitmapUtils.LoadBitmap(OpenFileDialog.FileName) /// /// ' Setup PictureBox /// PictureBox.Image = Image /// PictureBox.Size = Image.Size /// PictureBox.Location = New Point(0, 0) /// PictureBox.Enabled = True /// /// Finally /// Cursor.Current = Cursors.Default /// End Try /// /// Catch ex As Exception /// /// ' Show exception information, if any /// Windows.Forms.MessageBox.Show( _ /// String.Format("Failed to load file {0}:", OpenFileDialog.FileName), _ /// "Error", _ /// MessageBoxButtons.OK, _ /// MessageBoxIcon.Hand, _ /// MessageBoxDefaultButton.Button1 _ /// ) /// End Try /// End If /// </code> /// </example> /// /// </overloads> /// /// <summary> /// Loads a large JPEG image from a file and returns it as a /// <see cref="System.Drawing.Bitmap"/> /// </summary> /// /// <param name="fileName">A name of a JPEG file to load.</param> public static System.Drawing.Bitmap LoadBitmap(string fileName) { return LoadBitmap(System.IO.File.OpenRead(fileName)); } /// <summary> /// Loads a large JPEG image from a stream and returns it as a /// <see cref="System.Drawing.Bitmap"/>. /// </summary> /// /// <param name="stream">A stream that should be used as a source for JPEG bytes.</param> /// /// <remarks> /// <note>As this function have not opened the stream, it does not close it either. /// So you should close the stream by yourself (if you need to have it closed, of course).</note> /// </remarks> public static System.Drawing.Bitmap LoadBitmap(System.IO.Stream stream) { // Create decompressor instance using (JPEGator.Decompress decomp = new JPEGator.Decompress()) { // Start decompression process (setup source stream, read source picture header) decomp.Start(stream); return LoadBitmapFromDecompressor(decomp); } } private const int TempBitmapHeight = 8; private static System.Drawing.Bitmap LoadBitmapFromDecompressor(JPEGator.Decompress decomp) { // Create shortcuts for input image sizes int width = decomp.InputWidth; int height = decomp.InputHeight; #if NETCF1 System.Drawing.Bitmap bitmap; if (!HasLockBits()) { // // .NETCF 1.0 version // int bitmapLineSize = (width * 3 + 3) & ~3; // Creating dummy bitmap bitmap = new System.Drawing.Bitmap(width, height); IntPtr newBitmapHandle, dcHandle, bitmapBitsPtr; GetBitmapInternals(bitmap, out newBitmapHandle, out dcHandle, out bitmapBitsPtr); if (newBitmapHandle != IntPtr.Zero) { try { // // Converting our 24 bit bitmap to device-compatible one // IntPtr dc = CreateCompatibleDC(dcHandle); if (dc != IntPtr.Zero) { try { IntPtr prevBitmap; int bitmapOffset = 0; int tempY = 0; int i; for (i = 0; i < height; i++) { decomp.ReadScanline(bitmapBitsPtr, bitmapOffset); tempY++; bitmapOffset += bitmapLineSize; if (tempY >= TempBitmapHeight) { // Copy current stripe prevBitmap = SelectObject(dc, newBitmapHandle); try { BitBlt(dcHandle, 0, i - TempBitmapHeight + 1, width, TempBitmapHeight, dc, 0, 0, 0x00CC0020 /* SRCCOPY */); } finally { SelectObject(dc, prevBitmap); } tempY = 0; bitmapOffset = 0; } } // Copy last stripe prevBitmap = SelectObject(dc, newBitmapHandle); try { int h = height % TempBitmapHeight; if (h == 0) h = TempBitmapHeight; BitBlt(dcHandle, 0, height - h, width, h, dc, 0, 0, 0x00CC0020 /* SRCCOPY */); } finally { SelectObject(dc, prevBitmap); } } finally { DeleteDC(dc); } } } finally { DeleteObject(newBitmapHandle); } } else throw new ApplicationException("Failed to create thumbnail bitmap. Probably there is not enough memory available"); } else { // Creating dummy 24bit RGB bitmap bitmap = (System.Drawing.Bitmap)bitmapConstructor.Invoke( new object[] { width, height, format24bppRgb } ); object bits = lockBitsMethod.Invoke( bitmap, new object[] { new Rectangle(0, 0, width, height), writeOnly, format24bppRgb } ); IntPtr ptr = (IntPtr)scan0Property.GetValue(bits, null); int stride = (int)strideProperty.GetValue(bits, null); int bitmapOffset = 0; for (int i = 0; i < height; i++) { decomp.ReadScanline(ptr, bitmapOffset); bitmapOffset += stride; } unlockBitsMethod.Invoke(bitmap, new object[] { bits }); } #elif NETCF2 // // .NETCF 2.0 version // // Creating dummy 24bit RGB bitmap System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, PixelFormat.Format24bppRgb); BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); int bitmapOffset = 0; for (int i = 0; i < height; i++) { decomp.ReadScanline(bits.Scan0, bitmapOffset); bitmapOffset += bits.Stride; } bitmap.UnlockBits(bits); #else #error Framework is not supported or NETCF1/2 flag is not defined #endif return bitmap; } #if NETCF1 [DllImport(@"\windows\mscoree1_0.dll")] private static extern IntPtr NSLHandle_Reference(int type, IntPtr how); private struct BITMAPINFO { public int Size; public int Width; public int Height; public short Planes; public short BitCount; public int Compression; public int SizeImage; public int XPelsPerMeter; public int YPelsPerMeter; public int ClrUsed; public int ClrImportant; } [DllImport("coredll.dll")] private static extern IntPtr CreateDIBSection( IntPtr hdc, ref BITMAPINFO pbmi, int usage, out IntPtr bitsPtr, IntPtr section, int offset ); [DllImport("coredll.dll")] private static extern IntPtr CreateBitmap( int nWidth, int nHeight, uint cPlanes, uint cBitsPerPel, byte[] bits ); [DllImport("coredll.dll")] private static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("coredll.dll")] private static extern bool BitBlt( IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop ); [DllImport("coredll.dll")] private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("coredll.dll")] private static extern bool DeleteObject(IntPtr hgdiobj); [DllImport("coredll.dll")] private static extern bool DeleteDC(IntPtr hdc); #endif private BitmapUtils() { } // Squeeze single scanline of source image private static void SqueezeLine(byte[] line, uint[] destLine, uint sourWidth, uint destWidth) { uint stepW = sourWidth; uint stepR = stepW % destWidth; uint destWidth3 = destWidth * 3; uint s1w = destWidth; // (s + 1) * destWidth uint s1wend = sourWidth * destWidth; uint d3 = 0; uint s3 = 0; uint l = 0; uint nextW = stepW; uint r = stepR; while (true) { // Squeeze whole pixels while (s1w <= nextW) { destLine[d3 + 0] += line[s3++]; destLine[d3 + 1] += line[s3++]; destLine[d3 + 2] += line[s3++]; s1w += destWidth; } if (s1w >= s1wend) break; // Add left part of partial pixel destLine[d3++] += line[s3 + 0] * r / destWidth; destLine[d3++] += line[s3 + 1] * r / destWidth; destLine[d3++] += line[s3 + 2] * r / destWidth; if (d3 >= destWidth3) break; l = destWidth - r; r += stepR; if (r >= destWidth) r -= destWidth; // Set next pixel to the right part of partial pixel destLine[d3 + 0] += line[s3++] * l / destWidth; destLine[d3 + 1] += line[s3++] * l / destWidth; destLine[d3 + 2] += line[s3++] * l / destWidth; s1w += destWidth; nextW += stepW; } } /// <overloads> /// <summary> /// Creates a thumbnail <see cref="Bitmap"/> of specified size and with specified /// quality vs. speed settings from some JPEG stream or file. /// </summary> /// <example> /// For complete example see <c>ThumbnailViewer</c> from <b>\examples</b> folder. /// <code lang="C#"> /// /// // Create a thumbnail image /// pictureBox.Image = JPEGator.BitmapUtils.LoadThumbnail( /// // Put filename of your picture here /// fileName, /// // Put here the maximum size of thumbnail image you want to obtain. /// // If proportional flag is false then this will be an exact size /// // of thumbnail image, if not then this will be the size corrected /// // to retain proportions of original image /// pictureBox.Width, pictureBox.Height, /// // Select thumbnail quality here: image scaling method and DCT method depend on it; /// // the lower is quality, the better is speed. /// quality, /// // Indicates whether thumbnail image will retain proportions of original image /// proportions /// ); /// </code> /// </example> /// </overloads> /// /// <summary> /// Creates a thumbnail <see cref="Bitmap"/> of specified size and with specified /// quality vs. speed settings from a JPEG file. /// </summary> /// /// <param name="fileName">A name of an existing JPEG file, for which the thumbnail image should be created.</param> /// <param name="destinationWidth">A width of the thumbnail image.</param> /// <param name="destinationHeight">A height of the thumbnail image.</param> /// <param name="quality">A quality versus speed settings. See <see cref="ThumbnailQuality"/>.</param> /// <param name="proportional">If <c>true</c>, then this thumbnail image will retain its original proportions even /// if <c>destWidth/destHeight</c> ratio differs from proportions of a source JPEG image. /// <note> /// Images that are smaller than a destination image will always have their original sizes and /// proportions. /// </note> /// </param> /// /// <returns>An instance of the <see cref="System.Drawing.Bitmap"/> class containing needed thumbnail image. /// /// <note> /// Note that if <c>proportional</c> pramater is <c>true</c>, then size of resulting image most likely will differ from /// <paramref name="destWidth"/> x <paramref name="destHeight"/>. /// </note> /// /// </returns> public static System.Drawing.Bitmap LoadThumbnail(string fileName, int destinationWidth, int destinationHeight, ThumbnailQuality quality, bool proportional) { System.IO.Stream s = System.IO.File.OpenRead(fileName); try { return LoadThumbnail(s, destinationWidth, destinationHeight, quality, proportional); } finally { s.Close(); } } /// <summary> /// Creates a thumbnail <see cref="Bitmap"/> of specified size and with specified /// quality vs. speed settings from a JPEG stream. /// </summary> /// /// <param name="stream">A source JPEG stream.</param> /// <param name="destinationWidth">A width of thumbnail image.</param> /// <param name="destinationHeight">A height of thumbnail image.</param> /// <param name="quality">A quality versus speed settings. See <see cref="ThumbnailQuality"/>.</param> /// <param name="proportional">If <c>true</c>, then this thumbnail image will retain its original proportions even /// if <c>destWidth/destHeight</c> ratio differs from proportions of a source JPEG image. /// <note> /// Images that are smaller than a destination image will always have their original sizes and /// proportions. /// </note> /// </param> /// /// <returns>An instance of the <see cref="System.Drawing.Bitmap"/> class containing needed thumbnail image. /// /// <note> /// If <c>proportional</c> pramater is <c>true</c>, then size of resulting image most likely will differ from /// <paramref name="destWidth"/> x <paramref name="destHeight"/>. /// </note> /// /// </returns> public static System.Drawing.Bitmap LoadThumbnail(System.IO.Stream stream, int destinationWidth, int destinationHeight, ThumbnailQuality quality, bool proportional) { uint destWidth = (uint)destinationWidth; uint destHeight = (uint)destinationHeight; // Create decompressor instance using (JPEGator.Decompress decomp = new JPEGator.Decompress()) { // Select DCT method depending on thumbnail quality decomp.DCTMethod = (quality >= ThumbnailQuality.Low) ? DCTMethod.Slow : DCTMethod.Fast; // Start decompression process (setup source stream, read source picture header) decomp.Start(stream); // Create shortcuts for input image sizes uint sourWidth = (uint)decomp.InputWidth; uint sourHeight = (uint)decomp.InputHeight; // Check whether thumbnail size is less than whole image size if (destWidth > sourWidth) destWidth = sourWidth; if (destHeight > sourHeight) destHeight = sourHeight; // If proportional mode is in effect, then adjust thumbnail size to retain proportions of original image if (proportional) { if (destWidth * sourHeight < sourWidth * destHeight) destHeight = sourHeight * destWidth / sourWidth; else destWidth = sourWidth * destHeight / sourHeight; } if (sourWidth <= destWidth && sourHeight <= destHeight) return LoadBitmapFromDecompressor(decomp); #if NETCF1 // Allocating bitmap buffer int bitmapLineSize = ((int)destWidth * 3 + 3) & ~3; byte[] bitmapBits = new byte[bitmapLineSize * destHeight]; #elif NETCF2 System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)destWidth, (int)destHeight); System.Drawing.Imaging.BitmapData data = bitmap.LockBits( new Rectangle(0, 0, (int)destWidth, (int)destHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb ); int bitmapLineSize = data.Stride; unsafe { byte* bitmapBits = (byte*)data.Scan0; #else #error Framework is not supported or NETCF1/2 flag is not defined #endif int bitmapOffset = 0; // Allocating scanline buffer byte[] line = new byte[sourWidth * 3]; // Squeeze image depending on quality settings if (quality >= ThumbnailQuality.High) { // // High quality downscaling: using linear interpolation // // Getting shortcuts for some values (not sure if they can be optimized by JIT) uint sourWidthHeight = sourWidth * sourHeight; uint destWidthHeight = destWidth * destHeight; // // Prepare temporary buffers // uint[] destLine = new uint[destWidth * 3]; // Temp scanline of destination image byte[] destByteLine = new byte[destWidth * 3]; // Ready for output scanline of destination image // // Prepare scaling algorithm vars // uint stepH = sourHeight; uint stepB = sourHeight % destHeight; uint nextH = stepH; uint b = stepB; uint i = 0; uint d = 0; // Go through scanlines and squeeze them while (true) { // Squeeze scanlines that fit into a single scanline of the destination image while ((i + 1) * destHeight <= nextH) { decomp.ReadScanline(line); SqueezeLine(line, destLine, sourWidth, destWidth); i++; } // // Squeeze source scanline that partially belongs to two scanlines of destination image // // Squeeze first part uint[] tempLine = new uint[destWidth * 3]; if (i < sourHeight) { decomp.ReadScanline(line); SqueezeLine(line, tempLine, sourWidth, destWidth); int offset = bitmapOffset; for (d = 0; d < destWidth * 3; d++) { bitmapBits[offset] = (byte)((destLine[d] * destHeight + tempLine[d] * b) * destWidth / sourWidthHeight); offset++; } bitmapOffset += bitmapLineSize; } else { System.Diagnostics.Trace.Assert(b == 0); int offset = bitmapOffset; for (d = 0; d < destWidth * 3; d++) { bitmapBits[offset] = (byte)(destLine[d] * destWidthHeight / sourWidthHeight); offset++; } break; } // Squeeze second part uint t = destHeight - b; for (d = 0; d < destWidth * 3; d++) destLine[d] = tempLine[d] * t / destHeight; b += stepB; if (b >= destHeight) b -= destHeight; i++; nextH += stepH; } } else { // // Low quality downscaling: just throw away some pixels of original image // uint lineNumber = 0; uint y = 0; uint sourHeightDestHeight = sourHeight * destHeight; uint sourWidthDestWidth = sourWidth * destWidth; unsafe { #if NETCF1 fixed (byte *bitmapBitsPtr = bitmapBits) #elif NETCF2 byte *bitmapBitsPtr = bitmapBits; #endif fixed (byte* linePtr = line) while (true) { decomp.ReadScanline(line); lineNumber += destHeight; uint x = 0; int d = bitmapOffset; while (x < sourWidthDestWidth) { uint xx = 3 * (x / destWidth); bitmapBitsPtr[d++] = line[xx]; bitmapBitsPtr[d++] = line[xx + 1]; bitmapBitsPtr[d++] = line[xx + 2]; x += sourWidth; } bitmapOffset += bitmapLineSize; y += sourHeight; if (y >= sourHeightDestHeight) break; uint linesToSkip = (y - lineNumber) / destHeight; if (linesToSkip > 0) decomp.SkipScanlines((int)linesToSkip); lineNumber += linesToSkip * destHeight; } } } #if NETCF1 return BitmapFromBGR24(bitmapBits, 0, (int)destWidth, (int)destHeight); #elif NETCF2 } bitmap.UnlockBits(data); return bitmap; #else #error Framework is not supported or NETCF1/2 flag is not defined #endif } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.InteropServices; namespace System { public partial class String { public bool Contains(string value) { return (IndexOf(value, StringComparison.Ordinal) >= 0); } public bool Contains(string value, StringComparison comparisonType) { return (IndexOf(value, comparisonType) >= 0); } public bool Contains(char value) { return IndexOf(value) != -1; } public bool Contains(char value, StringComparison comparisonType) { return IndexOf(value, comparisonType) != -1; } // Returns the index of the first occurrence of a specified character in the current instance. // The search starts at startIndex and runs thorough the next count characters. // public int IndexOf(char value) { return IndexOf(value, 0, this.Length); } public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } public int IndexOf(char value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.Ordinal); case StringComparison.OrdinalIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.OrdinalIgnoreCase); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public unsafe int IndexOf(char value, int startIndex, int count) { if (startIndex < 0 || startIndex > Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count > Length - startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh + 1) == value) goto ReturnIndex1; if (*(pCh + 2) == value) goto ReturnIndex2; if (*(pCh + 3) == value) goto ReturnIndex3; count -= 4; pCh += 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh++; } return -1; ReturnIndex3: pCh++; ReturnIndex2: pCh++; ReturnIndex1: pCh++; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the first occurrence of any specified character in the current instance. // The search starts at startIndex and runs to startIndex + count - 1. // public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, this.Length); } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, this.Length - startIndex); } public int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException(nameof(anyOf)); if ((uint)startIndex > (uint)Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if ((uint)count > (uint)(Length - startIndex)) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (anyOf.Length == 2) { // Very common optimization for directory separators (/, \), quotes (", '), brackets, etc return IndexOfAny(anyOf[0], anyOf[1], startIndex, count); } else if (anyOf.Length == 3) { return IndexOfAny(anyOf[0], anyOf[1], anyOf[2], startIndex, count); } else if (anyOf.Length > 3) { return IndexOfCharArray(anyOf, startIndex, count); } else if (anyOf.Length == 1) { return IndexOf(anyOf[0], startIndex, count); } else // anyOf.Length == 0 { return -1; } } private unsafe int IndexOfAny(char value1, char value2, int startIndex, int count) { fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { char c = *pCh; if (c == value1 || c == value2) return (int)(pCh - pChars); // Possibly reads outside of count and can include null terminator // Handled in the return logic c = *(pCh + 1); if (c == value1 || c == value2) return (count == 1 ? -1 : (int)(pCh - pChars) + 1); pCh += 2; count -= 2; } return -1; } } private unsafe int IndexOfAny(char value1, char value2, char value3, int startIndex, int count) { fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { char c = *pCh; if (c == value1 || c == value2 || c == value3) return (int)(pCh - pChars); pCh++; count--; } return -1; } } private unsafe int IndexOfCharArray(char[] anyOf, int startIndex, int count) { // use probabilistic map, see InitializeProbabilisticMap ProbabilisticMap map = default(ProbabilisticMap); uint* charMap = (uint*)&map; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { int thisChar = *pCh; if (IsCharBitSet(charMap, (byte)thisChar) && IsCharBitSet(charMap, (byte)(thisChar >> 8)) && ArrayContains((char)thisChar, anyOf)) { return (int)(pCh - pChars); } count--; pCh++; } return -1; } } private const int PROBABILISTICMAP_BLOCK_INDEX_MASK = 0x7; private const int PROBABILISTICMAP_BLOCK_INDEX_SHIFT = 0x3; private const int PROBABILISTICMAP_SIZE = 0x8; // A probabilistic map is an optimization that is used in IndexOfAny/ // LastIndexOfAny methods. The idea is to create a bit map of the characters we // are searching for and use this map as a "cheap" check to decide if the // current character in the string exists in the array of input characters. // There are 256 bits in the map, with each character mapped to 2 bits. Every // character is divided into 2 bytes, and then every byte is mapped to 1 bit. // The character map is an array of 8 integers acting as map blocks. The 3 lsb // in each byte in the character is used to index into this map to get the // right block, the value of the remaining 5 msb are used as the bit position // inside this block. private static unsafe void InitializeProbabilisticMap(uint* charMap, ReadOnlySpan<char> anyOf) { bool hasAscii = false; uint* charMapLocal = charMap; // https://github.com/dotnet/coreclr/issues/14264 for (int i = 0; i < anyOf.Length; ++i) { int c = anyOf[i]; // Map low bit SetCharBit(charMapLocal, (byte)c); // Map high bit c >>= 8; if (c == 0) { hasAscii = true; } else { SetCharBit(charMapLocal, (byte)c); } } if (hasAscii) { // Common to search for ASCII symbols. Just set the high value once. charMapLocal[0] |= 1u; } } private static bool ArrayContains(char searchChar, char[] anyOf) { for (int i = 0; i < anyOf.Length; i++) { if (anyOf[i] == searchChar) return true; } return false; } private unsafe static bool IsCharBitSet(uint* charMap, byte value) { return (charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] & (1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0; } private unsafe static void SetCharBit(uint* charMap, byte value) { charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] |= 1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT); } public int IndexOf(String value) { return IndexOf(value, StringComparison.CurrentCulture); } public int IndexOf(String value, int startIndex) { return IndexOf(value, startIndex, StringComparison.CurrentCulture); } public int IndexOf(String value, int startIndex, int count) { if (startIndex < 0 || startIndex > this.Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if (count < 0 || count > this.Length - startIndex) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } return IndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int IndexOf(String value, StringComparison comparisonType) { return IndexOf(value, 0, this.Length, comparisonType); } public int IndexOf(String value, int startIndex, StringComparison comparisonType) { return IndexOf(value, startIndex, this.Length - startIndex, comparisonType); } public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { // Validate inputs if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > this.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CompareInfo.Invariant.IndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CompareInfo.Invariant.IndexOfOrdinal(this, value, startIndex, count, ignoreCase: false); case StringComparison.OrdinalIgnoreCase: return CompareInfo.Invariant.IndexOfOrdinal(this, value, startIndex, count, ignoreCase: true); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } // Returns the index of the last occurrence of a specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(char value) { return LastIndexOf(value, this.Length - 1, this.Length); } public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public unsafe int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) return -1; if (startIndex < 0 || startIndex >= Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count - 1 > startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; //We search [startIndex..EndIndex] while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh - 1) == value) goto ReturnIndex1; if (*(pCh - 2) == value) goto ReturnIndex2; if (*(pCh - 3) == value) goto ReturnIndex3; count -= 4; pCh -= 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh--; } return -1; ReturnIndex3: pCh--; ReturnIndex2: pCh--; ReturnIndex1: pCh--; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the last occurrence of any specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOfAny(char[] anyOf) { return LastIndexOfAny(anyOf, this.Length - 1, this.Length); } public int LastIndexOfAny(char[] anyOf, int startIndex) { return LastIndexOfAny(anyOf, startIndex, startIndex + 1); } public unsafe int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException(nameof(anyOf)); if (Length == 0) return -1; if ((uint)startIndex >= (uint)Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if ((count < 0) || ((count - 1) > startIndex)) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } if (anyOf.Length > 1) { return LastIndexOfCharArray(anyOf, startIndex, count); } else if (anyOf.Length == 1) { return LastIndexOf(anyOf[0], startIndex, count); } else // anyOf.Length == 0 { return -1; } } private unsafe int LastIndexOfCharArray(char[] anyOf, int startIndex, int count) { // use probabilistic map, see InitializeProbabilisticMap ProbabilisticMap map = default(ProbabilisticMap); uint* charMap = (uint*)&map; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { int thisChar = *pCh; if (IsCharBitSet(charMap, (byte)thisChar) && IsCharBitSet(charMap, (byte)(thisChar >> 8)) && ArrayContains((char)thisChar, anyOf)) { return (int)(pCh - pChars); } count--; pCh--; } return -1; } } // Returns the index of the last occurrence of any character in value in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(String value) { return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture); } public int LastIndexOf(String value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture); } public int LastIndexOf(String value, int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int LastIndexOf(String value, StringComparison comparisonType) { return LastIndexOf(value, this.Length - 1, this.Length, comparisonType); } public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { return LastIndexOf(value, startIndex, startIndex + 1, comparisonType); } public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { if (value == null) throw new ArgumentNullException(nameof(value)); // Special case for 0 length input strings if (this.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Now after handling empty strings, make sure we're not out of range if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == this.Length if (startIndex == this.Length) { startIndex--; if (count > 0) count--; } // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); // If we are looking for nothing, just return startIndex if (value.Length == 0) return startIndex; switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CompareInfo.Invariant.LastIndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CompareInfo.Invariant.LastIndexOfOrdinal(this, value, startIndex, count, ignoreCase: false); case StringComparison.OrdinalIgnoreCase: return CompareInfo.Invariant.LastIndexOfOrdinal(this, value, startIndex, count, ignoreCase: true); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } [StructLayout(LayoutKind.Explicit, Size = PROBABILISTICMAP_SIZE * sizeof(uint))] private struct ProbabilisticMap { } } }
// <copyright file="RiakAsyncClient.cs" company="Basho Technologies, Inc."> // Copyright 2011 - OJ Reeves & Jeremiah Peschka // Copyright 2014 - Basho Technologies, Inc. // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // </copyright> namespace RiakClient { using System; using System.Collections.Generic; using System.Numerics; using System.Threading.Tasks; using Commands; using Models; using Models.Index; using Models.MapReduce; using Models.Search; /// <summary> /// An asyncronous version of <see cref="RiakClient"/>. /// </summary> internal class RiakAsyncClient : IRiakAsyncClient { private readonly IRiakClient client; /// <summary> /// Initializes a new instance of the <see cref="RiakAsyncClient"/> class from the specified <see cref="IRiakClient"/>. /// </summary> /// <param name="client">The <see cref="RiakClient"/> to use for all operations.</param> public RiakAsyncClient(IRiakClient client) { this.client = client; } /// <inheritdoc/> public Task<RiakResult> Ping() { return Task.Factory.StartNew(() => client.Ping()); } /// <inheritdoc/> public Task<RiakResult<RiakObject>> Get(string bucket, string key, RiakGetOptions options = null) { options = options ?? RiakGetOptions.Default; return Task.Factory.StartNew(() => client.Get(bucket, key, options)); } /// <inheritdoc/> public Task<RiakResult<RiakObject>> Get(RiakObjectId objectId, RiakGetOptions options = null) { options = options ?? RiakGetOptions.Default; return Task.Factory.StartNew(() => client.Get(objectId.Bucket, objectId.Key, options)); } /// <inheritdoc/> public Task<IEnumerable<RiakResult<RiakObject>>> Get(IEnumerable<RiakObjectId> objectIds, RiakGetOptions options = null) { options = options ?? RiakGetOptions.Default; return Task.Factory.StartNew(() => client.Get(objectIds, options)); } /// <inheritdoc/> public Task<RiakCounterResult> IncrementCounter(string bucket, string counter, long amount, RiakCounterUpdateOptions options = null) { return Task.Factory.StartNew(() => client.IncrementCounter(bucket, counter, amount, options)); } /// <inheritdoc/> public Task<RiakCounterResult> GetCounter(string bucket, string counter, RiakCounterGetOptions options = null) { return Task.Factory.StartNew(() => client.GetCounter(bucket, counter, options)); } /// <inheritdoc/> public Task<IEnumerable<RiakResult<RiakObject>>> Put(IEnumerable<RiakObject> values, RiakPutOptions options) { return Task.Factory.StartNew(() => client.Put(values, options)); } /// <inheritdoc/> public Task<RiakResult<RiakObject>> Put(RiakObject value, RiakPutOptions options) { return Task.Factory.StartNew(() => client.Put(value, options)); } /// <inheritdoc/> public Task<RiakResult> Delete(RiakObject riakObject, RiakDeleteOptions options = null) { return Task.Factory.StartNew(() => client.Delete(riakObject, options)); } /// <inheritdoc/> public Task<RiakResult> Delete(string bucket, string key, RiakDeleteOptions options = null) { return Task.Factory.StartNew(() => client.Delete(bucket, key, options)); } /// <inheritdoc/> public Task<RiakResult> Delete(RiakObjectId objectId, RiakDeleteOptions options = null) { return Task.Factory.StartNew(() => client.Delete(objectId.Bucket, objectId.Key, options)); } /// <inheritdoc/> public Task<IEnumerable<RiakResult>> Delete(IEnumerable<RiakObjectId> objectIds, RiakDeleteOptions options = null) { return Task.Factory.StartNew(() => client.Delete(objectIds, options)); } /// <inheritdoc/> public Task<RiakResult<RiakSearchResult>> Search(RiakSearchRequest search) { return Task.Factory.StartNew(() => client.Search(search)); } /// <inheritdoc/> public Task<RiakResult<RiakMapReduceResult>> MapReduce(RiakMapReduceQuery query) { return Task.Factory.StartNew(() => client.MapReduce(query)); } /// <inheritdoc/> public Task<RiakResult<RiakStreamedMapReduceResult>> StreamMapReduce(RiakMapReduceQuery query) { return Task.Factory.StartNew(() => client.StreamMapReduce(query)); } /// <inheritdoc/> public Task<RiakResult<IEnumerable<string>>> StreamListBuckets() { return Task.Factory.StartNew(() => client.StreamListBuckets()); } /// <inheritdoc/> public Task<RiakResult<IEnumerable<string>>> ListBuckets() { return Task.Factory.StartNew(() => client.ListBuckets()); } /// <inheritdoc/> public Task<RiakResult<IEnumerable<string>>> ListKeys(string bucket) { return Task.Factory.StartNew(() => client.ListKeys(bucket)); } /// <inheritdoc/> public Task<RiakResult<IEnumerable<string>>> StreamListKeys(string bucket) { return Task.Factory.StartNew(() => client.StreamListKeys(bucket)); } /// <inheritdoc/> public Task<RiakResult<RiakBucketProperties>> GetBucketProperties(string bucket) { return Task.Factory.StartNew(() => client.GetBucketProperties(bucket)); } /// <inheritdoc/> public Task<RiakResult> SetBucketProperties(string bucket, RiakBucketProperties properties) { return Task.Factory.StartNew(() => client.SetBucketProperties(bucket, properties)); } /// <inheritdoc/> public Task<RiakResult> ResetBucketProperties(string bucket) { return Task.Factory.StartNew(() => client.ResetBucketProperties(bucket)); } /// <inheritdoc/> public Task<RiakResult<IList<string>>> ListKeysFromIndex(string bucket) { return Task.Factory.StartNew(() => client.ListKeysFromIndex(bucket)); } /// <inheritdoc/> [Obsolete("Linkwalking has been deprecated as of Riak 2.0. This method will be removed in the next major version.")] public Task<RiakResult<IList<RiakObject>>> WalkLinks(RiakObject riakObject, IList<RiakLink> riakLinks) { #pragma warning disable 618 return Task.Factory.StartNew(() => client.WalkLinks(riakObject, riakLinks)); #pragma warning restore 618 } /// <inheritdoc/> [System.Obsolete("Please use RiakClient.Commands.ServerInfo instead.")] public Task<RiakResult<RiakServerInfo>> GetServerInfo() { return Task.Factory.StartNew(() => client.GetServerInfo()); } /// <inheritdoc/> public Task<RiakResult<RiakIndexResult>> GetSecondaryIndex(RiakIndexId index, BigInteger value, RiakIndexGetOptions options = null) { return Task.Factory.StartNew(() => client.GetSecondaryIndex(index, value, options)); } /// <inheritdoc/> public Task<RiakResult<RiakIndexResult>> GetSecondaryIndex(RiakIndexId index, string value, RiakIndexGetOptions options = null) { return Task.Factory.StartNew(() => client.GetSecondaryIndex(index, value, options)); } /// <inheritdoc/> public Task<RiakResult<RiakIndexResult>> GetSecondaryIndex(RiakIndexId index, BigInteger min, BigInteger max, RiakIndexGetOptions options = null) { return Task.Factory.StartNew(() => client.GetSecondaryIndex(index, min, max, options)); } /// <inheritdoc/> public Task<RiakResult<RiakIndexResult>> GetSecondaryIndex(RiakIndexId index, string min, string max, RiakIndexGetOptions options = null) { return Task.Factory.StartNew(() => client.GetSecondaryIndex(index, min, max, options)); } /// <inheritdoc/> public Task<RiakResult<RiakStreamedIndexResult>> StreamGetSecondaryIndex(RiakIndexId index, BigInteger value, RiakIndexGetOptions options = null) { return Task.Factory.StartNew(() => client.StreamGetSecondaryIndex(index, value, options)); } /// <inheritdoc/> public Task<RiakResult<RiakStreamedIndexResult>> StreamGetSecondaryIndex(RiakIndexId index, string value, RiakIndexGetOptions options = null) { return Task.Factory.StartNew(() => client.StreamGetSecondaryIndex(index, value, options)); } /// <inheritdoc/> public Task<RiakResult<RiakStreamedIndexResult>> StreamGetSecondaryIndex(RiakIndexId index, BigInteger min, BigInteger max, RiakIndexGetOptions options = null) { return Task.Factory.StartNew(() => client.StreamGetSecondaryIndex(index, min, max, options)); } /// <inheritdoc/> public Task<RiakResult<RiakStreamedIndexResult>> StreamGetSecondaryIndex(RiakIndexId index, string min, string max, RiakIndexGetOptions options = null) { return Task.Factory.StartNew(() => client.StreamGetSecondaryIndex(index, min, max, options)); } /// <inheritdoc/> public Task Batch(Action<IRiakBatchClient> batchAction) { return Task.Factory.StartNew(() => client.Batch(batchAction)); } // TODO: Everything under here isn't in the interface /// <inheritdoc/> public Task<T> Batch<T>(Func<IRiakBatchClient, T> batchFunc) { return Task.Factory.StartNew<T>(() => client.Batch(batchFunc)); } /// <inheritdoc/> public Task<RiakResult> Ping(Action<RiakResult> callback) { return Task.Factory.StartNew(() => client.Ping()); } /// <inheritdoc/> public void Get(string bucket, string key, Action<RiakResult<RiakObject>> callback, RiakGetOptions options = null) { options = options ?? RiakGetOptions.Default; ExecAsync(() => callback(client.Get(bucket, key, options))); } /// <inheritdoc/> public void Get(RiakObjectId objectId, Action<RiakResult<RiakObject>> callback, RiakGetOptions options = null) { options = options ?? RiakGetOptions.Default; ExecAsync(() => callback(client.Get(objectId.Bucket, objectId.Key, options))); } /// <inheritdoc/> public void Get(IEnumerable<RiakObjectId> objectIds, Action<IEnumerable<RiakResult<RiakObject>>> callback, RiakGetOptions options = null) { options = options ?? RiakGetOptions.Default; ExecAsync(() => callback(client.Get(objectIds, options))); } /// <inheritdoc/> public void Put(IEnumerable<RiakObject> values, Action<IEnumerable<RiakResult<RiakObject>>> callback, RiakPutOptions options) { ExecAsync(() => callback(client.Put(values, options))); } /// <inheritdoc/> public void Put(RiakObject value, Action<RiakResult<RiakObject>> callback, RiakPutOptions options) { ExecAsync(() => callback(client.Put(value, options))); } /// <inheritdoc/> public void Delete(string bucket, string key, Action<RiakResult> callback, RiakDeleteOptions options = null) { ExecAsync(() => callback(client.Delete(bucket, key, options))); } /// <inheritdoc/> public void Delete(RiakObjectId objectId, Action<RiakResult> callback, RiakDeleteOptions options = null) { ExecAsync(() => callback(client.Delete(objectId.Bucket, objectId.Key, options))); } /// <inheritdoc/> public void Delete(IEnumerable<RiakObjectId> objectIds, Action<IEnumerable<RiakResult>> callback, RiakDeleteOptions options = null) { ExecAsync(() => callback(client.Delete(objectIds, options))); } /// <inheritdoc/> public void MapReduce(RiakMapReduceQuery query, Action<RiakResult<RiakMapReduceResult>> callback) { ExecAsync(() => callback(client.MapReduce(query))); } /// <inheritdoc/> public void StreamMapReduce(RiakMapReduceQuery query, Action<RiakResult<RiakStreamedMapReduceResult>> callback) { ExecAsync(() => callback(client.StreamMapReduce(query))); } /// <inheritdoc/> public void ListBuckets(Action<RiakResult<IEnumerable<string>>> callback) { ExecAsync(() => callback(client.ListBuckets())); } /// <inheritdoc/> public void ListKeys(string bucket, Action<RiakResult<IEnumerable<string>>> callback) { ExecAsync(() => callback(client.ListKeys(bucket))); } /// <inheritdoc/> public void StreamListKeys(string bucket, Action<RiakResult<IEnumerable<string>>> callback) { ExecAsync(() => callback(client.StreamListKeys(bucket))); } /// <inheritdoc/> public void GetBucketProperties(string bucket, Action<RiakResult<RiakBucketProperties>> callback) { ExecAsync(() => callback(client.GetBucketProperties(bucket))); } /// <inheritdoc/> public void SetBucketProperties(string bucket, RiakBucketProperties properties, Action<RiakResult> callback) { ExecAsync(() => callback(client.SetBucketProperties(bucket, properties))); } /// <inheritdoc/> [System.Obsolete("Please use RiakClient.Commands.ServerInfo instead.")] public void GetServerInfo(Action<RiakResult<RiakServerInfo>> callback) { ExecAsync(() => callback(client.GetServerInfo())); } /// <inheritdoc/> public Task<RiakResult> Execute(IRiakCommand command) { return Task.Factory.StartNew(() => client.Execute(command)); } private static void ExecAsync(Action action) { Task.Factory.StartNew(action); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Timers; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// Encapsulate the asynchronous requests for the assets required for an archive operation /// </summary> class AssetsRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); enum RequestState { Initial, Running, Completed, Aborted }; /// <value> /// Timeout threshold if we still need assets or missing asset notifications but have stopped receiving them /// from the asset service /// </value> protected const int TIMEOUT = 60 * 1000; /// <value> /// If a timeout does occur, limit the amount of UUID information put to the console. /// </value> protected const int MAX_UUID_DISPLAY_ON_TIMEOUT = 3; protected System.Timers.Timer m_requestCallbackTimer; /// <value> /// State of this request /// </value> private RequestState m_requestState = RequestState.Initial; /// <value> /// uuids to request /// </value> protected ICollection<UUID> m_uuids; /// <value> /// Callback used when all the assets requested have been received. /// </value> protected AssetsRequestCallback m_assetsRequestCallback; /// <value> /// List of assets that were found. This will be passed back to the requester. /// </value> protected List<UUID> m_foundAssetUuids = new List<UUID>(); /// <value> /// Maintain a list of assets that could not be found. This will be passed back to the requester. /// </value> protected List<UUID> m_notFoundAssetUuids = new List<UUID>(); /// <value> /// Record the number of asset replies required so we know when we've finished /// </value> private int m_repliesRequired; /// <value> /// Asset service used to request the assets /// </value> protected IAssetService m_assetService; protected AssetsArchiver m_assetsArchiver; protected internal AssetsRequest( AssetsArchiver assetsArchiver, ICollection<UUID> uuids, IAssetService assetService, AssetsRequestCallback assetsRequestCallback) { m_assetsArchiver = assetsArchiver; m_uuids = uuids; m_assetsRequestCallback = assetsRequestCallback; m_assetService = assetService; m_repliesRequired = uuids.Count; m_requestCallbackTimer = new System.Timers.Timer(TIMEOUT); m_requestCallbackTimer.AutoReset = false; m_requestCallbackTimer.Elapsed += new ElapsedEventHandler(OnRequestCallbackTimeout); } protected internal void Execute() { m_requestState = RequestState.Running; m_log.DebugFormat("[ARCHIVER]: AssetsRequest executed looking for {0} assets", m_repliesRequired); // We can stop here if there are no assets to fetch if (m_repliesRequired == 0) { m_requestState = RequestState.Completed; PerformAssetsRequestCallback(null); return; } foreach (UUID uuid in m_uuids) { m_assetService.Get(uuid.ToString(), this, AssetRequestCallback); } m_requestCallbackTimer.Enabled = true; } protected void OnRequestCallbackTimeout(object source, ElapsedEventArgs args) { try { lock (this) { // Take care of the possibilty that this thread started but was paused just outside the lock before // the final request came in (assuming that such a thing is possible) if (m_requestState == RequestState.Completed) return; m_requestState = RequestState.Aborted; } // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure // case anyway. List<UUID> uuids = new List<UUID>(); foreach (UUID uuid in m_uuids) { uuids.Add(uuid); } foreach (UUID uuid in m_foundAssetUuids) { uuids.Remove(uuid); } foreach (UUID uuid in m_notFoundAssetUuids) { uuids.Remove(uuid); } m_log.ErrorFormat( "[ARCHIVER]: Asset service failed to return information about {0} requested assets", uuids.Count); int i = 0; foreach (UUID uuid in uuids) { m_log.ErrorFormat("[ARCHIVER]: No information about asset {0} received", uuid); if (++i >= MAX_UUID_DISPLAY_ON_TIMEOUT) break; } if (uuids.Count > MAX_UUID_DISPLAY_ON_TIMEOUT) m_log.ErrorFormat( "[ARCHIVER]: (... {0} more not shown)", uuids.Count - MAX_UUID_DISPLAY_ON_TIMEOUT); m_log.Error("[ARCHIVER]: OAR save aborted."); } catch (Exception e) { m_log.ErrorFormat("[ARCHIVER]: Timeout handler exception {0}", e); } finally { m_assetsArchiver.ForceClose(); } } /// <summary> /// Called back by the asset cache when it has the asset /// </summary> /// <param name="assetID"></param> /// <param name="asset"></param> public void AssetRequestCallback(string id, object sender, AssetBase asset) { try { lock (this) { //m_log.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id); m_requestCallbackTimer.Stop(); if (m_requestState == RequestState.Aborted) { m_log.WarnFormat( "[ARCHIVER]: Received information about asset {0} after archive save abortion. Ignoring.", id); return; } if (asset != null) { // m_log.DebugFormat("[ARCHIVER]: Recording asset {0} as found", id); m_foundAssetUuids.Add(asset.FullID); m_assetsArchiver.WriteAsset(asset); } else { // m_log.DebugFormat("[ARCHIVER]: Recording asset {0} as not found", id); m_notFoundAssetUuids.Add(new UUID(id)); } if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count == m_repliesRequired) { m_requestState = RequestState.Completed; m_log.DebugFormat( "[ARCHIVER]: Successfully added {0} assets ({1} assets notified missing)", m_foundAssetUuids.Count, m_notFoundAssetUuids.Count); // We want to stop using the asset cache thread asap // as we now need to do the work of producing the rest of the archive Util.FireAndForget(PerformAssetsRequestCallback); } else { m_requestCallbackTimer.Start(); } } } catch (Exception e) { m_log.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e); } } /// <summary> /// Perform the callback on the original requester of the assets /// </summary> protected void PerformAssetsRequestCallback(object o) { try { m_assetsRequestCallback(m_foundAssetUuids, m_notFoundAssetUuids); } catch (Exception e) { m_log.ErrorFormat( "[ARCHIVER]: Terminating archive creation since asset requster callback failed with {0}", e); } } } }
// Copyright (C) 2004-2007 MySQL AB // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as published by // the Free Software Foundation // // There are special exceptions to the terms and conditions of the GPL // as it is applied to this software. View the full text of the // exception in file EXCEPTIONS in the directory of this software // distribution. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System.Text; using MySql.Data.Common; using MySql.Data.Types; using System.Globalization; using System.Text.RegularExpressions; using System; namespace MySql.Data.MySqlClient { internal enum ColumnFlags : int { NOT_NULL = 1, PRIMARY_KEY = 2, UNIQUE_KEY = 4, MULTIPLE_KEY = 8, BLOB = 16, UNSIGNED = 32, ZERO_FILL = 64, BINARY = 128, ENUM = 256, AUTO_INCREMENT = 512, TIMESTAMP = 1024, SET = 2048, NUMBER = 32768 } ; /// <summary> /// Summary description for Field. /// </summary> internal class MySqlField { #region Fields // public fields public string CatalogName; public int ColumnLength; public string ColumnName; public string OriginalColumnName; public string TableName; public string RealTableName; public string DatabaseName; public Encoding Encoding; public int maxLength; // protected fields protected ColumnFlags colFlags; protected int charSetIndex; protected byte precision; protected byte scale; protected MySqlDbType mySqlDbType; protected DBVersion connVersion; protected MySqlConnection connection; protected bool binaryOk; #endregion public MySqlField(MySqlConnection connection) { this.connection = connection; connVersion = connection.driver.Version; maxLength = 1; binaryOk = true; } #region Properties public int CharacterSetIndex { get { return charSetIndex; } set { charSetIndex = value; } } public MySqlDbType Type { get { return mySqlDbType; } } public byte Precision { get { return precision; } set { precision = value; } } public byte Scale { get { return scale; } set { scale = value; } } public int MaxLength { get { return maxLength; } set { maxLength = value; } } public ColumnFlags Flags { get { return colFlags; } } public bool IsAutoIncrement { get { return (colFlags & ColumnFlags.AUTO_INCREMENT) > 0; } } public bool IsNumeric { get { return (colFlags & ColumnFlags.NUMBER) > 0; } } public bool AllowsNull { get { return (colFlags & ColumnFlags.NOT_NULL) == 0; } } public bool IsUnique { get { return (colFlags & ColumnFlags.UNIQUE_KEY) > 0; } } public bool IsPrimaryKey { get { return (colFlags & ColumnFlags.PRIMARY_KEY) > 0; } } public bool IsBlob { get { return (mySqlDbType >= MySqlDbType.TinyBlob && mySqlDbType <= MySqlDbType.Blob) || (mySqlDbType >= MySqlDbType.TinyText && mySqlDbType <= MySqlDbType.Text) || (colFlags & ColumnFlags.BLOB) > 0; } } public bool IsBinary { get { if (connVersion.isAtLeast(4, 1, 0)) return binaryOk && (CharacterSetIndex == 63); return binaryOk && ((colFlags & ColumnFlags.BINARY) > 0); } } public bool IsUnsigned { get { return (colFlags & ColumnFlags.UNSIGNED) > 0; } } public bool IsTextField { get { return Type == MySqlDbType.VarString || Type == MySqlDbType.VarChar || (IsBlob && !IsBinary); } } #endregion public void SetTypeAndFlags(MySqlDbType type, ColumnFlags flags) { colFlags = flags; mySqlDbType = type; if (String.IsNullOrEmpty(TableName) && String.IsNullOrEmpty(RealTableName) && connection.Settings.FunctionsReturnString) { mySqlDbType = MySqlDbType.VarString; // we are treating a binary as string so we have to choose some // charset index. Connection seems logical. CharacterSetIndex = connection.driver.ConnectionCharSetIndex; binaryOk = false; } // if our type is an unsigned number, then we need // to bump it up into our unsigned types // we're trusting that the server is not going to set the UNSIGNED // flag unless we are a number if (IsUnsigned) { switch (type) { case MySqlDbType.Byte: mySqlDbType = MySqlDbType.UByte; return; case MySqlDbType.Int16: mySqlDbType = MySqlDbType.UInt16; return; case MySqlDbType.Int24: mySqlDbType = MySqlDbType.UInt24; return; case MySqlDbType.Int32: mySqlDbType = MySqlDbType.UInt32; return; case MySqlDbType.Int64: mySqlDbType = MySqlDbType.UInt64; return; } } if (IsBlob) { // handle blob to UTF8 conversion if requested. This is only activated // on binary blobs if (IsBinary && connection.Settings.TreatBlobsAsUTF8) { bool convertBlob = false; Regex includeRegex = connection.Settings.BlobAsUTF8IncludeRegex; Regex excludeRegex = connection.Settings.BlobAsUTF8ExcludeRegex; if (includeRegex != null && includeRegex.IsMatch(ColumnName)) convertBlob = true; else if (includeRegex == null && excludeRegex != null && !excludeRegex.IsMatch(ColumnName)) convertBlob = true; if (convertBlob) { binaryOk = false; Encoding = System.Text.Encoding.GetEncoding("UTF-8"); charSetIndex = -1; // lets driver know we are in charge of encoding maxLength = 4; } } if (!IsBinary) { if (type == MySqlDbType.TinyBlob) mySqlDbType = MySqlDbType.TinyText; else if (type == MySqlDbType.MediumBlob) mySqlDbType = MySqlDbType.MediumText; else if (type == MySqlDbType.Blob) mySqlDbType = MySqlDbType.Text; else if (type == MySqlDbType.LongBlob) mySqlDbType = MySqlDbType.LongText; } } // now determine if we really should be binary if (connection.Settings.RespectBinaryFlags) CheckForExceptions(); if (!IsBinary) return; if (connection.Settings.RespectBinaryFlags) { if (type == MySqlDbType.String) mySqlDbType = MySqlDbType.Binary; else if (type == MySqlDbType.VarChar || type == MySqlDbType.VarString) mySqlDbType = MySqlDbType.VarBinary; } if (CharacterSetIndex == 63) CharacterSetIndex = connection.driver.ConnectionCharSetIndex; } private void CheckForExceptions() { string colName = String.Empty; if (OriginalColumnName != null) colName = OriginalColumnName.ToLower(); if (colName.StartsWith("char(")) binaryOk = false; else if (connection.IsExecutingBuggyQuery) binaryOk = false; } public IMySqlValue GetValueObject() { IMySqlValue v = GetIMySqlValue(Type); if (v is MySqlByte && ColumnLength == 1 && MaxLength == 1 && connection.Settings.TreatTinyAsBoolean) { MySqlByte b = (MySqlByte)v; b.TreatAsBoolean = true; v = b; } else if (Type == MySqlDbType.Binary && ColumnLength == 16) { MySqlBinary b = (MySqlBinary)v; b.IsGuid = true; v = b; } return v; } public static IMySqlValue GetIMySqlValue(MySqlDbType type) { switch (type) { case MySqlDbType.Byte: return new MySqlByte(); case MySqlDbType.UByte: return new MySqlUByte(); case MySqlDbType.Int16: return new MySqlInt16(); case MySqlDbType.UInt16: return new MySqlUInt16(); case MySqlDbType.Int24: case MySqlDbType.Int32: case MySqlDbType.Year: return new MySqlInt32(type, true); case MySqlDbType.UInt24: case MySqlDbType.UInt32: return new MySqlUInt32(type, true); case MySqlDbType.Bit: return new MySqlBit(); case MySqlDbType.Int64: return new MySqlInt64(); case MySqlDbType.UInt64: return new MySqlUInt64(); case MySqlDbType.Time: return new MySqlTimeSpan(); case MySqlDbType.Date: case MySqlDbType.DateTime: case MySqlDbType.Newdate: case MySqlDbType.Timestamp: return new MySqlDateTime(type, true); case MySqlDbType.Decimal: case MySqlDbType.NewDecimal: return new MySqlDecimal(); case MySqlDbType.Float: return new MySqlSingle(); case MySqlDbType.Double: return new MySqlDouble(); case MySqlDbType.Set: case MySqlDbType.Enum: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: case MySqlDbType.Text: case MySqlDbType.TinyText: case MySqlDbType.MediumText: case MySqlDbType.LongText: case (MySqlDbType) Field_Type.NULL: return new MySqlString(type, true); case MySqlDbType.Geometry: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.TinyBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return new MySqlBinary(type, true); default: throw new MySqlException("Unknown data type"); } } } }
/* * StreamWriter.cs - Implementation of the "System.IO.StreamWriter" class. * * Copyright (C) 2001 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.IO { using System; using System.Globalization; using System.Text; public class StreamWriter : TextWriter { #if !ECMA_COMPAT // The null stream writer. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null); #endif // Default and minimum buffer sizes to use for streams. private const int STREAM_BUFSIZ = 1024; private const int FILE_BUFSIZ = 4096; private const int MIN_BUFSIZ = 128; // Internal state. private Stream stream; private Encoding encoding; private Encoder encoder; private int bufferSize; private char[] inBuffer; private int inBufferLen; private byte[] outBuffer; private bool autoFlush; private bool streamOwner; // Constructors that are based on a stream. public StreamWriter(Stream stream) : this(stream, new UTF8Encoding(false, true), STREAM_BUFSIZ) {} public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, STREAM_BUFSIZ) {} public StreamWriter(Stream stream, Encoding encoding, int bufferSize) { // Validate the parameters. if(stream == null) { throw new ArgumentNullException("stream"); } if(encoding == null) { throw new ArgumentNullException("encoding"); } if(!stream.CanWrite) { throw new ArgumentException(_("IO_NotSupp_Write")); } if(bufferSize <= 0) { throw new ArgumentOutOfRangeException ("bufferSize", _("ArgRange_BufferSize")); } if(bufferSize < MIN_BUFSIZ) { bufferSize = MIN_BUFSIZ; } // Initialize this object. this.stream = stream; this.encoding = encoding; this.encoder = encoding.GetEncoder(); this.bufferSize = bufferSize; this.inBuffer = new char [bufferSize]; this.inBufferLen = 0; this.outBuffer = new byte [encoding.GetMaxByteCount(bufferSize)]; this.autoFlush = false; this.streamOwner = false; // Write the encoding's preamble. WritePreamble(); } // Constructors that are based on a filename. public StreamWriter(String path) : this(path, false, new UTF8Encoding(false, true), STREAM_BUFSIZ) {} public StreamWriter(String path, bool append) : this(path, append, new UTF8Encoding(false, true), STREAM_BUFSIZ) {} public StreamWriter(String path, bool append, Encoding encoding) : this(path, append, encoding, STREAM_BUFSIZ) {} public StreamWriter(String path, bool append, Encoding encoding, int bufferSize) { // Validate the parameters. if(path == null) { throw new ArgumentNullException("path"); } if(encoding == null) { throw new ArgumentNullException("encoding"); } if(bufferSize <= 0) { throw new ArgumentOutOfRangeException ("bufferSize", _("ArgRange_BufferSize")); } if(bufferSize < MIN_BUFSIZ) { bufferSize = MIN_BUFSIZ; } // Attempt to open the file. Stream stream = new FileStream(path, (append ? FileMode.Append : FileMode.Create), FileAccess.Write, FileShare.Read, FILE_BUFSIZ); // Initialize this object. this.stream = stream; this.encoding = encoding; this.encoder = encoding.GetEncoder(); this.bufferSize = bufferSize; this.inBuffer = new char [bufferSize]; this.inBufferLen = 0; this.outBuffer = new byte [encoding.GetMaxByteCount(bufferSize)]; this.autoFlush = false; this.streamOwner = true; // Write the encoding's preamble. WritePreamble(); } // Destructor. ~StreamWriter() { Dispose(false); } // Write the encoding's preamble to the output stream. private void WritePreamble() { byte[] preamble = encoding.GetPreamble(); if(preamble != null) { stream.Write(preamble, 0, preamble.Length); } } // Close this stream writer. public override void Close() { #if !CONFIG_SMALL_CONSOLE // Mimic MS behavior if(stream is System.Private.StdStream) { return; } #endif // Explicit close if(stream != null) { Convert(true); stream.Flush(); stream.Close(); stream = null; } Dispose(true); } // Dispose this stream writer. protected override void Dispose(bool disposing) { if(stream != null) { Convert(true); stream.Flush(); // Close only if stream is Owned exclusively if(this.streamOwner) { stream.Close(); } stream = null; } inBuffer = null; inBufferLen = 0; outBuffer = null; bufferSize = 0; base.Dispose(disposing); } // Convert the contents of the input buffer and write them. private void Convert(bool flush) { if(inBufferLen > 0) { int len = encoder.GetBytes(inBuffer, 0, inBufferLen, outBuffer, 0, flush); if(len > 0) { stream.Write(outBuffer, 0, len); } inBufferLen = 0; } } // Flush the contents of the writer's buffer to the underlying stream. public override void Flush() { if(stream == null) { throw new ObjectDisposedException(_("IO_StreamClosed")); } Convert(false); stream.Flush(); } // Write a string to the stream writer. public override void Write(String value) { if(value == null) return; int temp; int index = 0; int count = value.Length; if(stream == null) { throw new ObjectDisposedException(_("IO_StreamClosed")); } while(count > 0) { temp = bufferSize - inBufferLen; if(temp > count) { temp = count; } value.CopyTo(index, inBuffer, inBufferLen, temp); index += temp; count -= temp; inBufferLen += temp; if(inBufferLen >= bufferSize) { Convert(false); } } if(autoFlush) { Convert(false); stream.Flush(); } } // Write a buffer of characters to this stream writer. public override void Write(char[] buffer, int index, int count) { if(stream == null) { throw new ObjectDisposedException(_("IO_StreamClosed")); } // Validate the parameters. if(buffer == null) { throw new ArgumentNullException("buffer"); } if(index < 0) { throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array")); } if(count < 0) { throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array")); } if((buffer.Length - index) < count) { throw new ArgumentException (_("Arg_InvalidArrayRange")); } // Copy the characters to the input buffer. int temp; while(count > 0) { temp = bufferSize - inBufferLen; if(temp > count) { temp = count; } Array.Copy(buffer, index, inBuffer, inBufferLen, temp); index += temp; count -= temp; inBufferLen += temp; if(inBufferLen >= bufferSize) { Convert(false); } } if(autoFlush) { Convert(false); if(stream == null) { throw new ObjectDisposedException(_("IO_StreamClosed")); } stream.Flush(); } } public override void Write(char[] buffer) { if(buffer == null) { throw new ArgumentNullException("buffer"); } Write(buffer, 0, buffer.Length); } // Write a single character to this stream writer. public override void Write(char value) { if(stream == null) { throw new ObjectDisposedException(_("IO_StreamClosed")); } inBuffer[inBufferLen++] = value; if(inBufferLen >= bufferSize) { Convert(false); } if(autoFlush) { Convert(false); stream.Flush(); } } // Get or set the autoflush state of this stream writer. public virtual bool AutoFlush { get { return autoFlush; } set { autoFlush = value; } } // Get the base stream underlying this stream writer. public virtual Stream BaseStream { get { this.streamOwner=false; return stream; } } // Get the current encoding in use by this stream writer. public override Encoding Encoding { get { return encoding; } } }; // class StreamWriter }; // namespace System.IO
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.3.7. Electronic Emissions. Abstract superclass for distirubted emissions PDU /// </summary> [Serializable] [XmlRoot] public partial class DistributedEmissionsFamilyPdu : Pdu, IEquatable<DistributedEmissionsFamilyPdu> { /// <summary> /// Initializes a new instance of the <see cref="DistributedEmissionsFamilyPdu"/> class. /// </summary> public DistributedEmissionsFamilyPdu() { ProtocolFamily = (byte)6; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(DistributedEmissionsFamilyPdu left, DistributedEmissionsFamilyPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(DistributedEmissionsFamilyPdu left, DistributedEmissionsFamilyPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); return marshalSize; } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public virtual void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<DistributedEmissionsFamilyPdu>"); base.Reflection(sb); try { sb.AppendLine("</DistributedEmissionsFamilyPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as DistributedEmissionsFamilyPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(DistributedEmissionsFamilyPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); return result; } } }
using System; using System.Collections; using System.Windows.Forms; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// /// </summary> public class TeachingOrderWLSearch : Search { // Search parameters private bool m_IncludeConsonant; private bool m_IncludeVowels; private bool m_IncludeTone; private bool m_IncludeSyllograph; private SyllographFeatures.SyllographType m_SType; private bool m_IgnoreTone; private string m_Title; private Settings m_Settings; private GraphemeInventory m_GI; //Search Definition tags private const string kIncludeC = "includeconsonant"; private const string kIncludeV = "includevowel"; private const string kIncludeT = "includetonet"; private const string kIncludeS = "includesyllograph"; private const string kSyllType = "syllographtype"; private const string kIgnoreTone = "ignoretone"; //private const string kTitle = "Teaching Order for Word List"; //private const string kInitOrder = "Initializing Consonant Teaching Order"; //private const string kSearch = "Processing Consonant Teaching Order"; public TeachingOrderWLSearch(int number, Settings s) : base(number, SearchDefinition.kOrderWL) { m_Settings = s; m_Title = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearchT"); if (m_Title == "") m_Title = "Teaching Order from Word List"; m_GI = m_Settings.GraphemeInventory; } public bool IncludeConsonant { get { return m_IncludeConsonant; } set { m_IncludeConsonant = value; } } public bool IncludeVowel { get { return m_IncludeVowels; } set { m_IncludeVowels = value; } } public bool IncludeTone { get { return m_IncludeTone; } set { m_IncludeTone = value; } } public bool IncludeSyllograph { get { return m_IncludeSyllograph; } set { m_IncludeSyllograph = value; } } public SyllographFeatures.SyllographType SType { get { return m_SType; } set { m_SType = value; } } public bool IgnoreTone { get { return m_IgnoreTone; } set { m_IgnoreTone = value; } } public string Title { get {return m_Title;} } public GraphemeInventory GI { get {return m_GI;} } public bool SetupSearch() { bool flag = false; FormTeachingOrder form = new FormTeachingOrder(m_Settings.LocalizationTable); DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { this.IncludeConsonant = form.IncludeConsonant; this.IncludeVowel = form.IncludeVowel; this.IncludeTone = form.IncludeTone; this.IncludeSyllograph = form.IncludeSyllograph; this.SType = form.SType; this.IgnoreTone = form.IgnoreTone; SearchDefinition sd = new SearchDefinition(SearchDefinition.kOrderWL); SearchDefinitionParm sdp = null; if (this.IncludeConsonant) { sdp = new SearchDefinitionParm(TeachingOrderWLSearch.kIncludeC); sd.AddSearchParm(sdp); } if (this.IncludeVowel) { sdp = new SearchDefinitionParm(TeachingOrderWLSearch.kIncludeV); sd.AddSearchParm(sdp); } if (this.IncludeTone) { sdp = new SearchDefinitionParm(TeachingOrderWLSearch.kIncludeT); sd.AddSearchParm(sdp); } if (this.IncludeSyllograph) { sdp = new SearchDefinitionParm(TeachingOrderWLSearch.kIncludeS); sd.AddSearchParm(sdp); sdp = new SearchDefinitionParm(TeachingOrderWLSearch.kSyllType, this.SType.ToString()); sd.AddSearchParm(sdp); } if (this.IgnoreTone) { sdp = new SearchDefinitionParm(TeachingOrderWLSearch.kIgnoreTone); sd.AddSearchParm(sdp); } this.SearchDefinition = sd; flag = true; } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = true; string strTag = ""; for (int i = 0; i < sd.SearchParmsCount(); i++) { strTag = sd.GetSearchParmAt(i).GetTag(); if (strTag == TeachingOrderWLSearch.kIncludeC) { this.IncludeConsonant = true; flag = true; } if (strTag == TeachingOrderWLSearch.kIncludeV) { this.IncludeVowel = true; flag = true; } if (strTag == TeachingOrderWLSearch.kIncludeT) { this.IncludeTone = true; flag = true; } if (strTag == TeachingOrderWLSearch.kIncludeS) { this.IncludeSyllograph = true; flag = true; } if (strTag == TeachingOrderWLSearch.kSyllType) { switch (sd.GetSearchParmContent(strTag)) { case "Pri": this.SType = SyllographFeatures.SyllographType.Pri; break; case "Sec": this.SType = SyllographFeatures.SyllographType.Sec; break; case "Ter": this.SType = SyllographFeatures.SyllographType.Ter; break; default: this.SType = SyllographFeatures.SyllographType.None; break; } if (strTag == TeachingOrderWLSearch.kIgnoreTone) { this.IgnoreTone = true; flag = true; } flag = true; } } this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string strSN = ""; if (this.SearchNumber > 0) { strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; } strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; if (this.SearchNumber > 0) strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser; return strText; } public TeachingOrderWLSearch ExecuteOrderSearch(WordList wl) { GraphemeInventory giTemp = new GraphemeInventory(m_Settings); //Temporary Inventory string strRslt = ""; if (this.IncludeConsonant) strRslt += ProcessConsonants(wl); //Processing teaching order for consonants if (this.IncludeVowel) strRslt += ProcessVowels(wl); //Processing teaching order for vowels if (this.IncludeTone) strRslt += ProcessTones(wl); if (this.IncludeSyllograph) { if (this.SType == SyllographFeatures.SyllographType.None) strRslt += ProcessSyllographs(wl); //Process teaching order for syllographs else strRslt += ProcessSyllographFeatures(wl, this.SType); } //Indicate number of words being processed string strText = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch3"); if (strText == "") strText = "words processed from text data"; strRslt += wl.WordCount().ToString() + Constants.Space + strText; this.SearchResults = strRslt; return this; } private string ProcessConsonants(WordList wl) //Process teaching order for consonants { GraphemeInventory giTemp = new GraphemeInventory(m_Settings); //Temporary Inventory string strRslt = ""; string strText = ""; string strMsg = ""; Word wrd = null; Consonant cns = null; FormProgressBar form = null; // Get consoansts in inventory for (int i = 0; i < this.GI.ConsonantCount(); i++) { cns = this.GI.GetConsonant(i); giTemp.AddConsonant(cns); } // Reset all words in word list to be initially available strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch1"); if (strMsg == "") strMsg = "Initializing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, wl.WordCount()); for (int i = 0; i < wl.WordCount(); i++) { form.PB_Update(i); wrd = wl.GetWord(i); wrd.Available = true; } form.Close(); //Process Consonant order int ndx = 0; int num = 0; strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch2"); if (strMsg == "") strMsg = "Processing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, giTemp.ConsonantCount()); while (giTemp.ConsonantCount() > 0) { form.PB_Update(ndx); giTemp = wl.UpdateConsonantCounts(giTemp, this.IgnoreTone); //Update Consonant Counts cns = wl.LeastUsedConsonant(giTemp); //Get least used consonant cns.TeachingOrder = giTemp.ConsonantCount(); num = this.GI.FindConsonantIndex(cns.Symbol); this.GI.UpdConsonant(num, cns); num = giTemp.FindConsonantIndex(cns.Symbol); strText = cns.Symbol + Environment.NewLine + strText; strText = cns.TeachingOrder.ToString().PadLeft(3) + " - " + strText; giTemp.DelConsonant(num); wl.UnAvailWordsWithConsonant(cns); ndx++; } //Consonants teaching order strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch4"); if (strMsg == "") strMsg = "Consonants"; strRslt += strMsg + Environment.NewLine + Environment.NewLine + strText; strRslt += Environment.NewLine; form.Close(); return strRslt; } private string ProcessVowels(WordList wl) //Process tewaching order for vowels { GraphemeInventory giTemp = new GraphemeInventory(m_Settings); //Temporary Inventory string strRslt = ""; string strText = ""; string strMsg = ""; Word wrd = null; Vowel vwl = null; FormProgressBar form = null; // Get vowels in inventory for (int i = 0; i < this.GI.VowelCount(); i++) { vwl = this.GI.GetVowel(i); giTemp.AddVowel(vwl); } // Reset all words in word list to be initially available strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch1"); if (strMsg == "") strMsg = "Initializing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, wl.WordCount()); for (int i = 0; i < wl.WordCount(); i++) { form.PB_Update(i); wrd = wl.GetWord(i); wrd.Available = true; } form.Close(); //Processing vowel order strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch2"); if (strMsg == "") strMsg = "Processing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, giTemp.VowelCount()); int ndx = 0; int num = 0; while (giTemp.VowelCount() > 0) { form.PB_Update(ndx); giTemp = wl.UpdateVowelCounts(giTemp, this.IgnoreTone); //Update Vowel Counts vwl = wl.LeastUsedVowel(giTemp); //Get least used vowel vwl.TeachingOrder = giTemp.VowelCount(); num = this.GI.FindVowelIndex(vwl.Symbol); this.GI.UpdVowel(num, vwl); num = giTemp.FindVowelIndex(vwl.Symbol); strText = vwl.Symbol + Environment.NewLine + strText; strText = vwl.TeachingOrder.ToString().PadLeft(3) + " - " + strText; giTemp.DelVowel(num); wl.UnAvailWordsWithVowel(vwl); ndx++; } // vowels Teaching order strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch5"); if (strMsg == "") strMsg = "Vowels"; strRslt += strMsg + Environment.NewLine + Environment.NewLine + strText; strRslt += Environment.NewLine; form.Close(); return strRslt; } private string ProcessTones(WordList wl) //Process teaching order for tones { GraphemeInventory giTemp = new GraphemeInventory(m_Settings); //Temporary Inventory string strRslt = ""; string strText = ""; string strMsg = ""; Word wrd = null; Tone tone = null;; FormProgressBar form = null; //Get tones in inventory for (int i = 0; i < this.GI.ToneCount(); i++) { tone = this.GI.GetTone(i); giTemp.AddTone(tone); } // Reset all words in word list to be initially available strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch1"); if (strMsg == "") strMsg = "Initializing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, wl.WordCount()); for (int i = 0; i < wl.WordCount(); i++) { form.PB_Update(i); wrd = wl.GetWord(i); wrd.Available = true; } form.Close(); //Processing tone order int ndx = 0; int num = 0; strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch2"); if (strMsg == "") strMsg = "Processing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, giTemp.ToneCount()); while (giTemp.ToneCount() > 0) { form.PB_Update(ndx); giTemp = wl.UpdateToneCounts(giTemp); //Update Tone Counts tone = wl.LeastUsedTone(giTemp); //Get least used tone tone.TeachingOrder = giTemp.ToneCount(); num = this.GI.FindToneIndex(tone.Symbol); this.GI.UpdTone(num, tone); num = giTemp.FindToneIndex(tone.Symbol); strText = tone.Symbol + Environment.NewLine + strText; strText = tone.TeachingOrder.ToString().PadLeft(3) + " - " + strText; giTemp.DelTone(num); wl.UnAvailWordsWithTone(tone); ndx++; } //Tones teaching order strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch6"); if (strMsg == "") strMsg = "Tones"; strRslt += strMsg + Environment.NewLine + Environment.NewLine + strText; strRslt += Environment.NewLine; form.Close(); return strRslt; } private string ProcessSyllographs(WordList wl) //Process teaching order for syllographs { GraphemeInventory giTemp = new GraphemeInventory(m_Settings); //Temporary Inventory string strRslt = ""; string strText = ""; string strMsg = ""; Word wrd = null; Syllograph syllograph = null; FormProgressBar form = null; // Get syllographs in inventory for (int i = 0; i < this.GI.SyllographCount(); i++) { syllograph = this.GI.GetSyllograph(i); giTemp.AddSyllograph(syllograph); } // Reset all words in word list to be initially available strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch1"); if (strMsg == "") strMsg = "Initializing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, wl.WordCount()); for (int i = 0; i < wl.WordCount(); i++) { form.PB_Update(i); wrd = wl.GetWord(i); wrd.Available = true; } form.Close(); // Process syllograph order int ndx = 0; int num = 0; strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch2"); if (strMsg == "") strMsg = "Processing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, giTemp.SyllographCount()); while (giTemp.SyllographCount() > 0) { form.PB_Update(ndx); giTemp = wl.UpdateSyllographCounts(giTemp); //Update syllabaries counts syllograph = wl.LeastUsedSyllograph(giTemp); //Get least used syllograph syllograph.TeachingOrder = giTemp.SyllographCount(); num = this.GI.FindSyllographIndex(syllograph.Symbol); this.GI.UpdSyllograph(num, syllograph); num = giTemp.FindSyllographIndex(syllograph.Symbol); strText = syllograph.Symbol + Environment.NewLine + strText; strText = syllograph.TeachingOrder.ToString().PadLeft(3) + " - " + strText; giTemp.DelSyllograph(num); wl.UnAvailWordsWithSyllograph(syllograph); ndx++; } // Syllograph teaching order strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch7"); if (strMsg == "") strMsg = "Syllographs"; strRslt += strMsg + Environment.NewLine + Environment.NewLine + strText; strRslt += Environment.NewLine; form.Close(); return strRslt; } private string ProcessSyllographFeatures(WordList wl, SyllographFeatures.SyllographType typ) //Process teaching order based upon syllograph type { SortedList slFeatures= new SortedList(); SyllographFeatureInfo info = null; string strRslt = ""; string strText = ""; string strMsg = ""; Word wrd = null; Syllograph syllograph = null; FormProgressBar form = null; // Get syllograph featuress from inventory string strFeature = ""; for (int i = 0; i < this.GI.SyllographCount(); i++) { syllograph = this.GI.GetSyllograph(i); if (typ == SyllographFeatures.SyllographType.Pri) { strFeature = syllograph.CategoryPrimary; info = new SyllographFeatureInfo(strFeature, SyllographFeatures.SyllographType.Pri); if (!slFeatures.ContainsKey(strFeature)) slFeatures.Add(strFeature, info); } else if (typ == SyllographFeatures.SyllographType.Sec) { strFeature = syllograph.CategorySecondary; info = new SyllographFeatureInfo(strFeature, SyllographFeatures.SyllographType.Sec); if (!slFeatures.ContainsKey(strFeature)) slFeatures.Add(strFeature, info); } else if (typ == SyllographFeatures.SyllographType.Ter) { strFeature = syllograph.CategoryTertiary; info = new SyllographFeatureInfo(strFeature, SyllographFeatures.SyllographType.Ter); if (!slFeatures.ContainsKey(strFeature)) slFeatures.Add(strFeature,info); } else { strFeature = syllograph.Symbol; info = new SyllographFeatureInfo(strFeature, SyllographFeatures.SyllographType.None); if (!slFeatures.ContainsKey(strFeature)) slFeatures.Add(strFeature,info); } } // Reset all words in word list to be initially available strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch1"); if (strMsg == "") strMsg = "Initializing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0, wl.WordCount()); for (int i = 0; i < wl.WordCount(); i++) { form.PB_Update(i); wrd = wl.GetWord(i); wrd.Available = true; } form.Close(); //Process syllograph feature order int ndx = 0; int num = 0; strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch2"); if (strMsg == "") strMsg = "Processing teaching order"; form = new FormProgressBar(strMsg); form.PB_Init(0,slFeatures.Count); while (num < slFeatures.Count ) { form.PB_Update(ndx); slFeatures = wl.UpdateSyllographFeaturesCounts(slFeatures, this.GI); //update feature counts info = wl.LeastUsedSyllographFeature(slFeatures); info.OrderNumber = slFeatures.Count - num; info.Available = false; slFeatures.Remove(info.Feature); slFeatures.Add(info.Feature, info); strText = info.Feature + Environment.NewLine + strText; strText = info.OrderNumber.ToString().PadLeft(3) + " - " + strText; wl.UnAvailWordsWithSyllographFeature(info.Type, info.Feature); num++; ndx++; } // Syllograph teaching order (features) strMsg = m_Settings.LocalizationTable.GetMessage("TeachingOrderWLSearch7"); if (strMsg == "") strMsg = "Syllographs"; strRslt += strMsg + Environment.NewLine + Environment.NewLine + strText; strRslt += Environment.NewLine; form.Close(); return strRslt; } } }
using System; using System.Threading.Tasks; using Cirrious.CrossCore; using Cirrious.MvvmCross.Touch.Views; using Cirrious.MvvmCross.ViewModels; using Foundation; using LocalAuthentication; using Microsoft.IdentityModel.Clients.ActiveDirectory; using MyHealth.Client.Core; using MyHealth.Client.Core.Helpers; using MyHealth.Client.Core.ServiceAgents; using MyHealth.Client.Core.Services; using MyHealth.Client.Core.ViewModels; using UIKit; using Xamarin.Forms; namespace MyHealth.Client.iOS { partial class MainView : MvxTabBarViewController<MainViewModel> { private static readonly UIFont Font = UIFont.FromName ("Avenir-Book", 10); private int _tabsCreatedSoFar = 0; public MainView(IntPtr handle) : base(handle) { } public async override void ViewDidLoad() { base.ViewDidLoad(); if (this.ViewModel == null) { return; } SetUpNavBar(); SetUpTabBar(); var appDelegate = (MyHealthAppDelegate) UIApplication.SharedApplication.Delegate; appDelegate.Tabs = this; if (Settings.SecurityEnabled) { if (Settings.TouchIdEnrolledAndFingerprintDetected) AuthenticateThroughFingerprint(); else await AuthenticateThroughAzureADAndAddFingerprintAsync(); } } private void AuthenticateThroughFingerprint() { var context = new LAContext(); NSError authError; var myReason = new NSString( "Please, provide your fingerprint to access the app."); if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError)) { var replyHandler = new LAContextReplyHandler((success, error) => { this.InvokeOnMainThread(async () => { if (success) { await AuthenticateThroughAzureADAsync(); return; } var dialogService = Mvx.Resolve<IDialogService>(); await dialogService.AlertAsync( "We could not detect your fingerprint. " + "You will be asked again to enter your Azure AD credentials. " + "Thank you.", "Touch ID", "OK"); // Since we're waking up, we need to silently sign in, and // sign out just after to clear local cache await AuthenticateThroughAzureADAsync (); SignOutFromAzureAD (); // If fingerprint not detected, repeat Azure AD auth. await AuthenticateThroughAzureADAndAddFingerprintAsync() .ConfigureAwait(false); }); }); context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler); } } void SignOutFromAzureAD () { var myHealthClient = Mvx.Resolve<IMyHealthClient> (); myHealthClient?.AuthenticationService?.SignOut (); } private async Task AuthenticateThroughAzureADAsync () { var authenticationParentUiContext = new PlatformParameters (this); var myHealthClient = Mvx.Resolve<IMyHealthClient> (); ViewModel.IsBusy = true; if (myHealthClient != null) await myHealthClient.AuthenticationService.SignInAsync (authenticationParentUiContext); ViewModel.IsBusy = false; } private async Task AuthenticateThroughAzureADAndAddFingerprintAsync () { await AuthenticateThroughAzureADAsync (); // If we went beyond this line the Azure AD auth. was a success AddFingerprintAuthentication(); } private void AddFingerprintAuthentication() { var context = new LAContext(); NSError authError; var myReason = new NSString( "Please, provide your fingerprint to simplify the authentication."); if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError)) { var replyHandler = new LAContextReplyHandler((success, error) => { this.InvokeOnMainThread(() => { var dialogService = Mvx.Resolve<IDialogService>(); if (success) { Settings.TouchIdEnrolledAndFingerprintDetected = true; dialogService.AlertAsync( "Your fingerprint was successfully detected. " + "You can access the app through it from now on. " + "Thank you.", "Touch ID", "OK"); } else { Settings.TouchIdEnrolledAndFingerprintDetected = false; dialogService.AlertAsync( "We could not detect your fingerprint. " + "You will need to authenticate through Azure AD. " + "Thank you.", "Touch ID", "OK"); } }); }); context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler); } } private void SetUpNavBar () { var newAppointmentButton = new UIBarButtonItem ( UIImage.FromBundle("ic_newappointment.png"), UIBarButtonItemStyle.Plain, (sender, args) => ViewModel.ShowNewAppointment()); NavigationController.NavigationBar.BarTintColor = UIColor.FromRGB(0, 199, 188); NavigationController.HidesBarsOnSwipe = true; NavigationItem.SetRightBarButtonItem (newAppointmentButton, true); } private void SetUpTabBar() { var viewControllers = new UIViewController[] { CreateTabFor("Home", "ic_home_", this.ViewModel.HomeViewModel), CreateTabFor("Appointments", "ic_appointment_", this.ViewModel.AppointmentsViewModel), CreateTabFor("Treatments", "ic_treatment_", this.ViewModel.TreatmentViewModel), CreateTabFor("User", "ic_user_", this.ViewModel.UserViewModel), CreateTabFor("Settings", "ic_setting_", this.ViewModel.SettingsViewModel) }; ViewControllers = viewControllers; CustomizableViewControllers = new UIViewController[] { }; SelectedViewController = ViewControllers[0]; Title = SelectedViewController.Title; TabBar.TintColor = Colors.Accent; NavigationItem.Title = SelectedViewController.Title; this.ViewControllerSelected += (o, e) => { NavigationItem.Title = TabBar.SelectedItem.Title; }; } private UIViewController CreateTabFor(string title, string imageName, IMvxViewModel viewModel) { UIViewController screen; if (viewModel.GetType() == typeof(SettingsViewModel)) { screen = new SettingsPage().CreateViewController(); } else { screen = this.CreateViewControllerFor(viewModel) as UIViewController; viewModel.Start(); } SetTitleAndTabBarItem(screen, title, imageName); return screen; } private void SetTitleAndTabBarItem(UIViewController screen, string title, string imageName) { screen.Title = title; screen.TabBarItem = new UITabBarItem( title, UIImage.FromBundle(imageName + "normal.png").ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), _tabsCreatedSoFar); screen.TabBarItem.SelectedImage = UIImage.FromBundle(imageName + "active.png") .ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); screen.TabBarItem.SetTitleTextAttributes ( new UITextAttributes { TextColor = Colors.TabBarNormalText, Font = Font }, UIControlState.Normal); screen.TabBarItem.SetTitleTextAttributes ( new UITextAttributes { TextColor = Colors.Accent, Font = Font }, UIControlState.Selected); _tabsCreatedSoFar++; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; namespace fyiReporting.RdlDesign { /// <summary> /// Summary description for ChartCtl. /// </summary> internal class ChartAxisCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; // change flags bool fMonth, fVisible, fMajorTickMarks, fMargin,fReverse,fInterlaced; bool fMajorGLWidth,fMajorGLColor,fMajorGLStyle; bool fMinorGLWidth,fMinorGLColor,fMinorGLStyle; bool fMajorInterval, fMinorInterval,fMax,fMin; bool fMinorTickMarks,fScalar,fLogScale,fMajorGLShow, fMinorGLShow, fCanOmit; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.CheckBox chkMonth; private System.Windows.Forms.CheckBox chkVisible; private System.Windows.Forms.ComboBox cbMajorTickMarks; private System.Windows.Forms.CheckBox chkMargin; private System.Windows.Forms.CheckBox chkReverse; private System.Windows.Forms.CheckBox chkInterlaced; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox tbMajorGLWidth; private System.Windows.Forms.Button bMajorGLColor; private System.Windows.Forms.ComboBox cbMajorGLColor; private System.Windows.Forms.ComboBox cbMajorGLStyle; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label3; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox tbMinorGLWidth; private System.Windows.Forms.Button bMinorGLColor; private System.Windows.Forms.ComboBox cbMinorGLColor; private System.Windows.Forms.ComboBox cbMinorGLStyle; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox tbMajorInterval; private System.Windows.Forms.TextBox tbMinorInterval; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox tbMax; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox tbMin; private System.Windows.Forms.Label label12; private System.Windows.Forms.ComboBox cbMinorTickMarks; private System.Windows.Forms.CheckBox chkScalar; private System.Windows.Forms.CheckBox chkLogScale; private System.Windows.Forms.CheckBox chkMajorGLShow; private System.Windows.Forms.CheckBox chkMinorGLShow; private System.Windows.Forms.Button bMinorIntervalExpr; private System.Windows.Forms.Button bMajorIntervalExpr; private System.Windows.Forms.Button bMinExpr; private System.Windows.Forms.Button bMaxExpr; private CheckBox chkCanOmit; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal ChartAxisCtl(DesignXmlDraw dxDraw, List<XmlNode> ris) { _ReportItems = ris; _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { cbMajorGLColor.Items.AddRange(StaticLists.ColorList); cbMinorGLColor.Items.AddRange(StaticLists.ColorList); XmlNode node = _ReportItems[0]; chkMonth.Checked = _Draw.GetElementValue(node, "fyi:Month", "false").ToLower() == "true" ? true : false; //added checkbox for month category axis WP 12 may 2008 chkVisible.Checked = _Draw.GetElementValue(node, "Visible", "false").ToLower() == "true"? true: false; chkMargin.Checked = _Draw.GetElementValue(node, "Margin", "false").ToLower() == "true"? true: false; chkReverse.Checked = _Draw.GetElementValue(node, "Reverse", "false").ToLower() == "true"? true: false; chkInterlaced.Checked = _Draw.GetElementValue(node, "Interlaced", "false").ToLower() == "true"? true: false; chkScalar.Checked = _Draw.GetElementValue(node, "Scalar", "false").ToLower() == "true"? true: false; chkLogScale.Checked = _Draw.GetElementValue(node, "LogScale", "false").ToLower() == "true"? true: false; chkCanOmit.Checked = _Draw.GetElementValue(node, "fyi:CanOmit", "false").ToLower() == "true" ? true : false; cbMajorTickMarks.Text = _Draw.GetElementValue(node, "MajorTickMarks", "None"); cbMinorTickMarks.Text = _Draw.GetElementValue(node, "MinorTickMarks", "None"); // Major Grid Lines InitGridLines(node, "MajorGridLines", chkMajorGLShow, cbMajorGLColor, cbMajorGLStyle, tbMajorGLWidth); // Minor Grid Lines InitGridLines(node, "MinorGridLines", chkMinorGLShow, cbMinorGLColor, cbMinorGLStyle, tbMinorGLWidth); tbMajorInterval.Text = _Draw.GetElementValue(node, "MajorInterval", ""); tbMinorInterval.Text = _Draw.GetElementValue(node, "MinorInterval", ""); tbMax.Text = _Draw.GetElementValue(node, "Max", ""); tbMin.Text = _Draw.GetElementValue(node, "Min", ""); fMonth = fVisible = fMajorTickMarks = fMargin=fReverse=fInterlaced= fMajorGLWidth=fMajorGLColor=fMajorGLStyle= fMinorGLWidth=fMinorGLColor=fMinorGLStyle= fMajorInterval= fMinorInterval=fMax=fMin= fMinorTickMarks=fScalar=fLogScale=fMajorGLShow=fMinorGLShow=fCanOmit=false; } private void InitGridLines(XmlNode node, string type, CheckBox show, ComboBox color, ComboBox style, TextBox width) { XmlNode m = _Draw.GetNamedChildNode(node, type); if (m != null) { show.Checked = _Draw.GetElementValue(m, "ShowGridLines", "false").ToLower() == "true"? true: false; XmlNode st = _Draw.GetNamedChildNode(m, "Style"); if (st != null) { XmlNode work = _Draw.GetNamedChildNode(st, "BorderColor"); if (work != null) color.Text = _Draw.GetElementValue(work, "Default", "Black"); work = _Draw.GetNamedChildNode(st, "BorderStyle"); if (work != null) style.Text = _Draw.GetElementValue(work, "Default", "Solid"); work = _Draw.GetNamedChildNode(st, "BorderWidth"); if (work != null) width.Text = _Draw.GetElementValue(work, "Default", "1pt"); } } if (color.Text.Length == 0) color.Text = "Black"; if (style.Text.Length == 0) style.Text = "Solid"; if (width.Text.Length == 0) width.Text = "1pt"; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.cbMajorTickMarks = new System.Windows.Forms.ComboBox(); this.cbMinorTickMarks = new System.Windows.Forms.ComboBox(); this.chkVisible = new System.Windows.Forms.CheckBox(); this.chkMargin = new System.Windows.Forms.CheckBox(); this.chkReverse = new System.Windows.Forms.CheckBox(); this.chkInterlaced = new System.Windows.Forms.CheckBox(); this.chkScalar = new System.Windows.Forms.CheckBox(); this.chkLogScale = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.chkMajorGLShow = new System.Windows.Forms.CheckBox(); this.tbMajorGLWidth = new System.Windows.Forms.TextBox(); this.bMajorGLColor = new System.Windows.Forms.Button(); this.cbMajorGLColor = new System.Windows.Forms.ComboBox(); this.cbMajorGLStyle = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.chkMinorGLShow = new System.Windows.Forms.CheckBox(); this.tbMinorGLWidth = new System.Windows.Forms.TextBox(); this.bMinorGLColor = new System.Windows.Forms.Button(); this.cbMinorGLColor = new System.Windows.Forms.ComboBox(); this.cbMinorGLStyle = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.tbMajorInterval = new System.Windows.Forms.TextBox(); this.tbMinorInterval = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.tbMax = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.tbMin = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.bMinorIntervalExpr = new System.Windows.Forms.Button(); this.bMajorIntervalExpr = new System.Windows.Forms.Button(); this.bMinExpr = new System.Windows.Forms.Button(); this.bMaxExpr = new System.Windows.Forms.Button(); this.chkCanOmit = new System.Windows.Forms.CheckBox(); this.chkMonth = new System.Windows.Forms.CheckBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(16, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(104, 16); this.label1.TabIndex = 1; this.label1.Text = "Major Tick Marks"; // // label2 // this.label2.Location = new System.Drawing.Point(224, 8); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(112, 16); this.label2.TabIndex = 3; this.label2.Text = "Minor Tick Marks"; // // cbMajorTickMarks // this.cbMajorTickMarks.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbMajorTickMarks.Items.AddRange(new object[] { "None", "Inside", "Outside", "Cross"}); this.cbMajorTickMarks.Location = new System.Drawing.Point(128, 8); this.cbMajorTickMarks.Name = "cbMajorTickMarks"; this.cbMajorTickMarks.Size = new System.Drawing.Size(80, 21); this.cbMajorTickMarks.TabIndex = 2; this.cbMajorTickMarks.SelectedIndexChanged += new System.EventHandler(this.cbMajorTickMarks_SelectedIndexChanged); // // cbMinorTickMarks // this.cbMinorTickMarks.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbMinorTickMarks.Items.AddRange(new object[] { "None", "Inside", "Outside", "Cross"}); this.cbMinorTickMarks.Location = new System.Drawing.Point(336, 8); this.cbMinorTickMarks.Name = "cbMinorTickMarks"; this.cbMinorTickMarks.Size = new System.Drawing.Size(80, 21); this.cbMinorTickMarks.TabIndex = 4; this.cbMinorTickMarks.SelectedIndexChanged += new System.EventHandler(this.cbMinorTickMarks_SelectedIndexChanged); // // chkVisible // this.chkVisible.Location = new System.Drawing.Point(24, 224); this.chkVisible.Name = "chkVisible"; this.chkVisible.Size = new System.Drawing.Size(88, 24); this.chkVisible.TabIndex = 19; this.chkVisible.Text = "Visible"; this.chkVisible.CheckedChanged += new System.EventHandler(this.chkVisible_CheckedChanged); // // chkMargin // this.chkMargin.Location = new System.Drawing.Point(240, 224); this.chkMargin.Name = "chkMargin"; this.chkMargin.Size = new System.Drawing.Size(60, 24); this.chkMargin.TabIndex = 21; this.chkMargin.Text = "Margin"; this.chkMargin.CheckedChanged += new System.EventHandler(this.chkMargin_CheckedChanged); // // chkReverse // this.chkReverse.Location = new System.Drawing.Point(108, 248); this.chkReverse.Name = "chkReverse"; this.chkReverse.Size = new System.Drawing.Size(120, 24); this.chkReverse.TabIndex = 23; this.chkReverse.Text = "Reverse Direction"; this.chkReverse.CheckedChanged += new System.EventHandler(this.chkReverse_CheckedChanged); // // chkInterlaced // this.chkInterlaced.Location = new System.Drawing.Point(240, 248); this.chkInterlaced.Name = "chkInterlaced"; this.chkInterlaced.Size = new System.Drawing.Size(88, 24); this.chkInterlaced.TabIndex = 23; this.chkInterlaced.Text = "Interlaced"; this.chkInterlaced.CheckedChanged += new System.EventHandler(this.chkInterlaced_CheckedChanged); // // chkScalar // this.chkScalar.Location = new System.Drawing.Point(24, 248); this.chkScalar.Name = "chkScalar"; this.chkScalar.Size = new System.Drawing.Size(72, 24); this.chkScalar.TabIndex = 22; this.chkScalar.Text = "Scalar"; this.chkScalar.CheckedChanged += new System.EventHandler(this.chkScalar_CheckedChanged); // // chkLogScale // this.chkLogScale.Location = new System.Drawing.Point(108, 224); this.chkLogScale.Name = "chkLogScale"; this.chkLogScale.Size = new System.Drawing.Size(120, 24); this.chkLogScale.TabIndex = 20; this.chkLogScale.Text = "Log Scale"; this.chkLogScale.CheckedChanged += new System.EventHandler(this.chkLogScale_CheckedChanged); // // groupBox1 // this.groupBox1.Controls.Add(this.chkMajorGLShow); this.groupBox1.Controls.Add(this.tbMajorGLWidth); this.groupBox1.Controls.Add(this.bMajorGLColor); this.groupBox1.Controls.Add(this.cbMajorGLColor); this.groupBox1.Controls.Add(this.cbMajorGLStyle); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Location = new System.Drawing.Point(16, 32); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(400, 48); this.groupBox1.TabIndex = 5; this.groupBox1.TabStop = false; this.groupBox1.Text = "Major Grid Lines"; // // chkMajorGLShow // this.chkMajorGLShow.Location = new System.Drawing.Point(8, 14); this.chkMajorGLShow.Name = "chkMajorGLShow"; this.chkMajorGLShow.Size = new System.Drawing.Size(56, 24); this.chkMajorGLShow.TabIndex = 0; this.chkMajorGLShow.Text = "Show"; this.chkMajorGLShow.CheckedChanged += new System.EventHandler(this.chkMajorGLShow_CheckedChanged); // // tbMajorGLWidth // this.tbMajorGLWidth.Location = new System.Drawing.Point(352, 16); this.tbMajorGLWidth.Name = "tbMajorGLWidth"; this.tbMajorGLWidth.Size = new System.Drawing.Size(40, 20); this.tbMajorGLWidth.TabIndex = 7; this.tbMajorGLWidth.TextChanged += new System.EventHandler(this.tbMajorGLWidth_TextChanged); // // bMajorGLColor // this.bMajorGLColor.Location = new System.Drawing.Point(288, 14); this.bMajorGLColor.Name = "bMajorGLColor"; this.bMajorGLColor.Size = new System.Drawing.Size(24, 24); this.bMajorGLColor.TabIndex = 5; this.bMajorGLColor.Text = "..."; this.bMajorGLColor.Click += new System.EventHandler(this.bMajorGLColor_Click); // // cbMajorGLColor // this.cbMajorGLColor.Location = new System.Drawing.Point(208, 16); this.cbMajorGLColor.Name = "cbMajorGLColor"; this.cbMajorGLColor.Size = new System.Drawing.Size(72, 21); this.cbMajorGLColor.TabIndex = 4; this.cbMajorGLColor.SelectedIndexChanged += new System.EventHandler(this.cbMajorGLColor_SelectedIndexChanged); // // cbMajorGLStyle // this.cbMajorGLStyle.Items.AddRange(new object[] { "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", "WindowInset", "Outset"}); this.cbMajorGLStyle.Location = new System.Drawing.Point(96, 16); this.cbMajorGLStyle.Name = "cbMajorGLStyle"; this.cbMajorGLStyle.Size = new System.Drawing.Size(72, 21); this.cbMajorGLStyle.TabIndex = 2; this.cbMajorGLStyle.SelectedIndexChanged += new System.EventHandler(this.cbMajorGLStyle_SelectedIndexChanged); // // label7 // this.label7.Location = new System.Drawing.Point(176, 18); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(32, 16); this.label7.TabIndex = 3; this.label7.Text = "Color"; this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label6 // this.label6.Location = new System.Drawing.Point(320, 18); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(36, 16); this.label6.TabIndex = 6; this.label6.Text = "Width"; this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label3 // this.label3.Location = new System.Drawing.Point(64, 18); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(36, 16); this.label3.TabIndex = 1; this.label3.Text = "Style"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // groupBox2 // this.groupBox2.Controls.Add(this.chkMinorGLShow); this.groupBox2.Controls.Add(this.tbMinorGLWidth); this.groupBox2.Controls.Add(this.bMinorGLColor); this.groupBox2.Controls.Add(this.cbMinorGLColor); this.groupBox2.Controls.Add(this.cbMinorGLStyle); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.label8); this.groupBox2.Location = new System.Drawing.Point(16, 88); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(400, 48); this.groupBox2.TabIndex = 6; this.groupBox2.TabStop = false; this.groupBox2.Text = "Minor Grid Lines"; // // chkMinorGLShow // this.chkMinorGLShow.Location = new System.Drawing.Point(8, 14); this.chkMinorGLShow.Name = "chkMinorGLShow"; this.chkMinorGLShow.Size = new System.Drawing.Size(56, 24); this.chkMinorGLShow.TabIndex = 0; this.chkMinorGLShow.Text = "Show"; this.chkMinorGLShow.CheckedChanged += new System.EventHandler(this.chkMinorGLShow_CheckedChanged); // // tbMinorGLWidth // this.tbMinorGLWidth.Location = new System.Drawing.Point(352, 16); this.tbMinorGLWidth.Name = "tbMinorGLWidth"; this.tbMinorGLWidth.Size = new System.Drawing.Size(40, 20); this.tbMinorGLWidth.TabIndex = 7; this.tbMinorGLWidth.TextChanged += new System.EventHandler(this.tbMinorGLWidth_TextChanged); // // bMinorGLColor // this.bMinorGLColor.Location = new System.Drawing.Point(288, 14); this.bMinorGLColor.Name = "bMinorGLColor"; this.bMinorGLColor.Size = new System.Drawing.Size(24, 24); this.bMinorGLColor.TabIndex = 5; this.bMinorGLColor.Text = "..."; this.bMinorGLColor.Click += new System.EventHandler(this.bMinorGLColor_Click); // // cbMinorGLColor // this.cbMinorGLColor.Location = new System.Drawing.Point(208, 16); this.cbMinorGLColor.Name = "cbMinorGLColor"; this.cbMinorGLColor.Size = new System.Drawing.Size(72, 21); this.cbMinorGLColor.TabIndex = 4; this.cbMinorGLColor.SelectedIndexChanged += new System.EventHandler(this.cbMinorGLColor_SelectedIndexChanged); // // cbMinorGLStyle // this.cbMinorGLStyle.Items.AddRange(new object[] { "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", "WindowInset", "Outset"}); this.cbMinorGLStyle.Location = new System.Drawing.Point(96, 16); this.cbMinorGLStyle.Name = "cbMinorGLStyle"; this.cbMinorGLStyle.Size = new System.Drawing.Size(72, 21); this.cbMinorGLStyle.TabIndex = 2; this.cbMinorGLStyle.SelectedIndexChanged += new System.EventHandler(this.cbMinorGLStyle_SelectedIndexChanged); // // label4 // this.label4.Location = new System.Drawing.Point(176, 18); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(40, 16); this.label4.TabIndex = 3; this.label4.Text = "Color"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label5 // this.label5.Location = new System.Drawing.Point(320, 18); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(36, 16); this.label5.TabIndex = 6; this.label5.Text = "Width"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label8 // this.label8.Location = new System.Drawing.Point(64, 18); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(40, 16); this.label8.TabIndex = 1; this.label8.Text = "Style"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label9 // this.label9.Location = new System.Drawing.Point(16, 154); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(80, 16); this.label9.TabIndex = 7; this.label9.Text = "Major Interval"; // // tbMajorInterval // this.tbMajorInterval.Location = new System.Drawing.Point(104, 152); this.tbMajorInterval.Name = "tbMajorInterval"; this.tbMajorInterval.Size = new System.Drawing.Size(65, 20); this.tbMajorInterval.TabIndex = 8; this.tbMajorInterval.TextChanged += new System.EventHandler(this.tbMajorInterval_TextChanged); // // tbMinorInterval // this.tbMinorInterval.Location = new System.Drawing.Point(302, 152); this.tbMinorInterval.Name = "tbMinorInterval"; this.tbMinorInterval.Size = new System.Drawing.Size(65, 20); this.tbMinorInterval.TabIndex = 11; this.tbMinorInterval.TextChanged += new System.EventHandler(this.tbMinorInterval_TextChanged); // // label10 // this.label10.Location = new System.Drawing.Point(217, 154); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(80, 16); this.label10.TabIndex = 10; this.label10.Text = "Minor Interval"; // // tbMax // this.tbMax.Location = new System.Drawing.Point(302, 182); this.tbMax.Name = "tbMax"; this.tbMax.Size = new System.Drawing.Size(65, 20); this.tbMax.TabIndex = 17; this.tbMax.TextChanged += new System.EventHandler(this.tbMax_TextChanged); // // label11 // this.label11.Location = new System.Drawing.Point(216, 184); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(84, 16); this.label11.TabIndex = 16; this.label11.Text = "Maximum Value"; // // tbMin // this.tbMin.Location = new System.Drawing.Point(104, 182); this.tbMin.Name = "tbMin"; this.tbMin.Size = new System.Drawing.Size(65, 20); this.tbMin.TabIndex = 14; this.tbMin.TextChanged += new System.EventHandler(this.tbMin_TextChanged); // // label12 // this.label12.Location = new System.Drawing.Point(16, 184); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(88, 16); this.label12.TabIndex = 13; this.label12.Text = "Minimum Value"; // // bMinorIntervalExpr // this.bMinorIntervalExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bMinorIntervalExpr.Location = new System.Drawing.Point(375, 154); this.bMinorIntervalExpr.Name = "bMinorIntervalExpr"; this.bMinorIntervalExpr.Size = new System.Drawing.Size(22, 16); this.bMinorIntervalExpr.TabIndex = 12; this.bMinorIntervalExpr.Tag = "minorinterval"; this.bMinorIntervalExpr.Text = "fx"; this.bMinorIntervalExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bMinorIntervalExpr.Click += new System.EventHandler(this.bExpr_Click); // // bMajorIntervalExpr // this.bMajorIntervalExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bMajorIntervalExpr.Location = new System.Drawing.Point(177, 154); this.bMajorIntervalExpr.Name = "bMajorIntervalExpr"; this.bMajorIntervalExpr.Size = new System.Drawing.Size(22, 16); this.bMajorIntervalExpr.TabIndex = 9; this.bMajorIntervalExpr.Tag = "majorinterval"; this.bMajorIntervalExpr.Text = "fx"; this.bMajorIntervalExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bMajorIntervalExpr.Click += new System.EventHandler(this.bExpr_Click); // // bMinExpr // this.bMinExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bMinExpr.Location = new System.Drawing.Point(177, 184); this.bMinExpr.Name = "bMinExpr"; this.bMinExpr.Size = new System.Drawing.Size(22, 16); this.bMinExpr.TabIndex = 15; this.bMinExpr.Tag = "min"; this.bMinExpr.Text = "fx"; this.bMinExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bMinExpr.Click += new System.EventHandler(this.bExpr_Click); // // bMaxExpr // this.bMaxExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bMaxExpr.Location = new System.Drawing.Point(376, 184); this.bMaxExpr.Name = "bMaxExpr"; this.bMaxExpr.Size = new System.Drawing.Size(22, 16); this.bMaxExpr.TabIndex = 18; this.bMaxExpr.Tag = "max"; this.bMaxExpr.Text = "fx"; this.bMaxExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bMaxExpr.Click += new System.EventHandler(this.bExpr_Click); // // chkCanOmit // this.chkCanOmit.Location = new System.Drawing.Point(334, 224); this.chkCanOmit.Name = "chkCanOmit"; this.chkCanOmit.Size = new System.Drawing.Size(93, 48); this.chkCanOmit.TabIndex = 24; this.chkCanOmit.Text = "Can Omit Values on Truncation"; this.chkCanOmit.CheckedChanged += new System.EventHandler(this.chkCanOmit_CheckedChanged); // // chkMonth // this.chkMonth.Location = new System.Drawing.Point(24, 272); this.chkMonth.Name = "chkMonth"; this.chkMonth.Size = new System.Drawing.Size(145, 24); this.chkMonth.TabIndex = 25; this.chkMonth.Text = "Month Category Scale"; this.chkMonth.CheckedChanged += new System.EventHandler(this.chkMonth_CheckedChanged); // // ChartAxisCtl // this.Controls.Add(this.chkMonth); this.Controls.Add(this.chkCanOmit); this.Controls.Add(this.bMaxExpr); this.Controls.Add(this.bMinExpr); this.Controls.Add(this.bMajorIntervalExpr); this.Controls.Add(this.bMinorIntervalExpr); this.Controls.Add(this.tbMax); this.Controls.Add(this.label11); this.Controls.Add(this.tbMin); this.Controls.Add(this.label12); this.Controls.Add(this.tbMinorInterval); this.Controls.Add(this.label10); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.chkLogScale); this.Controls.Add(this.chkScalar); this.Controls.Add(this.chkInterlaced); this.Controls.Add(this.chkReverse); this.Controls.Add(this.chkMargin); this.Controls.Add(this.chkVisible); this.Controls.Add(this.cbMinorTickMarks); this.Controls.Add(this.cbMajorTickMarks); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.tbMajorInterval); this.Controls.Add(this.label9); this.Name = "ChartAxisCtl"; this.Size = new System.Drawing.Size(440, 303); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public bool IsValid() { return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); fMonth = fVisible = fMajorTickMarks = fMargin=fReverse=fInterlaced= fMajorGLWidth=fMajorGLColor=fMajorGLStyle= fMinorGLWidth=fMinorGLColor=fMinorGLStyle= fMajorInterval= fMinorInterval=fMax=fMin= fMinorTickMarks=fScalar=fLogScale=fMajorGLShow=fMinorGLShow=fCanOmit=false; } public void ApplyChanges(XmlNode node) { if (fMonth) { _Draw.SetElement(node, "fyi:Month", this.chkMonth.Checked? "true" : "false"); } if (fVisible) { _Draw.SetElement(node, "Visible", this.chkVisible.Checked? "true": "false"); } if (fMajorTickMarks) { _Draw.SetElement(node, "MajorTickMarks", this.cbMajorTickMarks.Text); } if (fMargin) { _Draw.SetElement(node, "Margin", this.chkMargin.Checked? "true": "false"); } if (fReverse) { _Draw.SetElement(node, "Reverse", this.chkReverse.Checked? "true": "false"); } if (fInterlaced) { _Draw.SetElement(node, "Interlaced", this.chkInterlaced.Checked? "true": "false"); } if (fMajorGLShow || fMajorGLWidth || fMajorGLColor || fMajorGLStyle) { ApplyGridLines(node, "MajorGridLines", chkMajorGLShow, cbMajorGLColor, cbMajorGLStyle, tbMajorGLWidth); } if (fMinorGLShow || fMinorGLWidth || fMinorGLColor || fMinorGLStyle) { ApplyGridLines(node, "MinorGridLines", chkMinorGLShow, cbMinorGLColor, cbMinorGLStyle, tbMinorGLWidth); } if (fMajorInterval) { _Draw.SetElement(node, "MajorInterval", this.tbMajorInterval.Text); } if (fMinorInterval) { _Draw.SetElement(node, "MinorInterval", this.tbMinorInterval.Text); } if (fMax) { _Draw.SetElement(node, "Max", this.tbMax.Text); } if (fMin) { _Draw.SetElement(node, "Min", this.tbMin.Text); } if (fMinorTickMarks) { _Draw.SetElement(node, "MinorTickMarks", this.cbMinorTickMarks.Text); } if (fScalar) { _Draw.SetElement(node, "Scalar", this.chkScalar.Checked? "true": "false"); } if (fLogScale) { _Draw.SetElement(node, "LogScale", this.chkLogScale.Checked? "true": "false"); } if (fCanOmit) { _Draw.SetElement(node, "fyi:CanOmit", this.chkCanOmit.Checked ? "true" : "false"); } } private void ApplyGridLines(XmlNode node, string type, CheckBox show, ComboBox color, ComboBox style, TextBox width) { XmlNode m = _Draw.GetNamedChildNode(node, type); if (m == null) { m = _Draw.CreateElement(node, type, null); } _Draw.SetElement(m, "ShowGridLines", show.Checked? "true": "false"); XmlNode st = _Draw.GetNamedChildNode(m, "Style"); if (st == null) st = _Draw.CreateElement(m, "Style", null); XmlNode work = _Draw.GetNamedChildNode(st, "BorderColor"); if (work == null) work = _Draw.CreateElement(st, "BorderColor", null); _Draw.SetElement(work, "Default", color.Text); work = _Draw.GetNamedChildNode(st, "BorderStyle"); if (work == null) work = _Draw.CreateElement(st, "BorderStyle", null); _Draw.SetElement(work, "Default", style.Text); work = _Draw.GetNamedChildNode(st, "BorderWidth"); if (work == null) work = _Draw.CreateElement(st, "BorderWidth", null); _Draw.SetElement(work, "Default", width.Text); } private void cbMajorTickMarks_SelectedIndexChanged(object sender, System.EventArgs e) { fMajorTickMarks = true; } private void cbMinorTickMarks_SelectedIndexChanged(object sender, System.EventArgs e) { fMinorTickMarks = true; } private void cbMajorGLStyle_SelectedIndexChanged(object sender, System.EventArgs e) { fMajorGLStyle = true; } private void cbMajorGLColor_SelectedIndexChanged(object sender, System.EventArgs e) { fMajorGLColor = true; } private void tbMajorGLWidth_TextChanged(object sender, System.EventArgs e) { fMajorGLWidth = true; } private void cbMinorGLStyle_SelectedIndexChanged(object sender, System.EventArgs e) { fMinorGLStyle = true; } private void cbMinorGLColor_SelectedIndexChanged(object sender, System.EventArgs e) { fMinorGLColor = true; } private void tbMinorGLWidth_TextChanged(object sender, System.EventArgs e) { fMinorGLWidth = true; } private void tbMajorInterval_TextChanged(object sender, System.EventArgs e) { fMajorInterval = true; } private void tbMinorInterval_TextChanged(object sender, System.EventArgs e) { fMinorInterval = true; } private void tbMin_TextChanged(object sender, System.EventArgs e) { fMin = true; } private void tbMax_TextChanged(object sender, System.EventArgs e) { fMax = true; } private void chkMonth_CheckedChanged(object sender, System.EventArgs e) { fMonth = true; } private void chkVisible_CheckedChanged(object sender, System.EventArgs e) { fVisible = true; } private void chkLogScale_CheckedChanged(object sender, System.EventArgs e) { fLogScale = true; } private void chkCanOmit_CheckedChanged(object sender, System.EventArgs e) { fCanOmit = true; } private void chkMargin_CheckedChanged(object sender, System.EventArgs e) { fMargin = true; } private void chkScalar_CheckedChanged(object sender, System.EventArgs e) { fScalar = true; } private void chkReverse_CheckedChanged(object sender, System.EventArgs e) { fReverse = true; } private void chkInterlaced_CheckedChanged(object sender, System.EventArgs e) { fInterlaced = true; } private void chkMajorGLShow_CheckedChanged(object sender, System.EventArgs e) { fMajorGLShow = true; } private void chkMinorGLShow_CheckedChanged(object sender, System.EventArgs e) { fMinorGLShow = true; } private void bMajorGLColor_Click(object sender, System.EventArgs e) { SetColor(this.cbMajorGLColor); } private void bMinorGLColor_Click(object sender, System.EventArgs e) { SetColor(this.cbMinorGLColor); } private void SetColor(ComboBox cbColor) { ColorDialog cd = new ColorDialog(); cd.AnyColor = true; cd.FullOpen = true; cd.CustomColors = RdlDesigner.GetCustomColors(); cd.Color = DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Empty); try { if (cd.ShowDialog() != DialogResult.OK) return; RdlDesigner.SetCustomColors(cd.CustomColors); cbColor.Text = ColorTranslator.ToHtml(cd.Color); } finally { cd.Dispose(); } return; } private void bExpr_Click(object sender, System.EventArgs e) { Button b = sender as Button; if (b == null) return; Control c = null; bool bColor=false; switch (b.Tag as string) { case "min": c = this.tbMin; break; case "max": c = this.tbMax; break; case "majorinterval": c = this.tbMajorInterval; break; case "minorinterval": c = this.tbMinorInterval; break; } if (c == null) return; XmlNode sNode = _ReportItems[0]; DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor); try { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) c.Text = ee.Expression; } finally { ee.Dispose(); } return; } } }
#region License /* Copyright (c) 2006 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections.Generic; using System.Diagnostics; namespace Sanford.Collections.Generic { public partial class UndoableList<T> : IList<T> { [Conditional("DEBUG")] public static void Test() { int count = 10; List<int> comparisonList = new List<int>(count); UndoableList<int> undoList = new UndoableList<int>(count); PopulateLists(comparisonList, undoList, count); TestAdd(comparisonList, undoList); TestClear(comparisonList, undoList); TestInsert(comparisonList, undoList); TestInsertRange(comparisonList, undoList); TestRemove(comparisonList, undoList); TestRemoveAt(comparisonList, undoList); TestRemoveRange(comparisonList, undoList); TestReverse(comparisonList, undoList); } [Conditional("DEBUG")] private static void TestAdd(List<int> comparisonList, UndoableList<int> undoList) { TestEquals(comparisonList, undoList); Stack<int> redoStack = new Stack<int>(); while(comparisonList.Count > 0) { redoStack.Push(comparisonList[comparisonList.Count - 1]); comparisonList.RemoveAt(comparisonList.Count - 1); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); } while(redoStack.Count > 0) { comparisonList.Add(redoStack.Pop()); Debug.Assert(undoList.Redo()); TestEquals(comparisonList, undoList); } } [Conditional("DEBUG")] private static void TestClear(List<int> comparisonList, UndoableList<int> undoList) { TestEquals(comparisonList, undoList); undoList.Clear(); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); } [Conditional("DEBUG")] private static void TestInsert(List<int> comparisonList, UndoableList<int> undoList) { TestEquals(comparisonList, undoList); int index = comparisonList.Count / 2; comparisonList.Insert(index, 999); undoList.Insert(index, 999); comparisonList.RemoveAt(index); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); comparisonList.Insert(index, 999); Debug.Assert(undoList.Redo()); TestEquals(comparisonList, undoList); } [Conditional("DEBUG")] private static void TestInsertRange(List<int> comparisonList, UndoableList<int> undoList) { TestEquals(comparisonList, undoList); int[] range = { 1, 2, 3, 4, 5 }; int index = comparisonList.Count / 2; comparisonList.InsertRange(index, range); undoList.InsertRange(index, range); TestEquals(comparisonList, undoList); comparisonList.RemoveRange(index, range.Length); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); comparisonList.InsertRange(index, range); Debug.Assert(undoList.Redo()); TestEquals(comparisonList, undoList); } [Conditional("DEBUG")] private static void TestRemove(List<int> comparisonList, UndoableList<int> undoList) { TestEquals(comparisonList, undoList); int index = comparisonList.Count / 2; int item = comparisonList[index]; comparisonList.Remove(item); undoList.Remove(item); TestEquals(comparisonList, undoList); comparisonList.Insert(index, item); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); } [Conditional("DEBUG")] private static void TestRemoveAt(List<int> comparisonList, UndoableList<int> undoList) { TestEquals(comparisonList, undoList); int index = comparisonList.Count / 2; int item = comparisonList[index]; comparisonList.RemoveAt(index); undoList.RemoveAt(index); TestEquals(comparisonList, undoList); comparisonList.Insert(index, item); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); } [Conditional("DEBUG")] private static void TestRemoveRange(List<int> comparisonList, UndoableList<int> undoList) { TestEquals(comparisonList, undoList); int index = comparisonList.Count / 2; int count = comparisonList.Count - index; List<int> range = comparisonList.GetRange(index, count); comparisonList.RemoveRange(index, count); undoList.RemoveRange(index, count); TestEquals(comparisonList, undoList); comparisonList.InsertRange(index, range); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); } [Conditional("DEBUG")] private static void TestReverse(List<int> comparisonList, UndoableList<int> undoList) { TestEquals(comparisonList, undoList); comparisonList.Reverse(); undoList.Reverse(); TestEquals(comparisonList, undoList); comparisonList.Reverse(); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); comparisonList.Reverse(); Debug.Assert(undoList.Redo()); TestEquals(comparisonList, undoList); int count = comparisonList.Count / 2; comparisonList.Reverse(0, count); undoList.Reverse(0, count); TestEquals(comparisonList, undoList); comparisonList.Reverse(0, count); Debug.Assert(undoList.Undo()); TestEquals(comparisonList, undoList); comparisonList.Reverse(0, count); Debug.Assert(undoList.Redo()); TestEquals(comparisonList, undoList); } [Conditional("DEBUG")] private static void PopulateLists(IList<int> a, IList<int> b, int count) { Random r = new Random(); int item; for(int i = 0; i < count; i++) { item = r.Next(); a.Add(item); b.Add(item); } } [Conditional("DEBUG")] private static void TestEquals(ICollection<int> a, ICollection<int> b) { bool equals = true; if(a.Count != b.Count) { equals = false; } IEnumerator<int> aEnumerator = a.GetEnumerator(); IEnumerator<int> bEnumerator = b.GetEnumerator(); while(equals && aEnumerator.MoveNext() && bEnumerator.MoveNext()) { equals = aEnumerator.Current.Equals(bEnumerator.Current); } Debug.Assert(equals); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Some floating-point math operations ** ** ===========================================================*/ namespace System { //This class contains only static members and doesn't require serialization. using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public static class Math { private static double doubleRoundLimit = 1e16d; private const int maxRoundingDigits = 15; // This table is required for the Round function which can specify the number of digits to round to private static double[] roundPower10Double = new double[] { 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 }; public const double PI = 3.14159265358979323846; public const double E = 2.7182818284590452354; [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Acos(double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Asin(double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Atan(double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Atan2(double y,double x); public static Decimal Ceiling(Decimal d) { return Decimal.Ceiling(d); } [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Ceiling(double a); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Cos (double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Cosh(double value); public static Decimal Floor(Decimal d) { return Decimal.Floor(d); } [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Floor(double d); private static unsafe double InternalRound(double value, int digits, MidpointRounding mode) { if (Abs(value) < doubleRoundLimit) { Double power10 = roundPower10Double[digits]; value *= power10; if (mode == MidpointRounding.AwayFromZero) { double fraction = SplitFractionDouble(&value); if (Abs(fraction) >= 0.5d) { value += Sign(fraction); } } else { // On X86 this can be inlined to just a few instructions value = Round(value); } value /= power10; } return value; } private unsafe static double InternalTruncate(double d) { SplitFractionDouble(&d); return d; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sin(double a); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Tan(double a); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sinh(double value); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Tanh(double value); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Round(double a); public static double Round(double value, int digits) { if ((digits < 0) || (digits > maxRoundingDigits)) throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); Contract.EndContractBlock(); return InternalRound(value, digits, MidpointRounding.ToEven); } public static double Round(double value, MidpointRounding mode) { return Round(value, 0, mode); } public static double Round(double value, int digits, MidpointRounding mode) { if ((digits < 0) || (digits > maxRoundingDigits)) throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, nameof(MidpointRounding)), nameof(mode)); } Contract.EndContractBlock(); return InternalRound(value, digits, mode); } public static Decimal Round(Decimal d) { return Decimal.Round(d,0); } public static Decimal Round(Decimal d, int decimals) { return Decimal.Round(d,decimals); } public static Decimal Round(Decimal d, MidpointRounding mode) { return Decimal.Round(d, 0, mode); } public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) { return Decimal.Round(d, decimals, mode); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern double SplitFractionDouble(double* value); public static Decimal Truncate(Decimal d) { return Decimal.Truncate(d); } public static double Truncate(double d) { return InternalTruncate(d); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sqrt(double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Log (double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Log10(double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Exp(double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Pow(double x, double y); public static double IEEERemainder(double x, double y) { if (Double.IsNaN(x)) { return x; // IEEE 754-2008: NaN payload must be preserved } if (Double.IsNaN(y)) { return y; // IEEE 754-2008: NaN payload must be preserved } double regularMod = x % y; if (Double.IsNaN(regularMod)) { return Double.NaN; } if (regularMod == 0) { if (Double.IsNegative(x)) { return Double.NegativeZero; } } double alternativeResult; alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x)); if (Math.Abs(alternativeResult) == Math.Abs(regularMod)) { double divisionResult = x/y; double roundedResult = Math.Round(divisionResult); if (Math.Abs(roundedResult) > Math.Abs(divisionResult)) { return alternativeResult; } else { return regularMod; } } if (Math.Abs(alternativeResult) < Math.Abs(regularMod)) { return alternativeResult; } else { return regularMod; } } /*================================Abs========================================= **Returns the absolute value of it's argument. ============================================================================*/ [CLSCompliant(false)] public static sbyte Abs(sbyte value) { if (value >= 0) return value; else return AbsHelper(value); } private static sbyte AbsHelper(sbyte value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == SByte.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return ((sbyte)(-value)); } public static short Abs(short value) { if (value >= 0) return value; else return AbsHelper(value); } private static short AbsHelper(short value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int16.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return (short) -value; } public static int Abs(int value) { if (value >= 0) return value; else return AbsHelper(value); } private static int AbsHelper(int value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int32.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return -value; } public static long Abs(long value) { if (value >= 0) return value; else return AbsHelper(value); } private static long AbsHelper(long value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int64.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return -value; } [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static float Abs(float value); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static double Abs(double value); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; public static Decimal Abs(Decimal value) { return Decimal.Abs(value); } /*================================MAX========================================= **Returns the larger of val1 and val2 ============================================================================*/ [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static sbyte Max(sbyte val1, sbyte val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static byte Max(byte val1, byte val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static short Max(short val1, short val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ushort Max(ushort val1, ushort val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static int Max(int val1, int val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static uint Max(uint val1, uint val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static long Max(long val1, long val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ulong Max(ulong val1, ulong val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Max(float val1, float val2) { if (val1 > val2) return val1; if (Single.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static double Max(double val1, double val2) { if (val1 > val2) return val1; if (Double.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static Decimal Max(Decimal val1, Decimal val2) { return Decimal.Max(val1,val2); } /*================================MIN========================================= **Returns the smaller of val1 and val2. ============================================================================*/ [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static sbyte Min(sbyte val1, sbyte val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static byte Min(byte val1, byte val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static short Min(short val1, short val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ushort Min(ushort val1, ushort val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static int Min(int val1, int val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static uint Min(uint val1, uint val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static long Min(long val1, long val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ulong Min(ulong val1, ulong val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Min(float val1, float val2) { if (val1 < val2) return val1; if (Single.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static double Min(double val1, double val2) { if (val1 < val2) return val1; if (Double.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static Decimal Min(Decimal val1, Decimal val2) { return Decimal.Min(val1,val2); } /*=====================================Clamp==================================== ** ==============================================================================*/ [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Byte Clamp(Byte value, Byte min, Byte max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Decimal Clamp(Decimal value, Decimal min, Decimal max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Double Clamp(Double value, Double min, Double max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Int16 Clamp(Int16 value, Int16 min, Int16 max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Int32 Clamp(Int32 value, Int32 min, Int32 max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Int64 Clamp(Int64 value, Int64 min, Int64 max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static SByte Clamp(SByte value, SByte min, SByte max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Single Clamp(Single value, Single min, Single max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static UInt16 Clamp(UInt16 value, UInt16 min, UInt16 max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static UInt32 Clamp(UInt32 value, UInt32 min, UInt32 max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static UInt64 Clamp(UInt64 value, UInt64 min, UInt64 max) { if (min > max) ThrowMinMaxException(min, max); if (value < min) return min; else if (value > max) return max; return value; } private static void ThrowMinMaxException<T>(T min, T max) { throw new ArgumentException(Environment.GetResourceString("Argument_MinMaxValue", min, max)); } /*=====================================Log====================================== ** ==============================================================================*/ public static double Log(double a, double newBase) { if (Double.IsNaN(a)) { return a; // IEEE 754-2008: NaN payload must be preserved } if (Double.IsNaN(newBase)) { return newBase; // IEEE 754-2008: NaN payload must be preserved } if (newBase == 1) return Double.NaN; if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase))) return Double.NaN; return (Log(a)/Log(newBase)); } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. [CLSCompliant(false)] public static int Sign(sbyte value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. public static int Sign(short value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. public static int Sign(int value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static int Sign(long value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static int Sign (float value) { if (value < 0) return -1; else if (value > 0) return 1; else if (value == 0) return 0; throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN")); } public static int Sign(double value) { if (value < 0) return -1; else if (value > 0) return 1; else if (value == 0) return 0; throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN")); } public static int Sign(Decimal value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static long BigMul(int a, int b) { return ((long)a) * b; } public static int DivRem(int a, int b, out int result) { // TODO https://github.com/dotnet/coreclr/issues/3439: // Restore to using % and / when the JIT is able to eliminate one of the idivs. // In the meantime, a * and - is measurably faster than an extra /. int div = a / b; result = a - (div * b); return div; } public static long DivRem(long a, long b, out long result) { // TODO https://github.com/dotnet/coreclr/issues/3439: // Restore to using % and / when the JIT is able to eliminate one of the idivs. // In the meantime, a * and - is measurably faster than an extra /. long div = a / b; result = a - (div * b); return div; } } }
// <copyright file="Rfc6455Handler.cs" company="WebDriver Committers"> // Copyright 2007-2012 WebDriver committers // Copyright 2007-2012 Google Inc. // Portions copyright 2012 Software Freedom Conservancy // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace OpenQA.Selenium.Safari.Internal.Handlers { /// <summary> /// Provides a handler for the RFC 6455 version of the WebSocket protocol. /// </summary> internal class Rfc6455Handler : RequestHandler { private const string WebSocketResponseGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private WebSocketHttpRequest request; private ReadState readState = new ReadState(); /// <summary> /// Initializes a new instance of the <see cref="Rfc6455Handler"/> class. /// </summary> /// <param name="request">The <see cref="WebSocketHttpRequest"/> to handle.</param> private Rfc6455Handler(WebSocketHttpRequest request) { this.request = request; } /// <summary> /// Creates a new instance of the handler. /// </summary> /// <param name="request">The request to handle.</param> /// <returns>A <see cref="IHandler"/> to perform handling of subsequent requests.</returns> public static IHandler Create(WebSocketHttpRequest request) { return new Rfc6455Handler(request); } /// <summary> /// Receives data from the protocol. /// </summary> protected override void ProcessReceivedData() { while (Data.Count >= 2) { var isFinal = (Data[0] & 128) != 0; var reservedBits = Data[0] & 112; var frameType = (FrameType)(Data[0] & 15); var isMasked = (Data[1] & 128) != 0; var length = Data[1] & 127; if (!isMasked || !Enum.IsDefined(typeof(FrameType), frameType) || reservedBits != 0 // Must be zero per spec 5.2 || (frameType == FrameType.Continuation && !this.readState.FrameType.HasValue)) { throw new WebSocketException(WebSocketStatusCodes.ProtocolError); } var index = 2; int payloadLength; if (length == 127) { if (Data.Count < index + 8) { // Not complete return; } payloadLength = Data.Skip(index).Take(8).ToArray().ToLittleEndianInt32(); index += 8; } else if (length == 126) { if (Data.Count < index + 2) { // Not complete return; } payloadLength = Data.Skip(index).Take(2).ToArray().ToLittleEndianInt32(); index += 2; } else { payloadLength = length; } if (Data.Count < index + 4) { // Not complete return; } var maskBytes = Data.Skip(index).Take(4).ToArray(); index += 4; if (Data.Count < index + payloadLength) { // Not complete return; } var payload = Data .Skip(index) .Take(payloadLength) .Select((x, i) => (byte)(x ^ maskBytes[i % 4])); this.readState.Data.AddRange(payload); Data.RemoveRange(0, index + payloadLength); if (frameType != FrameType.Continuation) { this.readState.FrameType = frameType; } if (isFinal && this.readState.FrameType.HasValue) { var stateData = this.readState.Data.ToArray(); var stateFrameType = this.readState.FrameType; this.readState.Clear(); this.ProcessFrame(stateFrameType.Value, stateData); } } } /// <summary> /// Prepares a text frame for the given text. /// </summary> /// <param name="text">The text for which to prepare the frame.</param> /// <returns>A byte array representing the frame in the WebSocket protocol.</returns> protected override byte[] GetTextFrame(string text) { return ConstructFrame(Encoding.UTF8.GetBytes(text), FrameType.Text); } /// <summary> /// Prepares a close frame for the given connection. /// </summary> /// <param name="code">The code to use in closing the connection.</param> /// <returns>A byte array representing the frame in the WebSocket protocol.</returns> protected override byte[] GetCloseFrame(int code) { return ConstructFrame(Convert.ToUInt16(code).ToBigEndianByteArray(), FrameType.Close); } /// <summary> /// Gets the handshake for WebSocket protocol. /// </summary> /// <returns>A byte array representing the handshake in the WebSocket protocol.</returns> protected override byte[] GetHandshake() { var builder = new StringBuilder(); builder.Append("HTTP/1.1 101 Switching Protocols\r\n"); builder.Append("Upgrade: websocket\r\n"); builder.Append("Connection: Upgrade\r\n"); var responseKey = CreateResponseKey(this.request["Sec-WebSocket-Key"]); builder.AppendFormat("Sec-WebSocket-Accept: {0}\r\n", responseKey); builder.Append("\r\n"); return Encoding.ASCII.GetBytes(builder.ToString()); } /// <summary> /// Prepares a binary frame for the given binary data. /// </summary> /// <param name="frameData">The binary data for which to prepare the frame.</param> /// <returns>A byte array representing the frame in the WebSocket protocol.</returns> protected override byte[] GetBinaryFrame(byte[] frameData) { return ConstructFrame(frameData, FrameType.Binary); } private static byte[] ConstructFrame(byte[] payload, FrameType frameType) { var memoryStream = new MemoryStream(); byte op = Convert.ToByte(Convert.ToByte(frameType, CultureInfo.InvariantCulture) + 128, CultureInfo.InvariantCulture); memoryStream.WriteByte(op); if (payload.Length > ushort.MaxValue) { memoryStream.WriteByte(127); var lengthBytes = Convert.ToUInt64(payload.Length).ToBigEndianByteArray(); memoryStream.Write(lengthBytes, 0, lengthBytes.Length); } else if (payload.Length > 125) { memoryStream.WriteByte(126); var lengthBytes = Convert.ToUInt16(payload.Length).ToBigEndianByteArray(); memoryStream.Write(lengthBytes, 0, lengthBytes.Length); } else { memoryStream.WriteByte(Convert.ToByte(payload.Length, CultureInfo.InvariantCulture)); } memoryStream.Write(payload, 0, payload.Length); return memoryStream.ToArray(); } private static string CreateResponseKey(string requestKey) { var combined = requestKey + WebSocketResponseGuid; var bytes = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(combined)); return Convert.ToBase64String(bytes); } private static string ReadUTF8PayloadData(byte[] bytes) { var encoding = new UTF8Encoding(false, true); try { return encoding.GetString(bytes); } catch (ArgumentException) { throw new WebSocketException(WebSocketStatusCodes.InvalidFramePayloadData); } } private void ProcessFrame(FrameType frameType, byte[] data) { switch (frameType) { case FrameType.Close: if (data.Length == 1 || data.Length > 125) { throw new WebSocketException(WebSocketStatusCodes.ProtocolError); } if (data.Length >= 2) { var closeCode = Convert.ToUInt16(data.Take(2).ToArray().ToLittleEndianInt32(), CultureInfo.InvariantCulture); if (!WebSocketStatusCodes.ValidCloseCodes.Contains(closeCode) && (closeCode < 3000 || closeCode > 4999)) { throw new WebSocketException(WebSocketStatusCodes.ProtocolError); } } if (data.Length > 2) { ReadUTF8PayloadData(data.Skip(2).ToArray()); } this.OnCloseHandled(new EventArgs()); break; case FrameType.Binary: this.OnBinaryMessageHandled(new BinaryMessageHandledEventArgs(data)); break; case FrameType.Text: this.OnTextMessageHandled(new TextMessageHandledEventArgs(ReadUTF8PayloadData(data))); break; default: break; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; using UnityEngine.SceneManagement; namespace UnityTest.IntegrationTests { [Serializable] public class PlatformRunnerSettingsWindow : EditorWindow { private BuildTarget m_BuildTarget; private List<string> m_IntegrationTestScenes; private List<string> m_OtherScenesToBuild; private List<string> m_AllScenesInProject; private Vector2 m_ScrollPositionIntegrationTests; private Vector2 m_ScrollPositionOtherScenes; private Vector2 m_ScrollPositionAllScenes; private readonly List<string> m_Interfaces = new List<string>(); private readonly List<string> m_SelectedScenes = new List<string>(); private int m_SelectedInterface; [SerializeField] private bool m_AdvancedNetworkingSettings; private PlatformRunnerSettings m_Settings; private string m_SelectedSceneInAll; private string m_SelectedSceneInTest; private string m_SelectedSceneInBuild; readonly GUIContent m_Label = new GUIContent("Results target directory", "Directory where the results will be saved. If no value is specified, the results will be generated in project's data folder."); void Awake() { if (m_OtherScenesToBuild == null) m_OtherScenesToBuild = new List<string> (); if (m_IntegrationTestScenes == null) m_IntegrationTestScenes = new List<string> (); titleContent = new GUIContent("Platform runner"); m_BuildTarget = PlatformRunner.defaultBuildTarget; position.Set(position.xMin, position.yMin, 200, position.height); m_AllScenesInProject = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.unity", SearchOption.AllDirectories).ToList(); m_AllScenesInProject.Sort(); var currentScene = (Directory.GetCurrentDirectory() + SceneManager.GetActiveScene().path).Replace("\\", "").Replace("/", ""); var currentScenePath = m_AllScenesInProject.Where(s => s.Replace("\\", "").Replace("/", "") == currentScene); m_SelectedScenes.AddRange(currentScenePath); m_Interfaces.Add("(Any)"); m_Interfaces.AddRange(TestRunnerConfigurator.GetAvailableNetworkIPs()); m_Interfaces.Add("127.0.0.1"); LoadFromPrefereneces (); } public void OnEnable() { m_Settings = ProjectSettingsBase.Load<PlatformRunnerSettings>(); // If not configured pre populate with all scenes that have test components on game objects // This needs to be done outsie of constructor if (m_IntegrationTestScenes.Count == 0) m_IntegrationTestScenes = GetScenesWithTestComponents (m_AllScenesInProject); } public void OnGUI() { EditorGUILayout.BeginVertical(); GUIContent label; /* We have three lists here, The tests to run, supporting scenes to include in the build and the list of all scenes so users can * pick the scenes they want to include. The motiviation here is that test scenes may require to additively load other scenes as part of the tests */ EditorGUILayout.BeginHorizontal (); // Integration Tests To Run EditorGUILayout.BeginVertical (); label = new GUIContent("Tests:", "All Integration Test scenes that you wish to run on the platform"); EditorGUILayout.LabelField(label, EditorStyles.boldLabel, GUILayout.Height(20f)); EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_SelectedSceneInTest)); if (GUILayout.Button("Remove Integration Test")) { m_IntegrationTestScenes.Remove(m_SelectedSceneInTest); m_SelectedSceneInTest = ""; } EditorGUI.EndDisabledGroup(); DrawVerticalSceneList (ref m_IntegrationTestScenes, ref m_SelectedSceneInTest, ref m_ScrollPositionIntegrationTests); EditorGUILayout.EndVertical (); // Extra scenes to include in build EditorGUILayout.BeginVertical (); label = new GUIContent("Other Scenes in Build:", "If your Integration Tests additivly load any other scenes then you want to include them here so they are part of the build"); EditorGUILayout.LabelField(label, EditorStyles.boldLabel, GUILayout.Height(20f)); EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_SelectedSceneInBuild)); if (GUILayout.Button("Remove From Build")) { m_OtherScenesToBuild.Remove(m_SelectedSceneInBuild); m_SelectedSceneInBuild = ""; } EditorGUI.EndDisabledGroup(); DrawVerticalSceneList (ref m_OtherScenesToBuild, ref m_SelectedSceneInBuild, ref m_ScrollPositionOtherScenes); EditorGUILayout.EndVertical (); EditorGUILayout.Separator (); // All Scenes EditorGUILayout.BeginVertical (); label = new GUIContent("Available Scenes", "These are all the scenes within your project, please select some to run tests"); EditorGUILayout.LabelField(label, EditorStyles.boldLabel, GUILayout.Height(20f)); EditorGUILayout.BeginHorizontal (); EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_SelectedSceneInAll)); if (GUILayout.Button("Add As Test")) { if (!m_IntegrationTestScenes.Contains (m_SelectedSceneInAll) && !m_OtherScenesToBuild.Contains (m_SelectedSceneInAll)) { m_IntegrationTestScenes.Add(m_SelectedSceneInAll); } } if (GUILayout.Button("Add to Build")) { if (!m_IntegrationTestScenes.Contains (m_SelectedSceneInAll) && !m_OtherScenesToBuild.Contains (m_SelectedSceneInAll)) { m_OtherScenesToBuild.Add(m_SelectedSceneInAll); } } EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal (); DrawVerticalSceneList (ref m_AllScenesInProject, ref m_SelectedSceneInAll, ref m_ScrollPositionAllScenes); EditorGUILayout.EndVertical (); // ButtoNetworkResultsReceiverns to edit scenes in lists EditorGUILayout.EndHorizontal (); GUILayout.Space(3); // Select target platform m_BuildTarget = (BuildTarget)EditorGUILayout.EnumPopup("Build tests for", m_BuildTarget); if (PlatformRunner.defaultBuildTarget != m_BuildTarget) { if (GUILayout.Button("Make default target platform")) { PlatformRunner.defaultBuildTarget = m_BuildTarget; } } GUI.enabled = true; // Select various Network settings DrawSetting(); var build = GUILayout.Button("Build and run tests"); EditorGUILayout.EndVertical(); if (build) { BuildAndRun (); } } private void DrawVerticalSceneList(ref List<string> sourceList, ref string selectString, ref Vector2 scrollPosition) { scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, Styles.testList); EditorGUI.indentLevel++; foreach (var scenePath in sourceList) { var path = Path.GetFileNameWithoutExtension(scenePath); var guiContent = new GUIContent(path, scenePath); var rect = GUILayoutUtility.GetRect(guiContent, EditorStyles.label); if (rect.Contains(Event.current.mousePosition)) { if (Event.current.type == EventType.MouseDown && Event.current.button == 0) { selectString = scenePath; Event.current.Use(); } } var style = new GUIStyle(EditorStyles.label); if (selectString == scenePath) style.normal.textColor = new Color(0.3f, 0.5f, 0.85f); EditorGUI.LabelField(rect, guiContent, style); } EditorGUI.indentLevel--; EditorGUILayout.EndScrollView(); } public static List<string> GetScenesWithTestComponents(List<string> allScenes) { List<Object> results = EditorReferencesUtil.FindScenesWhichContainAsset("TestComponent.cs"); List<string> integrationTestScenes = new List<string>(); foreach (Object obj in results) { string result = allScenes.FirstOrDefault(s => s.Contains(obj.name)); if (!string.IsNullOrEmpty(result)) integrationTestScenes.Add(result); } return integrationTestScenes; } private void DrawSetting() { EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginHorizontal(); m_Settings.resultsPath = EditorGUILayout.TextField(m_Label, m_Settings.resultsPath); if (GUILayout.Button("Search", EditorStyles.miniButton, GUILayout.Width(50))) { var selectedPath = EditorUtility.SaveFolderPanel("Result files destination", m_Settings.resultsPath, ""); if (!string.IsNullOrEmpty(selectedPath)) m_Settings.resultsPath = Path.GetFullPath(selectedPath); } EditorGUILayout.EndHorizontal(); if (!string.IsNullOrEmpty(m_Settings.resultsPath)) { Uri uri; if (!Uri.TryCreate(m_Settings.resultsPath, UriKind.Absolute, out uri) || !uri.IsFile || uri.IsWellFormedOriginalString()) { EditorGUILayout.HelpBox("Invalid URI path", MessageType.Warning); } } m_Settings.sendResultsOverNetwork = EditorGUILayout.Toggle("Send results to editor", m_Settings.sendResultsOverNetwork); EditorGUI.BeginDisabledGroup(!m_Settings.sendResultsOverNetwork); m_AdvancedNetworkingSettings = EditorGUILayout.Foldout(m_AdvancedNetworkingSettings, "Advanced network settings"); if (m_AdvancedNetworkingSettings) { m_SelectedInterface = EditorGUILayout.Popup("Network interface", m_SelectedInterface, m_Interfaces.ToArray()); EditorGUI.BeginChangeCheck(); m_Settings.port = EditorGUILayout.IntField("Network port", m_Settings.port); if (EditorGUI.EndChangeCheck()) { if (m_Settings.port > IPEndPoint.MaxPort) m_Settings.port = IPEndPoint.MaxPort; else if (m_Settings.port < IPEndPoint.MinPort) m_Settings.port = IPEndPoint.MinPort; } } EditorGUI.EndDisabledGroup(); if (EditorGUI.EndChangeCheck()) { m_Settings.Save(); } } private void BuildAndRun() { SaveToPreferences (); var config = new PlatformRunnerConfiguration { buildTarget = m_BuildTarget, buildScenes = m_OtherScenesToBuild, testScenes = m_IntegrationTestScenes, projectName = m_IntegrationTestScenes.Count > 1 ? "IntegrationTests" : Path.GetFileNameWithoutExtension(SceneManager.GetActiveScene().path), resultsDir = m_Settings.resultsPath, sendResultsOverNetwork = m_Settings.sendResultsOverNetwork, ipList = m_Interfaces.Skip(1).ToList(), port = m_Settings.port }; if (m_SelectedInterface > 0) config.ipList = new List<string> {m_Interfaces.ElementAt(m_SelectedInterface)}; PlatformRunner.BuildAndRunInPlayer(config); Close (); } public void OnLostFocus() { SaveToPreferences (); } public void OnDestroy() { SaveToPreferences (); } private void SaveToPreferences() { EditorPrefs.SetString (Animator.StringToHash (Application.dataPath + "uttTestScenes").ToString (), String.Join (",",m_IntegrationTestScenes.ToArray())); EditorPrefs.SetString (Animator.StringToHash (Application.dataPath + "uttBuildScenes").ToString (), String.Join (",",m_OtherScenesToBuild.ToArray())); } private void LoadFromPrefereneces() { string storedTestScenes = EditorPrefs.GetString (Animator.StringToHash (Application.dataPath + "uttTestScenes").ToString ()); string storedBuildScenes = EditorPrefs.GetString (Animator.StringToHash (Application.dataPath + "uttBuildScenes").ToString ()); List<string> parsedTestScenes = storedTestScenes.Split (',').ToList (); List<string> parsedBuildScenes = storedBuildScenes.Split (',').ToList (); // Sanity check scenes actually exist foreach (string str in parsedTestScenes) { if (m_AllScenesInProject.Contains(str)) m_IntegrationTestScenes.Add(str); } foreach (string str in parsedBuildScenes) { if (m_AllScenesInProject.Contains(str)) m_OtherScenesToBuild.Add(str); } } } }
using System; using Bridge.Contract; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem.Implementation; using System.Collections.Generic; using System.Linq; namespace Bridge.Translator { public class ArgumentsInfo { public IEmitter Emitter { get; private set; } public Expression Expression { get; private set; } public InvocationResolveResult ResolveResult { get; private set; } public OperatorResolveResult OperatorResolveResult { get; private set; } public Expression[] ArgumentsExpressions { get; set; } public string[] ArgumentsNames { get; set; } public Expression ParamsExpression { get; private set; } public NamedParamExpression[] NamedExpressions { get; set; } public TypeParamExpression[] TypeArguments { get; private set; } public object ThisArgument { get; set; } public string ThisName { get; set; } public bool IsExtensionMethod { get; set; } public bool HasTypeArguments { get; set; } public IMethod Method { get; private set; } public IAttribute Attribute { get; set; } public string[] StringArguments { get; set; } public IType ThisType { get; set; } public ArgumentsInfo(IEmitter emitter, IMethod method) { this.Emitter = emitter; this.Expression = null; this.Method = method; this.BuildTypedArguments(method); } public ArgumentsInfo(IEmitter emitter, IAttribute attr) { this.Emitter = emitter; this.Expression = null; this.Attribute = attr; } public ArgumentsInfo(IEmitter emitter, string[] args) { this.Emitter = emitter; this.Expression = null; this.StringArguments = args; } public ArgumentsInfo(IEmitter emitter, ConstructorInitializer initializer) { this.Emitter = emitter; this.Expression = null; var arguments = initializer.Arguments.ToList(); this.ResolveResult = emitter.Resolver.ResolveNode(initializer, emitter) as InvocationResolveResult; this.BuildArgumentsList(arguments); if (this.ResolveResult != null) { this.HasTypeArguments = ((IMethod)this.ResolveResult.Member).TypeArguments.Count > 0; } } public ArgumentsInfo(IEmitter emitter, InvocationExpression invocationExpression, IMethod method = null) { this.Emitter = emitter; this.Expression = invocationExpression; var arguments = invocationExpression.Arguments.ToList(); var rr = emitter.Resolver.ResolveNode(invocationExpression, emitter); this.ResolveResult = rr as InvocationResolveResult; var drr = rr as DynamicInvocationResolveResult; if (this.ResolveResult == null && drr != null) { this.BuildDynamicArgumentsList(drr, arguments); } else { this.BuildArgumentsList(arguments); } if (this.ResolveResult != null) { this.HasTypeArguments = ((IMethod)this.ResolveResult.Member).TypeArguments.Count > 0; this.BuildTypedArguments(invocationExpression.Target); } if (method != null && method.Parameters.Count > 0) { this.ThisArgument = invocationExpression; var name = method.Parameters[0].Name; if (!this.ArgumentsNames.Contains(name)) { var list = this.ArgumentsNames.ToList(); list.Add(name); this.ArgumentsNames = list.ToArray(); var expr = this.ArgumentsExpressions.ToList(); expr.Insert(0, invocationExpression); this.ArgumentsExpressions = expr.ToArray(); var namedExpr = this.NamedExpressions.ToList(); namedExpr.Insert(0, new NamedParamExpression(name, invocationExpression)); this.NamedExpressions = namedExpr.ToArray(); } } } public ArgumentsInfo(IEmitter emitter, IndexerExpression invocationExpression, InvocationResolveResult rr = null) { this.Emitter = emitter; this.Expression = invocationExpression; var arguments = invocationExpression.Arguments.ToList(); this.ResolveResult = rr ?? emitter.Resolver.ResolveNode(invocationExpression, emitter) as InvocationResolveResult; this.BuildArgumentsList(arguments); if (this.ResolveResult != null) { this.BuildTypedArguments(this.ResolveResult.Member); } } public ArgumentsInfo(IEmitter emitter, Expression expression, InvocationResolveResult rr) { this.Emitter = emitter; this.Expression = expression; this.ResolveResult = rr; this.ArgumentsExpressions = new Expression[] { expression }; this.ArgumentsNames = new string[] { rr.Member.Parameters.Count > 0 ? rr.Member.Parameters.First().Name : "{this}" }; this.ThisArgument = expression; this.NamedExpressions = this.CreateNamedExpressions(this.ArgumentsNames, this.ArgumentsExpressions); this.BuildTypedArguments(rr.Member); } public ArgumentsInfo(IEmitter emitter, Expression expression, IMethod method) { this.Emitter = emitter; this.Expression = expression; this.ArgumentsExpressions = new Expression[] { expression }; this.ArgumentsNames = new string[] {method.Parameters.Count > 0 ? method.Parameters.First().Name : "{this}" }; this.ThisArgument = expression; this.NamedExpressions = this.CreateNamedExpressions(this.ArgumentsNames, this.ArgumentsExpressions); this.BuildTypedArguments(method); } public ArgumentsInfo(IEmitter emitter, Expression expression, ResolveResult rr = null) { this.Emitter = emitter; this.Expression = expression; this.ArgumentsExpressions = new Expression[] { expression }; this.ArgumentsNames = new string[] { "{this}" }; this.ThisArgument = expression; this.NamedExpressions = this.CreateNamedExpressions(this.ArgumentsNames, this.ArgumentsExpressions); if (rr is MemberResolveResult) { this.BuildTypedArguments(((MemberResolveResult)rr).Member); } } public ArgumentsInfo(IEmitter emitter, ObjectCreateExpression objectCreateExpression, IMethod method = null) { this.Emitter = emitter; this.Expression = objectCreateExpression; var arguments = objectCreateExpression.Arguments.ToList(); var rr = emitter.Resolver.ResolveNode(objectCreateExpression, emitter); var drr = rr as DynamicInvocationResolveResult; if (drr != null) { var group = drr.Target as MethodGroupResolveResult; if (group != null && group.Methods.Count() > 1) { throw new EmitterException(objectCreateExpression, Bridge.Translator.Constants.Messages.Exceptions.DYNAMIC_INVOCATION_TOO_MANY_OVERLOADS); } } this.ResolveResult = rr as InvocationResolveResult; this.BuildArgumentsList(arguments); this.BuildTypedArguments(objectCreateExpression.Type); if (method != null && method.Parameters.Count > 0) { this.ThisArgument = objectCreateExpression; var name = method.Parameters[0].Name; if (!this.ArgumentsNames.Contains(name)) { var list = this.ArgumentsNames.ToList(); list.Add(name); this.ArgumentsNames = list.ToArray(); var expr = this.ArgumentsExpressions.ToList(); expr.Add(objectCreateExpression); this.ArgumentsExpressions = expr.ToArray(); var namedExpr = this.NamedExpressions.ToList(); namedExpr.Add(new NamedParamExpression(name, objectCreateExpression)); this.NamedExpressions = namedExpr.ToArray(); } } } public ArgumentsInfo(IEmitter emitter, AssignmentExpression assignmentExpression, OperatorResolveResult operatorResolveResult, IMethod method) { this.Emitter = emitter; this.Expression = assignmentExpression; this.OperatorResolveResult = operatorResolveResult; this.BuildOperatorArgumentsList(new Expression[] { assignmentExpression.Left, assignmentExpression.Right }, operatorResolveResult.UserDefinedOperatorMethod ?? method); this.BuildOperatorTypedArguments(); } public ArgumentsInfo(IEmitter emitter, BinaryOperatorExpression binaryOperatorExpression, OperatorResolveResult operatorResolveResult, IMethod method) { this.Emitter = emitter; this.Expression = binaryOperatorExpression; this.OperatorResolveResult = operatorResolveResult; this.BuildOperatorArgumentsList(new Expression[] { binaryOperatorExpression.Left, binaryOperatorExpression.Right }, operatorResolveResult.UserDefinedOperatorMethod ?? method); this.BuildOperatorTypedArguments(); } public ArgumentsInfo(IEmitter emitter, UnaryOperatorExpression unaryOperatorExpression, OperatorResolveResult operatorResolveResult, IMethod method) { this.Emitter = emitter; this.Expression = unaryOperatorExpression; this.OperatorResolveResult = operatorResolveResult; this.BuildOperatorArgumentsList(new Expression[] { unaryOperatorExpression.Expression }, operatorResolveResult.UserDefinedOperatorMethod ?? method); this.BuildOperatorTypedArguments(); } private void BuildTypedArguments(AstType type) { var simpleType = type as SimpleType; if (simpleType != null) { AstNodeCollection<AstType> typedArguments = simpleType.TypeArguments; IList<ITypeParameter> typeParams = null; if (this.ResolveResult.Member.DeclaringTypeDefinition != null) { typeParams = this.ResolveResult.Member.DeclaringTypeDefinition.TypeParameters; } else if (this.ResolveResult.Member is SpecializedMethod) { typeParams = ((SpecializedMethod)this.ResolveResult.Member).TypeParameters; } this.TypeArguments = new TypeParamExpression[typedArguments.Count]; var list = typedArguments.ToList(); for (int i = 0; i < list.Count; i++) { this.TypeArguments[i] = new TypeParamExpression(typeParams[i].Name, list[i], null); } } } private void BuildTypedArguments(IMember member) { var typeParams = member.DeclaringTypeDefinition.TypeParameters; var typeArgs = member.DeclaringType.TypeArguments; var temp = new TypeParamExpression[typeParams.Count]; for (int i = 0; i < typeParams.Count; i++) { temp[i] = new TypeParamExpression(typeParams[i].Name, null, typeArgs[i], true); } this.TypeArguments = temp; } private void BuildTypedArguments(Expression expression) { AstNodeCollection<AstType> typedArguments = null; var identifierExpression = expression as IdentifierExpression; if (identifierExpression != null) { typedArguments = identifierExpression.TypeArguments; } else { var memberRefExpression = expression as MemberReferenceExpression; if (memberRefExpression != null) { typedArguments = memberRefExpression.TypeArguments; } } var method = this.ResolveResult.Member as IMethod; if (method != null) { this.TypeArguments = new TypeParamExpression[method.TypeParameters.Count]; if (typedArguments != null && typedArguments.Count == method.TypeParameters.Count) { var list = typedArguments.ToList(); for (int i = 0; i < list.Count; i++) { this.TypeArguments[i] = new TypeParamExpression(method.TypeParameters[i].Name, list[i], null); } } else { for (int i = 0; i < method.TypeArguments.Count; i++) { this.TypeArguments[i] = new TypeParamExpression(method.TypeParameters[i].Name, null, method.TypeArguments[i]); } } if (method.DeclaringType != null && method.DeclaringTypeDefinition != null && method.DeclaringTypeDefinition.TypeParameters.Count > 0) { var typeParams = method.DeclaringTypeDefinition.TypeParameters; var typeArgs = method.DeclaringType.TypeArguments; var temp = new TypeParamExpression[typeParams.Count]; for (int i = 0; i < typeParams.Count; i++) { temp[i] = new TypeParamExpression(typeParams[i].Name, null, typeArgs[i], true); } this.TypeArguments = this.TypeArguments.Concat(temp).ToArray(); } } } private void BuildOperatorTypedArguments() { var method = this.OperatorResolveResult.UserDefinedOperatorMethod; if (method != null) { for (int i = 0; i < method.TypeArguments.Count; i++) { this.TypeArguments[i] = new TypeParamExpression(method.TypeParameters[i].Name, null, method.TypeArguments[i]); } } } private void BuildDynamicArgumentsList(DynamicInvocationResolveResult drr, IList<Expression> arguments) { Expression paramsArg = null; string paramArgName = null; IMethod method = null; var group = drr.Target as MethodGroupResolveResult; if (group != null && group.Methods.Count() > 1) { method = group.Methods.FirstOrDefault(m => { if (drr.Arguments.Count != m.Parameters.Count) { return false; } for (int i = 0; i < m.Parameters.Count; i++) { var argType = drr.Arguments[i].Type; if (argType.Kind == TypeKind.Dynamic) { argType = this.Emitter.Resolver.Compilation.FindType(TypeCode.Object); } if (!m.Parameters[i].Type.Equals(argType)) { return false; } } return true; }); if (method == null) { throw new EmitterException(this.Expression, Bridge.Translator.Constants.Messages.Exceptions.DYNAMIC_INVOCATION_TOO_MANY_OVERLOADS); } } if (method != null) { var member = method; var parameters = method.Parameters; Expression[] result = new Expression[parameters.Count]; string[] names = new string[result.Length]; bool named = false; int i = 0; bool isInterfaceMember = false; if (member != null) { var inlineStr = this.Emitter.GetInline(member); named = !string.IsNullOrEmpty(inlineStr); isInterfaceMember = member.DeclaringTypeDefinition != null && member.DeclaringTypeDefinition.Kind == TypeKind.Interface; } foreach (var arg in arguments) { if (arg is NamedArgumentExpression) { NamedArgumentExpression namedArg = (NamedArgumentExpression)arg; var namedParam = parameters.First(p => p.Name == namedArg.Name); var index = parameters.IndexOf(namedParam); result[index] = namedArg.Expression; names[index] = namedArg.Name; named = true; if (paramsArg == null && (parameters.Count > i) && parameters[i].IsParams) { if (member.DeclaringTypeDefinition == null || !this.Emitter.Validator.IsExternalType(member.DeclaringTypeDefinition)) { paramsArg = namedArg.Expression; } paramArgName = namedArg.Name; } } else { if (paramsArg == null && (parameters.Count > i) && parameters[i].IsParams) { if (member.DeclaringTypeDefinition == null || !this.Emitter.Validator.IsExternalType(member.DeclaringTypeDefinition)) { paramsArg = arg; } paramArgName = parameters[i].Name; } if (i >= result.Length) { var list = result.ToList(); list.AddRange(new Expression[arguments.Count - i]); var strList = names.ToList(); strList.AddRange(new string[arguments.Count - i]); result = list.ToArray(); names = strList.ToArray(); } result[i] = arg; names[i] = i < parameters.Count ? parameters[i].Name : paramArgName; } i++; } for (i = 0; i < result.Length; i++) { if (result[i] == null) { var p = parameters[i]; object t = null; if (p.Type.Kind == TypeKind.Enum) { t = Helpers.GetEnumValue(this.Emitter, p.Type, p.ConstantValue); } else { t = p.ConstantValue; } if ((named || isInterfaceMember) && !p.IsParams) { if (t == null) { result[i] = new PrimitiveExpression(new RawValue("void 0")); } else { result[i] = new PrimitiveExpression(t); } } names[i] = parameters[i].Name; } } this.ArgumentsExpressions = result; this.ArgumentsNames = names; this.ParamsExpression = paramsArg; this.NamedExpressions = this.CreateNamedExpressions(names, result); } else { this.ArgumentsExpressions = arguments.ToArray(); } } private void BuildArgumentsList(IList<Expression> arguments) { Expression paramsArg = null; string paramArgName = null; var resolveResult = this.ResolveResult; if (resolveResult != null) { var parameters = resolveResult.Member.Parameters; var resolvedMethod = resolveResult.Member as IMethod; var invocationResult = resolveResult as CSharpInvocationResolveResult; var isDelegate = resolveResult.Member.DeclaringType.Kind == TypeKind.Delegate; int shift = 0; if (resolvedMethod != null && invocationResult != null && resolvedMethod.IsExtensionMethod && invocationResult.IsExtensionMethodInvocation) { shift = 1; this.ThisName = resolvedMethod.Parameters[0].Name; this.IsExtensionMethod = true; } Expression[] result = new Expression[parameters.Count - shift]; string[] names = new string[result.Length]; bool named = false; int i = 0; bool isInterfaceMember = false; if (resolveResult.Member != null) { var inlineStr = this.Emitter.GetInline(resolveResult.Member); named = !string.IsNullOrEmpty(inlineStr); isInterfaceMember = resolveResult.Member.DeclaringTypeDefinition != null && resolveResult.Member.DeclaringTypeDefinition.Kind == TypeKind.Interface; } var expandParams = resolveResult.Member.Attributes.Any(a => a.AttributeType.FullName == "Bridge.ExpandParamsAttribute"); foreach (var arg in arguments) { if (arg is NamedArgumentExpression) { NamedArgumentExpression namedArg = (NamedArgumentExpression)arg; var namedParam = parameters.First(p => p.Name == namedArg.Name); var index = parameters.IndexOf(namedParam) - shift; result[index] = namedArg.Expression; names[index] = namedArg.Name; named = true; if (paramsArg == null && parameters.FirstOrDefault(p => p.Name == namedArg.Name).IsParams) { if (resolveResult.Member.DeclaringTypeDefinition == null || !this.Emitter.Validator.IsExternalType(resolveResult.Member.DeclaringTypeDefinition)) { paramsArg = namedArg.Expression; } paramArgName = namedArg.Name; } } else { if (paramsArg == null && (parameters.Count > (i + shift)) && parameters[i + shift].IsParams) { if (resolveResult.Member.DeclaringTypeDefinition == null || !this.Emitter.Validator.IsExternalType(resolveResult.Member.DeclaringTypeDefinition) || expandParams) { paramsArg = arg; } paramArgName = parameters[i + shift].Name; } if (i >= result.Length) { var list = result.ToList(); list.AddRange(new Expression[arguments.Count - i]); var strList = names.ToList(); strList.AddRange(new string[arguments.Count - i]); result = list.ToArray(); names = strList.ToArray(); } result[i] = arg; names[i] = (i + shift) < parameters.Count ? parameters[i + shift].Name : paramArgName; } i++; } for (i = 0; i < result.Length; i++) { if (result[i] == null) { var p = parameters[i + shift]; object t = null; if (p.Type.Kind == TypeKind.Enum) { t = Helpers.GetEnumValue(this.Emitter, p.Type, p.ConstantValue); } else { t = p.ConstantValue; } if ((named || isInterfaceMember || isDelegate) && !p.IsParams) { if (t == null) { result[i] = new PrimitiveExpression(new RawValue("void 0")); } else { result[i] = new PrimitiveExpression(t); } } names[i] = parameters[i + shift].Name; } } this.ArgumentsExpressions = result; this.ArgumentsNames = names; this.ParamsExpression = paramsArg; this.NamedExpressions = this.CreateNamedExpressions(names, result); } else { this.ArgumentsExpressions = arguments.ToArray(); } } private void BuildOperatorArgumentsList(IList<Expression> arguments, IMethod method) { if (method != null) { var parameters = method.Parameters; Expression[] result = new Expression[parameters.Count]; string[] names = new string[result.Length]; int i = 0; foreach (var arg in arguments) { if (arg is NamedArgumentExpression) { NamedArgumentExpression namedArg = (NamedArgumentExpression)arg; var namedParam = parameters.First(p => p.Name == namedArg.Name); var index = parameters.IndexOf(namedParam); result[index] = namedArg.Expression; names[index] = namedArg.Name; } else { if (i >= result.Length) { var list = result.ToList(); list.AddRange(new Expression[arguments.Count - i]); var strList = names.ToList(); strList.AddRange(new string[arguments.Count - i]); result = list.ToArray(); names = strList.ToArray(); } result[i] = arg; names[i] = parameters[i].Name; } i++; } for (i = 0; i < result.Length; i++) { if (result[i] == null) { var p = parameters[i]; if (p.Type.Kind == TypeKind.Enum) { result[i] = new PrimitiveExpression(Helpers.GetEnumValue(this.Emitter, p.Type, p.ConstantValue)); } else { result[i] = new PrimitiveExpression(p.ConstantValue); } names[i] = parameters[i].Name; } } this.ArgumentsExpressions = result; this.ArgumentsNames = names; this.NamedExpressions = this.CreateNamedExpressions(names, result); } else { this.ArgumentsExpressions = arguments.ToArray(); } } public NamedParamExpression[] CreateNamedExpressions(string[] names, Expression[] expressions) { var result = new NamedParamExpression[names.Length]; for (int i = 0; i < result.Length; i++) { result[i] = new NamedParamExpression(names[i], expressions[i]); } return result; } public string GetThisValue() { if (this.ThisArgument != null) { if (this.ThisArgument is string) { return this.ThisArgument.ToString(); } if (this.ThisArgument is Expression) { ((Expression)this.ThisArgument).AcceptVisitor(this.Emitter); return null; } } return "null"; } public void AddExtensionParam() { var result = this.ArgumentsExpressions; var namedResult = this.NamedExpressions; var names = this.ArgumentsNames; if (this.IsExtensionMethod) { var list = result.ToList(); list.Insert(0, null); var strList = names.ToList(); strList.Insert(0, null); var namedList = namedResult.ToList(); namedList.Insert(0, new NamedParamExpression(this.ThisName, null)); result = list.ToArray(); names = strList.ToArray(); namedResult = namedList.ToArray(); result[0] = null; names[0] = this.ThisName; } this.ArgumentsExpressions = result; this.ArgumentsNames = names; this.NamedExpressions = namedResult; } } public class NamedParamExpression { public NamedParamExpression(string name, Expression expression) { this.Name = name; this.Expression = expression; } public string Name { get; private set; } public Expression Expression { get; private set; } } public class TypeParamExpression { public TypeParamExpression(string name, AstType type, IType iType, bool inherited = false) { this.Name = name; this.AstType = type; this.IType = iType; this.Inherited = inherited; } public string Name { get; private set; } public AstType AstType { get; private set; } public IType IType { get; private set; } public bool Inherited { get; private set; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ClientSessionEncoder { public const ushort BLOCK_LENGTH = 12; public const ushort TEMPLATE_ID = 102; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private ClientSessionEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public ClientSessionEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ClientSessionEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public ClientSessionEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ClusterSessionIdEncodingOffset() { return 0; } public static int ClusterSessionIdEncodingLength() { return 8; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public ClientSessionEncoder ClusterSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int ResponseStreamIdEncodingOffset() { return 8; } public static int ResponseStreamIdEncodingLength() { return 4; } public static int ResponseStreamIdNullValue() { return -2147483648; } public static int ResponseStreamIdMinValue() { return -2147483647; } public static int ResponseStreamIdMaxValue() { return 2147483647; } public ClientSessionEncoder ResponseStreamId(int value) { _buffer.PutInt(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int ResponseChannelId() { return 3; } public static string ResponseChannelCharacterEncoding() { return "US-ASCII"; } public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ResponseChannelHeaderLength() { return 4; } public ClientSessionEncoder PutResponseChannel(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClientSessionEncoder PutResponseChannel(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClientSessionEncoder ResponseChannel(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public static int EncodedPrincipalId() { return 4; } public static string EncodedPrincipalMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int EncodedPrincipalHeaderLength() { return 4; } public ClientSessionEncoder PutEncodedPrincipal(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClientSessionEncoder PutEncodedPrincipal(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { ClientSessionDecoder writer = new ClientSessionDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ConsoleKey ** ** ** Purpose: This enumeration represents characters returned from a keyboard. ** The list is derived from a list of Windows virtual key codes, ** and is very similar to the Windows Forms Keys class. ** ** =============================================================================*/ namespace System { [Serializable] public enum ConsoleKey { Backspace = 0x8, Tab = 0x9, // 0xA, // Reserved // 0xB, // Reserved Clear = 0xC, Enter = 0xD, // 0E-0F, // Undefined // SHIFT = 0x10, // CONTROL = 0x11, // Alt = 0x12, Pause = 0x13, // CAPSLOCK = 0x14, // Kana = 0x15, // Ime Mode // Hangul = 0x15, // Ime Mode // 0x16, // Undefined // Junja = 0x17, // Ime Mode // Final = 0x18, // Ime Mode // Hanja = 0x19, // Ime Mode // Kanji = 0x19, // Ime Mode // 0x1A, // Undefined Escape = 0x1B, // Convert = 0x1C, // Ime Mode // NonConvert = 0x1D, // Ime Mode // Accept = 0x1E, // Ime Mode // ModeChange = 0x1F, // Ime Mode Spacebar = 0x20, PageUp = 0x21, PageDown = 0x22, End = 0x23, Home = 0x24, LeftArrow = 0x25, UpArrow = 0x26, RightArrow = 0x27, DownArrow = 0x28, Select = 0x29, Print = 0x2A, Execute = 0x2B, PrintScreen = 0x2C, Insert = 0x2D, Delete = 0x2E, Help = 0x2F, D0 = 0x30, // 0 through 9 D1 = 0x31, D2 = 0x32, D3 = 0x33, D4 = 0x34, D5 = 0x35, D6 = 0x36, D7 = 0x37, D8 = 0x38, D9 = 0x39, // 3A-40 , // Undefined A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4A, K = 0x4B, L = 0x4C, M = 0x4D, N = 0x4E, O = 0x4F, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5A, LeftWindows = 0x5B, // Microsoft Natural keyboard RightWindows = 0x5C, // Microsoft Natural keyboard Applications = 0x5D, // Microsoft Natural keyboard // 5E , // Reserved Sleep = 0x5F, // Computer Sleep Key NumPad0 = 0x60, NumPad1 = 0x61, NumPad2 = 0x62, NumPad3 = 0x63, NumPad4 = 0x64, NumPad5 = 0x65, NumPad6 = 0x66, NumPad7 = 0x67, NumPad8 = 0x68, NumPad9 = 0x69, Multiply = 0x6A, Add = 0x6B, Separator = 0x6C, Subtract = 0x6D, Decimal = 0x6E, Divide = 0x6F, F1 = 0x70, F2 = 0x71, F3 = 0x72, F4 = 0x73, F5 = 0x74, F6 = 0x75, F7 = 0x76, F8 = 0x77, F9 = 0x78, F10 = 0x79, F11 = 0x7A, F12 = 0x7B, F13 = 0x7C, F14 = 0x7D, F15 = 0x7E, F16 = 0x7F, F17 = 0x80, F18 = 0x81, F19 = 0x82, F20 = 0x83, F21 = 0x84, F22 = 0x85, F23 = 0x86, F24 = 0x87, // 88-8F, // Undefined // NumberLock = 0x90, // ScrollLock = 0x91, // 0x92, // OEM Specific // 97-9F , // Undefined // LeftShift = 0xA0, // RightShift = 0xA1, // LeftControl = 0xA2, // RightControl = 0xA3, // LeftAlt = 0xA4, // RightAlt = 0xA5, BrowserBack = 0xA6, // Windows 2000/XP BrowserForward = 0xA7, // Windows 2000/XP BrowserRefresh = 0xA8, // Windows 2000/XP BrowserStop = 0xA9, // Windows 2000/XP BrowserSearch = 0xAA, // Windows 2000/XP BrowserFavorites = 0xAB, // Windows 2000/XP BrowserHome = 0xAC, // Windows 2000/XP VolumeMute = 0xAD, // Windows 2000/XP VolumeDown = 0xAE, // Windows 2000/XP VolumeUp = 0xAF, // Windows 2000/XP MediaNext = 0xB0, // Windows 2000/XP MediaPrevious = 0xB1, // Windows 2000/XP MediaStop = 0xB2, // Windows 2000/XP MediaPlay = 0xB3, // Windows 2000/XP LaunchMail = 0xB4, // Windows 2000/XP LaunchMediaSelect = 0xB5, // Windows 2000/XP LaunchApp1 = 0xB6, // Windows 2000/XP LaunchApp2 = 0xB7, // Windows 2000/XP // B8-B9, // Reserved Oem1 = 0xBA, // Misc characters, varies by keyboard. For US standard, ;: OemPlus = 0xBB, // Misc characters, varies by keyboard. For US standard, + OemComma = 0xBC, // Misc characters, varies by keyboard. For US standard, , OemMinus = 0xBD, // Misc characters, varies by keyboard. For US standard, - OemPeriod = 0xBE, // Misc characters, varies by keyboard. For US standard, . Oem2 = 0xBF, // Misc characters, varies by keyboard. For US standard, /? Oem3 = 0xC0, // Misc characters, varies by keyboard. For US standard, `~ // 0xC1, // Reserved // D8-DA, // Unassigned Oem4 = 0xDB, // Misc characters, varies by keyboard. For US standard, [{ Oem5 = 0xDC, // Misc characters, varies by keyboard. For US standard, \| Oem6 = 0xDD, // Misc characters, varies by keyboard. For US standard, ]} Oem7 = 0xDE, // Misc characters, varies by keyboard. For US standard, Oem8 = 0xDF, // Used for miscellaneous characters; it can vary by keyboard // 0xE0, // Reserved // 0xE1, // OEM specific Oem102 = 0xE2, // Win2K/XP: Either angle or backslash on RT 102-key keyboard // 0xE3, // OEM specific Process = 0xE5, // Windows: IME Process Key // 0xE6, // OEM specific Packet = 0xE7, // Win2K/XP: Used to pass Unicode chars as if keystrokes // 0xE8, // Unassigned // 0xE9, // OEM specific Attention = 0xF6, CrSel = 0xF7, ExSel = 0xF8, EraseEndOfFile = 0xF9, Play = 0xFA, Zoom = 0xFB, NoName = 0xFC, // Reserved Pa1 = 0xFD, OemClear = 0xFE, } }
/******************************************************************************* * Copyright 2009-2015 Amazon Services. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0 * 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. ******************************************************************************* * Get Lowest Priced Offers For SKU Request * API Version: 2011-10-01 * Library Version: 2015-09-01 * Generated: Thu Sep 10 06:52:19 PDT 2015 */ using System; using System.Xml; using System.Xml.Serialization; using MWSClientCsRuntime; namespace MarketplaceWebServiceProducts.Model { [XmlTypeAttribute(Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")] [XmlRootAttribute(Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01", IsNullable = false)] public class GetLowestPricedOffersForSKURequest : AbstractMwsObject { private string _sellerId; private string _mwsAuthToken; private string _marketplaceId; private string _sellerSKU; private string _itemCondition; /// <summary> /// Gets and sets the SellerId property. /// </summary> [XmlElementAttribute(ElementName = "SellerId")] public string SellerId { get { return this._sellerId; } set { this._sellerId = value; } } /// <summary> /// Sets the SellerId property. /// </summary> /// <param name="sellerId">SellerId property.</param> /// <returns>this instance.</returns> public GetLowestPricedOffersForSKURequest WithSellerId(string sellerId) { this._sellerId = sellerId; return this; } /// <summary> /// Checks if SellerId property is set. /// </summary> /// <returns>true if SellerId property is set.</returns> public bool IsSetSellerId() { return this._sellerId != null; } /// <summary> /// Gets and sets the MWSAuthToken property. /// </summary> [XmlElementAttribute(ElementName = "MWSAuthToken")] public string MWSAuthToken { get { return this._mwsAuthToken; } set { this._mwsAuthToken = value; } } /// <summary> /// Sets the MWSAuthToken property. /// </summary> /// <param name="mwsAuthToken">MWSAuthToken property.</param> /// <returns>this instance.</returns> public GetLowestPricedOffersForSKURequest WithMWSAuthToken(string mwsAuthToken) { this._mwsAuthToken = mwsAuthToken; return this; } /// <summary> /// Checks if MWSAuthToken property is set. /// </summary> /// <returns>true if MWSAuthToken property is set.</returns> public bool IsSetMWSAuthToken() { return this._mwsAuthToken != null; } /// <summary> /// Gets and sets the MarketplaceId property. /// </summary> [XmlElementAttribute(ElementName = "MarketplaceId")] public string MarketplaceId { get { return this._marketplaceId; } set { this._marketplaceId = value; } } /// <summary> /// Sets the MarketplaceId property. /// </summary> /// <param name="marketplaceId">MarketplaceId property.</param> /// <returns>this instance.</returns> public GetLowestPricedOffersForSKURequest WithMarketplaceId(string marketplaceId) { this._marketplaceId = marketplaceId; return this; } /// <summary> /// Checks if MarketplaceId property is set. /// </summary> /// <returns>true if MarketplaceId property is set.</returns> public bool IsSetMarketplaceId() { return this._marketplaceId != null; } /// <summary> /// Gets and sets the SellerSKU property. /// </summary> [XmlElementAttribute(ElementName = "SellerSKU")] public string SellerSKU { get { return this._sellerSKU; } set { this._sellerSKU = value; } } /// <summary> /// Sets the SellerSKU property. /// </summary> /// <param name="sellerSKU">SellerSKU property.</param> /// <returns>this instance.</returns> public GetLowestPricedOffersForSKURequest WithSellerSKU(string sellerSKU) { this._sellerSKU = sellerSKU; return this; } /// <summary> /// Checks if SellerSKU property is set. /// </summary> /// <returns>true if SellerSKU property is set.</returns> public bool IsSetSellerSKU() { return this._sellerSKU != null; } /// <summary> /// Gets and sets the ItemCondition property. /// </summary> [XmlElementAttribute(ElementName = "ItemCondition")] public string ItemCondition { get { return this._itemCondition; } set { this._itemCondition = value; } } /// <summary> /// Sets the ItemCondition property. /// </summary> /// <param name="itemCondition">ItemCondition property.</param> /// <returns>this instance.</returns> public GetLowestPricedOffersForSKURequest WithItemCondition(string itemCondition) { this._itemCondition = itemCondition; return this; } /// <summary> /// Checks if ItemCondition property is set. /// </summary> /// <returns>true if ItemCondition property is set.</returns> public bool IsSetItemCondition() { return this._itemCondition != null; } public override void ReadFragmentFrom(IMwsReader reader) { _sellerId = reader.Read<string>("SellerId"); _mwsAuthToken = reader.Read<string>("MWSAuthToken"); _marketplaceId = reader.Read<string>("MarketplaceId"); _sellerSKU = reader.Read<string>("SellerSKU"); _itemCondition = reader.Read<string>("ItemCondition"); } public override void WriteFragmentTo(IMwsWriter writer) { writer.Write("SellerId", _sellerId); writer.Write("MWSAuthToken", _mwsAuthToken); writer.Write("MarketplaceId", _marketplaceId); writer.Write("SellerSKU", _sellerSKU); writer.Write("ItemCondition", _itemCondition); } public override void WriteTo(IMwsWriter writer) { writer.Write("http://mws.amazonservices.com/schema/Products/2011-10-01", "GetLowestPricedOffersForSKURequest", this); } public GetLowestPricedOffersForSKURequest() : base() { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type Complex with 3 columns and 2 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct cmat3x2 : IReadOnlyList<Complex>, IEquatable<cmat3x2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public Complex m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public Complex m01; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public Complex m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public Complex m11; /// <summary> /// Column 2, Rows 0 /// </summary> [DataMember] public Complex m20; /// <summary> /// Column 2, Rows 1 /// </summary> [DataMember] public Complex m21; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public cmat3x2(Complex m00, Complex m01, Complex m10, Complex m11, Complex m20, Complex m21) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; this.m20 = m20; this.m21 = m21; } /// <summary> /// Constructs this matrix from a cmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = Complex.Zero; this.m21 = Complex.Zero; } /// <summary> /// Constructs this matrix from a cmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; } /// <summary> /// Constructs this matrix from a cmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; } /// <summary> /// Constructs this matrix from a cmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = Complex.Zero; this.m21 = Complex.Zero; } /// <summary> /// Constructs this matrix from a cmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; } /// <summary> /// Constructs this matrix from a cmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; } /// <summary> /// Constructs this matrix from a cmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = Complex.Zero; this.m21 = Complex.Zero; } /// <summary> /// Constructs this matrix from a cmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; } /// <summary> /// Constructs this matrix from a cmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cvec2 c0, cvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = Complex.Zero; this.m21 = Complex.Zero; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat3x2(cvec2 c0, cvec2 c1, cvec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public Complex[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public Complex[] Values1D => new[] { m00, m01, m10, m11, m20, m21 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public cvec2 Column0 { get { return new cvec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public cvec2 Column1 { get { return new cvec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public cvec2 Column2 { get { return new cvec2(m20, m21); } set { m20 = value.x; m21 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public cvec3 Row0 { get { return new cvec3(m00, m10, m20); } set { m00 = value.x; m10 = value.y; m20 = value.z; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public cvec3 Row1 { get { return new cvec3(m01, m11, m21); } set { m01 = value.x; m11 = value.y; m21 = value.z; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static cmat3x2 Zero { get; } = new cmat3x2(Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero); /// <summary> /// Predefined all-ones matrix /// </summary> public static cmat3x2 Ones { get; } = new cmat3x2(Complex.One, Complex.One, Complex.One, Complex.One, Complex.One, Complex.One); /// <summary> /// Predefined identity matrix /// </summary> public static cmat3x2 Identity { get; } = new cmat3x2(Complex.One, Complex.Zero, Complex.Zero, Complex.One, Complex.Zero, Complex.Zero); /// <summary> /// Predefined all-imaginary-ones matrix /// </summary> public static cmat3x2 ImaginaryOnes { get; } = new cmat3x2(Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne); /// <summary> /// Predefined diagonal-imaginary-one matrix /// </summary> public static cmat3x2 ImaginaryIdentity { get; } = new cmat3x2(Complex.ImaginaryOne, Complex.Zero, Complex.Zero, Complex.ImaginaryOne, Complex.Zero, Complex.Zero); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<Complex> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; yield return m20; yield return m21; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (3 x 2 = 6). /// </summary> public int Count => 6; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public Complex this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; case 4: return m20; case 5: return m21; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; case 4: this.m20 = value; break; case 5: this.m21 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public Complex this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(cmat3x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m10.Equals(rhs.m10)) && ((m11.Equals(rhs.m11) && m20.Equals(rhs.m20)) && m21.Equals(rhs.m21))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is cmat3x2 && Equals((cmat3x2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(cmat3x2 lhs, cmat3x2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(cmat3x2 lhs, cmat3x2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public cmat2x3 Transposed => new cmat2x3(m00, m10, m20, m01, m11, m21); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public double Length => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + m10.LengthSqr()) + ((m11.LengthSqr() + m20.LengthSqr()) + m21.LengthSqr()))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public double LengthSqr => (((m00.LengthSqr() + m01.LengthSqr()) + m10.LengthSqr()) + ((m11.LengthSqr() + m20.LengthSqr()) + m21.LengthSqr())); /// <summary> /// Returns the sum of all fields. /// </summary> public Complex Sum => (((m00 + m01) + m10) + ((m11 + m20) + m21)); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public double Norm => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + m10.LengthSqr()) + ((m11.LengthSqr() + m20.LengthSqr()) + m21.LengthSqr()))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public double Norm1 => (((m00.Magnitude + m01.Magnitude) + m10.Magnitude) + ((m11.Magnitude + m20.Magnitude) + m21.Magnitude)); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public double Norm2 => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + m10.LengthSqr()) + ((m11.LengthSqr() + m20.LengthSqr()) + m21.LengthSqr()))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public Complex NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00.Magnitude, m01.Magnitude), m10.Magnitude), m11.Magnitude), m20.Magnitude), m21.Magnitude); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow((((Math.Pow((double)m00.Magnitude, p) + Math.Pow((double)m01.Magnitude, p)) + Math.Pow((double)m10.Magnitude, p)) + ((Math.Pow((double)m11.Magnitude, p) + Math.Pow((double)m20.Magnitude, p)) + Math.Pow((double)m21.Magnitude, p))), 1 / p); /// <summary> /// Executes a matrix-matrix-multiplication cmat3x2 * cmat2x3 -> cmat2. /// </summary> public static cmat2 operator*(cmat3x2 lhs, cmat2x3 rhs) => new cmat2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12)); /// <summary> /// Executes a matrix-matrix-multiplication cmat3x2 * cmat3 -> cmat3x2. /// </summary> public static cmat3x2 operator*(cmat3x2 lhs, cmat3 rhs) => new cmat3x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22)); /// <summary> /// Executes a matrix-matrix-multiplication cmat3x2 * cmat4x3 -> cmat4x2. /// </summary> public static cmat4x2 operator*(cmat3x2 lhs, cmat4x3 rhs) => new cmat4x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + lhs.m20 * rhs.m32), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + lhs.m21 * rhs.m32)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static cvec2 operator*(cmat3x2 m, cvec3 v) => new cvec2(((m.m00 * v.x + m.m10 * v.y) + m.m20 * v.z), ((m.m01 * v.x + m.m11 * v.y) + m.m21 * v.z)); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static cmat3x2 CompMul(cmat3x2 A, cmat3x2 B) => new cmat3x2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11, A.m20 * B.m20, A.m21 * B.m21); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static cmat3x2 CompDiv(cmat3x2 A, cmat3x2 B) => new cmat3x2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11, A.m20 / B.m20, A.m21 / B.m21); /// <summary> /// Executes a component-wise + (add). /// </summary> public static cmat3x2 CompAdd(cmat3x2 A, cmat3x2 B) => new cmat3x2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11, A.m20 + B.m20, A.m21 + B.m21); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static cmat3x2 CompSub(cmat3x2 A, cmat3x2 B) => new cmat3x2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11, A.m20 - B.m20, A.m21 - B.m21); /// <summary> /// Executes a component-wise + (add). /// </summary> public static cmat3x2 operator+(cmat3x2 lhs, cmat3x2 rhs) => new cmat3x2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static cmat3x2 operator+(cmat3x2 lhs, Complex rhs) => new cmat3x2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m20 + rhs, lhs.m21 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static cmat3x2 operator+(Complex lhs, cmat3x2 rhs) => new cmat3x2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m20, lhs + rhs.m21); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static cmat3x2 operator-(cmat3x2 lhs, cmat3x2 rhs) => new cmat3x2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static cmat3x2 operator-(cmat3x2 lhs, Complex rhs) => new cmat3x2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m20 - rhs, lhs.m21 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static cmat3x2 operator-(Complex lhs, cmat3x2 rhs) => new cmat3x2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m20, lhs - rhs.m21); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static cmat3x2 operator/(cmat3x2 lhs, Complex rhs) => new cmat3x2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m20 / rhs, lhs.m21 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static cmat3x2 operator/(Complex lhs, cmat3x2 rhs) => new cmat3x2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m20, lhs / rhs.m21); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static cmat3x2 operator*(cmat3x2 lhs, Complex rhs) => new cmat3x2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m20 * rhs, lhs.m21 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static cmat3x2 operator*(Complex lhs, cmat3x2 rhs) => new cmat3x2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m20, lhs * rhs.m21); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Build.Construction; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools; namespace TestUtilities.SharedProject { /// <summary> /// Base class for all test cases which generate projects at runtime in a language /// agnostic way. This class will initialize the MEF catalog and get the various /// project kind(s) to be tested. The kinds wil be available via the ProjectKinds /// property. /// /// It also provides a number of convenience methods for creating project definitions. /// This helps to make the project definition more readable and similar to typical /// MSBuild structure. /// </summary> [TestClass] public class SharedProjectTest { public static CompositionContainer Container; public static IEnumerable<ProjectType> ProjectTypes { get; set; } static SharedProjectTest() { var runningLoc = Path.GetDirectoryName(typeof(SharedProjectTest).Assembly.Location); // we want to pick up all of the MEF exports which are available, but they don't // depend upon us. So if we're just running some tests in the IDE when the deployment // happens it won't have the DLLS with the MEF exports. So we copy them here. TestData.Deploy(null, includeTestData: false); // load all of the available DLLs that depend upon TestUtilities into our catalog List<AssemblyCatalog> catalogs = new List<AssemblyCatalog>(); foreach (var file in Directory.GetFiles(runningLoc, "*.dll")) { TryAddAssembly(catalogs, file); } // Compose everything var catalog = new AggregateCatalog(catalogs.ToArray()); var container = Container = new CompositionContainer(catalog); var compBatch = new CompositionBatch(); container.Compose(compBatch); // Initialize our ProjectTypes information from the catalog. // First, get a mapping from extension type to all available IProjectProcessor's for // that extension var processorsMap = container .GetExports<IProjectProcessor, IProjectProcessorMetadata>() .GroupBy(x => x.Metadata.ProjectExtension) .ToDictionary( x => x.Key, x => x.Select(lazy => lazy.Value).ToArray(), StringComparer.OrdinalIgnoreCase ); // Then create the ProjectTypes ProjectTypes = container .GetExports<ProjectTypeDefinition, IProjectTypeDefinitionMetadata>() .Select(lazyVal => { var md = lazyVal.Metadata; IProjectProcessor[] processors; processorsMap.TryGetValue(md.ProjectExtension, out processors); return new ProjectType( md.CodeExtension, md.ProjectExtension, Guid.Parse(md.ProjectTypeGuid), md.SampleCode, processors ); }); // something's broken if we don't have any languages to test against, so fail the test. Assert.IsTrue(ProjectTypes.Count() > 0, "no project types were registered and no tests will run"); } private static void TryAddAssembly(List<AssemblyCatalog> catalogs, string file) { Assembly asm; try { asm = Assembly.Load(Path.GetFileNameWithoutExtension(file)); } catch { return; } // Include any test assemblies which reference this assembly, they might // have defined a project kind. foreach (var reference in asm.GetReferencedAssemblies()) { if (reference.FullName == typeof(SharedProjectTest).Assembly.GetName().FullName) { Console.WriteLine("Including {0}", file); catalogs.Add(new AssemblyCatalog(asm)); break; } } } /// <summary> /// Helper function to create a ProjectProperty object to simply syntax in /// project definitions. /// </summary> public static ProjectProperty Property(string name, string value) { return new ProjectProperty(name, value); } /// <summary> /// Helper function to create a StartupFileProjectProperty object to simply syntax in /// project definitions. /// </summary> public static StartupFileProjectProperty StartupFile(string filename) { return new StartupFileProjectProperty(filename); } /// <summary> /// Helper function to create a group of properties when creating project definitions. /// These aren't strictly necessary and just serve to add structure to the code /// and make it similar to an MSBuild project file. /// </summary> public static ProjectContentGroup PropertyGroup(params ProjectProperty[] properties) { return new ProjectContentGroup(properties); } /// <summary> /// Helper function to create a CompileItem object to simply syntax in /// defining project definitions. /// </summary> public static CompileItem Compile(string name, string content = null, bool isExcluded = false, bool isMissing = false) { return new CompileItem(name, content, isExcluded, isMissing); } /// <summary> /// Helper function to create a CompileItem object to simply syntax in /// defining project definitions. /// </summary> public static ContentItem Content(string name, string content, bool isExcluded = false) { return new ContentItem(name, content, isExcluded); } /// <summary> /// Helper function to create a SymbolicLinkItem object to simply syntax in /// defining project definitions. /// </summary> public static SymbolicLinkItem SymbolicLink(string name, string referencePath, bool isExcluded = false, bool isMissing = false) { return new SymbolicLinkItem(name, referencePath, isExcluded, isMissing); } /// <summary> /// Helper function to create a FolderItem object to simply syntax in /// defining project definitions. /// </summary> public static FolderItem Folder(string name, bool isExcluded = false, bool isMissing = false) { return new FolderItem(name, isExcluded, isMissing); } /// <summary> /// Helper function to create a CustomItem object which is an MSBuild item with /// the specified item type. /// </summary> public static CustomItem CustomItem(string itemType, string name, string content = null, bool isExcluded = false, bool isMissing = false, IEnumerable<KeyValuePair<string, string>> metadata = null) { return new CustomItem(itemType, name, content, isExcluded, isMissing, metadata); } /// <summary> /// Helper function to create a group of items when creating project definitions. /// These aren't strictly necessary and just serve to add structure to the code /// and make it similar to an MSBuild project file. /// </summary> public static ProjectContentGroup ItemGroup(params ProjectContentGenerator[] properties) { return new ProjectContentGroup(properties); } /// <summary> /// Returns a new SolutionFolder object which can be used to create /// a solution folder in the generated project. /// </summary> public static SolutionFolder SolutionFolder(string name) { return new SolutionFolder(name); } /// <summary> /// Returns a new TargetDefinition which represents a specified Target /// inside of the project file. The various stages of the target can be /// created using the members of the static Tasks class. /// </summary> public static TargetDefinition Target(string name, params Action<ProjectTargetElement>[] creators) { return new TargetDefinition(name, creators); } /// <summary> /// Returns a new TargetDefinition which represents a specified Target /// inside of the project file. The various stages of the target can be /// created using the members of the static Tasks class. /// </summary> public static TargetDefinition Target(string name, string dependsOnTargets, params Action<ProjectTargetElement>[] creators) { return new TargetDefinition(name, creators) { DependsOnTargets = dependsOnTargets }; } /// <summary> /// Returns a new ImportDefinition for the specified project. /// </summary> /// <param name="project"></param> /// <returns></returns> public static ImportDefinition Import(string project) { return new ImportDefinition(project); } /// <summary> /// Provides tasks for creating target definitions in generated projects. /// </summary> public static class Tasks { /// <summary> /// Creates a task which outputs a message during the build. /// </summary> public static Action<ProjectTargetElement> Message(string message, string importance = null) { return target => { var messageTask = target.AddTask("Message"); messageTask.SetParameter("Text", message); if (importance != null) { messageTask.SetParameter("Importance", importance); } }; } } } }
using Breeze.Core; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Linq; using System.Reflection; namespace Breeze.Persistence.EFCore { public interface IEFContextProvider { DbContext DbContext { get; } String GetEntitySetName(Type entityType); } // T is a subclass of DbContext public class EFPersistenceManager<T> : PersistenceManager, IEFContextProvider where T : DbContext { private T _context; static EFPersistenceManager() { EntityQuery.ApplyExpand = EFExtensions.ApplyExpand; EntityQuery.ApplyCustomLogic = EFExtensions.ApplyAsNoTracking; } public EFPersistenceManager() { _context = null; } public EFPersistenceManager(T context) { _context = context; // Added for EF Core 3 _context.ChangeTracker.CascadeDeleteTiming = CascadeTiming.OnSaveChanges; _context.ChangeTracker.DeleteOrphansTiming = CascadeTiming.OnSaveChanges; } public DbContext DbContext { get { return _context; } } public T Context { get { return _context; } } //protected virtual T CreateContext() { // throw new NotImplementedException("A CreateContext method must be implemented - if you do not instantiate this PersistenceManager with a Context"); ; //} /// <summary>Gets the EntityConnection from the ObjectContext.</summary> public DbConnection EntityConnection { get { return (DbConnection)GetDbConnection(); } } /// <summary>Gets the current transaction, if one is in progress.</summary> public IDbContextTransaction EntityTransaction { get; private set; } ///// <summary>Gets the EntityConnection from the ObjectContext.</summary> public override IDbConnection GetDbConnection() { return DbContext.Database.GetDbConnection(); } /// <summary> /// Opens the DbConnection used by the Context. /// If the connection will be used outside of the DbContext, this method should be called prior to DbContext /// initialization, so that the connection will already be open when the DbContext uses it. This keeps /// the DbContext from closing the connection, so it must be closed manually. /// See http://blogs.msdn.com/b/diego/archive/2012/01/26/exception-from-dbcontext-api-entityconnection-can-only-be-constructed-with-a-closed-dbconnection.aspx /// </summary> /// <returns></returns> protected override void OpenDbConnection() { DbContext.Database.OpenConnection(); } protected override void CloseDbConnection() { if (_context != null) { DbContext.Database.CloseConnection(); } } // Override BeginTransaction so we can keep the current transaction in a property protected override IDbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) { var conn = GetDbConnection(); if (conn == null) return null; EntityTransaction = DbContext.Database.BeginTransaction(isolationLevel); return EntityTransaction.GetDbTransaction(); } #region Base implementation overrides protected override string BuildJsonMetadata() { var metadata = MetadataBuilder.BuildFrom(DbContext); var jss = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore, }; jss.Converters.Add(new StringEnumConverter()); var json = JsonConvert.SerializeObject(metadata, jss); var altMetadata = BuildAltJsonMetadata(); if (altMetadata != null) { json = "{ \"altMetadata\": " + altMetadata + "," + json.Substring(1); } return json; } protected virtual string BuildAltJsonMetadata() { // default implementation return null; // "{ \"foo\": 8, \"bar\": \"xxx\" }"; } protected override EntityInfo CreateEntityInfo() { return new EFEntityInfo(); } public override object[] GetKeyValues(EntityInfo entityInfo) { return GetKeyValues(entityInfo.Entity); } public object[] GetKeyValues(object entity) { var et = entity.GetType(); var values = GetKeyProperties(et).Select(kp => kp.GetValue(entity)).ToArray(); return values; } private IEnumerable<PropertyInfo> GetKeyProperties(Type entityType) { var pk = Context.Model.FindEntityType(entityType).FindPrimaryKey(); var props = pk.Properties.Select(k => k.PropertyInfo); return props; } protected override void SaveChangesCore(SaveWorkState saveWorkState) { var saveMap = saveWorkState.SaveMap; var deletedEntities = ProcessSaves(saveMap); if (deletedEntities.Any()) { ProcessAllDeleted(deletedEntities); } ProcessAutogeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys); try { DbContext.SaveChanges(); } catch (DbUpdateException e) { var nextException = (Exception)e; while (nextException.InnerException != null) { nextException = nextException.InnerException; } if (nextException == e) { throw; } else { //create a new exception that contains the toplevel exception //but has the innermost exception message propogated to the top. //For EF exceptions, this is often the most 'relevant' message. throw new Exception(nextException.Message, e); } } catch (Exception) { throw; } saveWorkState.KeyMappings = UpdateAutoGeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys); // insures that only a flat list of entities is returned by stubbing out any navigations saveWorkState.SaveMap.SelectMany(kvp => kvp.Value).ToList().ForEach(e => { var ee = GetEntityEntry(e.Entity); ee.State = Microsoft.EntityFrameworkCore.EntityState.Detached; ee.Navigations.ToList().ForEach(n => n.CurrentValue = null); }); } #endregion #region Save related methods private List<EFEntityInfo> ProcessSaves(Dictionary<Type, List<EntityInfo>> saveMap) { var deletedEntities = new List<EFEntityInfo>(); foreach (var kvp in saveMap) { if (kvp.Value == null || kvp.Value.Count == 0) continue; // skip GetEntitySetName if no entities var entityType = kvp.Key; var entitySetName = GetEntitySetName(entityType); foreach (EFEntityInfo entityInfo in kvp.Value) { // entityInfo.EFContextProvider = this; may be needed eventually. entityInfo.EntitySetName = entitySetName; ProcessEntity(entityInfo); if (entityInfo.EntityState == EntityState.Deleted) { deletedEntities.Add(entityInfo); } } } return deletedEntities; } private void ProcessAllDeleted(List<EFEntityInfo> deletedEntities) { deletedEntities.ForEach(entityInfo => { RestoreOriginal(entityInfo); var entry = GetOrAddEntityEntry(entityInfo); entry.State = Microsoft.EntityFrameworkCore.EntityState.Deleted; // Handle owned entities - ( complex types). var ownedNavs = entry.Navigations.Where(n => n.Metadata.GetTargetType().IsOwned()); ownedNavs.ToList().ForEach(n => { var nEntry = GetEntityEntry(n.CurrentValue); nEntry.State = Microsoft.EntityFrameworkCore.EntityState.Deleted; }); entityInfo.EntityEntry = entry; }); } private void ProcessAutogeneratedKeys(List<EntityInfo> entitiesWithAutoGeneratedKeys) { var tempKeys = entitiesWithAutoGeneratedKeys.Cast<EFEntityInfo>().Where( entityInfo => entityInfo.AutoGeneratedKey.AutoGeneratedKeyType == AutoGeneratedKeyType.KeyGenerator) .Select(ei => new TempKeyInfo(ei)) .ToList(); if (tempKeys.Count == 0) return; if (this.KeyGenerator == null) { this.KeyGenerator = GetKeyGenerator(); } this.KeyGenerator.UpdateKeys(tempKeys); tempKeys.ForEach(tki => { // Clever hack - next 3 lines cause all entities related to tki.Entity to have // their relationships updated. So all related entities for each tki are updated. // Basically we set the entity to look like a preexisting entity by setting its // entityState to unchanged. This is what fixes up the relations, then we set it back to added // Now when we update the pk - all fks will get changed as well. Note that the fk change will only // occur during the save. var entry = GetEntityEntry(tki.Entity); entry.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged; entry.State = Microsoft.EntityFrameworkCore.EntityState.Added; var val = ConvertValue(tki.RealValue, tki.Property.PropertyType); tki.Property.SetValue(tki.Entity, val, null); }); } private IKeyGenerator GetKeyGenerator() { var generatorType = KeyGeneratorType.Value; return (IKeyGenerator)Activator.CreateInstance(generatorType, this.GetDbConnection()); } private EntityInfo ProcessEntity(EFEntityInfo entityInfo) { EntityEntry ose; if (entityInfo.EntityState == EntityState.Modified) { ose = HandleModified(entityInfo); } else if (entityInfo.EntityState == EntityState.Added) { ose = HandleAdded(entityInfo); } else if (entityInfo.EntityState == EntityState.Deleted) { // for 1st pass this does NOTHING ose = HandleDeletedPart1(entityInfo); } else { // needed for many to many to get both ends into the objectContext ose = HandleUnchanged(entityInfo); } entityInfo.EntityEntry = ose; return entityInfo; } private EntityEntry HandleAdded(EFEntityInfo entityInfo) { var entry = AddEntityEntry(entityInfo); if (entityInfo.AutoGeneratedKey != null) { var propName = entityInfo.AutoGeneratedKey.PropertyName; entityInfo.AutoGeneratedKey.TempValue = GetEntryPropertyValue(entry, propName); if (entityInfo.AutoGeneratedKey.AutoGeneratedKeyType == AutoGeneratedKeyType.Identity) { // HACK: because EF Core will not allow inserts to an Identity column where a value exists on incoming entity. entry.Property(propName).IsTemporary = true; } } MarkEntryAndOwnedChildren(entry, Microsoft.EntityFrameworkCore.EntityState.Added); return entry; } private EntityEntry HandleModified(EFEntityInfo entityInfo) { var entry = AddEntityEntry(entityInfo); // EntityState will be changed to modified during the update from the OriginalValuesMap // Do NOT change this to EntityState.Modified because this will cause the entire record to update. entry.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged; // updating the original values is necessary under certain conditions when we change a foreign key field // because the before value is used to determine ordering. UpdateOriginalValues(entry, entityInfo); // SetModified(entry, entityInfo.ForceUpdate); MarkEntryAndOwnedChildren(entry, Microsoft.EntityFrameworkCore.EntityState.Modified); return entry; } private void MarkEntryAndOwnedChildren(EntityEntry entry, Microsoft.EntityFrameworkCore.EntityState state ) { entry.State = state; // Handle owned entities - ( complex types). var ownedNavs = entry.Navigations.Where(n => n.Metadata.GetTargetType().IsOwned()); ownedNavs.ToList().ForEach(n => { var nEntry = GetEntityEntry(n.CurrentValue); nEntry.State = state; }); } private EntityEntry HandleUnchanged(EFEntityInfo entityInfo) { var entry = AddEntityEntry(entityInfo); MarkEntryAndOwnedChildren(entry, Microsoft.EntityFrameworkCore.EntityState.Unchanged); // entry.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged; return entry; } private EntityEntry HandleDeletedPart1(EntityInfo entityInfo) { return null; } private EntityInfo RestoreOriginal(EntityInfo entityInfo) { // fk's can get cleared depending on the order in which deletions occur - // EF needs the original values of these fk's under certain circumstances - ( not sure entirely what these are). // so we restore the original fk values right before we attach the entity // shouldn't be any side effects because we delete it immediately after. // ??? Do concurrency values also need to be restored in some cases // This method restores more than it actually needs to because we don't // have metadata easily avail here, but usually a deleted entity will // not have much in the way of OriginalValues. if (entityInfo.OriginalValuesMap == null || entityInfo.OriginalValuesMap.Keys.Count == 0) { return entityInfo; } var entity = entityInfo.Entity; var entityType = entity.GetType(); var keyPropertyNames = GetKeyProperties(entityType).Select(kp => kp.Name).ToList(); var ovl = entityInfo.OriginalValuesMap.ToList(); for (var i = 0; i < ovl.Count; i++) { var kvp = ovl[i]; var propName = kvp.Key; // keys should be ignored if (keyPropertyNames.Contains(propName)) continue; var pi = entityType.GetProperty(propName); // unmapped properties should be ignored. if (pi == null) continue; var nnPropType = TypeFns.GetNonNullableType(pi.PropertyType); // presumption here is that only a predefined type could be a fk or concurrency property if (TypeFns.IsPredefinedType(nnPropType)) { SetPropertyValue(entity, propName, kvp.Value); } } return entityInfo; } private static void UpdateOriginalValues(EntityEntry entry, EntityInfo entityInfo) { var originalValuesMap = entityInfo.OriginalValuesMap; if (originalValuesMap == null || originalValuesMap.Keys.Count == 0) return; originalValuesMap.ToList().ForEach(kvp => { var propertyName = kvp.Key; var originalValue = kvp.Value; if (originalValue is JObject) { // only really need to perform updating original values on key properties // and a complex object cannot be a key. return; } try { var propEntry = entry.Property(propertyName); propEntry.IsModified = true; var fieldType = propEntry.Metadata.ClrType; var originalValueConverted = ConvertValue(originalValue, fieldType); propEntry.OriginalValue = originalValueConverted; } catch (Exception e) { if (e.Message.Contains(" part of the entity's key")) { throw; } else { // this can happen for "custom" data entity properties. } } }); } private List<KeyMapping> UpdateAutoGeneratedKeys(List<EntityInfo> entitiesWithAutoGeneratedKeys) { // where clause is necessary in case the Entities were suppressed in the beforeSave event. var keyMappings = entitiesWithAutoGeneratedKeys.Cast<EFEntityInfo>() .Where(entityInfo => entityInfo.EntityEntry != null) .Select((Func<EFEntityInfo, KeyMapping>)(entityInfo => { var autoGeneratedKey = entityInfo.AutoGeneratedKey; if (autoGeneratedKey.AutoGeneratedKeyType == AutoGeneratedKeyType.Identity) { autoGeneratedKey.RealValue = GetEntryPropertyValue(entityInfo.EntityEntry, autoGeneratedKey.PropertyName); } return new KeyMapping() { EntityTypeName = entityInfo.Entity.GetType().FullName, TempValue = autoGeneratedKey.TempValue, RealValue = autoGeneratedKey.RealValue }; })); return keyMappings.ToList(); } private Object GetEntryPropertyValue(EntityEntry entry, String propertyName) { var currentValues = entry.CurrentValues; return currentValues[propertyName]; } private void SetEntryPropertyValue(EntityEntry entry, String propertyName, Object value) { var currentValues = entry.CurrentValues; currentValues[propertyName] = value; } private void SetPropertyToDefaultValue(Object entity, String propertyName) { var propInfo = entity.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // exit if unmapped property. if (propInfo == null) return; if (propInfo.CanWrite) { var val = TypeFns.GetDefaultValue(propInfo.PropertyType); propInfo.SetValue(entity, val, null); } else { throw new Exception(String.Format("Unable to write to property '{0}' on type: '{1}'", propertyName, entity.GetType())); } } private void SetPropertyValue(Object entity, String propertyName, Object value) { var propInfo = entity.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // exit if unmapped property. if (propInfo == null) return; if (propInfo.CanWrite) { var val = ConvertValue(value, propInfo.PropertyType); propInfo.SetValue(entity, val, null); } else { throw new Exception(String.Format("Unable to write to property '{0}' on type: '{1}'", propertyName, entity.GetType())); } } private static Object ConvertValue(Object val, Type toType) { Object result; if (val == null) return val; if (toType == val.GetType()) return val; var nnToType = TypeFns.GetNonNullableType(toType); if (nnToType.IsEnum && val is string) { result = Enum.Parse(nnToType, val as string, true); } else if (typeof(IConvertible).IsAssignableFrom(nnToType)) { result = Convert.ChangeType(val, nnToType, System.Threading.Thread.CurrentThread.CurrentCulture); } else if (val is JObject) { var serializer = new JsonSerializer(); result = serializer.Deserialize(new JTokenReader((JObject)val), toType); } else { // Guids fail above - try this TypeConverter typeConverter = TypeDescriptor.GetConverter(toType); if (typeConverter.CanConvertFrom(val.GetType())) { result = typeConverter.ConvertFrom(val); } else if (val is DateTime && toType == typeof(DateTimeOffset)) { // handle case where JSON deserializes to DateTime, but toType is DateTimeOffset. DateTimeOffsetConverter doesn't work! result = new DateTimeOffset((DateTime)val); } else { result = val; } } return result; } private EntityEntry GetOrAddEntityEntry(EFEntityInfo entityInfo) { return AddEntityEntry(entityInfo); } private EntityEntry AddEntityEntry(EFEntityInfo entityInfo) { var entry = GetEntityEntry(entityInfo.Entity); if (entry.State == Microsoft.EntityFrameworkCore.EntityState.Detached) { return DbContext.Add(entityInfo.Entity); } else { return entry; } } private EntityEntry AttachEntityEntry(EFEntityInfo entityInfo) { return DbContext.Attach(entityInfo.Entity); } private EntityEntry GetEntityEntry(EFEntityInfo entityInfo) { return GetEntityEntry(entityInfo.Entity); } private EntityEntry GetEntityEntry(Object entity) { var entry = this.DbContext.Entry(entity); return entry; } #endregion public String GetEntitySetName(Type entityType) { return this.Context.Model.FindEntityType(entityType).Name; } } public class EFEntityInfo : EntityInfo { internal EFEntityInfo() { } internal String EntitySetName; internal EntityEntry EntityEntry; } public class EFEntityError : EntityError { public EFEntityError(EntityInfo entityInfo, String errorName, String errorMessage, String propertyName) { if (entityInfo != null) { this.EntityTypeName = entityInfo.Entity.GetType().FullName; this.KeyValues = GetKeyValues(entityInfo); } ErrorName = errorName; ErrorMessage = errorMessage; PropertyName = propertyName; } private Object[] GetKeyValues(EntityInfo entityInfo) { return entityInfo.ContextProvider.GetKeyValues(entityInfo); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Spatial4n.Core.Context; using Spatial4n.Core.Shapes; namespace Lucene.Net.Spatial.Prefix.Tree { /// <summary> /// Implementation of {@link SpatialPrefixTree} which uses a quad tree /// (http://en.wikipedia.org/wiki/Quadtree) /// </summary> public class QuadPrefixTree : SpatialPrefixTree { /// <summary> /// Factory for creating {@link QuadPrefixTree} instances with useful defaults /// </summary> public class Factory : SpatialPrefixTreeFactory { protected override int GetLevelForDistance(double degrees) { var grid = new QuadPrefixTree(ctx, MAX_LEVELS_POSSIBLE); return grid.GetLevelForDistance(degrees); } protected override SpatialPrefixTree NewSPT() { return new QuadPrefixTree(ctx, maxLevels != null ? maxLevels.Value : MAX_LEVELS_POSSIBLE); } } public static readonly int MAX_LEVELS_POSSIBLE = 50;//not really sure how big this should be public static readonly int DEFAULT_MAX_LEVELS = 12; private double xmin; private double xmax; private double ymin; private double ymax; private double xmid; private double ymid; private double gridW; private double gridH; double[] levelW; double[] levelH; int[] levelS; // side int[] levelN; // number public QuadPrefixTree(SpatialContext ctx, Rectangle bounds, int maxLevels) : base(ctx, maxLevels) { Init(ctx, bounds, maxLevels); } public QuadPrefixTree(SpatialContext ctx) : base(ctx, DEFAULT_MAX_LEVELS) { Init(ctx, ctx.GetWorldBounds(), DEFAULT_MAX_LEVELS); } public QuadPrefixTree(SpatialContext ctx, int maxLevels) : base(ctx, maxLevels) { Init(ctx, ctx.GetWorldBounds(), maxLevels); } protected void Init(SpatialContext ctx, Rectangle bounds, int maxLevels) { this.xmin = bounds.GetMinX(); this.xmax = bounds.GetMaxX(); this.ymin = bounds.GetMinY(); this.ymax = bounds.GetMaxY(); levelW = new double[maxLevels]; levelH = new double[maxLevels]; levelS = new int[maxLevels]; levelN = new int[maxLevels]; gridW = xmax - xmin; gridH = ymax - ymin; xmid = xmin + gridW / 2.0; ymid = ymin + gridH / 2.0; levelW[0] = gridW / 2.0; levelH[0] = gridH / 2.0; levelS[0] = 2; levelN[0] = 4; for (int i = 1; i < levelW.Length; i++) { levelW[i] = levelW[i - 1] / 2.0; levelH[i] = levelH[i - 1] / 2.0; levelS[i] = levelS[i - 1] * 2; levelN[i] = levelN[i - 1] * 4; } } public override int GetLevelForDistance(double dist) { if (dist == 0)//short circuit return maxLevels; for (int i = 0; i < maxLevels - 1; i++) { //note: level[i] is actually a lookup for level i+1 if (dist > levelW[i] && dist > levelH[i]) { return i + 1; } } return maxLevels; } protected override Node GetNode(Point p, int level) { var cells = new List<Node>(1); Build(xmid, ymid, 0, cells, new StringBuilder(), ctx.MakePoint(p.GetX(), p.GetY()), level); return cells[0];//note cells could be longer if p on edge } public override Node GetNode(string token) { return new QuadCell(token, this); } public override Node GetNode(byte[] bytes, int offset, int len) { throw new System.NotImplementedException(); } public override IList<Node> GetNodes(Shape shape, int detailLevel, bool inclParents) { var point = shape as Point; if (point != null) return base.GetNodesAltPoint(point, detailLevel, inclParents); else return base.GetNodes(shape, detailLevel, inclParents); } private void Build(double x, double y, int level, List<Node> matches, StringBuilder str, Shape shape, int maxLevel) { Debug.Assert(str.Length == level); double w = levelW[level] / 2; double h = levelH[level] / 2; // Z-Order // http://en.wikipedia.org/wiki/Z-order_%28curve%29 CheckBattenberg('A', x - w, y + h, level, matches, str, shape, maxLevel); CheckBattenberg('B', x + w, y + h, level, matches, str, shape, maxLevel); CheckBattenberg('C', x - w, y - h, level, matches, str, shape, maxLevel); CheckBattenberg('D', x + w, y - h, level, matches, str, shape, maxLevel); // possibly consider hilbert curve // http://en.wikipedia.org/wiki/Hilbert_curve // http://blog.notdot.net/2009/11/Damn-Cool-Algorithms-Spatial-indexing-with-Quadtrees-and-Hilbert-Curves // if we actually use the range property in the query, this could be useful } private void CheckBattenberg( char c, double cx, double cy, int level, List<Node> matches, StringBuilder str, Shape shape, int maxLevel) { Debug.Assert(str.Length == level); double w = levelW[level] / 2; double h = levelH[level] / 2; int strlen = str.Length; Rectangle rectangle = ctx.MakeRectangle(cx - w, cx + w, cy - h, cy + h); SpatialRelation v = shape.Relate(rectangle); if (SpatialRelation.CONTAINS == v) { str.Append(c); //str.append(SpatialPrefixGrid.COVER); matches.Add(new QuadCell(str.ToString(), v.Transpose(), this)); } else if (SpatialRelation.DISJOINT == v) { // nothing } else { // SpatialRelation.WITHIN, SpatialRelation.INTERSECTS str.Append(c); int nextLevel = level + 1; if (nextLevel >= maxLevel) { //str.append(SpatialPrefixGrid.INTERSECTS); matches.Add(new QuadCell(str.ToString(), v.Transpose(), this)); } else { Build(cx, cy, nextLevel, matches, str, shape, maxLevel); } } str.Length = strlen; } public class QuadCell : Node { public QuadCell(String token, QuadPrefixTree enclosingInstance) : base(enclosingInstance, token) { } public QuadCell(String token, SpatialRelation shapeRel, QuadPrefixTree enclosingInstance) : base(enclosingInstance, token) { this.shapeRel = shapeRel; } public override void Reset(string newToken) { base.Reset(newToken); shape = null; } public override IList<Node> GetSubCells() { var tree = (QuadPrefixTree)spatialPrefixTree; var cells = new List<Node>(4) { new QuadCell(GetTokenString() + "A", tree), new QuadCell(GetTokenString() + "B", tree), new QuadCell(GetTokenString() + "C", tree), new QuadCell(GetTokenString() + "D", tree) }; return cells; } public override int GetSubCellsSize() { return 4; } public override Node GetSubCell(Point p) { return ((QuadPrefixTree)spatialPrefixTree).GetNode(p, GetLevel() + 1); //not performant! } private Shape shape;//cache public override Shape GetShape() { if (shape == null) shape = MakeShape(); return shape; } private Rectangle MakeShape() { String token = GetTokenString(); var tree = ((QuadPrefixTree)spatialPrefixTree); double xmin = tree.xmin; double ymin = tree.ymin; for (int i = 0; i < token.Length; i++) { char c = token[i]; if ('A' == c || 'a' == c) { ymin += tree.levelH[i]; } else if ('B' == c || 'b' == c) { xmin += tree.levelW[i]; ymin += tree.levelH[i]; } else if ('C' == c || 'c' == c) { // nothing really } else if ('D' == c || 'd' == c) { xmin += tree.levelW[i]; } else { throw new Exception("unexpected char: " + c); } } int len = token.Length; double width, height; if (len > 0) { width = tree.levelW[len - 1]; height = tree.levelH[len - 1]; } else { width = tree.gridW; height = tree.gridH; } return spatialPrefixTree.ctx.MakeRectangle(xmin, xmin + width, ymin, ymin + height); } }//QuadCell } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Concurrent; using System.Collections.Specialized; using System.Configuration; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; using System.Threading; using Microsoft.Xrm.Client.Configuration; using Microsoft.Xrm.Client.Runtime; using Microsoft.Xrm.Client.Services.Samples; using Microsoft.Xrm.Client.Threading; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Query; namespace Microsoft.Xrm.Client.Services { /// <summary> /// An <see cref="IOrganizationService"/> that is constructed from a <see cref="CrmConnection"/>. /// </summary> public class OrganizationService : IDisposable, IOrganizationService, IInitializable { private static readonly string _organizationUri = "/XRMServices/2011/Organization.svc"; private static IServiceConfiguration<IOrganizationService> _config; private static readonly ConcurrentDictionary<string, IServiceConfiguration<IOrganizationService>> _configLookup = new ConcurrentDictionary<string, IServiceConfiguration<IOrganizationService>>(); private static readonly ConcurrentDictionary<string, SecurityTokenResponse> _userTokenLookup = new ConcurrentDictionary<string, SecurityTokenResponse>(); private readonly InnerOrganizationService _service; internal static void Reset() { _config = null; _configLookup.Clear(); _userTokenLookup.Clear(); } /// <summary> /// The nested proxy service. /// </summary> public IOrganizationService InnerService { get { return _service.Value; } } public OrganizationService(string connectionStringName) : this(new CrmConnection(connectionStringName)) { } public OrganizationService(CrmConnection connection) { _service = new InnerOrganizationService(error => ToOrganizationService(connection, error), connection.Timeout); } public OrganizationService(IOrganizationService service) { _service = new InnerOrganizationService(error => service, null); } /// <summary> /// Initializes custom settings. /// </summary> /// <param name="name"></param> /// <param name="config"></param> public virtual void Initialize(string name, NameValueCollection config) { } protected virtual IOrganizationService ToOrganizationService(CrmConnection connection) { return ToOrganizationService(connection, null); } protected virtual IOrganizationService ToOrganizationService(CrmConnection connection, Exception error) { var service = ToOrganizationServiceProxy(connection); return service; } protected virtual OrganizationServiceProxy ToOrganizationServiceProxy(CrmConnection connection) { connection.ThrowOnNull("connection"); if (connection.ServiceUri == null) throw new ConfigurationErrorsException("The connection's 'ServiceUri' must be specified."); var clientCredentials = connection.ClientCredentials; OrganizationServiceProxy service; // retrieve the ServiceConfiguration from cache var config = GetServiceConfiguration(connection); var isClaimsMode = config.AuthenticationType == AuthenticationProviderType.Federation || config.AuthenticationType == AuthenticationProviderType.OnlineFederation || config.AuthenticationType == AuthenticationProviderType.LiveId; if (isClaimsMode && clientCredentials != null) { // get the user token for claims authentication var userTokenResponse = GetUserTokenResponse(connection, config); Assert(userTokenResponse != null && userTokenResponse.Token != null, "The user authentication failed!"); service = new OrganizationServiceProxy(config, userTokenResponse); } else { // AD authentication service = new OrganizationServiceProxy(config, clientCredentials); } service.CallerId = connection.CallerId ?? Guid.Empty; if (connection.Timeout != null) service.Timeout = connection.Timeout.Value; return service; } protected virtual IServiceConfiguration<IOrganizationService> GetServiceConfiguration(CrmConnection connection) { var mode = connection.ServiceConfigurationInstanceMode; if (mode == ServiceConfigurationInstanceMode.Static) { return _config ?? (_config = CreateServiceConfiguration(connection)); } if (mode == ServiceConfigurationInstanceMode.PerName) { var key = connection.GetConnectionId(); if (!_configLookup.ContainsKey(key)) { _configLookup[key] = CreateServiceConfiguration(connection); } return _configLookup[key]; } if (mode == ServiceConfigurationInstanceMode.PerRequest && HttpSingleton<IServiceConfiguration<IOrganizationService>>.Enabled) { var key = connection.GetConnectionId(); return HttpSingleton<IServiceConfiguration<IOrganizationService>>.GetInstance(key, () => CreateServiceConfiguration(connection)); } var config = CreateServiceConfiguration(connection); return config; } protected virtual IServiceConfiguration<IOrganizationService> CreateServiceConfiguration(CrmConnection connection) { var uri = connection.ServiceUri; var fullServiceUri = uri.AbsolutePath.EndsWith(_organizationUri, StringComparison.OrdinalIgnoreCase) ? uri : new Uri(uri, uri.AbsolutePath.TrimEnd('/') + _organizationUri); var proxyTypesEnabled = connection.ProxyTypesEnabled; var proxyTypesAssembly = connection.ProxyTypesAssembly; var config = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(fullServiceUri); if (proxyTypesEnabled) { // configure the data contract surrogate at configuration time instead of at runtime var behavior = new ProxyTypesBehavior(proxyTypesAssembly) as IEndpointBehavior; behavior.ApplyClientBehavior(config.CurrentServiceEndpoint, null); } return config; } private static void Assert(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } protected virtual SecurityTokenResponse GetUserTokenResponse(CrmConnection connection, IServiceConfiguration<IOrganizationService> config) { var expiryWindow = connection.UserTokenExpiryWindow; if (expiryWindow != TimeSpan.Zero) { var key = connection.GetConnectionId(); SecurityTokenResponse token; // check if the token has expired if (!_userTokenLookup.TryGetValue(key, out token) || CheckIfTokenIsExpired(token, expiryWindow)) { token = CreateUserTokenResponse(connection, config); _userTokenLookup[key] = token; } return token; } var userTokenResponse = CreateUserTokenResponse(connection, config); return userTokenResponse; } protected bool CheckIfTokenIsExpired(SecurityTokenResponse token, TimeSpan? expiryWindow) { var now = DateTime.UtcNow; var duration = token.Token.ValidTo - token.Token.ValidFrom; if (expiryWindow == null || duration < expiryWindow.Value) return now >= token.Token.ValidTo; var expired = (now + expiryWindow.Value) > token.Token.ValidTo; return expired; } protected virtual SecurityTokenResponse CreateUserTokenResponse(CrmConnection connection, IServiceConfiguration<IOrganizationService> config) { var homeRealmUri = connection.HomeRealmUri; var clientCredentials = connection.ClientCredentials; var deviceCredentials = connection.DeviceCredentials; if (clientCredentials == null) throw new ConfigurationErrorsException("The connection's user credentials must be specified."); SecurityTokenResponse userTokenResponse; if (config.AuthenticationType == AuthenticationProviderType.LiveId) { if (deviceCredentials == null || deviceCredentials.UserName == null) { throw new ConfigurationErrorsException("The connection's device credentials must be specified."); } var deviceUserName = deviceCredentials.UserName.UserName; var devicePassword = deviceCredentials.UserName.Password; if (string.IsNullOrWhiteSpace(deviceUserName)) throw new ConfigurationErrorsException("The connection's device Id must be specified."); if (string.IsNullOrWhiteSpace(devicePassword)) throw new ConfigurationErrorsException("The connection's device password must be specified."); if (devicePassword.Length < 6) throw new ConfigurationErrorsException("The connection's device password must be at least 6 characters."); // prepend the DevicePrefix to the device Id var extendedDeviceCredentials = new ClientCredentials(); extendedDeviceCredentials.UserName.UserName = DeviceIdManager.DevicePrefix + deviceCredentials.UserName.UserName; extendedDeviceCredentials.UserName.Password = deviceCredentials.UserName.Password; SecurityTokenResponse deviceTokenResponse; try { deviceTokenResponse = config.AuthenticateDevice(extendedDeviceCredentials); } catch (MessageSecurityException) { // try register the device credentials deviceTokenResponse = RegisterDeviceCredentials(deviceCredentials) // try re-authenticate ? config.AuthenticateDevice(extendedDeviceCredentials) : null; } Assert(deviceTokenResponse != null && deviceTokenResponse.Token != null, "The device authentication failed!"); userTokenResponse = config.Authenticate(clientCredentials, deviceTokenResponse); } else { if (homeRealmUri != null) { var appliesTo = config.PolicyConfiguration.SecureTokenServiceIdentifier; var homeRealmSecurityTokenResponse = config.AuthenticateCrossRealm(clientCredentials, appliesTo, homeRealmUri); Assert(homeRealmSecurityTokenResponse != null && homeRealmSecurityTokenResponse.Token != null, "The user authentication failed!"); userTokenResponse = config.Authenticate(homeRealmSecurityTokenResponse.Token); } else { userTokenResponse = config.Authenticate(clientCredentials); } } return userTokenResponse; } protected bool RegisterDeviceCredentials(ClientCredentials deviceCredentials) { var response = DeviceIdManager.RegisterDevice(deviceCredentials); return response.IsSuccess; } #region IOrganizationService Members public virtual Guid Create(Entity entity) { return _service.UsingService(s => s.Create(entity)); } public virtual Entity Retrieve(string entityName, Guid id, ColumnSet columnSet) { return _service.UsingService(s => s.Retrieve(entityName, id, columnSet)); } public virtual void Update(Entity entity) { _service.UsingService(s => s.Update(entity)); } public virtual void Delete(string entityName, Guid id) { _service.UsingService(s => s.Delete(entityName, id)); } public virtual OrganizationResponse Execute(OrganizationRequest request) { return _service.UsingService(s => s.Execute(request)); } public virtual void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities) { _service.UsingService(s => s.Associate(entityName, entityId, relationship, relatedEntities)); } public virtual void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities) { _service.UsingService(s => s.Disassociate(entityName, entityId, relationship, relatedEntities)); } public virtual EntityCollection RetrieveMultiple(QueryBase query) { return _service.UsingService(s => s.RetrieveMultiple(query)); } #endregion #region IDisposable Members public virtual void Dispose() { var service = _service.Value as IDisposable; if (service != null) { service.Dispose(); } } #endregion private class InnerOrganizationService { private readonly Func<Exception, IOrganizationService> _serviceFactory; private readonly ReaderWriterLockSlim _serviceLock = new ReaderWriterLockSlim(); private readonly TimeSpan _serviceLockTimeout; private Lazy<IOrganizationService> _service; public InnerOrganizationService(Func<Exception, IOrganizationService> serviceFactory, TimeSpan? serviceLockTimeout) { if (serviceFactory == null) { throw new ArgumentNullException("serviceFactory"); } _serviceFactory = serviceFactory; _service = new Lazy<IOrganizationService>(() => _serviceFactory(null)); _serviceLockTimeout = serviceLockTimeout ?? TimeSpan.FromSeconds(30); } public IOrganizationService Value { get { if (!_serviceLock.TryEnterReadLock(_serviceLockTimeout)) { throw new TimeoutException("Failed to acquire read lock on inner service."); } try { return _service.Value; } finally { _serviceLock.ExitReadLock(); } } } public void UsingService(Action<IOrganizationService> action) { if (!_serviceLock.TryEnterReadLock(_serviceLockTimeout)) { throw new TimeoutException("Failed to acquire read lock on inner service."); } try { try { action(_service.Value); } finally { _serviceLock.ExitReadLock(); } } catch (FaultException<OrganizationServiceFault> e) when (e.Detail.ErrorCode == -2147176347) { ResetService(e, action); } catch (EndpointNotFoundException e) { ResetService(e, action); } catch (TimeoutException e) { ResetService(e, action); } catch (MessageSecurityException) { ResetService(null, action); } } public TResult UsingService<TResult>(Func<IOrganizationService, TResult> action) { if (!_serviceLock.TryEnterReadLock(_serviceLockTimeout)) { throw new TimeoutException("Failed to acquire read lock on inner service."); } try { try { return action(_service.Value); } finally { _serviceLock.ExitReadLock(); } } catch (FaultException<OrganizationServiceFault> e) when (e.Detail.ErrorCode == -2147176347) { return ResetService(e, action); } catch (EndpointNotFoundException e) { return ResetService(e, action); } catch (TimeoutException e) { return ResetService(e, action); } catch (MessageSecurityException) { return ResetService(null, action); } } private void ResetService(Exception e, Action<IOrganizationService> action) { ResetService(e); if (!_serviceLock.TryEnterReadLock(_serviceLockTimeout)) { throw new TimeoutException("Failed to acquire read lock on inner service."); } try { action(_service.Value); } finally { _serviceLock.ExitReadLock(); } } private TResult ResetService<TResult>(Exception e, Func<IOrganizationService, TResult> action) { ResetService(e); if (!_serviceLock.TryEnterReadLock(_serviceLockTimeout)) { throw new TimeoutException("Failed to acquire read lock on inner service."); } try { return action(_service.Value); } finally { _serviceLock.ExitReadLock(); } } private void ResetService(Exception e) { if (!_serviceLock.TryEnterWriteLock(_serviceLockTimeout)) { throw new TimeoutException("Failed to acquire write lock on inner service."); } try { _service = new Lazy<IOrganizationService>(() => _serviceFactory(e)); } finally { _serviceLock.ExitWriteLock(); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Unmanaged { using System.Runtime.InteropServices; using System.Security; /// <summary> /// Ignite JNI native methods. /// </summary> [SuppressUnmanagedCodeSecurity] internal unsafe static class IgniteJniNativeMethods { [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteReallocate")] public static extern int Reallocate(long memPtr, int cap); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteIgnitionStart")] public static extern void* IgnitionStart(void* ctx, sbyte* cfgPath, sbyte* gridName, int factoryId, long dataPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteIgnitionStop")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool IgnitionStop(void* ctx, sbyte* gridName, [MarshalAs(UnmanagedType.U1)] bool cancel); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteIgnitionStopAll")] public static extern void IgnitionStopAll(void* ctx, [MarshalAs(UnmanagedType.U1)] bool cancel); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorReleaseStart")] public static extern void ProcessorReleaseStart(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorProjection")] public static extern void* ProcessorProjection(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorCache")] public static extern void* ProcessorCache(void* ctx, void* obj, sbyte* name); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorCreateCache")] public static extern void* ProcessorCreateCache(void* ctx, void* obj, sbyte* name); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorGetOrCreateCache")] public static extern void* ProcessorGetOrCreateCache(void* ctx, void* obj, sbyte* name); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorAffinity")] public static extern void* ProcessorAffinity(void* ctx, void* obj, sbyte* name); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorDataStreamer")] public static extern void* ProcessorDataStreamer(void* ctx, void* obj, sbyte* name, [MarshalAs(UnmanagedType.U1)] bool keepBinary); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorTransactions")] public static extern void* ProcessorTransactions(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorCompute")] public static extern void* ProcessorCompute(void* ctx, void* obj, void* prj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorMessage")] public static extern void* ProcessorMessage(void* ctx, void* obj, void* prj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorEvents")] public static extern void* ProcessorEvents(void* ctx, void* obj, void* prj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorServices")] public static extern void* ProcessorServices(void* ctx, void* obj, void* prj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorExtensions")] public static extern void* ProcessorExtensions(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProcessorAtomicLong")] public static extern void* ProcessorAtomicLong(void* ctx, void* obj, sbyte* name, long initVal, [MarshalAs(UnmanagedType.U1)] bool create); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetInStreamOutLong")] public static extern long TargetInStreamOutLong(void* ctx, void* target, int opType, long memPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetInStreamOutStream")] public static extern void TargetInStreamOutStream(void* ctx, void* target, int opType, long inMemPtr, long outMemPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetInStreamOutObject")] public static extern void* TargetInStreanOutObject(void* ctx, void* target, int opType, long memPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetInObjectStreamOutStream")] public static extern void TargetInObjectStreamOutStream(void* ctx, void* target, int opType, void* arg, long inMemPtr, long outMemPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetOutLong")] public static extern long TargetOutLong(void* ctx, void* target, int opType); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetOutStream")] public static extern void TargetOutStream(void* ctx, void* target, int opType, long memPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetOutObject")] public static extern void* TargetOutObject(void* ctx, void* target, int opType); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetListenFuture")] public static extern void TargetListenFut(void* ctx, void* target, long futId, int typ); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetListenFutureForOperation")] public static extern void TargetListenFutForOp(void* ctx, void* target, long futId, int typ, int opId); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetListenFutureAndGet")] public static extern void* TargetListenFutAndGet(void* ctx, void* target, long futId, int typ); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTargetListenFutureForOperationAndGet")] public static extern void* TargetListenFutForOpAndGet(void* ctx, void* target, long futId, int typ, int opId); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAffinityPartitions")] public static extern int AffinityParts(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheWithSkipStore")] public static extern void* CacheWithSkipStore(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheWithNoRetries")] public static extern void* CacheWithNoRetries(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheWithExpiryPolicy")] public static extern void* CacheWithExpiryPolicy(void* ctx, void* obj, long create, long update, long access); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheWithAsync")] public static extern void* CacheWithAsync(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheWithKeepPortable")] public static extern void* CacheWithKeepBinary(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheClear")] public static extern void CacheClear(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheRemoveAll")] public static extern void CacheRemoveAll(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheOutOpQueryCursor")] public static extern void* CacheOutOpQueryCursor(void* ctx, void* obj, int type, long memPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheOutOpContinuousQuery")] public static extern void* CacheOutOpContinuousQuery(void* ctx, void* obj, int type, long memPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheIterator")] public static extern void* CacheIterator(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheLocalIterator")] public static extern void* CacheLocalIterator(void* ctx, void* obj, int peekModes); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheEnterLock")] public static extern void CacheEnterLock(void* ctx, void* obj, long id); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheExitLock")] public static extern void CacheExitLock(void* ctx, void* obj, long id); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheTryEnterLock")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool CacheTryEnterLock(void* ctx, void* obj, long id, long timeout); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheCloseLock")] public static extern void CacheCloseLock(void* ctx, void* obj, long id); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheRebalance")] public static extern void CacheRebalance(void* ctx, void* obj, long futId); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheSize")] public static extern int CacheSize(void* ctx, void* obj, int peekModes, [MarshalAs(UnmanagedType.U1)] bool loc); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCacheStoreCallbackInvoke")] public static extern void CacheStoreCallbackInvoke(void* ctx, void* obj, long memPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteComputeWithNoFailover")] public static extern void ComputeWithNoFailover(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteComputeWithTimeout")] public static extern void ComputeWithTimeout(void* ctx, void* target, long timeout); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteComputeExecuteNative")] public static extern void* ComputeExecuteNative(void* ctx, void* target, long taskPtr, long topVer); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteContinuousQueryClose")] public static extern void ContinuousQryClose(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteContinuousQueryGetInitialQueryCursor")] public static extern void* ContinuousQryGetInitialQueryCursor(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerListenTopology")] public static extern void DataStreamerListenTop(void* ctx, void* obj, long ptr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerAllowOverwriteGet")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool DataStreamerAllowOverwriteGet(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerAllowOverwriteSet")] public static extern void DataStreamerAllowOverwriteSet(void* ctx, void* obj, [MarshalAs(UnmanagedType.U1)] bool val); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerSkipStoreGet")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool DataStreamerSkipStoreGet(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerSkipStoreSet")] public static extern void DataStreamerSkipStoreSet(void* ctx, void* obj, [MarshalAs(UnmanagedType.U1)] bool val); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerPerNodeBufferSizeGet")] public static extern int DataStreamerPerNodeBufferSizeGet(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerPerNodeBufferSizeSet")] public static extern void DataStreamerPerNodeBufferSizeSet(void* ctx, void* obj, int val); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerPerNodeParallelOperationsGet")] public static extern int DataStreamerPerNodeParallelOpsGet(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDataStreamerPerNodeParallelOperationsSet")] public static extern void DataStreamerPerNodeParallelOpsSet(void* ctx, void* obj, int val); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteMessagingWithAsync")] public static extern void* MessagingWithAsync(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProjectionForOthers")] public static extern void* ProjectionForOthers(void* ctx, void* obj, void* prj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProjectionForRemotes")] public static extern void* ProjectionForRemotes(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProjectionForDaemons")] public static extern void* ProjectionForDaemons(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProjectionForRandom")] public static extern void* ProjectionForRandom(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProjectionForOldest")] public static extern void* ProjectionForOldest(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProjectionForYoungest")] public static extern void* ProjectionForYoungest(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProjectionResetMetrics")] public static extern void ProjectionResetMetrics(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteProjectionOutOpRet")] public static extern void* ProjectionOutOpRet(void* ctx, void* obj, int type, long memPtr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteQueryCursorIterator")] public static extern void QryCursorIterator(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteQueryCursorClose")] public static extern void QryCursorClose(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAcquire")] public static extern void* Acquire(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteRelease")] public static extern void Release(void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsStart")] public static extern long TxStart(void* ctx, void* target, int concurrency, int isolation, long timeout, int txSize); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsCommit")] public static extern int TxCommit(void* ctx, void* target, long id); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsCommitAsync")] public static extern void TxCommitAsync(void* ctx, void* target, long id, long futId); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsRollback")] public static extern int TxRollback(void* ctx, void* target, long id); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsRollbackAsync")] public static extern void TxRollbackAsync(void* ctx, void* target, long id, long futId); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsClose")] public static extern int TxClose(void* ctx, void* target, long id); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsState")] public static extern int TxState(void* ctx, void* target, long id); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsSetRollbackOnly")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool TxSetRollbackOnly(void* ctx, void* target, long id); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteTransactionsResetMetrics")] public static extern void TxResetMetrics(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteThrowToJava")] public static extern void ThrowToJava(void* ctx, char* msg); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteHandlersSize")] public static extern int HandlersSize(); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteCreateContext")] public static extern void* CreateContext(void* opts, int optsLen, void* cbs); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDeleteContext")] public static extern void DeleteContext(void* ptr); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteDestroyJvm")] public static extern void DestroyJvm(void* ctx); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteEventsWithAsync")] public static extern void* EventsWithAsync(void* ctx, void* obj); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteEventsStopLocalListen")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool EventsStopLocalListen(void* ctx, void* obj, long hnd); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteEventsLocalListen")] public static extern void EventsLocalListen(void* ctx, void* obj, long hnd, int type); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteEventsIsEnabled")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool EventsIsEnabled(void* ctx, void* obj, int type); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteServicesWithAsync")] public static extern void* ServicesWithAsync(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteServicesWithServerKeepPortable")] public static extern void* ServicesWithServerKeepBinary(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteServicesCancel")] public static extern long ServicesCancel(void* ctx, void* target, char* name); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteServicesCancelAll")] public static extern long ServicesCancelAll(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteServicesGetServiceProxy")] public static extern void* ServicesGetServiceProxy(void* ctx, void* target, char* name, [MarshalAs(UnmanagedType.U1)] bool sticky); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAtomicLongGet")] public static extern long AtomicLongGet(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAtomicLongIncrementAndGet")] public static extern long AtomicLongIncrementAndGet(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAtomicLongAddAndGet")] public static extern long AtomicLongAddAndGet(void* ctx, void* target, long value); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAtomicLongDecrementAndGet")] public static extern long AtomicLongDecrementAndGet(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAtomicLongGetAndSet")] public static extern long AtomicLongGetAndSet(void* ctx, void* target, long value); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAtomicLongCompareAndSetAndGet")] public static extern long AtomicLongCompareAndSetAndGet(void* ctx, void* target, long expVal, long newVal); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAtomicLongIsClosed")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool AtomicLongIsClosed(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteAtomicLongClose")] public static extern void AtomicLongClose(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteListenableCancel")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool ListenableCancel(void* ctx, void* target); [DllImport(IgniteUtils.FileIgniteJniDll, EntryPoint = "IgniteListenableIsCancelled")] [return: MarshalAs(UnmanagedType.U1)] public static extern bool ListenableIsCancelled(void* ctx, void* target); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { public class XmlCustomReader : XmlReader { private bool _iscalled; public bool IsCalled { get { return _iscalled; } set { _iscalled = value; } } private XmlReader _wrappedreader = null; public XmlCustomReader(string filename, XmlReaderSettings settings) { XmlReader w = ReaderHelper.Create(filename, settings); XmlReaderSettings wsettings = new XmlReaderSettings(); wsettings.CheckCharacters = true; wsettings.DtdProcessing = DtdProcessing.Ignore; wsettings.ConformanceLevel = ConformanceLevel.Auto; _wrappedreader = ReaderHelper.Create(w, wsettings); } public XmlCustomReader(Stream stream, XmlReaderSettings settings, string baseUri) { XmlReader w = ReaderHelper.Create(stream, settings, baseUri); XmlReaderSettings wsettings = new XmlReaderSettings(); wsettings.CheckCharacters = true; wsettings.DtdProcessing = DtdProcessing.Ignore; wsettings.ConformanceLevel = ConformanceLevel.Auto; _wrappedreader = ReaderHelper.Create(w, wsettings); } public XmlCustomReader(XmlReader reader, XmlReaderSettings settings) { XmlReader w = ReaderHelper.Create(reader, settings); XmlReaderSettings wsettings = new XmlReaderSettings(); wsettings.CheckCharacters = true; wsettings.DtdProcessing = DtdProcessing.Ignore; wsettings.ConformanceLevel = ConformanceLevel.Auto; _wrappedreader = ReaderHelper.Create(w, wsettings); } public XmlCustomReader(TextReader textReader, XmlReaderSettings settings, string baseUri) { XmlReader w = ReaderHelper.Create(textReader, settings, baseUri); XmlReaderSettings wsettings = new XmlReaderSettings(); wsettings.CheckCharacters = true; wsettings.DtdProcessing = DtdProcessing.Ignore; wsettings.ConformanceLevel = ConformanceLevel.Auto; _wrappedreader = ReaderHelper.Create(w, wsettings); } public override XmlReaderSettings Settings { get { this.IsCalled = true; return _wrappedreader.Settings; } } // Node Properties public override XmlNodeType NodeType { get { this.IsCalled = true; return _wrappedreader.NodeType; } } public override string Name { get { this.IsCalled = true; return _wrappedreader.Name; } } public override string LocalName { get { this.IsCalled = true; return _wrappedreader.LocalName; } } public override string NamespaceURI { get { this.IsCalled = true; return _wrappedreader.NamespaceURI; } } public override string Prefix { get { this.IsCalled = true; return _wrappedreader.Prefix; } } public override bool HasValue { get { this.IsCalled = true; return _wrappedreader.HasValue; } } public override string Value { get { this.IsCalled = true; return _wrappedreader.Value; } } public override int Depth { get { this.IsCalled = true; return _wrappedreader.Depth; } } public override string BaseURI { get { this.IsCalled = true; return _wrappedreader.BaseURI; } } public override bool IsEmptyElement { get { this.IsCalled = true; return _wrappedreader.IsEmptyElement; } } public override bool IsDefault { get { this.IsCalled = true; return _wrappedreader.IsDefault; } } public override XmlSpace XmlSpace { get { this.IsCalled = true; return _wrappedreader.XmlSpace; } } public override string XmlLang { get { this.IsCalled = true; return _wrappedreader.XmlLang; } } // Reading Typed Content Methods public override System.Type ValueType { get { this.IsCalled = true; return _wrappedreader.ValueType; } } public override object ReadContentAsObject() { this.IsCalled = true; return _wrappedreader.ReadContentAsObject(); } public override bool ReadContentAsBoolean() { this.IsCalled = true; return _wrappedreader.ReadContentAsBoolean(); } public override DateTimeOffset ReadContentAsDateTimeOffset() { this.IsCalled = true; return _wrappedreader.ReadContentAsDateTimeOffset(); } public override double ReadContentAsDouble() { this.IsCalled = true; return _wrappedreader.ReadContentAsDouble(); } public override float ReadContentAsFloat() { this.IsCalled = true; return _wrappedreader.ReadContentAsFloat(); } public override decimal ReadContentAsDecimal() { this.IsCalled = true; return _wrappedreader.ReadContentAsDecimal(); } public override long ReadContentAsLong() { this.IsCalled = true; return _wrappedreader.ReadContentAsLong(); } public override int ReadContentAsInt() { this.IsCalled = true; return _wrappedreader.ReadContentAsInt(); } public override string ReadContentAsString() { this.IsCalled = true; return _wrappedreader.ReadContentAsString(); } public override object ReadContentAs(System.Type returnType, IXmlNamespaceResolver namespaceResolver) { this.IsCalled = true; return _wrappedreader.ReadContentAs(returnType, namespaceResolver); } public override object ReadElementContentAsObject() { this.IsCalled = true; return _wrappedreader.ReadElementContentAsObject(); } public override object ReadElementContentAsObject(string localName, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsObject(localName, NamespaceURI); } public override bool ReadElementContentAsBoolean() { this.IsCalled = true; return _wrappedreader.ReadElementContentAsBoolean(); } public override bool ReadElementContentAsBoolean(string localName, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsBoolean(localName, namespaceURI); } public override decimal ReadElementContentAsDecimal() { this.IsCalled = true; return _wrappedreader.ReadElementContentAsDecimal(); } public override decimal ReadElementContentAsDecimal(string localname, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsDecimal(localname, namespaceURI); } public override float ReadElementContentAsFloat() { this.IsCalled = true; return _wrappedreader.ReadElementContentAsFloat(); } public override float ReadElementContentAsFloat(string localname, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsFloat(localname, namespaceURI); } public override double ReadElementContentAsDouble() { this.IsCalled = true; return _wrappedreader.ReadElementContentAsDouble(); } public override double ReadElementContentAsDouble(string localname, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsDouble(localname, namespaceURI); } public override long ReadElementContentAsLong() { this.IsCalled = true; return _wrappedreader.ReadElementContentAsLong(); } public override long ReadElementContentAsLong(string localname, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsLong(localname, namespaceURI); } public override int ReadElementContentAsInt() { this.IsCalled = true; return _wrappedreader.ReadElementContentAsInt(); } public override int ReadElementContentAsInt(string localname, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsInt(localname, namespaceURI); } public override string ReadElementContentAsString() { this.IsCalled = true; return _wrappedreader.ReadElementContentAsString(); } public override string ReadElementContentAsString(string localname, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsString(localname, namespaceURI); } public override object ReadElementContentAs(System.Type returnType, IXmlNamespaceResolver namespaceResolver) { this.IsCalled = true; return _wrappedreader.ReadElementContentAs(returnType, namespaceResolver); } public override object ReadElementContentAs(System.Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadElementContentAs(returnType, namespaceResolver, localName, namespaceURI); } public override bool CanReadValueChunk { get { this.IsCalled = true; return _wrappedreader.CanReadValueChunk; } } public override int ReadValueChunk(char[] buffer, int startIndex, int count) { this.IsCalled = true; return _wrappedreader.ReadValueChunk(buffer, startIndex, count); } public override bool CanReadBinaryContent { get { this.IsCalled = true; return _wrappedreader.CanReadBinaryContent; } } public override int ReadContentAsBase64(byte[] buffer, int startIndex, int count) { this.IsCalled = true; return _wrappedreader.ReadContentAsBase64(buffer, startIndex, count); } public override int ReadContentAsBinHex(byte[] buffer, int startIndex, int count) { this.IsCalled = true; return _wrappedreader.ReadContentAsBinHex(buffer, startIndex, count); } public override int ReadElementContentAsBase64(byte[] buffer, int startIndex, int count) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsBase64(buffer, startIndex, count); } public override int ReadElementContentAsBinHex(byte[] buffer, int startIndex, int count) { this.IsCalled = true; return _wrappedreader.ReadElementContentAsBinHex(buffer, startIndex, count); } // Attribute Accessors public override int AttributeCount { get { this.IsCalled = true; return _wrappedreader.AttributeCount; } } public override bool HasAttributes { get { this.IsCalled = true; return _wrappedreader.HasAttributes; } } public override string GetAttribute(string name) { this.IsCalled = true; return _wrappedreader.GetAttribute(name); } public override string GetAttribute(string name, string namespaceURI) { this.IsCalled = true; return _wrappedreader.GetAttribute(name, namespaceURI); } public override string GetAttribute(int i) { this.IsCalled = true; return _wrappedreader.GetAttribute(i); } public override bool MoveToAttribute(string name) { this.IsCalled = true; return _wrappedreader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string ns) { this.IsCalled = true; return _wrappedreader.MoveToAttribute(name, ns); } public override void MoveToAttribute(int i) { this.IsCalled = true; _wrappedreader.MoveToAttribute(i); } public override bool MoveToFirstAttribute() { this.IsCalled = true; return _wrappedreader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { this.IsCalled = true; return _wrappedreader.MoveToNextAttribute(); } public override bool MoveToElement() { this.IsCalled = true; return _wrappedreader.MoveToElement(); } // Moving through the Stream public override bool Read() { this.IsCalled = true; return _wrappedreader.Read(); } public override bool EOF { get { this.IsCalled = true; return _wrappedreader.EOF; } } public override ReadState ReadState { get { this.IsCalled = true; return _wrappedreader.ReadState; } } public override void Skip() { this.IsCalled = true; _wrappedreader.Skip(); } public override string ReadInnerXml() { this.IsCalled = true; return _wrappedreader.ReadInnerXml(); } public override string ReadOuterXml() { this.IsCalled = true; return _wrappedreader.ReadOuterXml(); } // Helper Methods public override XmlReader ReadSubtree() { this.IsCalled = true; return _wrappedreader.ReadSubtree(); } public override XmlNodeType MoveToContent() { this.IsCalled = true; return _wrappedreader.MoveToContent(); } public override bool IsStartElement() { this.IsCalled = true; return _wrappedreader.IsStartElement(); } public override bool IsStartElement(string localname) { this.IsCalled = true; return _wrappedreader.IsStartElement(localname); } public override bool IsStartElement(string name, string ns) { this.IsCalled = true; return _wrappedreader.IsStartElement(name, ns); } public override void ReadStartElement() { this.IsCalled = true; _wrappedreader.ReadStartElement(); } public override void ReadStartElement(string name) { this.IsCalled = true; _wrappedreader.ReadStartElement(name); } public override void ReadStartElement(string localname, string ns) { this.IsCalled = true; _wrappedreader.ReadStartElement(localname, ns); } public override void ReadEndElement() { this.IsCalled = true; _wrappedreader.ReadEndElement(); } public override bool ReadToFollowing(string name) { this.IsCalled = true; return _wrappedreader.ReadToFollowing(name); } public override bool ReadToFollowing(string localName, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadToFollowing(localName, namespaceURI); } public override bool ReadToDescendant(string name) { this.IsCalled = true; return _wrappedreader.ReadToDescendant(name); } public override bool ReadToDescendant(string localName, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadToDescendant(localName, namespaceURI); } public override bool ReadToNextSibling(string name) { this.IsCalled = true; return _wrappedreader.ReadToNextSibling(name); } public override bool ReadToNextSibling(string localName, string namespaceURI) { this.IsCalled = true; return _wrappedreader.ReadToNextSibling(localName, namespaceURI); } // Nametable and Namespace Helpers public override XmlNameTable NameTable { get { this.IsCalled = true; return _wrappedreader.NameTable; } } public override string LookupNamespace(string prefix) { this.IsCalled = true; return _wrappedreader.LookupNamespace(prefix); } // Entity Handling public override bool ReadAttributeValue() { this.IsCalled = true; return _wrappedreader.ReadAttributeValue(); } public override void ResolveEntity() { this.IsCalled = true; _wrappedreader.ResolveEntity(); } public override bool CanResolveEntity { get { this.IsCalled = true; return _wrappedreader.CanResolveEntity; } } } }
using System; using System.Text; using System.Data.Common; using System.Data.Linq; using System.Data.Entity; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Runtime.Serialization; using System.Configuration; using System.ServiceModel; using System.IO; using System.Linq; using System.ComponentModel; using System.Reflection; using System.Xml; using System.Xml.Serialization; using System.Xml.Linq; using Hydra.Framework; using Hydra.Framework.Java; using Hydra.Framework.Helpers; using Hydra.Framework.Cryptographics; using Hydra.Framework.Mapping.CoordinateSystems; using Hydra.Framework.Collections; using Hydra.Framework.Conversions; using DomainModel = Hydra.DomainModel; using Hydra.DomainStatus; using Hydra.Data.Model; using Hydra.Data.RepositoryInterfaces; using Hydra.Domain.Mapping; using Hydra.SqlRepository; using Hydra.SqlRepository.EntityConfiguration; using Hydra.ServiceContracts; namespace Hydra.Services { /// <summary> /// Image Business Service - Responsible for Maintaining Image data /// </summary> [Serializable] [DataContract(Namespace = "http://www.Hydra.com/BusinessServices")] public class ImageService : IImageService { #region Member Variables /// <summary> /// Gets or sets the repository. /// </summary> /// <value>The repository.</value> public IRepository<Hydra.Data.Model.Image> Repository { get; private set; } /// <summary> /// Organisational Mapper /// </summary> private ImageMapping mapper = new ImageMapping(); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ImageService"/> class. /// </summary> /// <param name="repository">The repository I want the Image manager to support.</param> public ImageService(IRepository<Hydra.Data.Model.Image> repository) : base() { try { // Create RoleRepository Reference Repository = repository; } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } } #endregion #region Properties #endregion #region Private Methods /// <summary> /// Performs the date validation. /// </summary> /// <param name="image">The image.</param> private void PerformDateValidation(DomainModel.InternalImage image) { try { if (image.ChangedOn != null && image.ChangedOn.Equals(DateTime.MinValue)) image.ChangedOn = DateTime.Now; } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } } /// <summary> /// Performs the mandatory validation. /// </summary> /// <param name="image">The image.</param> private void PerformMandatoryValidation(DomainModel.InternalImage image) { try { if (image.ID.Equals(-1)) throw new MandatoryDataValidationException("Internal Validation Error processing Mandatory Attribute", "ID"); if (string.IsNullOrEmpty(image.Name)) throw new MandatoryDataValidationException("Internal Validation Error processing Mandatory Attribute", "Name"); if (string.IsNullOrEmpty(image.Path)) throw new MandatoryDataValidationException("Internal Validation Error processing Mandatory Attribute", "Path"); if (image.PointX <= 0.0F || image.PointY <= 0.0F) throw new MandatoryDataValidationException("Internal Validation Error processing Mandatory Attribute", "Size"); } catch (MandatoryDataValidationException me) { CacheUtil.ReportException(me); throw me; } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } } #endregion #region Public Methods /// <summary> /// Updates the image. /// </summary> /// <param name="image">The image.</param> public void Update(DomainModel.InternalImage image) { try { PerformDateValidation(image); PerformMandatoryValidation(image); Repository.Update(mapper.MapDomainEntityToDataEntity(image)); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } } /// <summary> /// Adds the image. /// </summary> /// <param name="image">The image.</param> public void Add(ref DomainModel.InternalImage image) { int maxRecords = -1; try { PerformDateValidation(image); PerformMandatoryValidation(image); Image newImage = Repository.Add(mapper.MapDomainEntityToDataEntity(image)); // Retrieve Count maxRecords = Repository.Count; // Translate to new image image = mapper.MapDataEntityToDomainEntity(newImage); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } } /// <summary> /// Deletes the image. /// </summary> /// <param name="image">The image.</param> public void Delete(DomainModel.InternalImage image) { try { Repository.Delete(image.ID); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } } /// <summary> /// Gets the specified image /// </summary> /// <param name="id">The image id.</param> /// <returns></returns> public DomainModel.InternalImage Get(int id) { DomainModel.InternalImage image = null; try { image = mapper.MapDataEntityToDomainEntity(Repository.GetById(id)); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return image; } /// <summary> /// Does the item Exist in the repository /// </summary> /// <param name="id">The item id.</param> /// <returns>Boolean, true if exists</returns> public bool Exists(int id) { bool result = false; try { result = (id > 0 && Repository.GetById(id) != null); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return result; } /// <summary> /// Find the Maximum Number of objects currently in persisted cache. /// </summary> /// <returns>Max Number of items</returns> public int MaxID() { return (from c in Repository.GetAll.ToList<Image>() select c.ID).Max(); } /// <summary> /// AccountList of Images /// </summary> /// <returns></returns> public List<DomainModel.InternalImage> List() { List<DomainModel.InternalImage> myList = new System.Collections.Generic.List<DomainModel.InternalImage>(); try { var q = from c in Repository.GetAll.ToList<Image>() select c; foreach (Image or in q) myList.Add(mapper.MapDataEntityToDomainEntity(or)); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return myList; } /// <summary> /// AccountList of Images /// </summary> /// <param name="organisationId">The organisation id.</param> /// <returns></returns> public List<DomainModel.InternalImage> List(int organisationId) { List<DomainModel.InternalImage> myList = new System.Collections.Generic.List<DomainModel.InternalImage>(); try { var q = from c in Repository.GetAll.ToList<Image>() where c.OrganisationID.Equals(organisationId) select c; foreach (Image or in q) myList.Add(mapper.MapDataEntityToDomainEntity(or)); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return myList; } /// <summary> /// AccountList of Images /// </summary> /// <param name="organisationId">The organisation id.</param> /// <param name="type">The type.</param> /// <returns></returns> public List<DomainModel.InternalImage> List(int organisationId, DomainModel.ImageType type) { List<DomainModel.InternalImage> myList = new System.Collections.Generic.List<DomainModel.InternalImage>(); try { var q = from c in Repository.GetAll.ToList<Image>() where c.OrganisationID.Equals(organisationId) && c.Type.Equals(type) select c; foreach (Image or in q) myList.Add(mapper.MapDataEntityToDomainEntity(or)); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return myList; } /// <summary> /// AccountList of Images /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public List<DomainModel.InternalImage> List(DomainModel.ImageType type) { List<DomainModel.InternalImage> myList = new System.Collections.Generic.List<DomainModel.InternalImage>(); try { var q = from c in Repository.GetAll.ToList<Image>() where c.Type.Equals((int)type) select c; foreach (Image or in q) myList.Add(mapper.MapDataEntityToDomainEntity(or)); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return myList; } /// <summary> /// Builds the cache list from database. /// </summary> /// <returns>A new Dictionary</returns> public Dictionary<int, DomainModel.InternalImage> BuildCacheListFromDatabase() { Dictionary<int, DomainModel.InternalImage> tree = null; try { tree = new System.Collections.Generic.Dictionary<int, DomainModel.InternalImage>(); List().ForEach((item) => { tree.Add(item.ID, item); }); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return tree; } /// <summary> /// Serializes the specified image. /// </summary> /// <param name="image">The image to serialize.</param> /// <returns></returns> public string Serialize(DomainModel.InternalImage image) { string result = string.Empty; try { using (MemoryStream ms = new MemoryStream()) { using (XmlTextWriter writer = new XmlTextWriter(ms, System.Text.Encoding.GetEncoding(Strings.ENCODING))) { XmlSerializer s = new XmlSerializer(typeof(DomainModel.InternalImage)); if (s != null) { s.Serialize(writer, image); result = System.Text.Encoding.GetEncoding(Strings.ENCODING).GetString(ms.ToArray()); } } } } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return result; } /// <summary> /// Serialize a list of Images. /// </summary> /// <param name="list">The list of Images.</param> /// <returns></returns> public string Serialize(List<DomainModel.InternalImage> list) { StringBuilder sb = new StringBuilder(); string result = string.Empty; try { sb.Append(Strings.XMLHEADER); sb.Append(string.Format("<{0}>", Strings.IMAGE_COLLECTION_NAME)); list.ForEach((item) => { result = Serialize(item); sb.Append(result.Replace(Strings.XMLHEADER, "").Replace(Strings.XMLXSI, "").Replace(Strings.XMLXSD, "")); }); sb.Append(string.Format("</{0}>", Strings.IMAGE_COLLECTION_NAME)); } catch (Exception ex) { CacheUtil.ReportException(ex); throw ex; } return sb.ToString(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Transactions; using Orleans.Utilities; namespace Orleans.CodeGeneration { internal static class GrainInterfaceUtils { private static readonly IEqualityComparer<MethodInfo> MethodComparer = new MethodInfoComparer(); [Serializable] internal class RulesViolationException : ArgumentException { public RulesViolationException(string message, List<string> violations) : base(message) { Violations = violations; } public List<string> Violations { get; private set; } } public static bool IsGrainInterface(Type t) { if (t.GetTypeInfo().IsClass) return false; if (t == typeof(IGrainObserver) || t == typeof(IAddressable) || t == typeof(IGrainExtension)) return false; if (t == typeof(IGrain) || t == typeof(IGrainWithGuidKey) || t == typeof(IGrainWithIntegerKey) || t == typeof(IGrainWithGuidCompoundKey) || t == typeof(IGrainWithIntegerCompoundKey)) return false; if (t == typeof (ISystemTarget)) return false; return typeof (IAddressable).IsAssignableFrom(t); } public static MethodInfo[] GetMethods(Type grainType, bool bAllMethods = true) { var methodInfos = new List<MethodInfo>(); GetMethodsImpl(grainType, grainType, methodInfos); var flags = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance; if (!bAllMethods) flags |= BindingFlags.DeclaredOnly; MethodInfo[] infos = grainType.GetMethods(flags); foreach (var methodInfo in infos) if (!methodInfos.Contains(methodInfo, MethodComparer)) methodInfos.Add(methodInfo); return methodInfos.ToArray(); } public static string GetParameterName(ParameterInfo info) { var n = info.Name; return string.IsNullOrEmpty(n) ? "arg" + info.Position : n; } public static bool IsTaskType(Type t) { var typeInfo = t.GetTypeInfo(); return t == typeof (Task) || (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.Task`1"); } /// <summary> /// Whether method is read-only, i.e. does not modify grain state, /// a method marked with [ReadOnly]. /// </summary> /// <param name="info"></param> /// <returns></returns> public static bool IsReadOnly(MethodInfo info) { return info.GetCustomAttributes(typeof (ReadOnlyAttribute), true).Any(); } public static bool IsAlwaysInterleave(MethodInfo methodInfo) { return methodInfo.GetCustomAttributes(typeof (AlwaysInterleaveAttribute), true).Any(); } public static bool IsUnordered(MethodInfo methodInfo) { var declaringTypeInfo = methodInfo.DeclaringType.GetTypeInfo(); return declaringTypeInfo.GetCustomAttributes(typeof(UnorderedAttribute), true).Any() || (declaringTypeInfo.GetInterfaces().Any( i => i.GetTypeInfo().GetCustomAttributes(typeof(UnorderedAttribute), true).Any() && declaringTypeInfo.GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo))) || IsStatelessWorker(methodInfo); } public static bool IsStatelessWorker(MethodInfo methodInfo) { var declaringTypeInfo = methodInfo.DeclaringType.GetTypeInfo(); return declaringTypeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() || (declaringTypeInfo.GetInterfaces().Any( i => i.GetTypeInfo().GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() && declaringTypeInfo.GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo))); } public static bool IsNewTransactionRequired(MethodInfo methodInfo) { TransactionAttribute transactionAttribute = methodInfo.GetCustomAttribute<TransactionAttribute>(true); if (transactionAttribute != null) { return transactionAttribute.Requirement == TransactionOption.RequiresNew; } return false; } public static bool IsTransactionRequired(MethodInfo methodInfo) { TransactionAttribute transactionAttribute = methodInfo.GetCustomAttribute<TransactionAttribute>(true); if (transactionAttribute != null) { return transactionAttribute.Requirement == TransactionOption.Required; } return false; } public static Dictionary<int, Type> GetRemoteInterfaces(Type type, bool checkIsGrainInterface = true) { var dict = new Dictionary<int, Type>(); if (IsGrainInterface(type)) dict.Add(GetGrainInterfaceId(type), type); Type[] interfaces = type.GetInterfaces(); foreach (Type interfaceType in interfaces.Where(i => !checkIsGrainInterface || IsGrainInterface(i))) dict.Add(GetGrainInterfaceId(interfaceType), interfaceType); return dict; } public static int ComputeMethodId(MethodInfo methodInfo) { var attr = methodInfo.GetCustomAttribute<MethodIdAttribute>(true); if (attr != null) return attr.MethodId; var strMethodId = new StringBuilder(methodInfo.Name); if (methodInfo.IsGenericMethodDefinition) { strMethodId.Append('<'); var first = true; foreach (var arg in methodInfo.GetGenericArguments()) { if (!first) strMethodId.Append(','); else first = false; strMethodId.Append(RuntimeTypeNameFormatter.Format(arg)); } strMethodId.Append('>'); } strMethodId.Append('('); ParameterInfo[] parameters = methodInfo.GetParameters(); bool bFirstTime = true; foreach (ParameterInfo info in parameters) { if (!bFirstTime) strMethodId.Append(','); var pt = info.ParameterType; if (pt.IsGenericParameter) { strMethodId.Append(pt.Name); } else { strMethodId.Append(RuntimeTypeNameFormatter.Format(info.ParameterType)); } bFirstTime = false; } strMethodId.Append(')'); return Utils.CalculateIdHash(strMethodId.ToString()); } public static int GetGrainInterfaceId(Type grainInterface) { return GetTypeCode(grainInterface); } public static ushort GetGrainInterfaceVersion(Type grainInterface) { if (typeof(IGrainExtension).IsAssignableFrom(grainInterface)) return 0; var attr = grainInterface.GetTypeInfo().GetCustomAttribute<VersionAttribute>(); return attr?.Version ?? Constants.DefaultInterfaceVersion; } public static bool IsTaskBasedInterface(Type type) { var methods = type.GetMethods(); // An interface is task-based if it has at least one method that returns a Task or at least one parent that's task-based. return methods.Any(m => IsTaskType(m.ReturnType)) || type.GetInterfaces().Any(IsTaskBasedInterface); } public static bool IsGrainType(Type grainType) { return typeof (IGrain).IsAssignableFrom(grainType); } public static int GetGrainClassTypeCode(Type grainClass) { return GetTypeCode(grainClass); } internal static bool TryValidateInterfaceRules(Type type, out List<string> violations) { violations = new List<string>(); bool success = ValidateInterfaceMethods(type, violations); return success && ValidateInterfaceProperties(type, violations); } internal static void ValidateInterfaceRules(Type type) { List<string> violations; if (!TryValidateInterfaceRules(type, out violations)) { if (ConsoleText.IsConsoleAvailable) { foreach (var violation in violations) ConsoleText.WriteLine("ERROR: " + violation); } throw new RulesViolationException( string.Format("{0} does not conform to the grain interface rules.", type.FullName), violations); } } internal static void ValidateInterface(Type type) { if (!IsGrainInterface(type)) throw new ArgumentException(String.Format("{0} is not a grain interface", type.FullName)); ValidateInterfaceRules(type); } private static bool ValidateInterfaceMethods(Type type, List<string> violations) { bool success = true; MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { if (method.IsSpecialName) continue; if (IsPureObserverInterface(method.DeclaringType)) { if (method.ReturnType != typeof (void)) { success = false; violations.Add(String.Format("Method {0}.{1} must return void because it is defined within an observer interface.", type.FullName, method.Name)); } } else if (!IsTaskType(method.ReturnType)) { success = false; violations.Add(String.Format("Method {0}.{1} must return Task or Task<T> because it is defined within a grain interface.", type.FullName, method.Name)); } ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo parameter in parameters) { if (parameter.IsOut) { success = false; violations.Add(String.Format("Argument {0} of method {1}.{2} is an output parameter. Output parameters are not allowed in grain interfaces.", GetParameterName(parameter), type.FullName, method.Name)); } if (parameter.ParameterType.GetTypeInfo().IsByRef) { success = false; violations.Add(String.Format("Argument {0} of method {1}.{2} is an a reference parameter. Reference parameters are not allowed.", GetParameterName(parameter), type.FullName, method.Name)); } } } return success; } private static bool ValidateInterfaceProperties(Type type, List<string> violations) { bool success = true; PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { success = false; violations.Add(String.Format("Properties are not allowed on grain interfaces: {0}.{1}.", type.FullName, property.Name)); } return success; } /// <summary> /// decide whether the class is derived from Grain /// </summary> private static bool IsPureObserverInterface(Type t) { if (!typeof (IGrainObserver).IsAssignableFrom(t)) return false; if (t == typeof (IGrainObserver)) return true; if (t == typeof (IAddressable)) return false; bool pure = false; foreach (Type iface in t.GetInterfaces()) { if (iface == typeof (IAddressable)) // skip IAddressable that will be in the list regardless continue; if (iface == typeof (IGrainExtension)) // Skip IGrainExtension, it's just a marker that can go on observer or grain interfaces continue; pure = IsPureObserverInterface(iface); if (!pure) return false; } return pure; } private class MethodInfoComparer : IEqualityComparer<MethodInfo> { public bool Equals(MethodInfo x, MethodInfo y) { return ComputeMethodId(x) == ComputeMethodId(y); } public int GetHashCode(MethodInfo obj) { throw new NotImplementedException(); } } /// <summary> /// Recurses through interface graph accumulating methods /// </summary> /// <param name="grainType">Grain type</param> /// <param name="serviceType">Service interface type</param> /// <param name="methodInfos">Accumulated </param> private static void GetMethodsImpl(Type grainType, Type serviceType, List<MethodInfo> methodInfos) { Type[] iTypes = GetRemoteInterfaces(serviceType, false).Values.ToArray(); var typeInfo = grainType.GetTypeInfo(); foreach (Type iType in iTypes) { var mapping = new InterfaceMapping(); if (typeInfo.IsClass) mapping = typeInfo.GetRuntimeInterfaceMap(iType); if (typeInfo.IsInterface || mapping.TargetType == grainType) { foreach (var methodInfo in iType.GetMethods()) { if (typeInfo.IsClass) { var mi = methodInfo; var match = mapping.TargetMethods.Any(info => MethodComparer.Equals(mi, info) && info.DeclaringType == grainType); if (match) if (!methodInfos.Contains(mi, MethodComparer)) methodInfos.Add(mi); } else if (!methodInfos.Contains(methodInfo, MethodComparer)) { methodInfos.Add(methodInfo); } } } } } private static int GetTypeCode(Type grainInterfaceOrClass) { var typeInfo = grainInterfaceOrClass.GetTypeInfo(); var attr = typeInfo.GetCustomAttributes<TypeCodeOverrideAttribute>(false).FirstOrDefault(); if (attr != null && attr.TypeCode > 0) { return attr.TypeCode; } var fullName = TypeUtils.GetTemplatedName( TypeUtils.GetFullName(grainInterfaceOrClass), grainInterfaceOrClass, grainInterfaceOrClass.GetGenericArguments(), t => false); return Utils.CalculateIdHash(fullName); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Core.ExternalSharingWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
/* Copyright 2013 Esri Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using ESRI.ArcGIS.Client; using ESRI.ArcGIS.Client.Geometry; namespace ESRI.ArcGIS.SilverlightMapApp { /// <summary> /// OverviewMap2 Control /// </summary> [TemplatePart(Name = "OVMapImage", Type = typeof(Map))] [TemplatePart(Name = "AOI", Type = typeof(Grid))] [TemplatePart(Name = "MapExtentBorder", Type = typeof(Border))] [TemplatePart(Name = "MapDisplayBorder", Type = typeof(Border))] [TemplatePart(Name = "MapDisplayEllipse", Type = typeof(Ellipse))] [TemplatePart(Name = "AOIprojection", Type = typeof(PlaneProjection))] [TemplatePart(Name = "MapProjection", Type = typeof(PlaneProjection))] [System.Windows.Markup.ContentProperty("Layer")] public class OverviewMap2 : Control { #region Private fields #region Template items Map OVMapImage; Grid AOI; Border MapExtentBorder; Border MapDisplayBorder; PlaneProjection AOIprojection; PlaneProjection MapProjection; Ellipse MapDisplayEllipse; #endregion private Envelope mapExtent; private Envelope fullExtent; private Envelope lastMapExtent = new Envelope(); private Envelope lastOVExtent; private Point startPoint; double offsetLeft = 0; double offsetTop = 0; private bool dragOn = false; private double maxWidth = 0; private double maxHeight = 0; bool usePlaneProjection = false; double marginLRFactor = 0.125; double marginTBFactor = 0.25; bool showOversize = false; double mapAngle = 0; #endregion public OverviewMap2() { this.DefaultStyleKey = typeof(OverviewMap2); } /// <summary> /// Static initialization for the <see cref="OverviewMap"/> control. /// </summary> static OverviewMap2() { //DefaultStyleKeyProperty.OverrideMetadata(typeof(OverviewMap2), // new FrameworkPropertyMetadata(typeof(OverviewMap2))); } /// <summary> /// When overridden in a derived class, is invoked whenever application code /// or internal processes (such as a rebuilding layout pass) call /// <see cref="M:System.Windows.Controls.Control.ApplyTemplate"/>. /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); string strvalue = Application.Current.Resources["UsePlaneProjection"] as string; if (strvalue != null) usePlaneProjection = bool.Parse(strvalue); if (usePlaneProjection) { strvalue = Application.Current.Resources["MapLeftRightMarginFactor"] as string; if (strvalue != null) { double val = double.Parse(strvalue); marginLRFactor = val / (1 + (2 * val)); } strvalue = Application.Current.Resources["MapTopBottomMarginFactor"] as string; if (strvalue != null) { double val = double.Parse(strvalue); marginTBFactor = val / (1 + (2 * val)); } } OVMapImage = GetTemplateChild("OVMapImage") as Map; if (OVMapImage == null) { throw new ArgumentNullException("Template child 'OVMapImage' not found"); } OVMapImage.Width = Width; OVMapImage.Height = Height; OVMapImage.ExtentChanged += (s,e) => { UpdateAOI(); }; MapExtentBorder = GetTemplateChild("MapExtentBorder") as Border; MapDisplayBorder = GetTemplateChild("MapDisplayBorder") as Border; AOIprojection = GetTemplateChild("AOIprojection") as PlaneProjection; MapProjection = GetTemplateChild("MapProjection") as PlaneProjection; MapDisplayEllipse = GetTemplateChild("MapDisplayEllipse") as Ellipse; if (this.Layer != null) this.OVMapImage.Layers.Add(this.Layer); AOI = GetTemplateChild("AOI") as Grid; if (AOI != null) AOI.MouseLeftButtonDown += AOI_MouseLeftButtonDown; UpdateAOI(); } #region Properties /// <summary> /// Identifies the <see cref="Map"/> dependency property. /// </summary> public static readonly DependencyProperty MapProperty = DependencyProperty.Register("Map", typeof(Map), typeof(OverviewMap2), new PropertyMetadata(OnMapPropertyChanged)); private static void OnMapPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { OverviewMap2 ovmap = d as OverviewMap2; Map oldMap = e.OldValue as Map; if (oldMap != null) //clean up { if (ovmap.OVMapImage != null) ovmap.OVMapImage.Layers.Clear(); oldMap.ExtentChanged -= ovmap.UpdateOVMap; } Map newMap = e.NewValue as Map; if (newMap != null) { newMap.ExtentChanged += ovmap.UpdateOVMap; if (ovmap.Layer != null && ovmap.OVMapImage != null) ovmap.OVMapImage.Layers.Add(ovmap.Layer); } } /// <summary> /// Sets or gets the Map control associated with the OverviewMap. /// </summary> public Map Map { get { return (Map)GetValue(MapProperty); } set { SetValue(MapProperty, value); } } /// <summary> /// Identifies the <see cref="MaximumExtent"/> dependency property. /// </summary> public static readonly DependencyProperty MaximumExtentProperty = DependencyProperty.Register("MaximumExtent", typeof(Envelope), typeof(OverviewMap2), null); /// <summary> /// Gets or sets the maximum map extent of the overview map. /// If undefined, the maximum extent is derived from the layer. /// </summary> /// <value>The maximum extent.</value> public Envelope MaximumExtent { get { return (Envelope)GetValue(MaximumExtentProperty); } set { SetValue(MaximumExtentProperty, value); } } /// <summary> /// Identifies the <see cref="Layer"/> dependency property. /// </summary> public static readonly DependencyProperty LayerProperty = DependencyProperty.Register("Layer", typeof(Layer), typeof(OverviewMap2), new PropertyMetadata(OnLayerPropertyChanged)); private static void OnLayerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { OverviewMap2 ovmap = d as OverviewMap2; if (ovmap.OVMapImage != null) { ovmap.OVMapImage.Layers.Clear(); if (ovmap.Layer != null) ovmap.OVMapImage.Layers.Add(ovmap.Layer); } if (ovmap.Layer != null) { bool isInit = ovmap.Layer.IsInitialized; if (isInit) ovmap.Layer_LayersInitialized(ovmap.Layer, null); else ovmap.Layer.Initialized += ovmap.Layer_LayersInitialized; } } /// <summary> /// Gets or sets the layer used in the overview map. /// </summary> /// <value>The layer.</value> public Layer Layer { get { return (Layer)GetValue(LayerProperty); } set { SetValue(LayerProperty, value); } } /// <summary> /// Gets or sets the left/right margin factor used to define size of the MapDisplayBorder in the AOI. /// Used for showing difference between actual oversized map extent and area visible in map view when map is not slanted (angle 0). /// Only used when UsePlaneProjection is true. /// Automatically set if MapLeftRightMarginFactor has been defined in application resources (ResourceDictionary). /// Value should be MapLeftRightMarginFactor / (1 + (2 * MapLeftRightMarginFactor)). /// Defaults to 0.25, which is proportional to the actual map's negative margin being half of the extent's width or height (0.5). /// </summary> public double MarginLeftRightFactor { get { return marginLRFactor; } set { marginLRFactor = value; } } /// <summary> /// Gets or sets the top/bottom margin factor used to define size of the MapDisplayBorder in the AOI. /// Used for showing difference between actual oversized map extent and area visible in map view when map is not slanted (angle 0). /// Only used when UsePlaneProjection is true. /// Automatically set if MapTopBottomMarginFactor has been defined in application resources (ResourceDictionary). /// Value should be MapTopBottomMarginFactor / (1 + (2 * MapTopBottomMarginFactor)). /// Defaults to 0.25, which is proportional to the actual map's negative margin being half of the extent's width or height (0.5). /// </summary> public double MarginTopBottomFactor { get { return marginTBFactor; } set { marginTBFactor = value; } } /// <summary> /// Gets or sets UsePlaneProjection. If true, then map is assumed to be oversized to view to accomondate filling the side edges when the map is slanted. /// Automatically set if UsePlaneProjection has been defined in application resources (ResourceDictionary). /// Defaults to false. /// </summary> public bool UsePlaneProjection { get { return usePlaneProjection; } set { usePlaneProjection = value; } } public bool ShowOversize { get { return showOversize; } set { showOversize = value; MapExtentBorder.BorderBrush = showOversize ? new SolidColorBrush(Color.FromArgb(102, 51, 51, 51)) : new SolidColorBrush(Color.FromArgb(0, 255, 255, 255)); } } public double MapAngle { get { return mapAngle; } set { mapAngle = value; if (AOIprojection != null) AOIprojection.RotationX = mapAngle; if (MapProjection != null) MapProjection.RotationX = mapAngle; } } public bool UseEllipseAOI { get { return (bool)GetValue(UseEllipseAOIProperty); } set { SetValue(UseEllipseAOIProperty, value); } } public static readonly DependencyProperty UseEllipseAOIProperty = DependencyProperty.Register("UseEllipseAOI", typeof(bool), typeof(OverviewMap2), new PropertyMetadata(OnUseEllipseAOIPropertyChanged)); private static void OnUseEllipseAOIPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { OverviewMap2 ovmap = d as OverviewMap2; if (ovmap.UseEllipseAOI) { ovmap.MapDisplayEllipse.Visibility = Visibility.Visible; ovmap.MapDisplayBorder.Visibility = Visibility.Collapsed; } else { ovmap.MapDisplayEllipse.Visibility = Visibility.Collapsed; ovmap.MapDisplayBorder.Visibility = Visibility.Visible; } } #endregion /// <summary> /// Provides the behavior for the "Arrange" pass of Silverlight layout. /// Classes can override this method to define their own arrange pass behavior. /// </summary> /// <param name="finalSize">The final area within the parent that this /// object should use to arrange itself and its children.</param> /// <returns>The actual size used.</returns> protected override Size ArrangeOverride(Size finalSize) { this.Clip = new RectangleGeometry() { Rect = new Rect(0, 0, ActualWidth, ActualHeight) }; return base.ArrangeOverride(finalSize); } #region Private Methods /// <summary> /// Sets extents, limits, and events after layers have been initialized /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void Layer_LayersInitialized(object sender, EventArgs args) { fullExtent = OVMapImage.Layers.GetFullExtent(); OVMapImage.MinimumResolution = double.Epsilon; OVMapImage.MaximumResolution = double.MaxValue; if (MaximumExtent != null) { fullExtent = MaximumExtent.Clone(); maxWidth = fullExtent.Width; maxHeight = fullExtent.Height; OVMapImage.ZoomTo(fullExtent); } UpdateOVMap(); } #region Methods for setting extent of OverviewMap /// <summary> /// Determines if the OverviewMap extent should be changed. If so, set new /// extent and call ZoomTo or PanTo. If not, send to UpdateAOI /// </summary> private void UpdateOVMap() { if (Map == null || OVMapImage == null || OVMapImage.Extent == null || Map.Extent == null) { if(AOI!=null) AOI.Visibility = Visibility.Collapsed; return; } // update ov extent if necessary double mapWidth = Map.Extent.Width; double mapHeight = Map.Extent.Height; double ovWidth = OVMapImage.Extent.Width; double ovHeight = OVMapImage.Extent.Height; double widthRatio = mapWidth / ovWidth; double heightRatio = mapHeight / ovHeight; double minRatio = 0.15; double maxRatio = 0.8; Envelope extent; bool sameWidthHeight = (mapWidth == lastMapExtent.Width && mapHeight == lastMapExtent.Height); if (sameWidthHeight) { double halfWidth = ovWidth / 2; double halfHeight = ovHeight / 2; MapPoint newCenter = Map.Extent.GetCenter(); if (MaximumExtent != null) { if (newCenter.X - halfWidth < MaximumExtent.XMin) newCenter.X = MaximumExtent.XMin + halfWidth; if (newCenter.X + halfWidth > MaximumExtent.XMax) newCenter.X = MaximumExtent.XMax - halfWidth; if (newCenter.Y - halfHeight < MaximumExtent.YMin) newCenter.Y = MaximumExtent.YMin + halfHeight; if (newCenter.Y + halfHeight > MaximumExtent.YMax) newCenter.Y = MaximumExtent.YMax - halfHeight; } if (ovWidth >= maxWidth) UpdateAOI(); else { if (AOI != null) AOI.Visibility = Visibility.Collapsed; OVMapImage.PanTo(newCenter); } } else if (mapWidth >= maxWidth) ZoomFullExtent(); else { if (widthRatio <= minRatio || heightRatio <= minRatio || widthRatio >= maxRatio || heightRatio >= maxRatio) { //set new size around new mapextent if (AOI != null) AOI.Visibility = Visibility.Collapsed; if (maxWidth / 3 > mapWidth) { extent = new Envelope() { XMin = Map.Extent.XMin - mapWidth, XMax = Map.Extent.XMax + mapWidth, YMin = Map.Extent.YMin - mapHeight, YMax = Map.Extent.YMax + mapHeight }; if (MaximumExtent != null) { if (extent.XMin < MaximumExtent.XMin) extent.XMin = MaximumExtent.XMin; if (extent.XMax > MaximumExtent.XMax) extent.XMax = MaximumExtent.XMax; if (extent.YMin < MaximumExtent.YMin) extent.YMin = MaximumExtent.YMin; if (extent.YMax > MaximumExtent.YMax) extent.YMax = MaximumExtent.YMax; } OVMapImage.ZoomTo(extent); } else ZoomFullExtent(); } else UpdateAOI(); } } /// <summary> /// Overload of UpdateOVMap - ExtentEventHandler version /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateOVMap(object sender, ESRI.ArcGIS.Client.ExtentEventArgs e) { UpdateOVMap(); } private void ZoomFullExtent() { if (lastOVExtent == null) OVMapImage.ZoomTo(fullExtent); else if (lastOVExtent.Equals(fullExtent)) UpdateAOI(); else OVMapImage.ZoomTo(fullExtent); } #endregion #region Methods for setting size and position of AOI Box /// <summary> /// Sets size and position of AOI Box /// </summary> private void UpdateAOI() { if (Map == null || OVMapImage == null || OVMapImage.Extent == null || AOI == null) return; Envelope extent = Map.Extent; if (extent == null) { AOI.Visibility = Visibility.Collapsed; return; } MapPoint pt1 = new MapPoint(extent.XMin, extent.YMax); MapPoint pt2 = new MapPoint(extent.XMax, extent.YMin); Point topLeft = OVMapImage.MapToScreen(pt1); Point bottomRight = OVMapImage.MapToScreen(pt2); if (!double.IsNaN(topLeft.X) && !double.IsNaN(topLeft.Y) && !double.IsNaN(bottomRight.X) && !double.IsNaN(bottomRight.Y)) { AOI.Margin = new Thickness(topLeft.X, topLeft.Y, 0, 0); AOI.Width = bottomRight.X - topLeft.X; AOI.Height = bottomRight.Y - topLeft.Y; AOI.Visibility = Visibility.Visible; // the next if added for oversized map using plane projection if (usePlaneProjection) { double mwidth = AOI.Width * marginLRFactor; double mheight = AOI.Height * marginTBFactor; MapDisplayBorder.Margin = new Thickness(mwidth, mheight-1, mwidth, mheight+1); //AOIprojection.RotationX = mapAngle; MapProjection.RotationX = mapAngle; } } else AOI.Visibility = Visibility.Collapsed; lastMapExtent = extent; lastOVExtent = OVMapImage.Extent.Clone(); } #endregion #region Method for setting extent of Map /// <summary> /// Set new map extent of main map control. Called after AOI /// Box has been repositioned by user /// </summary> private void UpdateMap() { if (AOI == null) return; mapExtent = Map.Extent; double aoiLeft = AOI.Margin.Left; double aoiTop = AOI.Margin.Top; MapPoint pt = OVMapImage.ScreenToMap(new Point(aoiLeft, aoiTop)); double mapHalfWidth = mapExtent.Width / 2; double mapHalfHeight = mapExtent.Height / 2; MapPoint pnt = new MapPoint(pt.X + mapHalfWidth, pt.Y - mapHalfHeight); Map.PanTo(pnt); } #endregion #region AOI Box Mouse handlers private void AOI_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { dragOn = true; startPoint = e.GetPosition(this); offsetLeft = startPoint.X - AOI.Margin.Left; offsetTop = startPoint.Y - AOI.Margin.Top; AOI.MouseMove += AOI_MouseMove; AOI.MouseLeftButtonUp += AOI_MouseLeftButtonUp; AOI.CaptureMouse(); } private void AOI_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (dragOn) { AOI.MouseMove -= AOI_MouseMove; AOI.MouseLeftButtonUp -= AOI_MouseLeftButtonUp; UpdateMap(); dragOn = false; AOI.ReleaseMouseCapture(); } } private void AOI_MouseMove(object sender, MouseEventArgs e) { if (dragOn) { Point pos = e.GetPosition(this); AOI.Margin = new Thickness(pos.X - offsetLeft, pos.Y - offsetTop, 0, 0); } } #endregion #endregion } }
/* * Copyright (C) 2012, 2013 OUYA, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Unity JNI reference: http://docs.unity3d.com/Documentation/ScriptReference/AndroidJNI.html // JNI Spec: http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/jniTOC.html // Android Plugins: http://docs.unity3d.com/Documentation/Manual/Plugins.html#AndroidPlugins // Unity Android Plugin Guide: http://docs.unity3d.com/Documentation/Manual/PluginsForAndroid.html using System; using System.Collections.Generic; using System.Runtime.InteropServices; #if UNITY_ANDROID && !UNITY_EDITOR using com.unity3d.player; using org.json; using tv.ouya.console.api; using tv.ouya.console.api.content; using tv.ouya.sdk; #endif using UnityEngine; public static class OuyaSDK { public const string PLUGIN_VERSION = "1.2.1494.13"; #if UNITY_ANDROID && !UNITY_EDITOR /// <summary> /// Dictionary for quick localization string lookup /// </summary> private static Dictionary<string, string> m_stringResources = new Dictionary<string, string>(); static OuyaSDK() { // attach our thread to the java vm; obviously the main thread is already attached but this is good practice.. AndroidJNI.AttachCurrentThread(); new OuyaUnityPlugin(UnityPlayer.currentActivity); } public class NdkWrapper { [DllImport("lib-ouya-ndk")] // EXPORT_API float getAxis(int deviceId, int axis) public static extern float getAxis(int deviceId, int axis); [DllImport("lib-ouya-ndk")] // EXPORT_API bool isPressed(int deviceId, int keyCode) public static extern bool isPressed(int deviceId, int keyCode); [DllImport("lib-ouya-ndk")] // EXPORT_API bool isPressedDown(int deviceId, int keyCode) public static extern bool isPressedDown(int deviceId, int keyCode); [DllImport("lib-ouya-ndk")] // EXPORT_API bool isPressedUp(int deviceId, int keyCode) public static extern bool isPressedUp(int deviceId, int keyCode); [DllImport("lib-ouya-ndk")] // EXPORT_API void clearButtonStates() public static extern void clearButtonStates(); [DllImport("lib-ouya-ndk")] // EXPORT_API void clearAxes() public static extern void clearAxes(); [DllImport("lib-ouya-ndk")] // EXPORT_API void clearButtons() public static extern void clearButtons(); } #endif #if UNITY_ANDROID && !UNITY_EDITOR public class OuyaInput { #region Private API private static object m_lockObject = new object(); private static List<Dictionary<int, float>> m_axisStates = new List<Dictionary<int, float>>(); private static List<Dictionary<int, bool>> m_buttonStates = new List<Dictionary<int, bool>>(); private static List<Dictionary<int, bool>> m_buttonDownStates = new List<Dictionary<int, bool>>(); private static List<Dictionary<int, bool>> m_buttonUpStates = new List<Dictionary<int, bool>>(); static OuyaInput() { for (int deviceId = 0; deviceId < OuyaController.MAX_CONTROLLERS; ++deviceId) { m_axisStates.Add(new Dictionary<int, float>()); m_buttonStates.Add(new Dictionary<int, bool>()); m_buttonDownStates.Add(new Dictionary<int, bool>()); m_buttonUpStates.Add(new Dictionary<int, bool>()); } } private static float GetState(int axis, Dictionary<int, float> dictionary) { float result; lock (m_lockObject) { if (dictionary.ContainsKey(axis)) { result = dictionary[axis]; } else { result = 0f; } } return result; } private static bool GetState(int button, Dictionary<int, bool> dictionary) { bool result; lock (m_lockObject) { if (dictionary.ContainsKey(button)) { result = dictionary[button]; } else { result = false; } } return result; } private static bool GetState(bool isPressed, int button, Dictionary<int, bool> dictionary) { bool result; lock (m_lockObject) { if (dictionary.ContainsKey(button)) { result = isPressed == dictionary[button]; } else { result = false; } } return result; } public static void UpdateInputFrame() { lock (m_lockObject) { for (int deviceId = 0; deviceId < OuyaController.MAX_CONTROLLERS; ++deviceId) { #region Track Axis States Dictionary<int, float> axisState = m_axisStates[deviceId]; axisState[OuyaController.AXIS_LS_X] = NdkWrapper.getAxis(deviceId, OuyaController.AXIS_LS_X); axisState[OuyaController.AXIS_LS_Y] = NdkWrapper.getAxis(deviceId, OuyaController.AXIS_LS_Y); axisState[OuyaController.AXIS_RS_X] = NdkWrapper.getAxis(deviceId, OuyaController.AXIS_RS_X); axisState[OuyaController.AXIS_RS_Y] = NdkWrapper.getAxis(deviceId, OuyaController.AXIS_RS_Y); axisState[OuyaController.AXIS_L2] = NdkWrapper.getAxis(deviceId, OuyaController.AXIS_L2); axisState[OuyaController.AXIS_R2] = NdkWrapper.getAxis(deviceId, OuyaController.AXIS_R2); #endregion #region Track Button Up / Down States Dictionary<int, bool> buttonState = m_buttonStates[deviceId]; Dictionary<int, bool> buttonDownState = m_buttonDownStates[deviceId]; Dictionary<int, bool> buttonUpState = m_buttonUpStates[deviceId]; buttonState[OuyaController.BUTTON_O] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_O); buttonState[OuyaController.BUTTON_U] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_U); buttonState[OuyaController.BUTTON_Y] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_Y); buttonState[OuyaController.BUTTON_A] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_A); buttonState[OuyaController.BUTTON_L1] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_L1); buttonState[OuyaController.BUTTON_R1] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_R1); buttonState[OuyaController.BUTTON_L3] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_L3); buttonState[OuyaController.BUTTON_R3] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_R3); buttonState[OuyaController.BUTTON_DPAD_UP] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_DPAD_UP); buttonState[OuyaController.BUTTON_DPAD_DOWN] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_DPAD_DOWN); buttonState[OuyaController.BUTTON_DPAD_RIGHT] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_DPAD_RIGHT); buttonState[OuyaController.BUTTON_DPAD_LEFT] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_DPAD_LEFT); buttonState[OuyaController.BUTTON_MENU] = NdkWrapper.isPressed(deviceId, OuyaController.BUTTON_MENU); buttonDownState[OuyaController.BUTTON_O] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_O); buttonDownState[OuyaController.BUTTON_U] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_U); buttonDownState[OuyaController.BUTTON_Y] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_Y); buttonDownState[OuyaController.BUTTON_A] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_A); buttonDownState[OuyaController.BUTTON_L1] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_L1); buttonDownState[OuyaController.BUTTON_R1] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_R1); buttonDownState[OuyaController.BUTTON_L3] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_L3); buttonDownState[OuyaController.BUTTON_R3] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_R3); buttonDownState[OuyaController.BUTTON_DPAD_UP] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_DPAD_UP); buttonDownState[OuyaController.BUTTON_DPAD_DOWN] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_DPAD_DOWN); buttonDownState[OuyaController.BUTTON_DPAD_RIGHT] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_DPAD_RIGHT); buttonDownState[OuyaController.BUTTON_DPAD_LEFT] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_DPAD_LEFT); buttonDownState[OuyaController.BUTTON_MENU] = NdkWrapper.isPressedDown(deviceId, OuyaController.BUTTON_MENU); buttonUpState[OuyaController.BUTTON_O] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_O); buttonUpState[OuyaController.BUTTON_U] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_U); buttonUpState[OuyaController.BUTTON_Y] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_Y); buttonUpState[OuyaController.BUTTON_A] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_A); buttonUpState[OuyaController.BUTTON_L1] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_L1); buttonUpState[OuyaController.BUTTON_R1] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_R1); buttonUpState[OuyaController.BUTTON_L3] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_L3); buttonUpState[OuyaController.BUTTON_R3] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_R3); buttonUpState[OuyaController.BUTTON_DPAD_UP] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_DPAD_UP); buttonUpState[OuyaController.BUTTON_DPAD_DOWN] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_DPAD_DOWN); buttonUpState[OuyaController.BUTTON_DPAD_RIGHT] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_DPAD_RIGHT); buttonUpState[OuyaController.BUTTON_DPAD_LEFT] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_DPAD_LEFT); buttonUpState[OuyaController.BUTTON_MENU] = NdkWrapper.isPressedUp(deviceId, OuyaController.BUTTON_MENU); #endregion //debugOuyaController(deviceId); } } } public static void ClearButtonStates() { NdkWrapper.clearButtonStates(); } public static void ClearAxes() { NdkWrapper.clearAxes(); } public static void ClearButtons() { NdkWrapper.clearButtons(); } private static void debugOuyaController(int deviceId, int button) { if (GetButtonDown(deviceId, button)) { Debug.Log("Device=" + deviceId + " GetButtonDown: " + button); } if (GetButtonUp(deviceId, button)) { Debug.Log("Device=" + deviceId + " GetButtonUp: " + button); } } private static void debugOuyaController(int deviceId) { debugOuyaController(deviceId, OuyaController.BUTTON_O); debugOuyaController(deviceId, OuyaController.BUTTON_U); debugOuyaController(deviceId, OuyaController.BUTTON_Y); debugOuyaController(deviceId, OuyaController.BUTTON_A); debugOuyaController(deviceId, OuyaController.BUTTON_L1); debugOuyaController(deviceId, OuyaController.BUTTON_R1); debugOuyaController(deviceId, OuyaController.BUTTON_L3); debugOuyaController(deviceId, OuyaController.BUTTON_R3); debugOuyaController(deviceId, OuyaController.BUTTON_DPAD_UP); debugOuyaController(deviceId, OuyaController.BUTTON_DPAD_DOWN); debugOuyaController(deviceId, OuyaController.BUTTON_DPAD_RIGHT); debugOuyaController(deviceId, OuyaController.BUTTON_DPAD_LEFT); debugOuyaController(deviceId, OuyaController.BUTTON_MENU); } #endregion #region Public API public static bool IsControllerConnected(int playerNum) { if (playerNum >= 0 && null != OuyaSDK.Joysticks && playerNum < OuyaSDK.Joysticks.Length) { return (null != OuyaSDK.Joysticks[playerNum]); } else { return false; } } public static float GetAxis(int playerNum, int axis) { if (playerNum >= 0 && null != m_axisStates && playerNum < m_axisStates.Count) { return GetState(axis, m_axisStates[playerNum]); } else { return 0f; } } public static float GetAxisRaw(int playerNum, int axis) { if (playerNum >= 0 && null != m_axisStates && playerNum < m_axisStates.Count) { return GetState(axis, m_axisStates[playerNum]); } else { return 0f; } } //for the method GetButton(int button) I copied the code off of Github from the OUYA SDK page //The official Unity Download has not been updated to reflect the latest commits to the github source //https://github.com/ouya/ouya-sdk-examples/blob/master/Unity/OuyaSDK/Assets/Plugins/OuyaSDK.cs public static bool GetButton(int button) { for (int playerNum = 0; playerNum < OuyaController.MAX_CONTROLLERS; ++playerNum) { if (GetButton(playerNum, button)) { return true; } } return false; } public static bool GetButton(int playerNum, int button) { if (playerNum >= 0 && null != m_buttonStates && playerNum < m_buttonStates.Count) { return GetState(button, m_buttonStates[playerNum]); } else { return false; } } public static bool GetButtonDown(int playerNum, int button) { if (playerNum >= 0 && null != m_buttonDownStates && playerNum < m_buttonDownStates.Count) { return GetState(button, m_buttonDownStates[playerNum]); } else { return false; } } public static bool GetButtonUp(int playerNum, int button) { if (playerNum >= 0 && null != m_buttonUpStates && playerNum < m_buttonUpStates.Count) { return GetState(button, m_buttonUpStates[playerNum]); } else { return false; } } #endregion } #endif #if UNITY_ANDROID && !UNITY_EDITOR /// <summary> /// Cache joysticks /// </summary> public static string[] Joysticks = null; /// <summary> /// Query joysticks every N seconds /// </summary> private static DateTime m_timerJoysticks = DateTime.MinValue; private static string getDeviceName(int deviceId) { OuyaController ouyaController = OuyaController.getControllerByPlayer(deviceId); if (null != ouyaController) { return ouyaController.getDeviceName(); } return null; } #endif /// <summary> /// Update joysticks with a timer /// </summary> public static void UpdateJoysticks() { #if !UNITY_ANDROID || UNITY_EDITOR return; #else if (m_timerJoysticks < DateTime.Now) { //check for new joysticks every N seconds m_timerJoysticks = DateTime.Now + TimeSpan.FromSeconds(3); string[] joysticks = null; List<string> devices = new List<string>(); for (int deviceId = 0; deviceId < OuyaController.MAX_CONTROLLERS; ++deviceId) { string deviceName = getDeviceName(deviceId); //Debug.Log(string.Format("Device={0} name={1}", deviceId, deviceName)); devices.Add(deviceName); } joysticks = devices.ToArray(); // look for changes bool detectedChange = false; if (null == Joysticks) { detectedChange = true; } else if (joysticks.Length != Joysticks.Length) { detectedChange = true; } else { for (int index = 0; index < joysticks.Length; ++index) { if (joysticks[index] != Joysticks[index]) { detectedChange = true; break; } } } Joysticks = joysticks; if (detectedChange) { foreach (OuyaSDK.IJoystickCalibrationListener listener in OuyaSDK.getJoystickCalibrationListeners()) { //Debug.Log("OuyaGameObject: Invoke OuyaOnJoystickCalibration"); listener.OuyaOnJoystickCalibration(); } } } #endif } /// <summary> /// Initialized by OuyaGameObject /// </summary> public static void initOuyaPlugin(string jsonData) { #if UNITY_ANDROID && !UNITY_EDITOR OuyaUnityPlugin.initOuyaPlugin(jsonData); #endif } public static bool isIAPInitComplete() { #if UNITY_ANDROID && !UNITY_EDITOR return OuyaUnityPlugin.isInitialized(); #else return false; #endif } #region Mirror Java API public static void requestGamerInfo() { if (!isIAPInitComplete()) { return; } #if UNITY_ANDROID && !UNITY_EDITOR OuyaUnityPlugin.requestGamerInfo(); #endif } public static void putGameData(string key, string val) { if (!isIAPInitComplete()) { return; } #if UNITY_ANDROID && !UNITY_EDITOR OuyaUnityPlugin.putGameData(key, val); #endif } public static string getGameData(string key) { if (!isIAPInitComplete()) { return string.Empty; } #if UNITY_ANDROID && !UNITY_EDITOR return OuyaUnityPlugin.getGameData(key); #else return String.Empty; #endif } public static void requestProducts(List<Purchasable> purchasables) { if (!isIAPInitComplete()) { return; } #if UNITY_ANDROID && !UNITY_EDITOR JSONArray jsonArray = new JSONArray(); int index = 0; foreach (Purchasable purchasable in purchasables) { jsonArray.put(index, purchasable.productId); ++index; } OuyaUnityPlugin.requestProducts(jsonArray.toString()); jsonArray.Dispose(); #endif } public static void requestPurchase(Purchasable purchasable) { if (!isIAPInitComplete()) { return; } #if UNITY_ANDROID && !UNITY_EDITOR OuyaUnityPlugin.requestPurchase(purchasable.productId); #endif } public static void requestReceipts() { if (!isIAPInitComplete()) { return; } #if UNITY_ANDROID && !UNITY_EDITOR OuyaUnityPlugin.requestReceipts(); #endif } public static bool isRunningOnOUYASupportedHardware() { if (!isIAPInitComplete()) { return false; } #if UNITY_ANDROID && !UNITY_EDITOR return OuyaUnityPlugin.isRunningOnOUYASupportedHardware(); #else return false; #endif } /// <summary> /// 1f - Safe Area all the way to the edge of the screen /// 0f - Safe Area will use the maximum overscan border /// </summary> /// <param name="percentage"></param> public static void setSafeArea(float percentage) { if (!isIAPInitComplete()) { return; } #if UNITY_ANDROID && !UNITY_EDITOR OuyaUnityPlugin.setSafeArea(percentage); #endif } /// <summary> /// Clear input focus /// </summary> public static void clearFocus() { if (!isIAPInitComplete()) { return; } #if UNITY_ANDROID && !UNITY_EDITOR OuyaUnityPlugin.clearFocus(); #endif } /// <summary> /// Get localized string resource /// </summary> public static string getStringResource(string key) { if (!isIAPInitComplete()) { return string.Empty; } #if UNITY_ANDROID && !UNITY_EDITOR if (m_stringResources.ContainsKey(key)) { return m_stringResources[key]; } string val = OuyaUnityPlugin.getStringResource(key); m_stringResources.Add(key, val); return val; #else return string.Empty; #endif } #endregion #region Data containers [Serializable] public class GamerInfo { public string uuid = string.Empty; public string username = string.Empty; #if UNITY_ANDROID && !UNITY_EDITOR public static GamerInfo Parse(JSONObject jsonObject) { GamerInfo result = new GamerInfo(); //Debug.Log(jsonData); if (jsonObject.has("uuid")) { result.uuid = jsonObject.getString("uuid"); } if (jsonObject.has("username")) { result.username = jsonObject.getString("username"); } return result; } #endif } [Serializable] public class Purchasable { public string productId = string.Empty; } [Serializable] public class Product { public string currencyCode = string.Empty; public string description = string.Empty; public string identifier = string.Empty; public float localPrice = 0f; public string name = string.Empty; public float originalPrice = 0f; public float percentOff = 0f; public string developerName = string.Empty; #if UNITY_ANDROID && !UNITY_EDITOR public static Product Parse(JSONObject jsonData) { Product result = new Product(); if (jsonData.has("currencyCode")) { result.currencyCode = jsonData.getString("currencyCode"); } if (jsonData.has("description")) { result.description = jsonData.getString("description"); } if (jsonData.has("identifier")) { result.identifier = jsonData.getString("identifier"); } if (jsonData.has("localPrice")) { result.localPrice = (float)jsonData.getDouble("localPrice"); } if (jsonData.has("name")) { result.name = jsonData.getString("name"); } if (jsonData.has("originalPrice")) { result.originalPrice = (float)jsonData.getDouble("originalPrice"); } if (jsonData.has("percentOff")) { result.percentOff = (float)jsonData.getDouble("percentOff"); } if (jsonData.has("developerName")) { result.developerName = jsonData.getString("developerName"); } return result; } #endif } [Serializable] public class Receipt { public string currency = string.Empty; public string gamer = string.Empty; public DateTime generatedDate = DateTime.MinValue; public string identifier = string.Empty; public float localPrice = 0f; public DateTime purchaseDate = DateTime.MinValue; public string uuid = string.Empty; #if UNITY_ANDROID && !UNITY_EDITOR public static Receipt Parse(JSONObject jsonObject) { Receipt result = new Receipt(); if (jsonObject.has("identifier")) { result.identifier = jsonObject.getString("identifier"); } if (jsonObject.has("purchaseDate")) { DateTime date; DateTime.TryParse(jsonObject.getString("purchaseDate"), out date); result.purchaseDate = date; } if (jsonObject.has("gamer")) { result.gamer = jsonObject.getString("gamer"); } if (jsonObject.has("localPrice")) { result.localPrice = (float)jsonObject.getDouble("localPrice"); } if (jsonObject.has("uuid")) { result.uuid = jsonObject.getString("uuid"); } if (jsonObject.has("currency")) { result.currency = jsonObject.getString("currency"); } if (jsonObject.has("generatedDate")) { DateTime date; DateTime.TryParse(jsonObject.getString("generatedDate"), out date); result.generatedDate = date; } return result; } #endif } #endregion #if UNITY_ANDROID && !UNITY_EDITOR #region Joystick Callibration Listeners public interface IJoystickCalibrationListener { void OuyaOnJoystickCalibration(); } private static List<IJoystickCalibrationListener> m_joystickCalibrationListeners = new List<IJoystickCalibrationListener>(); public static List<IJoystickCalibrationListener> getJoystickCalibrationListeners() { return m_joystickCalibrationListeners; } public static void registerJoystickCalibrationListener(IJoystickCalibrationListener listener) { if (!m_joystickCalibrationListeners.Contains(listener)) { m_joystickCalibrationListeners.Add(listener); } } public static void unregisterJoystickCalibrationListener(IJoystickCalibrationListener listener) { if (m_joystickCalibrationListeners.Contains(listener)) { m_joystickCalibrationListeners.Remove(listener); } } #endregion #region Menu Appearing Listeners public interface IMenuAppearingListener { void OuyaMenuAppearing(); } private static List<IMenuAppearingListener> m_menuAppearingListeners = new List<IMenuAppearingListener>(); public static List<IMenuAppearingListener> getMenuAppearingListeners() { return m_menuAppearingListeners; } public static void registerMenuAppearingListener(IMenuAppearingListener listener) { if (!m_menuAppearingListeners.Contains(listener)) { m_menuAppearingListeners.Add(listener); } } public static void unregisterMenuAppearingListener(IMenuAppearingListener listener) { if (m_menuAppearingListeners.Contains(listener)) { m_menuAppearingListeners.Remove(listener); } } #endregion #region Pause Listeners public interface IPauseListener { void OuyaOnPause(); } private static List<IPauseListener> m_pauseListeners = new List<IPauseListener>(); public static List<IPauseListener> getPauseListeners() { return m_pauseListeners; } public static void registerPauseListener(IPauseListener listener) { if (!m_pauseListeners.Contains(listener)) { m_pauseListeners.Add(listener); } } public static void unregisterPauseListener(IPauseListener listener) { if (m_pauseListeners.Contains(listener)) { m_pauseListeners.Remove(listener); } } #endregion #region Resume Listeners public interface IResumeListener { void OuyaOnResume(); } private static List<IResumeListener> m_resumeListeners = new List<IResumeListener>(); public static List<IResumeListener> getResumeListeners() { return m_resumeListeners; } public static void registerResumeListener(IResumeListener listener) { if (!m_resumeListeners.Contains(listener)) { m_resumeListeners.Add(listener); } } public static void unregisterResumeListener(IResumeListener listener) { if (m_resumeListeners.Contains(listener)) { m_resumeListeners.Remove(listener); } } #endregion #region Content Initialized Listener public interface IContentInitializedListener { void ContentInitializedOnInitialized(); void ContentInitializedOnDestroyed(); } private static List<IContentInitializedListener> m_contentInitializedListeners = new List<IContentInitializedListener>(); public static List<IContentInitializedListener> getContentInitializedListeners() { return m_contentInitializedListeners; } public static void registerContentInitializedListener(IContentInitializedListener listener) { if (!m_contentInitializedListeners.Contains(listener)) { m_contentInitializedListeners.Add(listener); } } public static void unregisterContentInitializedListener(IContentInitializedListener listener) { if (m_contentInitializedListeners.Contains(listener)) { m_contentInitializedListeners.Remove(listener); } } #endregion #region Content Delete Listener public interface IContentDeleteListener { void ContentDeleteOnDeleted(OuyaMod ouyaMod); void ContentDeleteOnDeleteFailed(OuyaMod ouyaMod, int code, string reason); } private static List<IContentDeleteListener> m_contentDeleteListeners = new List<IContentDeleteListener>(); public static List<IContentDeleteListener> getContentDeleteListeners() { return m_contentDeleteListeners; } public static void registerContentDeleteListener(IContentDeleteListener listener) { if (!m_contentDeleteListeners.Contains(listener)) { m_contentDeleteListeners.Add(listener); } } public static void unregisterContentDeleteListener(IContentDeleteListener listener) { if (m_contentDeleteListeners.Contains(listener)) { m_contentDeleteListeners.Remove(listener); } } #endregion #region Content Download Listener public interface IContentDownloadListener { void ContentDownloadOnComplete(OuyaMod ouyaMod); void ContentDownloadOnFailed(OuyaMod ouyaMod); void ContentDownloadOnProgress(OuyaMod ouyaMod, int progress); } private static List<IContentDownloadListener> m_contentDownloadListeners = new List<IContentDownloadListener>(); public static List<IContentDownloadListener> getContentDownloadListeners() { return m_contentDownloadListeners; } public static void registerContentDownloadListener(IContentDownloadListener listener) { if (!m_contentDownloadListeners.Contains(listener)) { m_contentDownloadListeners.Add(listener); } } public static void unregisterContentDownloadListener(IContentDownloadListener listener) { if (m_contentDownloadListeners.Contains(listener)) { m_contentDownloadListeners.Remove(listener); } } #endregion #region Content Installed Search Listener public interface IContentInstalledSearchListener { void ContentInstalledSearchOnResults(List<OuyaMod> ouyaMods, int count); void ContentInstalledSearchOnError(int code, string reason); } private static List<IContentInstalledSearchListener> m_contentInstalledSearchListeners = new List<IContentInstalledSearchListener>(); public static List<IContentInstalledSearchListener> getContentInstalledSearchListeners() { return m_contentInstalledSearchListeners; } public static void registerContentInstalledSearchListener(IContentInstalledSearchListener listener) { if (!m_contentInstalledSearchListeners.Contains(listener)) { m_contentInstalledSearchListeners.Add(listener); } } public static void unregisterContentInstalledSearchListener(IContentInstalledSearchListener listener) { if (m_contentInstalledSearchListeners.Contains(listener)) { m_contentInstalledSearchListeners.Remove(listener); } } #endregion #region Content Published Search Listener public interface IContentPublishedSearchListener { void ContentPublishedSearchOnResults(List<OuyaMod> ouyaMods, int count); void ContentPublishedSearchOnError(int code, string reason); } private static List<IContentPublishedSearchListener> m_contentPublishedSearchListeners = new List<IContentPublishedSearchListener>(); public static List<IContentPublishedSearchListener> getContentPublishedSearchListeners() { return m_contentPublishedSearchListeners; } public static void registerContentPublishedSearchListener(IContentPublishedSearchListener listener) { if (!m_contentPublishedSearchListeners.Contains(listener)) { m_contentPublishedSearchListeners.Add(listener); } } public static void unregisterContentPublishedSearchListener(IContentPublishedSearchListener listener) { if (m_contentPublishedSearchListeners.Contains(listener)) { m_contentPublishedSearchListeners.Remove(listener); } } #endregion #region Content Publish Listener public interface IContentPublishListener { void ContentPublishOnSuccess(OuyaMod ouyaMod); void ContentPublishOnError(OuyaMod ouyaMod, int code, string reason); } private static List<IContentPublishListener> m_contentPublishListeners = new List<IContentPublishListener>(); public static List<IContentPublishListener> getContentPublishListeners() { return m_contentPublishListeners; } public static void registerContentPublishListener(IContentPublishListener listener) { if (!m_contentPublishListeners.Contains(listener)) { m_contentPublishListeners.Add(listener); } } public static void unregisterContentPublishListener(IContentPublishListener listener) { if (m_contentPublishListeners.Contains(listener)) { m_contentPublishListeners.Remove(listener); } } #endregion #region Content Save Listener public interface IContentSaveListener { void ContentSaveOnSuccess(OuyaMod ouyaMod); void ContentSaveOnError(OuyaMod ouyaMod, int code, string reason); } private static List<IContentSaveListener> m_contentSaveListeners = new List<IContentSaveListener>(); public static List<IContentSaveListener> getContentSaveListeners() { return m_contentSaveListeners; } public static void registerContentSaveListener(IContentSaveListener listener) { if (!m_contentSaveListeners.Contains(listener)) { m_contentSaveListeners.Add(listener); } } public static void unregisterContentSaveListener(IContentSaveListener listener) { if (m_contentSaveListeners.Contains(listener)) { m_contentSaveListeners.Remove(listener); } } #endregion #region Content Unpublish Listener public interface IContentUnpublishListener { void ContentUnpublishOnSuccess(OuyaMod ouyaMod); void ContentUnpublishOnError(OuyaMod ouyaMod, int code, string reason); } private static List<IContentUnpublishListener> m_contentUnpublishListeners = new List<IContentUnpublishListener>(); public static List<IContentUnpublishListener> getContentUnpublishListeners() { return m_contentUnpublishListeners; } public static void registerContentUnpublishListener(IContentUnpublishListener listener) { if (!m_contentUnpublishListeners.Contains(listener)) { m_contentUnpublishListeners.Add(listener); } } public static void unregisterContentUnpublishListener(IContentUnpublishListener listener) { if (m_contentUnpublishListeners.Contains(listener)) { m_contentUnpublishListeners.Remove(listener); } } #endregion #region Request Gamer Info Listener public interface IRequestGamerInfoListener { void RequestGamerInfoOnSuccess(GamerInfo gamerInfo); void RequestGamerInfoOnFailure(int errorCode, string errorMessage); void RequestGamerInfoOnCancel(); } private static List<IRequestGamerInfoListener> m_requestGamerInfoListeners = new List<IRequestGamerInfoListener>(); public static List<IRequestGamerInfoListener> getRequestGamerInfoListeners() { return m_requestGamerInfoListeners; } public static void registerRequestGamerInfoListener(IRequestGamerInfoListener listener) { if (!m_requestGamerInfoListeners.Contains(listener)) { m_requestGamerInfoListeners.Add(listener); } } public static void unregisterRequestGamerInfoListener(IRequestGamerInfoListener listener) { if (m_requestGamerInfoListeners.Contains(listener)) { m_requestGamerInfoListeners.Remove(listener); } } #endregion #region Request Products Listeners public interface IRequestProductsListener { void RequestProductsOnSuccess(List<OuyaSDK.Product> products); void RequestProductsOnFailure(int errorCode, string errorMessage); void RequestProductsOnCancel(); } private static List<IRequestProductsListener> m_requestProductsListeners = new List<IRequestProductsListener>(); public static List<IRequestProductsListener> getRequestProductsListeners() { return m_requestProductsListeners; } public static void registerRequestProductsListener(IRequestProductsListener listener) { if (!m_requestProductsListeners.Contains(listener)) { m_requestProductsListeners.Add(listener); } } public static void unregisterRequestProductsListener(IRequestProductsListener listener) { if (m_requestProductsListeners.Contains(listener)) { m_requestProductsListeners.Remove(listener); } } #endregion #region Request Purchase Listener public interface IRequestPurchaseListener { void RequestPurchaseOnSuccess(OuyaSDK.Product product); void RequestPurchaseOnFailure(int errorCode, string errorMessage); void RequestPurchaseOnCancel(); } private static List<IRequestPurchaseListener> m_requestPurchaseListeners = new List<IRequestPurchaseListener>(); public static List<IRequestPurchaseListener> getRequestPurchaseListeners() { return m_requestPurchaseListeners; } public static void registerRequestPurchaseListener(IRequestPurchaseListener listener) { if (!m_requestPurchaseListeners.Contains(listener)) { m_requestPurchaseListeners.Add(listener); } } public static void unregisterRequestPurchaseListener(IRequestPurchaseListener listener) { if (m_requestPurchaseListeners.Contains(listener)) { m_requestPurchaseListeners.Remove(listener); } } #endregion #region Request Receipts Listeners public interface IRequestReceiptsListener { void RequestReceiptsOnSuccess(List<Receipt> receipts); void RequestReceiptsOnFailure(int errorCode, string errorMessage); void RequestReceiptsOnCancel(); } private static List<IRequestReceiptsListener> m_requestReceiptsListeners = new List<IRequestReceiptsListener>(); public static List<IRequestReceiptsListener> getRequestReceiptsListeners() { return m_requestReceiptsListeners; } public static void registerRequestReceiptsListener(IRequestReceiptsListener listener) { if (!m_requestReceiptsListeners.Contains(listener)) { m_requestReceiptsListeners.Add(listener); } } public static void unregisterRequestReceiptsListener(IRequestReceiptsListener listener) { if (m_requestReceiptsListeners.Contains(listener)) { m_requestReceiptsListeners.Remove(listener); } } #endregion #endif }
using System; using System.IO; using System.Collections; using System.Collections.Specialized; namespace HtmlHelp.ChmDecoding { /// <summary> /// The class <c>CHMUrlstr</c> implements a string collection storing the URL strings of the help file /// </summary> internal sealed class CHMUrlstr : IDisposable { /// <summary> /// Constant specifying the size of the string blocks /// </summary> private const int BLOCK_SIZE = 0x1000; /// <summary> /// Internal flag specifying if the object is going to be disposed /// </summary> private bool disposed = false; /// <summary> /// Internal member storing the binary file data /// </summary> private byte[] _binaryFileData = null; /// <summary> /// Internal member storing the url dictionary /// </summary> private Hashtable _urlDictionary = new Hashtable(); /// <summary> /// Internal member storing the framename dictionary /// </summary> private Hashtable _framenameDictionary = new Hashtable(); /// <summary> /// Internal member storing the associated chmfile object /// </summary> private CHMFile _associatedFile = null; /// <summary> /// Constructor of the class /// </summary> /// <param name="binaryFileData">binary file data of the #URLSTR file</param> /// <param name="associatedFile">associated chm file</param> public CHMUrlstr(byte[] binaryFileData, CHMFile associatedFile) { _binaryFileData = binaryFileData; _associatedFile = associatedFile; DecodeData(); // clear internal binary data after extraction _binaryFileData = null; } /// <summary> /// Standard constructor /// </summary> internal CHMUrlstr() { } #region Data dumping /// <summary> /// Dump the class data to a binary writer /// </summary> /// <param name="writer">writer to write the data</param> internal void Dump(ref BinaryWriter writer) { writer.Write( _urlDictionary.Count ); if (_urlDictionary.Count != 0) { IDictionaryEnumerator iDictionaryEnumerator = _urlDictionary.GetEnumerator(); while (iDictionaryEnumerator.MoveNext()) { DictionaryEntry dictionaryEntry = (DictionaryEntry)iDictionaryEnumerator.Current; writer.Write( Int32.Parse(dictionaryEntry.Key.ToString()) ); writer.Write( dictionaryEntry.Value.ToString() ); } } writer.Write( _framenameDictionary.Count ); if (_framenameDictionary.Count != 0) { IDictionaryEnumerator iDictionaryEnumerator = _framenameDictionary.GetEnumerator(); while (iDictionaryEnumerator.MoveNext()) { DictionaryEntry dictionaryEntry = (DictionaryEntry)iDictionaryEnumerator.Current; writer.Write( Int32.Parse(dictionaryEntry.Key.ToString()) ); writer.Write( dictionaryEntry.Value.ToString() ); } } } /// <summary> /// Reads the object data from a dump store /// </summary> /// <param name="reader">reader to read the data</param> internal void ReadDump(ref BinaryReader reader) { int i=0; int nCnt = reader.ReadInt32(); for(i=0; i<nCnt;i++) { int nKey = reader.ReadInt32(); string sValue = reader.ReadString(); _urlDictionary[nKey.ToString()] = sValue; } nCnt = reader.ReadInt32(); for(i=0; i<nCnt;i++) { int nKey = reader.ReadInt32(); string sValue = reader.ReadString(); _framenameDictionary[nKey.ToString()] = sValue; } } /// <summary> /// Sets the associated CHMFile instance /// </summary> /// <param name="associatedFile">instance to set</param> internal void SetCHMFile(CHMFile associatedFile) { _associatedFile = associatedFile; } #endregion /// <summary> /// Decodes the binary file data and fills the internal properties /// </summary> /// <returns>true if succeeded</returns> private bool DecodeData() { bool bRet = true; MemoryStream memStream = new MemoryStream(_binaryFileData); BinaryReader binReader = new BinaryReader(memStream); int nCurOffset = 0; while( (memStream.Position < memStream.Length) && (bRet) ) { nCurOffset = (int)memStream.Position; byte [] dataBlock = binReader.ReadBytes(BLOCK_SIZE); bRet &= DecodeBlock(dataBlock, ref nCurOffset); } return bRet; } /// <summary> /// Decodes a block of url-string data /// </summary> /// <param name="dataBlock">block of data</param> /// <param name="nOffset">current file offset</param> /// <returns>true if succeeded</returns> private bool DecodeBlock( byte[] dataBlock, ref int nOffset ) { bool bRet = true; int blockOffset = nOffset; MemoryStream memStream = new MemoryStream(dataBlock); BinaryReader binReader = new BinaryReader(memStream); if(nOffset==0) binReader.ReadByte(); // first block starts with an unknown byte while( (memStream.Position < (memStream.Length-8)) && (bRet) ) { int entryOffset = blockOffset + (int)memStream.Position; int urlOffset = binReader.ReadInt32(); int frameOffset = binReader.ReadInt32(); // There is one way to tell where the end of the URL/FrameName // pairs occurs: Repeat the following: read 2 DWORDs and if both // are less than the current offset then this is the start of the Local // strings else skip two NT strings. // if(( (urlOffset < (entryOffset+8)) && (frameOffset < (entryOffset+8)) )) // { // //TODO: add correct string reading if an offset has been found // /* // int curOffset = (int)memStream.Position; // // memStream.Seek( (long)(blockOffset-urlOffset), SeekOrigin.Begin); // string sTemp = CHMReader.ExtractString(ref binReader, 0, true); // // memStream.Seek( (long)(blockOffset-frameOffset), SeekOrigin.Begin); // sTemp = CHMReader.ExtractString(ref binReader, 0, true); // // memStream.Seek((long)curOffset, SeekOrigin.Begin); // */ // // // int curOffs = (int)memStream.Position; // BinaryReaderHelp.ExtractString(ref binReader, 0, true, _associatedFile.TextEncoding); // nOffset += (int)memStream.Position - curOffs; // // curOffs = (int)memStream.Position; // BinaryReaderHelp.ExtractString(ref binReader, 0, true, _associatedFile.TextEncoding); // nOffset += (int)memStream.Position - curOffs; // } // else { bool bFoundTerminator = false; string sTemp = BinaryReaderHelp.ExtractString(ref binReader, ref bFoundTerminator, 0, true, _associatedFile.TextEncoding); if(sTemp == "") { //nOffset = nOffset + 1 + (int)memStream.Length - (int)memStream.Position; memStream.Seek(memStream.Length-1, SeekOrigin.Begin); } else { _urlDictionary[entryOffset.ToString()] = sTemp.ToString(); _framenameDictionary[ entryOffset.ToString() ] = sTemp.ToString() ; } } } return bRet; } /// <summary> /// Gets the url at a given offset /// </summary> /// <param name="offset">offset of url</param> /// <returns>the url at the given offset</returns> public string GetURLatOffset(int offset) { if(offset == -1) return String.Empty; string sTemp = (string)_urlDictionary[ offset.ToString() ]; if(sTemp == null) return String.Empty; return sTemp; } /// <summary> /// Gets the framename at a given offset /// </summary> /// <param name="offset">offset of the framename</param> /// <returns>the frame name at the given offset</returns> public string GetFrameNameatOffset(int offset) { if(offset == -1) return String.Empty; string sTemp = (string)_framenameDictionary[ offset.ToString() ]; if(sTemp == null) return String.Empty; return sTemp; } /// <summary> /// Implement IDisposable. /// </summary> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing">disposing flag</param> private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if(!this.disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if(disposing) { // Dispose managed resources. _binaryFileData = null; _urlDictionary = null; _framenameDictionary = null; } } disposed = true; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Data; using System.Text; using System.Windows.Forms; namespace gView.Framework.UI.Controls { [DefaultProperty("BlockSize")] public partial class ProgressDisk : UserControl { private GraphicsPath bkGroundPath1 = new GraphicsPath(); private GraphicsPath bkGroundPath2 = new GraphicsPath(); private GraphicsPath valuePath = new GraphicsPath(); private GraphicsPath freGroundPath = new GraphicsPath(); private int sliceCount; private int value; [DefaultValue(0)] public int Value { get { return value; } set { this.value = value; Render(); } } private Color backGrndColor = Color.White; [DefaultValue(typeof(Color), "White")] public Color BackGroundColor { get { return backGrndColor; } set { backGrndColor = value; Render(); } } private Color activeforeColor1 = Color.Blue; [DefaultValue(typeof(Color), "Blue")] public Color ActiveForeColor1 { get { return activeforeColor1; } set { activeforeColor1 = value; Render(); } } private Color activeforeColor2 = Color.LightBlue; [DefaultValue(typeof(Color), "LightBlue")] public Color ActiveForeColor2 { get { return activeforeColor2; } set { activeforeColor2 = value; Render(); } } private Color inactiveforeColor1 = Color.Green; [DefaultValue(typeof(Color), "Green")] public Color InactiveForeColor1 { get { return inactiveforeColor1; } set { inactiveforeColor1 = value; Render(); } } private Color inactiveforeColor2 = Color.LightGreen; [DefaultValue(typeof(Color), "LightGreen")] public Color InactiveForeColor2 { get { return inactiveforeColor2; } set { inactiveforeColor2 = value; Render(); } } private int size = 50; [DefaultValue(50)] public int SquareSize { get { return size; } set { size = value; Size = new Size(size, size); } } private float blockRatio = .4f; private BlockSize bs = BlockSize.Small; [DefaultValue(typeof(BlockSize), "Small")] public BlockSize BlockSize { get { return bs; } set { bs = value; switch (bs) { case BlockSize.XSmall: blockRatio = 0.49f; break; case BlockSize.Small: blockRatio = 0.4f; break; case BlockSize.Medium: blockRatio = 0.3f; break; case BlockSize.Large: blockRatio = 0.2f; break; case BlockSize.XLarge: blockRatio = 0.1f; break; case BlockSize.XXLarge: blockRatio = 0.01f; break; default: break; } } } [DefaultValue(12)] public int SliceCount { get { return sliceCount; } set { sliceCount = value; } } public ProgressDisk() { InitializeComponent(); // CheckForIllegalCrossThreadCalls = false; Render(); } private Region region = new Region(); protected override void OnPaint(PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; region = new Region(ClientRectangle); if (backGrndColor == Color.Transparent) { region.Exclude(bkGroundPath2); Region = region; } e.Graphics.FillPath(new SolidBrush(backGrndColor), bkGroundPath1); e.Graphics.FillPath( new LinearGradientBrush(new Rectangle(0, 0, size, size), inactiveforeColor1, inactiveforeColor2, value * 360 / 12, true), valuePath); e.Graphics.FillPath( new LinearGradientBrush(new Rectangle(0, 0, size, size), activeforeColor1, activeforeColor2, value * 360 / 12, true), freGroundPath); e.Graphics.FillPath(new SolidBrush(backGrndColor), bkGroundPath2); base.OnPaint(e); } private void Render() { // bkGroundPath1 = new GraphicsPath(); // bkGroundPath2 = new GraphicsPath(); // valuePath = new GraphicsPath(); // freGroundPath = new GraphicsPath(); bkGroundPath1.Reset(); bkGroundPath2.Reset(); valuePath.Reset(); freGroundPath.Reset(); bkGroundPath1.AddPie(new Rectangle(0, 0, size, size), 0, 360); //just in case... if (sliceCount == 0) { sliceCount = 12; } float sliceAngle = 360 / sliceCount; float sweepAngle = sliceAngle - 5; for (int i = 0; i < sliceCount; i++) { if (value != i) { valuePath.AddPie(0, 0, size, size, i * sliceAngle, sweepAngle); } } bkGroundPath2.AddPie( (size / 2 - size * blockRatio), (size / 2 - size * blockRatio), (blockRatio * 2 * size), (blockRatio * 2 * size), 0, 360); freGroundPath.AddPie(new Rectangle(0, 0, size, size), value * sliceAngle, sweepAngle); Invalidate(); } protected override void OnSizeChanged(EventArgs e) { size = Math.Max(Width, Height); Size = new Size(size, size); Render(); base.OnSizeChanged(e); } protected override void OnResize(EventArgs e) { size = Math.Max(Width, Height); Size = new Size(size, size); Render(); base.OnResize(e); } public void Start(int interval) { timer1.Interval = interval; timer1.Start(); } public void Stop() { timer1.Stop(); } private void timer1_Tick(object sender, EventArgs e) { this.Value = this.Value + 1; } } public enum BlockSize { XSmall, Small, Medium, Large, XLarge, XXLarge } }
// ------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All Rights Reserved. // ------------------------------------------------------------------- //From \\authoring\Sparkle\Source\1.0.1083.0\Common\Source\Framework\Properties namespace System.Activities.Presentation.Internal.PropertyEditing.FromExpression.Framework.PropertyInspector { using System; using System.Collections; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Media; using System.Diagnostics; using System.Activities.Presentation.PropertyEditing; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime; using System.Diagnostics.CodeAnalysis; using System.Activities.Presentation; //Cider change [CLSCompliant(false)] internal partial class CategoryContainer : ContentControl { // This will be set by the property inspector if the category is hosted in a popup. public static readonly DependencyProperty PopupHostProperty = DependencyProperty.RegisterAttached( "PopupHost", typeof(Popup), typeof(CategoryContainer), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits, OnPopupHostChanged)); public static readonly DependencyProperty CategoryProperty = DependencyProperty.Register( "Category", typeof(CategoryBase), typeof(CategoryContainer), new PropertyMetadata( (CategoryEntry)null, new PropertyChangedCallback(OnCategoryPropertyChanged))); public static readonly DependencyProperty ExpandedProperty = DependencyProperty.Register("Expanded", typeof(bool), typeof(CategoryContainer), new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnExpandedChanged))); public static readonly DependencyProperty AdvancedSectionPinnedProperty = DependencyProperty.Register("AdvancedSectionPinned", typeof(bool), typeof(CategoryContainer), new FrameworkPropertyMetadata(false)); public static readonly DependencyProperty BasicPropertyMatchesFilterProperty = DependencyProperty.Register("BasicPropertyMatchesFilter", typeof(bool), typeof(CategoryContainer), new FrameworkPropertyMetadata(true)); public static readonly DependencyProperty AdvancedPropertyMatchesFilterProperty = DependencyProperty.Register("AdvancedPropertyMatchesFilter", typeof(bool), typeof(CategoryContainer), new FrameworkPropertyMetadata(true, new PropertyChangedCallback(CategoryContainer.OnAdvancedPropertyMatchesFilterChanged))); public static readonly DependencyProperty ShowAdvancedHeaderProperty = DependencyProperty.Register("ShowAdvancedHeader", typeof(bool), typeof(CategoryContainer), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None, null, new CoerceValueCallback(CategoryContainer.CoerceShowAdvancedHeader))); public static readonly DependencyProperty OwningCategoryContainerProperty = DependencyProperty.RegisterAttached("OwningCategoryContainer", typeof(CategoryContainer), typeof(CategoryContainer), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits)); // Data for managing expanded state based on a filter. private FilterState filterIsEmpty = FilterState.Unknown; // garylins 11/15/2006 - This variable has been added to fix bug 29740. The real fix is to find // a way to update CategoryContainers expansion state when the Category changes. The bug comes about // because when UpdateFilter is called from the PI, it fires the FilterUpdated event. At this time // the CategoryContainer is not yet built out, so it hasn't hooked up to listen to the event and hence // never gets it's filter state related variables updated. private bool haveCachedExpanded = false; private bool wasAdvancedPinnedBeforeFilter = false; private bool wasExpandedBeforeFilter = true; // used for managing category editors and overflow properties. private ObservableCollection<CategoryEditor> basicCategoryEditors = new ObservableCollection<CategoryEditor>(); private ObservableCollection<CategoryEditor> advancedCategoryEditors = new ObservableCollection<CategoryEditor>(); private ObservableCollection<PropertyEntry> unconsumedBasicProperties = new ObservableCollection<PropertyEntry>(); private ObservableCollection<PropertyEntry> unconsumedAdvancedProperties = new ObservableCollection<PropertyEntry>(); public CategoryContainer() : this(true) { } public CategoryContainer(bool initializeComponent) { if (initializeComponent) { this.InitializeComponent(); } SetOwningCategoryContainer(this, this); Binding basicMatchesFilterBinding = new Binding("Category.BasicPropertyMatchesFilter"); basicMatchesFilterBinding.Source = this; basicMatchesFilterBinding.Mode = BindingMode.OneWay; this.SetBinding(CategoryContainer.BasicPropertyMatchesFilterProperty, basicMatchesFilterBinding); Binding advancedMatchesFilterBinding = new Binding("Category.AdvancedPropertyMatchesFilter"); advancedMatchesFilterBinding.Source = this; advancedMatchesFilterBinding.Mode = BindingMode.OneWay; this.SetBinding(CategoryContainer.AdvancedPropertyMatchesFilterProperty, advancedMatchesFilterBinding); } public ObservableCollection<CategoryEditor> BasicCategoryEditors { get { return this.basicCategoryEditors; } } public ObservableCollection<CategoryEditor> AdvancedCategoryEditors { get { return this.advancedCategoryEditors; } } public ObservableCollection<PropertyEntry> UnconsumedBasicProperties { get { return this.unconsumedBasicProperties; } } public ObservableCollection<PropertyEntry> UnconsumedAdvancedProperties { get { return this.unconsumedAdvancedProperties; } } public CategoryBase Category { get { return (CategoryBase)this.GetValue(CategoryContainer.CategoryProperty); } set { this.SetValue(CategoryContainer.CategoryProperty, value); } } public bool Expanded { get { return (bool)this.GetValue(CategoryContainer.ExpandedProperty); } set { this.SetValue(CategoryContainer.ExpandedProperty, value); } } public bool AdvancedSectionPinned { get { return (bool)this.GetValue(CategoryContainer.AdvancedSectionPinnedProperty); } set { this.SetValue(CategoryContainer.AdvancedSectionPinnedProperty, value); } } public bool BasicPropertyMatchesFilter { get { return (bool)this.GetValue(CategoryContainer.BasicPropertyMatchesFilterProperty); } set { this.SetValue(CategoryContainer.BasicPropertyMatchesFilterProperty, value); } } public bool AdvancedPropertyMatchesFilter { get { return (bool)this.GetValue(CategoryContainer.AdvancedPropertyMatchesFilterProperty); } set { this.SetValue(CategoryContainer.AdvancedPropertyMatchesFilterProperty, value); } } public bool ShowAdvancedHeader { get { return (bool)this.GetValue(CategoryContainer.ShowAdvancedHeaderProperty); } set { this.SetValue(CategoryContainer.ShowAdvancedHeaderProperty, value); } } // <summary> // Writes the attached property OwningCategoryContainer to the given element. // </summary> // <param name="d">The element to which to write the attached property.</param> // <param name="value">The property value to set</param> public static void SetOwningCategoryContainer(DependencyObject dependencyObject, CategoryContainer value) { if (dependencyObject == null) { throw FxTrace.Exception.ArgumentNull("dependencyObject"); } dependencyObject.SetValue(CategoryContainer.OwningCategoryContainerProperty, value); } // <summary> // Reads the attached property OwningCategoryContainer from the given element. // </summary> // <param name="d">The element from which to read the attached property.</param> // <returns>The property's value.</returns> public static CategoryContainer GetOwningCategoryContainer(DependencyObject dependencyObject) { if (dependencyObject == null) { throw FxTrace.Exception.ArgumentNull("dependencyObject"); } return (CategoryContainer)dependencyObject.GetValue(CategoryContainer.OwningCategoryContainerProperty); } public static Popup GetPopupHost(DependencyObject target) { return (Popup)target.GetValue(CategoryContainer.PopupHostProperty); } public static void SetPopupHost(DependencyObject target, Popup value) { target.SetValue(CategoryContainer.PopupHostProperty, value); } private static void OnPopupHostChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CategoryContainer categoryEditor = d as CategoryContainer; if (categoryEditor != null) { // If we are hosted in a popup, do not show the advanced category expander, and pin the advanced section. if (e.NewValue != null) { categoryEditor.AdvancedSectionPinned = true; } else { categoryEditor.AdvancedSectionPinned = false; } } } private static void OnCategoryPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CategoryContainer theThis = (CategoryContainer)d; if (e.NewValue != null) { CategoryBase category = (CategoryBase)e.NewValue; theThis.SetValue( System.Activities.Presentation.Internal.PropertyEditing.FromExpression.Diagnostics.Automation.AutomationElement.IdProperty, category.CategoryName + "Category"); CategoryBase oldCategory = (CategoryBase)e.OldValue; if (oldCategory != null) { oldCategory.FilterApplied -= new EventHandler<PropertyFilterAppliedEventArgs>(theThis.OnFilterApplied); category.CategoryEditors.CollectionChanged -= theThis.CategoryEditors_CollectionChanged; theThis.basicCategoryEditors.Clear(); theThis.advancedCategoryEditors.Clear(); category.BasicProperties.CollectionChanged -= theThis.BasicProperties_CollectionChanged; category.AdvancedProperties.CollectionChanged -= theThis.AdvancedProperties_CollectionChanged; theThis.unconsumedBasicProperties.Clear(); theThis.unconsumedAdvancedProperties.Clear(); } if (category != null) { category.FilterApplied += new EventHandler<PropertyFilterAppliedEventArgs>(theThis.OnFilterApplied); theThis.AddCategoryEditors(category.CategoryEditors); category.CategoryEditors.CollectionChanged += theThis.CategoryEditors_CollectionChanged; foreach (PropertyEntry property in category.BasicProperties) { theThis.AddProperty(property, theThis.unconsumedBasicProperties, theThis.Category.BasicProperties, theThis.basicCategoryEditors); } foreach (PropertyEntry property in category.AdvancedProperties) { theThis.AddProperty(property, theThis.unconsumedAdvancedProperties, theThis.Category.AdvancedProperties, theThis.advancedCategoryEditors); } category.BasicProperties.CollectionChanged += theThis.BasicProperties_CollectionChanged; category.AdvancedProperties.CollectionChanged += theThis.AdvancedProperties_CollectionChanged; } theThis.CoerceValue(CategoryContainer.ShowAdvancedHeaderProperty); } } // ################################################### // CIDER-SPECIFIC CHANGE IN NEED OF PORTING - BEGIN // ################################################### // This method used to be non-virtual, private protected virtual void AddProperty(PropertyEntry property, ObservableCollection<PropertyEntry> unconsumedProperties, ObservableCollection<PropertyEntry> referenceOrder, ObservableCollection<CategoryEditor> categoryEditors) { // ################################################### // CIDER-SPECIFIC CHANGE IN NEED OF PORTING - END // ################################################### bool consumed = false; foreach (CategoryEditor categoryEditor in categoryEditors) { if (categoryEditor.ConsumesProperty(property)) { consumed = true; } } if (!consumed) { // We need to insert this property in the correct location. Reference order is sorted and contains all properties in the unconsumed properties collection. Fx.Assert(referenceOrder.Contains(property), "Reference order should contain the property to be added."); #if DEBUG foreach (PropertyEntry unconsumedProperty in unconsumedProperties) { Fx.Assert(referenceOrder.Contains(unconsumedProperty), "Reference order should contain all unconsumed properties."); } #endif // We'll walk both collections, and advance the insertion index whenever we see an unconsumed property come ahead of the target in the reference order. int referenceIndex = 0; int insertionIndex = 0; while (referenceOrder[referenceIndex] != property && insertionIndex < unconsumedProperties.Count) { if (unconsumedProperties[insertionIndex] == referenceOrder[referenceIndex]) { insertionIndex++; } referenceIndex++; } unconsumedProperties.Insert(insertionIndex, property); } } private void OnFilterApplied(object source, PropertyFilterAppliedEventArgs args) { // If the filter just switched between empty and non-empty if (args.Filter.IsEmpty && this.filterIsEmpty != FilterState.Empty || !args.Filter.IsEmpty && this.filterIsEmpty != FilterState.NotEmpty) { // If the filter is now empty if (args.Filter.IsEmpty) { if (this.haveCachedExpanded) { // Set Pinned and Expanded to what they were before the filter this.Expanded = this.wasExpandedBeforeFilter; this.AdvancedSectionPinned = this.wasAdvancedPinnedBeforeFilter; } } else { // Cache the Pinned and Expanded state this.haveCachedExpanded = true; this.wasExpandedBeforeFilter = this.Expanded; this.wasAdvancedPinnedBeforeFilter = this.AdvancedSectionPinned; } } if (!args.Filter.IsEmpty) { this.Expanded = this.BasicPropertyMatchesFilter || this.AdvancedPropertyMatchesFilter; this.AdvancedSectionPinned = this.AdvancedPropertyMatchesFilter; } this.filterIsEmpty = args.Filter.IsEmpty ? FilterState.Empty : FilterState.NotEmpty; } private static void OnExpandedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (CategoryContainerCommands.UpdateCategoryExpansionState.CanExecute(null, d as IInputElement)) { CategoryContainerCommands.UpdateCategoryExpansionState.Execute(null, d as IInputElement); } } private void OnMinimizeButtonClick(object sender, RoutedEventArgs e) { // dismiss the popup Popup popupHost = CategoryContainer.GetPopupHost(this); Fx.Assert(popupHost != null, "popupHost should not be null"); if (popupHost != null) { popupHost.IsOpen = false; } } private static void OnAdvancedPropertyMatchesFilterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CategoryContainer editor = d as CategoryContainer; if (editor != null) { editor.CoerceValue(CategoryContainer.ShowAdvancedHeaderProperty); } } private static object CoerceShowAdvancedHeader(DependencyObject d, object value) { CategoryContainer editor = d as CategoryContainer; if (editor != null) { // ################################################### // CIDER-SPECIFIC CHANGE IN NEED OF PORTING - BEGIN // ################################################### // Bugfix: this condition used to reference editor.Category.AdvancedProperties.Count instead of // editor.unconsumedAdvancedProperties, which is a bug. if ((editor.unconsumedAdvancedProperties.Count <= 0 && editor.advancedCategoryEditors.Count == 0) || !editor.AdvancedPropertyMatchesFilter) // ################################################### // CIDER-SPECIFIC CHANGE IN NEED OF PORTING - END // ################################################### { return false; } } return true; } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.Loaded += new RoutedEventHandler(CategoryContainer_Loaded); } private void CategoryContainer_Loaded(object sender, RoutedEventArgs e) { IPropertyInspector owningPI = PropertyInspectorHelper.GetOwningPropertyInspectorModel(this); if (owningPI != null) { if (CategoryContainer.GetPopupHost(this) == null) { this.Expanded = owningPI.IsCategoryExpanded(this.Category.CategoryName); } } } // Category editor management private void AdvancedProperties_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Add: foreach (PropertyEntry property in e.NewItems) { this.AddProperty(property, this.unconsumedAdvancedProperties, this.Category.AdvancedProperties, this.advancedCategoryEditors); } break; case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: foreach (PropertyEntry property in e.OldItems) { this.unconsumedAdvancedProperties.Remove(property); } break; default: Debug.Fail("BasicProperties should not change in a way other than an add or a remove."); break; } this.CoerceValue(CategoryContainer.ShowAdvancedHeaderProperty); } private void BasicProperties_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Add: foreach (PropertyEntry property in e.NewItems) { this.AddProperty(property, this.unconsumedBasicProperties, this.Category.BasicProperties, this.basicCategoryEditors); } break; case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: foreach (PropertyEntry property in e.OldItems) { this.unconsumedBasicProperties.Remove(property); } break; default: Debug.Fail("BasicProperties should not change in a way other than an add or a remove."); break; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Propagating the error might cause VS to crash")] [SuppressMessage("Reliability", "Reliability108", Justification = "Propagating the error might cause VS to crash")] private bool IsAdvanced(CategoryEditor editor) { AttributeCollection attributes = null; try { attributes = TypeDescriptor.GetAttributes(editor); } catch (Exception) { } if (attributes != null) { foreach (Attribute attribute in attributes) { EditorBrowsableAttribute browsable = attribute as EditorBrowsableAttribute; if (browsable != null) { return browsable.State == EditorBrowsableState.Advanced; } } } return false; } private void AddCategoryEditors(IList editors) { foreach (CategoryEditor editor in editors) { if (this.IsAdvanced(editor)) { this.advancedCategoryEditors.Add(editor); this.UpdateUnconsumedProperties(editor, this.unconsumedAdvancedProperties); } else { this.basicCategoryEditors.Add(editor); this.UpdateUnconsumedProperties(editor, this.unconsumedBasicProperties); } } } private void UpdateUnconsumedProperties(CategoryEditor newEditor, ObservableCollection<PropertyEntry> unconsumedProperties) { for (int i = unconsumedProperties.Count - 1; i >= 0; i--) { if (newEditor.ConsumesProperty(unconsumedProperties[i])) { unconsumedProperties.RemoveAt(i); } } } // ################################################### // CIDER-SPECIFIC CHANGE IN NEED OF PORTING - BEGIN // ################################################### // This change is a result of bug 88870. Blend has this issue // as well and will need to address it soon. // Original code: //private void RemoveCategoryEditors(IList editors) { // foreach (CategoryEditor editor in editors) { // if (this.IsAdvanced(editor)) { // this.advancedCategoryEditors.Remove(editor); // } // else { // this.basicCategoryEditors.Remove(editor); // } // } //} // Updated code: private void RemoveCategoryEditors(IList editors) { bool refreshBasicProperties = false; bool refreshAdvancedProperties = false; foreach (CategoryEditor editor in editors) { if (this.IsAdvanced(editor)) { this.advancedCategoryEditors.Remove(editor); refreshAdvancedProperties = true; } else { this.basicCategoryEditors.Remove(editor); refreshBasicProperties = true; } } if (this.Category != null) { if (refreshBasicProperties) { RefreshConsumedProperties(this.unconsumedBasicProperties, this.Category.BasicProperties, this.basicCategoryEditors); } if (refreshAdvancedProperties) { RefreshConsumedProperties(this.unconsumedAdvancedProperties, this.Category.AdvancedProperties, this.advancedCategoryEditors); } } } private void RefreshConsumedProperties(ObservableCollection<PropertyEntry> unconsumedProperties, ObservableCollection<PropertyEntry> allProperties, ObservableCollection<CategoryEditor> categoryEditors) { if (allProperties == null || unconsumedProperties == null || unconsumedProperties.Count == allProperties.Count) { return; } foreach (PropertyEntry property in allProperties) { if (!unconsumedProperties.Contains(property)) { // The following method will only add the specified property to the unconsumed // list if it isn't already consumed by some existing category editor. AddProperty(property, unconsumedProperties, allProperties, categoryEditors); } } } // ################################################# // CIDER-SPECIFIC CHANGE IN NEED OF PORTING - END // ################################################# private void CategoryEditors_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { // we need to add/remove category editors switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Reset: this.basicCategoryEditors.Clear(); this.advancedCategoryEditors.Clear(); break; case System.Collections.Specialized.NotifyCollectionChangedAction.Add: this.AddCategoryEditors(e.NewItems); break; case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: this.RemoveCategoryEditors(e.OldItems); break; case System.Collections.Specialized.NotifyCollectionChangedAction.Replace: this.RemoveCategoryEditors(e.OldItems); this.AddCategoryEditors(e.NewItems); break; } } // Constructors private enum FilterState { Unknown, Empty, NotEmpty } // Fields } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; #pragma warning disable 0414 namespace System.Reflection.Tests { public class ConstructorInfoTests { [Fact] public void ConstructorName() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Equal(3, constructors.Length); foreach (ConstructorInfo constructorInfo in constructors) { Assert.Equal(ConstructorInfo.ConstructorName, constructorInfo.Name); } } public static IEnumerable<object[]> Equals_TestData() { ConstructorInfo[] methodSampleConstructors1 = GetConstructors(typeof(ClassWith3Constructors)); ConstructorInfo[] methodSampleConstructors2 = GetConstructors(typeof(ClassWith3Constructors)); yield return new object[] { methodSampleConstructors1[0], methodSampleConstructors2[0], true }; yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[1], true }; yield return new object[] { methodSampleConstructors1[2], methodSampleConstructors2[2], true }; yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[2], false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) { Assert.Equal(expected, constructorInfo1.Equals(constructorInfo2)); } [Fact] public void GetHashCodeTest() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); foreach (ConstructorInfo constructorInfo in constructors) { Assert.NotEqual(0, constructorInfo.GetHashCode()); } } [Fact] public void Invoke() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Equal(constructors.Length, 3); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[0].Invoke(null); Assert.NotNull(obj); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Invoking static constructors are not supported on UapAot.")] public void Invoke_StaticConstructor_NullObject_NullParameters() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWithStaticConstructor)); Assert.Equal(1, constructors.Length); object obj = constructors[0].Invoke(null, new object[] { }); Assert.Null(obj); } [Fact] public void Invoke_StaticConstructor_ThrowsMemberAccessException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWithStaticConstructor)); Assert.Equal(1, constructors.Length); Assert.Throws<MemberAccessException>(() => constructors[0].Invoke(new object[0])); } [Fact] public void Invoke_OneDimensionalArray() { ConstructorInfo[] constructors = GetConstructors(typeof(object[])); int[] arraylength = { 1, 2, 99, 65535 }; // Try to invoke Array ctors with different lengths foreach (int length in arraylength) { // Create big Array with elements object[] arr = (object[])constructors[0].Invoke(new object[] { length }); Assert.Equal(arr.Length, length); } } [Fact] public void Invoke_OneDimensionalArray_NegativeLengths_ThrowsOverflowException() { ConstructorInfo[] constructors = GetConstructors(typeof(object[])); int[] arraylength = new int[] { -1, -2, -99 }; // Try to invoke Array ctors with different lengths foreach (int length in arraylength) { // Create big Array with elements Assert.Throws<OverflowException>(() => (object[])constructors[0].Invoke(new object[] { length })); } } [Fact] public void Invoke_OneParameter() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[1].Invoke(new object[] { 100 }); Assert.Equal(obj.intValue, 100); } [Fact] public void Invoke_TwoParameters() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[2].Invoke(new object[] { 101, "hello" }); Assert.Equal(obj.intValue, 101); Assert.Equal(obj.stringValue, "hello"); } [Fact] public void Invoke_NoParameters_ThowsTargetParameterCountException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Throws<TargetParameterCountException>(() => constructors[2].Invoke(new object[0])); } [Fact] public void Invoke_ParameterMismatch_ThrowsTargetParameterCountException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Throws<TargetParameterCountException>(() => (ClassWith3Constructors)constructors[2].Invoke(new object[] { 121 })); } [Fact] public void Invoke_ParameterWrongType_ThrowsArgumentException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); AssertExtensions.Throws<ArgumentException>(null, () => (ClassWith3Constructors)constructors[1].Invoke(new object[] { "hello" })); } [Fact] public void Invoke_ExistingInstance() { // Should not prouce a second object. ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj1 = new ClassWith3Constructors(100, "hello"); ClassWith3Constructors obj2 = (ClassWith3Constructors)constructors[2].Invoke(obj1, new object[] { 999, "initialized" }); Assert.Null(obj2); Assert.Equal(obj1.intValue, 999); Assert.Equal(obj1.stringValue, "initialized"); } [Fact] public void Invoke_AbstractClass_ThrowsMemberAccessException() { ConstructorInfo[] constructors = GetConstructors(typeof(ConstructorInfoAbstractBase)); Assert.Throws<MemberAccessException>(() => (ConstructorInfoAbstractBase)constructors[0].Invoke(new object[0])); } [Fact] public void Invoke_SubClass() { ConstructorInfo[] constructors = GetConstructors(typeof(ConstructorInfoDerived)); ConstructorInfoDerived obj = null; obj = (ConstructorInfoDerived)constructors[0].Invoke(new object[] { }); Assert.NotNull(obj); } [Fact] public void Invoke_Struct() { ConstructorInfo[] constructors = GetConstructors(typeof(StructWith1Constructor)); StructWith1Constructor obj; obj = (StructWith1Constructor)constructors[0].Invoke(new object[] { 1, 2 }); Assert.Equal(1, obj.x); Assert.Equal(2, obj.y); } [Fact] public void IsConstructor_ReturnsTrue() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.All(constructors, constructorInfo => Assert.True(constructorInfo.IsConstructor)); } [Fact] public void IsPublic() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.True(constructors[0].IsPublic); } public static ConstructorInfo[] GetConstructors(Type type) { return type.GetTypeInfo().DeclaredConstructors.ToArray(); } } // Metadata for Reflection public abstract class ConstructorInfoAbstractBase { public ConstructorInfoAbstractBase() { } } public class ConstructorInfoDerived : ConstructorInfoAbstractBase { public ConstructorInfoDerived() { } } public class ClassWith3Constructors { public int intValue = 0; public string stringValue = ""; public ClassWith3Constructors() { } public ClassWith3Constructors(int intValue) { this.intValue = intValue; } public ClassWith3Constructors(int intValue, string stringValue) { this.intValue = intValue; this.stringValue = stringValue; } public string Method1(DateTime dt) => ""; } public static class ClassWithStaticConstructor { static ClassWithStaticConstructor() { } } public struct StructWith1Constructor { public int x; public int y; public StructWith1Constructor(int x, int y) { this.x = x; this.y = y; } } }
// GtkSharp.Generation.CallbackGen.cs - The Callback Generatable. // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2002-2003 Mike Kestner // Copyright (c) 2007 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GtkSharp.Generation { using System; using System.IO; using System.Xml; public class CallbackGen : GenBase, IAccessor { private Parameters parms; private Signature sig = null; private ReturnValue retval; private bool valid = true; public CallbackGen (XmlElement ns, XmlElement elem) : base (ns, elem) { retval = new ReturnValue (elem ["return-type"]); parms = new Parameters (elem ["parameters"]); parms.HideData = true; } public override string DefaultValue { get { return "null"; } } public override bool Validate () { if (!retval.Validate ()) { Console.WriteLine ("rettype: " + retval.CType + " in callback " + CName); Statistics.ThrottledCount++; valid = false; return false; } if (!parms.Validate ()) { Console.WriteLine (" in callback " + CName); Statistics.ThrottledCount++; valid = false; return false; } valid = true; return true; } public string InvokerName { get { if (!valid) return String.Empty; return NS + "Sharp." + Name + "Invoker"; } } public override string MarshalType { get { if (valid) return NS + "Sharp." + Name + "Native"; else return ""; } } public override string CallByName (string var_name) { return var_name + ".NativeDelegate"; } public override string FromNative (string var) { return NS + "Sharp." + Name + "Wrapper.GetManagedDelegate (" + var + ")"; } public void WriteAccessors (StreamWriter sw, string indent, string var) { sw.WriteLine (indent + "get {"); sw.WriteLine (indent + "\treturn " + FromNative (var) + ";"); sw.WriteLine (indent + "}"); } string CastFromInt (string type) { return type != "int" ? "(" + type + ") " : ""; } string InvokeString { get { if (parms.Count == 0) return String.Empty; string[] result = new string [parms.Count]; for (int i = 0; i < parms.Count; i++) { Parameter p = parms [i]; IGeneratable igen = p.Generatable; if (i > 0 && parms [i - 1].IsString && p.IsLength) { string string_name = parms [i - 1].Name; result[i] = igen.CallByName (CastFromInt (p.CSType) + "System.Text.Encoding.UTF8.GetByteCount (" + string_name + ")"); continue; } p.CallName = p.Name; result [i] = p.CallString; if (p.IsUserData) result [i] = "__data"; } return String.Join (", ", result); } } MethodBody body; void GenInvoker (GenerationInfo gen_info, StreamWriter sw) { if (sig == null) sig = new Signature (parms); sw.WriteLine ("\tinternal class " + Name + "Invoker {"); sw.WriteLine (); sw.WriteLine ("\t\t" + Name + "Native native_cb;"); sw.WriteLine ("\t\tIntPtr __data;"); sw.WriteLine ("\t\tGLib.DestroyNotify __notify;"); sw.WriteLine (); sw.WriteLine ("\t\t~" + Name + "Invoker ()"); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\tif (__notify == null)"); sw.WriteLine ("\t\t\t\treturn;"); sw.WriteLine ("\t\t\t__notify (__data);"); sw.WriteLine ("\t\t}"); sw.WriteLine (); sw.WriteLine ("\t\tinternal " + Name + "Invoker (" + Name + "Native native_cb) : this (native_cb, IntPtr.Zero, null) {}"); sw.WriteLine (); sw.WriteLine ("\t\tinternal " + Name + "Invoker (" + Name + "Native native_cb, IntPtr data) : this (native_cb, data, null) {}"); sw.WriteLine (); sw.WriteLine ("\t\tinternal " + Name + "Invoker (" + Name + "Native native_cb, IntPtr data, GLib.DestroyNotify notify)"); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\tthis.native_cb = native_cb;"); sw.WriteLine ("\t\t\t__data = data;"); sw.WriteLine ("\t\t\t__notify = notify;"); sw.WriteLine ("\t\t}"); sw.WriteLine (); sw.WriteLine ("\t\tinternal " + QualifiedName + " Handler {"); sw.WriteLine ("\t\t\tget {"); sw.WriteLine ("\t\t\t\treturn new " + QualifiedName + "(InvokeNative);"); sw.WriteLine ("\t\t\t}"); sw.WriteLine ("\t\t}"); sw.WriteLine (); sw.WriteLine ("\t\t" + retval.CSType + " InvokeNative (" + sig + ")"); sw.WriteLine ("\t\t{"); body.Initialize (gen_info); string call = "native_cb (" + InvokeString + ")"; if (retval.IsVoid) sw.WriteLine ("\t\t\t" + call + ";"); else sw.WriteLine ("\t\t\t" + retval.CSType + " result = " + retval.FromNative (call) + ";"); body.Finish (sw, String.Empty); if (!retval.IsVoid) sw.WriteLine ("\t\t\treturn result;"); sw.WriteLine ("\t\t}"); sw.WriteLine ("\t}"); sw.WriteLine (); } public string GenWrapper (GenerationInfo gen_info) { string wrapper = Name + "Native"; string qualname = MarshalType; if (!Validate ()) return String.Empty; body = new MethodBody (parms); StreamWriter save_sw = gen_info.Writer; StreamWriter sw = gen_info.Writer = gen_info.OpenStream (qualname); sw.WriteLine ("namespace " + NS + "Sharp {"); sw.WriteLine (); sw.WriteLine ("\tusing System;"); sw.WriteLine ("\tusing System.Runtime.InteropServices;"); sw.WriteLine (); sw.WriteLine ("#region Autogenerated code"); sw.WriteLine ("\t[GLib.CDeclCallback]"); sw.WriteLine ("\tinternal delegate " + retval.MarshalType + " " + wrapper + "(" + parms.ImportSignature + ");"); sw.WriteLine (); GenInvoker (gen_info, sw); sw.WriteLine ("\tinternal class " + Name + "Wrapper {"); sw.WriteLine (); ManagedCallString call = new ManagedCallString (parms, false); sw.WriteLine ("\t\tpublic " + retval.MarshalType + " NativeCallback (" + parms.ImportSignature + ")"); sw.WriteLine ("\t\t{"); string unconditional = call.Unconditional ("\t\t\t"); if (unconditional.Length > 0) sw.WriteLine (unconditional); sw.WriteLine ("\t\t\ttry {"); string call_setup = call.Setup ("\t\t\t\t"); if (call_setup.Length > 0) sw.WriteLine (call_setup); if (retval.CSType == "void") sw.WriteLine ("\t\t\t\tmanaged ({0});", call); else sw.WriteLine ("\t\t\t\t{0} __ret = managed ({1});", retval.CSType, call); string finish = call.Finish ("\t\t\t\t"); if (finish.Length > 0) sw.WriteLine (finish); sw.WriteLine ("\t\t\t\tif (release_on_call)\n\t\t\t\t\tgch.Free ();"); if (retval.CSType != "void") sw.WriteLine ("\t\t\t\treturn {0};", retval.ToNative ("__ret")); /* If the function expects one or more "out" parameters(error parameters are excluded) or has a return value different from void and bool, exceptions * thrown in the managed function have to be considered fatal meaning that an exception is to be thrown and the function call cannot not return */ bool fatal = (retval.MarshalType != "void" && retval.MarshalType != "bool") || call.HasOutParam; sw.WriteLine ("\t\t\t} catch (Exception e) {"); sw.WriteLine ("\t\t\t\tGLib.ExceptionManager.RaiseUnhandledException (e, " + (fatal ? "true" : "false") + ");"); if (fatal) { sw.WriteLine ("\t\t\t\t// NOTREACHED: Above call does not return."); sw.WriteLine ("\t\t\t\tthrow e;"); } else if (retval.MarshalType == "bool") { sw.WriteLine ("\t\t\t\treturn false;"); } sw.WriteLine ("\t\t\t}"); sw.WriteLine ("\t\t}"); sw.WriteLine (); sw.WriteLine ("\t\tbool release_on_call = false;"); sw.WriteLine ("\t\tGCHandle gch;"); sw.WriteLine (); sw.WriteLine ("\t\tpublic void PersistUntilCalled ()"); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\trelease_on_call = true;"); sw.WriteLine ("\t\t\tgch = GCHandle.Alloc (this);"); sw.WriteLine ("\t\t}"); sw.WriteLine (); sw.WriteLine ("\t\tinternal " + wrapper + " NativeDelegate;"); sw.WriteLine ("\t\t" + NS + "." + Name + " managed;"); sw.WriteLine (); sw.WriteLine ("\t\tpublic " + Name + "Wrapper (" + NS + "." + Name + " managed)"); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\tthis.managed = managed;"); sw.WriteLine ("\t\t\tif (managed != null)"); sw.WriteLine ("\t\t\t\tNativeDelegate = new " + wrapper + " (NativeCallback);"); sw.WriteLine ("\t\t}"); sw.WriteLine (); sw.WriteLine ("\t\tpublic static " + NS + "." + Name + " GetManagedDelegate (" + wrapper + " native)"); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\tif (native == null)"); sw.WriteLine ("\t\t\t\treturn null;"); sw.WriteLine ("\t\t\t" + Name + "Wrapper wrapper = (" + Name + "Wrapper) native.Target;"); sw.WriteLine ("\t\t\tif (wrapper == null)"); sw.WriteLine ("\t\t\t\treturn null;"); sw.WriteLine ("\t\t\treturn wrapper.managed;"); sw.WriteLine ("\t\t}"); sw.WriteLine ("\t}"); sw.WriteLine ("#endregion"); sw.WriteLine ("}"); sw.Close (); gen_info.Writer = save_sw; return NS + "Sharp." + Name + "Wrapper"; } public override void Generate (GenerationInfo gen_info) { gen_info.CurrentType = Name; sig = new Signature (parms); StreamWriter sw = gen_info.OpenStream (Name); sw.WriteLine ("namespace " + NS + " {"); sw.WriteLine (); sw.WriteLine ("\tusing System;"); sw.WriteLine (); sw.WriteLine ("\t{0} delegate " + retval.CSType + " " + Name + "(" + sig.ToString() + ");", IsInternal ? "internal" : "public"); sw.WriteLine (); sw.WriteLine ("}"); sw.Close (); GenWrapper (gen_info); Statistics.CBCount++; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H11_City_Child (editable child object).<br/> /// This is a generated base class of <see cref="H11_City_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="H10_City"/> collection. /// </remarks> [Serializable] public partial class H11_City_Child : BusinessBase<H11_City_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name"); /// <summary> /// Gets or sets the CityRoads Child Name. /// </summary> /// <value>The CityRoads Child Name.</value> public string City_Child_Name { get { return GetProperty(City_Child_NameProperty); } set { SetProperty(City_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H11_City_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="H11_City_Child"/> object.</returns> internal static H11_City_Child NewH11_City_Child() { return DataPortal.CreateChild<H11_City_Child>(); } /// <summary> /// Factory method. Loads a <see cref="H11_City_Child"/> object, based on given parameters. /// </summary> /// <param name="city_ID1">The City_ID1 parameter of the H11_City_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="H11_City_Child"/> object.</returns> internal static H11_City_Child GetH11_City_Child(int city_ID1) { return DataPortal.FetchChild<H11_City_Child>(city_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H11_City_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public H11_City_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="H11_City_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="H11_City_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="city_ID1">The City ID1.</param> protected void Child_Fetch(int city_ID1) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetH11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", city_ID1).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, city_ID1); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="H11_City_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="H11_City_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(H10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddH11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="H11_City_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(H10_City parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateH11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="H11_City_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(H10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteH11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsRequiredOptional { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class ImplicitModelExtensions { /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pathParameter'> /// </param> public static Error GetRequiredPath(this IImplicitModel operations, string pathParameter) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredPathAsync(pathParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pathParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredPathAsync( this IImplicitModel operations, string pathParameter, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.GetRequiredPathWithHttpMessagesAsync(pathParameter, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> public static void PutOptionalQuery(this IImplicitModel operations, string queryParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalQueryAsync(queryParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalQueryAsync( this IImplicitModel operations, string queryParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalQueryWithHttpMessagesAsync(queryParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> public static void PutOptionalHeader(this IImplicitModel operations, string queryParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalHeaderAsync(queryParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalHeaderAsync( this IImplicitModel operations, string queryParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalHeaderWithHttpMessagesAsync(queryParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PutOptionalBody(this IImplicitModel operations, string bodyParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalBodyAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalBodyAsync( this IImplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalBodyWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetRequiredGlobalPath(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredGlobalPathAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredGlobalPathAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.GetRequiredGlobalPathWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetRequiredGlobalQuery(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredGlobalQueryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredGlobalQueryAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.GetRequiredGlobalQueryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetOptionalGlobalQuery(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetOptionalGlobalQueryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetOptionalGlobalQueryAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.GetOptionalGlobalQueryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
//------------------------------------------------------------------------------- // <copyright file="ExceptionCasesTest.cs" company="Appccelerate"> // Copyright (c) 2008-2015 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //------------------------------------------------------------------------------- namespace Appccelerate.StateMachine.Machine { using System; using System.Collections.Generic; using Appccelerate.StateMachine.Persistence; using Appccelerate.StateMachine.Syntax; using FakeItEasy; using FluentAssertions; using Xunit; /// <summary> /// Tests exception behavior of the <see cref="StateMachine{TState,TEvent}"/>. /// </summary> public class ExceptionCasesTest { private readonly StateMachine<StateMachine.States, StateMachine.Events> testee; private StateMachine.States? recordedStateId; private StateMachine.Events? recordedEventId; private object recordedEventArgument; private Exception recordedException; public ExceptionCasesTest() { this.testee = new StateMachine<StateMachine.States, StateMachine.Events>(); this.testee.TransitionExceptionThrown += (sender, eventArgs) => { this.recordedStateId = eventArgs.StateId; this.recordedEventId = eventArgs.EventId; this.recordedEventArgument = eventArgs.EventArgument; this.recordedException = eventArgs.Exception; }; } /// <summary> /// When the state machine is not initialized then an exception is throw when firing events on it. /// </summary> [Fact] public void ExceptionIfNotInitialized() { Action action = () => this.testee.Fire(StateMachine.Events.A); action.ShouldThrow<InvalidOperationException>(); } [Fact] public void ExceptionIfNotInitialized_WhenAccessingCurrentState() { Action action = () => { var state = this.testee.CurrentStateId; }; action.ShouldThrow<InvalidOperationException>(); } /// <summary> /// When the state machine is initialized twice then an exception is thrown /// </summary> [Fact] public void ExceptionIfInitializeIsCalledTwice() { this.testee.Initialize(StateMachine.States.A); Action action = () => this.testee.Initialize(StateMachine.States.B); action.ShouldThrow<InvalidOperationException>(); } /// <summary> /// When a guard throws an exception then it is captured and the <see cref="StateMachine{TState,TEvent}.TransitionExceptionThrown"/> event is fired. /// The transition is not executed and if there is no other transition then the state machine remains in the same state. /// </summary> [Fact] public void ExceptionThrowingGuard() { var eventArguments = new object[] { 1, 2, "test" }; Exception exception = new Exception(); this.testee.In(StateMachine.States.A) .On(StateMachine.Events.B) .If(() => { throw exception; }).Goto(StateMachine.States.B); bool transitionDeclined = false; this.testee.TransitionDeclined += (sender, e) => transitionDeclined = true; this.testee.Initialize(StateMachine.States.A); this.testee.EnterInitialState(); this.testee.Fire(StateMachine.Events.B, eventArguments); this.AssertException(StateMachine.States.A, StateMachine.Events.B, eventArguments, exception); this.testee.CurrentStateId.Should().Be(StateMachine.States.A); transitionDeclined.Should().BeTrue("transition was not declined."); } /// <summary> /// When a transition throws an exception then the exception is captured and the <see cref="StateMachine{TState,TEvent}.TransitionExceptionThrown"/> event is fired. /// The transition is executed and the state machine is in the target state. /// </summary> [Fact] public void ExceptionThrowingAction() { var eventArguments = new object[] { 1, 2, "test" }; Exception exception = new Exception(); this.testee.In(StateMachine.States.A) .On(StateMachine.Events.B).Goto(StateMachine.States.B).Execute(() => { throw exception; }); this.testee.Initialize(StateMachine.States.A); this.testee.EnterInitialState(); this.testee.Fire(StateMachine.Events.B, eventArguments); this.AssertException(StateMachine.States.A, StateMachine.Events.B, eventArguments, exception); this.testee.CurrentStateId.Should().Be(StateMachine.States.B); } [Fact] public void EntryActionWhenThrowingExceptionThenNotificationAndStateIsEntered() { var eventArguments = new object[] { 1, 2, "test" }; Exception exception = new Exception(); this.testee.In(StateMachine.States.A) .On(StateMachine.Events.B).Goto(StateMachine.States.B); this.testee.In(StateMachine.States.B) .ExecuteOnEntry(() => { throw exception; }); this.testee.Initialize(StateMachine.States.A); this.testee.EnterInitialState(); this.testee.Fire(StateMachine.Events.B, eventArguments); this.AssertException(StateMachine.States.A, StateMachine.Events.B, eventArguments, exception); this.testee.CurrentStateId.Should().Be(StateMachine.States.B); } [Fact] public void ExitActionWhenThrowingExceptionThenNotificationAndStateIsEntered() { var eventArguments = new object[] { 1, 2, "test" }; Exception exception = new Exception(); this.testee.In(StateMachine.States.A) .ExecuteOnExit(() => { throw exception; }) .On(StateMachine.Events.B).Goto(StateMachine.States.B); this.testee.Initialize(StateMachine.States.A); this.testee.EnterInitialState(); this.testee.Fire(StateMachine.Events.B, eventArguments); this.AssertException(StateMachine.States.A, StateMachine.Events.B, eventArguments, exception); this.testee.CurrentStateId.Should().Be(StateMachine.States.B); } /// <summary> /// The state machine has to be initialized before events can be fired. /// </summary> [Fact] public void NotInitialized() { Action action = () => this.testee.Fire(StateMachine.Events.B); action.ShouldThrow<InvalidOperationException>(); } /// <summary> /// When a state is added to two super states then an exception is thrown. /// </summary> [Fact] public void DefineNonTreeHierarchy() { this.testee.DefineHierarchyOn(StateMachine.States.A) .WithHistoryType(HistoryType.None) .WithInitialSubState(StateMachine.States.B); Action action = () => { var x = this.testee.DefineHierarchyOn(StateMachine.States.C) .WithHistoryType(HistoryType.None) .WithInitialSubState(StateMachine.States.B); }; action.ShouldThrow<InvalidOperationException>(); } [Fact] public void MultipleTransitionsWithoutGuardsWhenDefiningAGotoThenInvalidOperationException() { this.testee.In(StateMachine.States.A) .On(StateMachine.Events.B).If(() => false).Goto(StateMachine.States.C) .On(StateMachine.Events.B).Goto(StateMachine.States.B); Action action = () => this.testee.In(StateMachine.States.A).On(StateMachine.Events.B).Goto(StateMachine.States.C); action.ShouldThrow<InvalidOperationException>().WithMessage(ExceptionMessages.OnlyOneTransitionMayHaveNoGuard); } [Fact] public void MultipleTransitionsWithoutGuardsWhenDefiningAnActionThenInvalidOperationException() { this.testee.In(StateMachine.States.A) .On(StateMachine.Events.B).Goto(StateMachine.States.B); Action action = () => this.testee.In(StateMachine.States.A).On(StateMachine.Events.B).Execute(() => { }); action.ShouldThrow<InvalidOperationException>().WithMessage(ExceptionMessages.OnlyOneTransitionMayHaveNoGuard); } [Fact] public void TransitionWithoutGuardHasToBeLast() { this.testee.In(StateMachine.States.A) .On(StateMachine.Events.B).Goto(StateMachine.States.B); Action action = () => this.testee.In(StateMachine.States.A).On(StateMachine.Events.B).If(() => false).Execute(() => { }); action.ShouldThrow<InvalidOperationException>().WithMessage(ExceptionMessages.TransitionWithoutGuardHasToBeLast); } [Fact] public void ThrowsExceptionOnLoading_WhenAlreadyInitialized() { this.testee.Initialize(StateMachine.States.A); Action action = () => this.testee.Load(A.Fake<IStateMachineLoader<StateMachine.States>>()); action.ShouldThrow<InvalidOperationException>().WithMessage(ExceptionMessages.StateMachineIsAlreadyInitialized); } [Fact] public void ThrowsExceptionOnLoading_WhenSettingALastActiveStateThatIsNotASubState() { this.testee.DefineHierarchyOn(StateMachine.States.B) .WithHistoryType(HistoryType.Deep) .WithInitialSubState(StateMachine.States.B1) .WithSubState(StateMachine.States.B2); var loader = A.Fake<IStateMachineLoader<StateMachine.States>>(); A.CallTo(() => loader.LoadHistoryStates()) .Returns(new Dictionary<StateMachine.States, StateMachine.States> { { StateMachine.States.B, StateMachine.States.A } }); Action action = () => this.testee.Load(loader); action.ShouldThrow<InvalidOperationException>() .WithMessage(ExceptionMessages.CannotSetALastActiveStateThatIsNotASubState); } /// <summary> /// Asserts that the correct exception was notified. /// </summary> /// <param name="expectedStateId">The expected state id.</param> /// <param name="expectedEventId">The expected event id.</param> /// <param name="expectedEventArguments">The expected event arguments.</param> /// <param name="expectedException">The expected exception.</param> private void AssertException(StateMachine.States expectedStateId, StateMachine.Events expectedEventId, object[] expectedEventArguments, Exception expectedException) { this.recordedStateId.Should().Be(expectedStateId); this.recordedEventId.Should().Be(expectedEventId); this.recordedEventArgument.Should().Be(expectedEventArguments); this.recordedException.Should().Be(expectedException); } } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using NodaTime.Globalization; using NodaTime.Properties; using NodaTime.Text.Patterns; using NodaTime.TimeZones; namespace NodaTime.Text { internal sealed class ZonedDateTimePatternParser : IPatternParser<ZonedDateTime> { // Split the template value once, to avoid doing it every time we parse. private readonly LocalDate templateValueDate; private readonly LocalTime templateValueTime; private readonly DateTimeZone templateValueZone; private readonly IDateTimeZoneProvider zoneProvider; private readonly ZoneLocalMappingResolver resolver; private static readonly Dictionary<char, CharacterHandler<ZonedDateTime, ZonedDateTimeParseBucket>> PatternCharacterHandlers = new Dictionary<char, CharacterHandler<ZonedDateTime, ZonedDateTimeParseBucket>> { { '%', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePercent }, { '\'', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandleQuote }, { '\"', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandleQuote }, { '\\', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandleBackslash }, { '/', (pattern, builder) => builder.AddLiteral(builder.FormatInfo.DateSeparator, ParseResult<ZonedDateTime>.DateSeparatorMismatch) }, { 'T', (pattern, builder) => builder.AddLiteral('T', ParseResult<ZonedDateTime>.MismatchedCharacter) }, { 'y', DatePatternHelper.CreateYearOfEraHandler<ZonedDateTime, ZonedDateTimeParseBucket>(value => value.YearOfEra, (bucket, value) => bucket.Date.YearOfEra = value) }, { 'u', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (4, PatternFields.Year, -9999, 9999, value => value.Year, (bucket, value) => bucket.Date.Year = value) }, { 'M', DatePatternHelper.CreateMonthOfYearHandler<ZonedDateTime, ZonedDateTimeParseBucket> (value => value.Month, (bucket, value) => bucket.Date.MonthOfYearText = value, (bucket, value) => bucket.Date.MonthOfYearNumeric = value) }, { 'd', DatePatternHelper.CreateDayHandler<ZonedDateTime, ZonedDateTimeParseBucket> (value => value.Day, value => value.DayOfWeek, (bucket, value) => bucket.Date.DayOfMonth = value, (bucket, value) => bucket.Date.DayOfWeek = value) }, { '.', TimePatternHelper.CreatePeriodHandler<ZonedDateTime, ZonedDateTimeParseBucket>(9, value => value.NanosecondOfSecond, (bucket, value) => bucket.Time.FractionalSeconds = value) }, { ';', TimePatternHelper.CreateCommaDotHandler<ZonedDateTime, ZonedDateTimeParseBucket>(9, value => value.NanosecondOfSecond, (bucket, value) => bucket.Time.FractionalSeconds = value) }, { ':', (pattern, builder) => builder.AddLiteral(builder.FormatInfo.TimeSeparator, ParseResult<ZonedDateTime>.TimeSeparatorMismatch) }, { 'h', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (2, PatternFields.Hours12, 1, 12, value => value.ClockHourOfHalfDay, (bucket, value) => bucket.Time.Hours12 = value) }, { 'H', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (2, PatternFields.Hours24, 0, 24, value => value.Hour, (bucket, value) => bucket.Time.Hours24 = value) }, { 'm', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (2, PatternFields.Minutes, 0, 59, value => value.Minute, (bucket, value) => bucket.Time.Minutes = value) }, { 's', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (2, PatternFields.Seconds, 0, 59, value => value.Second, (bucket, value) => bucket.Time.Seconds = value) }, { 'f', TimePatternHelper.CreateFractionHandler<ZonedDateTime, ZonedDateTimeParseBucket>(9, value => value.NanosecondOfSecond, (bucket, value) => bucket.Time.FractionalSeconds = value) }, { 'F', TimePatternHelper.CreateFractionHandler<ZonedDateTime, ZonedDateTimeParseBucket>(9, value => value.NanosecondOfSecond, (bucket, value) => bucket.Time.FractionalSeconds = value) }, { 't', TimePatternHelper.CreateAmPmHandler<ZonedDateTime, ZonedDateTimeParseBucket>(time => time.Hour, (bucket, value) => bucket.Time.AmPm = value) }, { 'c', DatePatternHelper.CreateCalendarHandler<ZonedDateTime, ZonedDateTimeParseBucket>(value => value.LocalDateTime.Calendar, (bucket, value) => bucket.Date.Calendar = value) }, { 'g', DatePatternHelper.CreateEraHandler<ZonedDateTime, ZonedDateTimeParseBucket>(value => value.Era, bucket => bucket.Date) }, { 'z', HandleZone }, { 'x', HandleZoneAbbreviation }, { 'o', HandleOffset }, { 'l', (cursor, builder) => builder.AddEmbeddedLocalPartial(cursor, bucket => bucket.Date, bucket => bucket.Time, value => value.Date, value => value.TimeOfDay, value => value.LocalDateTime) }, }; internal ZonedDateTimePatternParser(ZonedDateTime templateValue, ZoneLocalMappingResolver resolver, IDateTimeZoneProvider zoneProvider) { templateValueDate = templateValue.Date; templateValueTime = templateValue.TimeOfDay; templateValueZone = templateValue.Zone; this.resolver = resolver; this.zoneProvider = zoneProvider; } // Note: public to implement the interface. It does no harm, and it's simpler than using explicit // interface implementation. public IPattern<ZonedDateTime> ParsePattern(string patternText, NodaFormatInfo formatInfo) { // Nullity check is performed in ZonedDateTimePattern. if (patternText.Length == 0) { throw new InvalidPatternException(Messages.Parse_FormatStringEmpty); } // Handle standard patterns if (patternText.Length == 1) { switch (patternText[0]) { case 'G': return ZonedDateTimePattern.Patterns.GeneralFormatOnlyPatternImpl .WithZoneProvider(zoneProvider) .WithResolver(resolver); case 'F': return ZonedDateTimePattern.Patterns.ExtendedFormatOnlyPatternImpl .WithZoneProvider(zoneProvider) .WithResolver(resolver); default: throw new InvalidPatternException(Messages.Parse_UnknownStandardFormat, patternText[0], typeof(ZonedDateTime)); } } var patternBuilder = new SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>(formatInfo, () => new ZonedDateTimeParseBucket(templateValueDate, templateValueTime, templateValueZone, resolver, zoneProvider)); if (zoneProvider == null) { patternBuilder.SetFormatOnly(); } patternBuilder.ParseCustomPattern(patternText, PatternCharacterHandlers); patternBuilder.ValidateUsedFields(); return patternBuilder.Build(templateValueDate.At(templateValueTime).InZoneLeniently(templateValueZone)); } private static void HandleZone(PatternCursor pattern, SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket> builder) { builder.AddField(PatternFields.Zone, pattern.Current); builder.AddParseAction(ParseZone); builder.AddFormatAction((value, sb) => sb.Append(value.Zone.Id)); } private static void HandleZoneAbbreviation(PatternCursor pattern, SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket> builder) { builder.AddField(PatternFields.ZoneAbbreviation, pattern.Current); builder.SetFormatOnly(); builder.AddFormatAction((value, sb) => sb.Append(value.GetZoneInterval().Name)); } private static void HandleOffset(PatternCursor pattern, SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket> builder) { builder.AddField(PatternFields.EmbeddedOffset, pattern.Current); string embeddedPattern = pattern.GetEmbeddedPattern(); var offsetPattern = OffsetPattern.Create(embeddedPattern, builder.FormatInfo).UnderlyingPattern; builder.AddEmbeddedPattern(offsetPattern, (bucket, offset) => bucket.Offset = offset, zdt => zdt.Offset); } private static ParseResult<ZonedDateTime> ParseZone(ValueCursor value, ZonedDateTimeParseBucket bucket) => bucket.ParseZone(value); private sealed class ZonedDateTimeParseBucket : ParseBucket<ZonedDateTime> { internal readonly LocalDatePatternParser.LocalDateParseBucket Date; internal readonly LocalTimePatternParser.LocalTimeParseBucket Time; private DateTimeZone Zone; internal Offset Offset; private readonly ZoneLocalMappingResolver resolver; private readonly IDateTimeZoneProvider zoneProvider; internal ZonedDateTimeParseBucket(LocalDate templateDate, LocalTime templateTime, DateTimeZone templateZone, ZoneLocalMappingResolver resolver, IDateTimeZoneProvider zoneProvider) { Date = new LocalDatePatternParser.LocalDateParseBucket(templateDate); Time = new LocalTimePatternParser.LocalTimeParseBucket(templateTime); Zone = templateZone; this.resolver = resolver; this.zoneProvider = zoneProvider; } internal ParseResult<ZonedDateTime> ParseZone(ValueCursor value) { DateTimeZone zone = TryParseFixedZone(value) ?? TryParseProviderZone(value); if (zone == null) { return ParseResult<ZonedDateTime>.NoMatchingZoneId(value); } Zone = zone; return null; } /// <summary> /// Attempts to parse a fixed time zone from "UTC" with an optional /// offset, expressed as +HH, +HH:mm, +HH:mm:ss or +HH:mm:ss.fff - i.e. the /// general format. If it manages, it will move the cursor and return the /// zone. Otherwise, it will return null and the cursor will remain where /// it was. /// </summary> private DateTimeZone TryParseFixedZone(ValueCursor value) { if (value.CompareOrdinal(DateTimeZone.UtcId) != 0) { return null; } value.Move(value.Index + 3); var pattern = OffsetPattern.GeneralInvariantPattern.UnderlyingPattern; var parseResult = pattern.ParsePartial(value); return parseResult.Success ? DateTimeZone.ForOffset(parseResult.Value) : DateTimeZone.Utc; } /// <summary> /// Tries to parse a time zone ID from the provider. Returns the zone /// on success (after moving the cursor to the end of the ID) or null on failure /// (leaving the cursor where it was). /// </summary> private DateTimeZone TryParseProviderZone(ValueCursor value) { // The IDs from the provider are guaranteed to be in order (using ordinal comparisons). // Use a binary search to find a match, then make sure it's the longest possible match. var ids = zoneProvider.Ids; int lowerBound = 0; // Inclusive int upperBound = ids.Count; // Exclusive while (lowerBound < upperBound) { int guess = (lowerBound + upperBound) / 2; int result = value.CompareOrdinal(ids[guess]); if (result < 0) { // Guess is later than our text: lower the upper bound upperBound = guess; } else if (result > 0) { // Guess is earlier than our text: raise the lower bound lowerBound = guess + 1; } else { // We've found a match! But it may not be as long as it // could be. Keep looking until we find a value which isn't a match... while (guess + 1 < upperBound && value.CompareOrdinal(ids[guess + 1]) == 0) { guess++; } string id = ids[guess]; value.Move(value.Index + id.Length); return zoneProvider[id]; } } return null; } internal override ParseResult<ZonedDateTime> CalculateValue(PatternFields usedFields, string text) { var localResult = LocalDateTimePatternParser.LocalDateTimeParseBucket.CombineBuckets(usedFields, Date, Time, text); if (!localResult.Success) { return localResult.ConvertError<ZonedDateTime>(); } var localDateTime = localResult.Value; // No offset - so just use the resolver if ((usedFields & PatternFields.EmbeddedOffset) == 0) { try { return ParseResult<ZonedDateTime>.ForValue(Zone.ResolveLocal(localDateTime, resolver)); } catch (SkippedTimeException) { return ParseResult<ZonedDateTime>.SkippedLocalTime(text); } catch (AmbiguousTimeException) { return ParseResult<ZonedDateTime>.AmbiguousLocalTime(text); } } // We were given an offset, so we can resolve and validate using that var mapping = Zone.MapLocal(localDateTime); ZonedDateTime result; switch (mapping.Count) { // If the local time was skipped, the offset has to be invalid. case 0: return ParseResult<ZonedDateTime>.InvalidOffset(text); case 1: result = mapping.First(); // We'll validate in a minute break; case 2: result = mapping.First().Offset == Offset ? mapping.First() : mapping.Last(); break; default: throw new InvalidOperationException("Mapping has count outside range 0-2; should not happen."); } if (result.Offset != Offset) { return ParseResult<ZonedDateTime>.InvalidOffset(text); } return ParseResult<ZonedDateTime>.ForValue(result); } } } }
using AllReady.Areas.Admin.Controllers; using AllReady.Areas.Admin.Features.Invite; using AllReady.Areas.Admin.ViewModels.Invite; using AllReady.Features.Campaigns; using AllReady.Features.Events; using AllReady.Models; using AllReady.UnitTest.Extensions; using MediatR; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using System; using System.Threading.Tasks; using Xunit; namespace AllReady.UnitTest.Areas.Admin.Controllers { public class InviteControllerTests { private const int campaignId = 100; private const int eventId = 200; #region SendCampaignManagerInvite GET Tests [Fact] public async Task SendCampaignManagerInviteSendsCampaignByCampaignIdQueryWithCorrectCampaignId() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); // Act await sut.SendCampaignManagerInvite(campaignId); // Assert mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignByCampaignIdQuery>(c => c.CampaignId == campaignId))); } [Fact] public async Task SendCampaignManagerInviteReturnsNotFoundResult_WhenNoCampaignMatchesId() { // Arrange var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync((Campaign)null); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId); // Assert Assert.IsType<NotFoundResult>(result); } [Fact] public async Task SendCampaignManagerInviteReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin() { // Arrange var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(new Campaign()); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserNotAnOrgAdmin(); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId); // Assert Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task SendCampaignManagerInviteReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "2"); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId); // Assert Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task SendCampaignManagerInviteReturnsSendView_WhenUserIsOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "1"); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId); // Assert Assert.IsType<ViewResult>(result); ViewResult view = result as ViewResult; Assert.Equal("Send", view.ViewName); } [Fact] public async Task SendCampaignManagerInviteReturnsPassesCorrectViewModelToView() { // Arrange var mockMediator = new Mock<IMediator>(); var campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "1"); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId); // Assert ViewResult view = result as ViewResult; var model = Assert.IsType<InviteViewModel>(view.ViewData.Model); Assert.Equal(campaignId, model.CampaignId); Assert.Equal("SendCampaignManagerInvite", model.FormAction); Assert.Equal("Send Campaign Manager Invite", model.Title); } #endregion #region SendEventManagerInvite GET Tests [Fact] public async Task SendEventManagerInviteSendsEventByEventIdQueryWithCorrectEventId() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); // Act await sut.SendEventManagerInvite(eventId); // Assert mockMediator.Verify(mock => mock.SendAsync(It.Is<EventByEventIdQuery>(e => e.EventId == eventId))); } [Fact] public async Task SendEventManagerInviteReturnsNotFoundResult_WhenNoEventMatchesId() { // Arrange var mockMediator = new Mock<IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync((Event)null); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); // Act IActionResult result = await sut.SendEventManagerInvite(eventId); // Assert Assert.IsType<NotFoundResult>(result); } [Fact] public async Task SendEventManagerInviteReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event(); @event.Campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserNotAnOrgAdmin(); // Act IActionResult result = await sut.SendEventManagerInvite(eventId); // Assert Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task SendEventManagerInviteReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event(); @event.Campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "2"); // Act IActionResult result = await sut.SendEventManagerInvite(eventId); // Assert Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task SendEventManagerInviteReturnsSendView_WhenUserIsOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event(); @event.Campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "1"); // Act IActionResult result = await sut.SendEventManagerInvite(eventId); // Assert Assert.IsType<ViewResult>(result); ViewResult view = result as ViewResult; Assert.Equal("Send", view.ViewName); } [Fact] public async Task SendEventManagerInviteReturnsPassesCorrectViewModelToView() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event(); @event.Campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "1"); // Act IActionResult result = await sut.SendEventManagerInvite(eventId); // Assert ViewResult view = result as ViewResult; var model = Assert.IsType<InviteViewModel>(view.ViewData.Model); Assert.Equal(eventId, model.EventId); Assert.Equal("Send Event Manager Invite", model.Title); Assert.Equal("SendEventManagerInvite", model.FormAction); } #endregion #region SendCampaignManagerInvite POST Tests [Fact] public async Task SendCampaignManagerInviteReturnsBadRequestResult_WhenViewModelIsNull() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId, null); // Assert Assert.IsType<BadRequestResult>(result); } [Fact] public async Task SendCampaignManagerInviteShouldNotCreateInvite_WhenViewModelIsNull() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId, null); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendCampaignManagerInviteReturnsSendView_WhenModelStateIsNotValid() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.ModelState.AddModelError("Error", "Message"); // Act var result = await sut.SendCampaignManagerInvite(campaignId, new InviteViewModel()); // Assert var view = Assert.IsType<ViewResult>(result); Assert.Equal("Send", view.ViewName); } [Fact] public async Task SendCampaignManagerInviteShouldNotCreateInvite_WhenModelStateIsNotValid() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.ModelState.AddModelError("Error", "Message"); // Act var result = await sut.SendCampaignManagerInvite(campaignId, new InviteViewModel()); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendCampaignManagerInviteReturnsBadRequestResult_WhenNoCampaignMatchesId() { // Arrange var mockMediator = new Mock<IMediator>(); mockMediator.Setup(x => x.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync((Campaign)null); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); var invite = new InviteViewModel(); // Act var result = await sut.SendCampaignManagerInvite(campaignId, new InviteViewModel()); // Assert Assert.IsType<BadRequestResult>(result); } [Fact] public async Task SendCampaignManagerInviteShouldNotCreateInvite_WhenNoCampaignMatchesId() { // Arrange var mockMediator = new Mock<IMediator>(); mockMediator.Setup(x => x.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync((Campaign)null); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); var invite = new InviteViewModel(); // Act var result = await sut.SendCampaignManagerInvite(campaignId, new InviteViewModel()); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendCampaignManagerInvitePostReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin() { // Arrange var mockMediator = new Mock<IMediator>(); var campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserNotAnOrgAdmin(); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId, invite); // Assert Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task SendCampaignManagerInviteShouldNotCreateInvite_WhenUserIsNotOrgAdmin() { // Arrange var mockMediator = new Mock<IMediator>(); var campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserNotAnOrgAdmin(); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendCampaignManagerInvitePostReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "2"); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId, invite); // Assert Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task SendCampaignManagerInviteShouldNotCreateInvite_WhenUserIsNotOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "2"); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendCampaignManagerInviteShouldCreateInvite_WhenUserIsOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var campaign = new Campaign() { ManagingOrganizationId = 1 }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "1"); var invite = new InviteViewModel { CampaignId = 1, InviteeEmailAddress = "test@test.com", CustomMessage = "test message" }; // Act IActionResult result = await sut.SendCampaignManagerInvite(campaignId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.Is<CreateCampaignManagerInviteCommand>(c => c.Invite == invite)), Times.Once); } #endregion #region SendEventManagerInvite POST Tests [Fact] public async Task SendEventManagerInviteReturnsBadRequestResult_WhenViewModelIsNull() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); // Act IActionResult result = await sut.SendEventManagerInvite(eventId, null); // Assert Assert.IsType<BadRequestResult>(result); } [Fact] public async Task SendEventManagerInviteShouldNotCreateInvite_WhenViewModelIsNull() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); // Act IActionResult result = await sut.SendEventManagerInvite(eventId, null); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendEventManagerInviteReturnsSendView_WhenModelStateIsNotValid() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.ModelState.AddModelError("Error", "Message"); // Act var result = await sut.SendEventManagerInvite(eventId, new InviteViewModel()); // Assert var view = Assert.IsType<ViewResult>(result); Assert.Equal("Send", view.ViewName); } [Fact] public async Task SendEventManagerInviteShouldNotCreateInvite_WhenModelStateIsNotValid() { // Arrange var mockMediator = new Mock<IMediator>(); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.ModelState.AddModelError("Error", "Message"); // Act var result = await sut.SendEventManagerInvite(eventId, new InviteViewModel()); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendEventManagerInviteReturnsBadRequestResult_WhenNoCampaignMatchesId() { // Arrange var mockMediator = new Mock<IMediator>(); mockMediator.Setup(x => x.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync((Event)null); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); var invite = new InviteViewModel(); // Act var result = await sut.SendEventManagerInvite(eventId, invite); // Assert Assert.IsType<BadRequestResult>(result); } [Fact] public async Task SendEventManagerInviteShouldNotCreateInvite_WhenNoCampaignMatchesId() { // Arrange var mockMediator = new Mock<IMediator>(); mockMediator.Setup(x => x.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync((Event)null); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); var invite = new InviteViewModel(); // Act var result = await sut.SendCampaignManagerInvite(eventId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendEventManagerInvitePostReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event { Campaign = new Campaign() { ManagingOrganizationId = 1 } }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserNotAnOrgAdmin(); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendEventManagerInvite(eventId, invite); // Assert Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task SendEventManagerInviteShouldNotCreateInvite_WhenUserIsNotOrgAdmin() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event { Campaign = new Campaign() { ManagingOrganizationId = 1 } }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserNotAnOrgAdmin(); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendEventManagerInvite(eventId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendEventManagerInvitePostReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event { Campaign = new Campaign() { ManagingOrganizationId = 1 } }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "2"); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendEventManagerInvite(eventId, invite); // Assert Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task SendEventManagerInviteShouldNotCreateInvite_WhenUserIsNotOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event { Campaign = new Campaign() { ManagingOrganizationId = 1 } }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "2"); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendEventManagerInvite(eventId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never); } [Fact] public async Task SendEventManagerInviteShouldCreateInvite_WhenUserIsOrgAdminForCampaign() { // Arrange var mockMediator = new Mock<IMediator>(); var @event = new Event { Campaign = new Campaign() { ManagingOrganizationId = 1 } }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "1"); var invite = new InviteViewModel { EventId = 1, InviteeEmailAddress = "test@test.com", CustomMessage = "test message" }; // Act IActionResult result = await sut.SendEventManagerInvite(invite.EventId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.Is<CreateEventManagerInviteCommand>(c => c.Invite == invite)), Times.Once); } #endregion private class FakeUserManager : UserManager<ApplicationUser> { public FakeUserManager() : base(new Mock<IUserStore<ApplicationUser>>().Object, new Mock<IOptions<IdentityOptions>>().Object, new Mock<IPasswordHasher<ApplicationUser>>().Object, new IUserValidator<ApplicationUser>[0], new IPasswordValidator<ApplicationUser>[0], new Mock<ILookupNormalizer>().Object, new Mock<IdentityErrorDescriber>().Object, new Mock<IServiceProvider>().Object, new Mock<ILogger<UserManager<ApplicationUser>>>().Object) { } public int FindByEmailAsyncCallCount { get; private set; } public override Task<ApplicationUser> FindByEmailAsync(string email) { FindByEmailAsyncCallCount += 1; return Task.FromResult(new ApplicationUser { Id = "123", Email = email }); } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; namespace Lucene.Net.Index { using Lucene.Net.Support; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BinaryDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.BinaryDocValuesUpdate; using NumericDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.NumericDocValuesUpdate; using Query = Lucene.Net.Search.Query; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; /* Holds buffered deletes and updates, by docID, term or query for a * single segment. this is used to hold buffered pending * deletes and updates against the to-be-flushed segment. Once the * deletes and updates are pushed (on flush in DocumentsWriter), they * are converted to a FrozenDeletes instance. */ // NOTE: instances of this class are accessed either via a private // instance on DocumentWriterPerThread, or via sync'd code by // DocumentsWriterDeleteQueue public class BufferedUpdates { /* Rough logic: HashMap has an array[Entry] w/ varying load factor (say 2 * POINTER). Entry is object w/ Term key, Integer val, int hash, Entry next (OBJ_HEADER + 3*POINTER + INT). Term is object w/ String field and String text (OBJ_HEADER + 2*POINTER). Term's field is String (OBJ_HEADER + 4*INT + POINTER + OBJ_HEADER + string.length*CHAR). Term's text is String (OBJ_HEADER + 4*INT + POINTER + OBJ_HEADER + string.length*CHAR). Integer is OBJ_HEADER + INT. */ internal static readonly int BYTES_PER_DEL_TERM = 9 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + 7 * RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 10 * RamUsageEstimator.NUM_BYTES_INT; /* Rough logic: del docIDs are List<Integer>. Say list allocates ~2X size (2*POINTER). Integer is OBJ_HEADER + int */ internal static readonly int BYTES_PER_DEL_DOCID = 2 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + RamUsageEstimator.NUM_BYTES_INT; /* Rough logic: HashMap has an array[Entry] w/ varying load factor (say 2 * POINTER). Entry is object w/ Query key, Integer val, int hash, Entry next (OBJ_HEADER + 3*POINTER + INT). Query we often undercount (say 24 bytes). Integer is OBJ_HEADER + INT. */ internal static readonly int BYTES_PER_DEL_QUERY = 5 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + 2 * RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 2 * RamUsageEstimator.NUM_BYTES_INT + 24; /* Rough logic: NumericUpdate calculates its actual size, * including the update Term and DV field (String). The * per-field map holds a reference to the updated field, and * therefore we only account for the object reference and * map space itself. this is incremented when we first see * an updated field. * * HashMap has an array[Entry] w/ varying load * factor (say 2*POINTER). Entry is an object w/ String key, * LinkedHashMap val, int hash, Entry next (OBJ_HEADER + 3*POINTER + INT). * * LinkedHashMap (val) is counted as OBJ_HEADER, array[Entry] ref + header, 4*INT, 1*FLOAT, * Set (entrySet) (2*OBJ_HEADER + ARRAY_HEADER + 2*POINTER + 4*INT + FLOAT) */ internal static readonly int BYTES_PER_NUMERIC_FIELD_ENTRY = 7 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + 3 * RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + 5 * RamUsageEstimator.NUM_BYTES_INT + RamUsageEstimator.NUM_BYTES_FLOAT; /* Rough logic: Incremented when we see another Term for an already updated * field. * LinkedHashMap has an array[Entry] w/ varying load factor * (say 2*POINTER). Entry is an object w/ Term key, NumericUpdate val, * int hash, Entry next, Entry before, Entry after (OBJ_HEADER + 5*POINTER + INT). * * Term (key) is counted only as POINTER. * NumericUpdate (val) counts its own size and isn't accounted for here. */ internal static readonly int BYTES_PER_NUMERIC_UPDATE_ENTRY = 7 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + RamUsageEstimator.NUM_BYTES_INT; /* Rough logic: BinaryUpdate calculates its actual size, * including the update Term and DV field (String). The * per-field map holds a reference to the updated field, and * therefore we only account for the object reference and * map space itself. this is incremented when we first see * an updated field. * * HashMap has an array[Entry] w/ varying load * factor (say 2*POINTER). Entry is an object w/ String key, * LinkedHashMap val, int hash, Entry next (OBJ_HEADER + 3*POINTER + INT). * * LinkedHashMap (val) is counted as OBJ_HEADER, array[Entry] ref + header, 4*INT, 1*FLOAT, * Set (entrySet) (2*OBJ_HEADER + ARRAY_HEADER + 2*POINTER + 4*INT + FLOAT) */ internal static readonly int BYTES_PER_BINARY_FIELD_ENTRY = 7 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + 3 * RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + 5 * RamUsageEstimator.NUM_BYTES_INT + RamUsageEstimator.NUM_BYTES_FLOAT; /* Rough logic: Incremented when we see another Term for an already updated * field. * LinkedHashMap has an array[Entry] w/ varying load factor * (say 2*POINTER). Entry is an object w/ Term key, BinaryUpdate val, * int hash, Entry next, Entry before, Entry after (OBJ_HEADER + 5*POINTER + INT). * * Term (key) is counted only as POINTER. * BinaryUpdate (val) counts its own size and isn't accounted for here. */ internal static readonly int BYTES_PER_BINARY_UPDATE_ENTRY = 7 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + RamUsageEstimator.NUM_BYTES_INT; internal readonly AtomicInteger NumTermDeletes = new AtomicInteger(); internal readonly AtomicInteger NumNumericUpdates = new AtomicInteger(); internal readonly AtomicInteger NumBinaryUpdates = new AtomicInteger(); internal readonly IDictionary<Query, int?> Queries = new Dictionary<Query, int?>(); internal readonly IList<int?> DocIDs = new List<int?>(); // TODO LUCENENET make get access internal and make accessible from Tests public IDictionary<Term, int?> Terms { get; private set; } // Map<dvField,Map<updateTerm,NumericUpdate>> // For each field we keep an ordered list of NumericUpdates, key'd by the // update Term. OrderedDictionary guarantees we will later traverse the map in // insertion order (so that if two terms affect the same document, the last // one that came in wins), and helps us detect faster if the same Term is // used to update the same field multiple times (so we later traverse it // only once). internal readonly IDictionary<string, OrderedDictionary> NumericUpdates = new Dictionary<string, OrderedDictionary>(); // Map<dvField,Map<updateTerm,BinaryUpdate>> // For each field we keep an ordered list of BinaryUpdates, key'd by the // update Term. OrderedDictionary guarantees we will later traverse the map in // insertion order (so that if two terms affect the same document, the last // one that came in wins), and helps us detect faster if the same Term is // used to update the same field multiple times (so we later traverse it // only once). internal readonly IDictionary<string, OrderedDictionary> BinaryUpdates = new Dictionary<string, OrderedDictionary>(); public static readonly int MAX_INT = Convert.ToInt32(int.MaxValue); internal readonly AtomicLong BytesUsed; private const bool VERBOSE_DELETES = false; internal long Gen; public BufferedUpdates() { this.BytesUsed = new AtomicLong(); Terms = new Dictionary<Term, int?>(); } public override string ToString() { if (VERBOSE_DELETES) { return "gen=" + Gen + " numTerms=" + NumTermDeletes + ", terms=" + Terms + ", queries=" + Queries + ", docIDs=" + DocIDs + ", numericUpdates=" + NumericUpdates + ", binaryUpdates=" + BinaryUpdates + ", bytesUsed=" + BytesUsed; } else { string s = "gen=" + Gen; if (NumTermDeletes.Get() != 0) { s += " " + NumTermDeletes.Get() + " deleted terms (unique count=" + Terms.Count + ")"; } if (Queries.Count != 0) { s += " " + Queries.Count + " deleted queries"; } if (DocIDs.Count != 0) { s += " " + DocIDs.Count + " deleted docIDs"; } if (NumNumericUpdates.Get() != 0) { s += " " + NumNumericUpdates.Get() + " numeric updates (unique count=" + NumericUpdates.Count + ")"; } if (NumBinaryUpdates.Get() != 0) { s += " " + NumBinaryUpdates.Get() + " binary updates (unique count=" + BinaryUpdates.Count + ")"; } if (BytesUsed.Get() != 0) { s += " bytesUsed=" + BytesUsed.Get(); } return s; } } public virtual void AddQuery(Query query, int docIDUpto) { int? prev; Queries.TryGetValue(query, out prev); Queries[query] = docIDUpto; // increment bytes used only if the query wasn't added so far. if (prev == null) { BytesUsed.AddAndGet(BYTES_PER_DEL_QUERY); } } public virtual void AddDocID(int docID) { DocIDs.Add(Convert.ToInt32(docID)); BytesUsed.AddAndGet(BYTES_PER_DEL_DOCID); } public virtual void AddTerm(Term term, int docIDUpto) { int? current; Terms.TryGetValue(term, out current); if (current != null && docIDUpto < current) { // Only record the new number if it's greater than the // current one. this is important because if multiple // threads are replacing the same doc at nearly the // same time, it's possible that one thread that got a // higher docID is scheduled before the other // threads. If we blindly replace than we can // incorrectly get both docs indexed. return; } Terms[term] = Convert.ToInt32(docIDUpto); // note that if current != null then it means there's already a buffered // delete on that term, therefore we seem to over-count. this over-counting // is done to respect IndexWriterConfig.setMaxBufferedDeleteTerms. NumTermDeletes.IncrementAndGet(); if (current == null) { BytesUsed.AddAndGet(BYTES_PER_DEL_TERM + term.Bytes.Length + (RamUsageEstimator.NUM_BYTES_CHAR * term.Field.Length)); } } public virtual void AddNumericUpdate(NumericDocValuesUpdate update, int docIDUpto) { OrderedDictionary fieldUpdates = null; if (!NumericUpdates.TryGetValue(update.Field, out fieldUpdates)) { fieldUpdates = new OrderedDictionary(); NumericUpdates[update.Field] = fieldUpdates; BytesUsed.AddAndGet(BYTES_PER_NUMERIC_FIELD_ENTRY); } NumericDocValuesUpdate current = null; if (fieldUpdates.Contains(update.Term)) { current = fieldUpdates[update.Term] as NumericDocValuesUpdate; } if (current != null && docIDUpto < current.DocIDUpto) { // Only record the new number if it's greater than or equal to the current // one. this is important because if multiple threads are replacing the // same doc at nearly the same time, it's possible that one thread that // got a higher docID is scheduled before the other threads. return; } update.DocIDUpto = docIDUpto; // since it's an OrderedDictionary, we must first remove the Term entry so that // it's added last (we're interested in insertion-order). if (current != null) { fieldUpdates.Remove(update.Term); } fieldUpdates[update.Term] = update; NumNumericUpdates.IncrementAndGet(); if (current == null) { BytesUsed.AddAndGet(BYTES_PER_NUMERIC_UPDATE_ENTRY + update.SizeInBytes()); } } public virtual void AddBinaryUpdate(BinaryDocValuesUpdate update, int docIDUpto) { OrderedDictionary fieldUpdates; if (!BinaryUpdates.TryGetValue(update.Field, out fieldUpdates)) { fieldUpdates = new OrderedDictionary(); BinaryUpdates[update.Field] = fieldUpdates; BytesUsed.AddAndGet(BYTES_PER_BINARY_FIELD_ENTRY); } BinaryDocValuesUpdate current = null; if (fieldUpdates.Contains(update.Term)) { current = fieldUpdates[update.Term] as BinaryDocValuesUpdate; } if (current != null && docIDUpto < current.DocIDUpto) { // Only record the new number if it's greater than or equal to the current // one. this is important because if multiple threads are replacing the // same doc at nearly the same time, it's possible that one thread that // got a higher docID is scheduled before the other threads. return; } update.DocIDUpto = docIDUpto; // since it's an OrderedDictionary, we must first remove the Term entry so that // it's added last (we're interested in insertion-order). if (current != null) { fieldUpdates.Remove(update.Term); } fieldUpdates[update.Term] = update; NumBinaryUpdates.IncrementAndGet(); if (current == null) { BytesUsed.AddAndGet(BYTES_PER_BINARY_UPDATE_ENTRY + update.SizeInBytes()); } } internal virtual void Clear() { Terms.Clear(); Queries.Clear(); DocIDs.Clear(); NumericUpdates.Clear(); BinaryUpdates.Clear(); NumTermDeletes.Set(0); NumNumericUpdates.Set(0); NumBinaryUpdates.Set(0); BytesUsed.Set(0); } internal virtual bool Any() { return Terms.Count > 0 || DocIDs.Count > 0 || Queries.Count > 0 || NumericUpdates.Count > 0 || BinaryUpdates.Count > 0; } } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; using Fluent.Extensions; using Fluent.Internal; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents backstage button /// </summary> [ContentProperty(nameof(Content))] public class Backstage : RibbonControl { private static readonly object syncIsOpen = new object(); /// <summary> /// Occurs when IsOpen has been changed /// </summary> public event DependencyPropertyChangedEventHandler? IsOpenChanged; private BackstageAdorner? adorner; #region Properties /// <summary> /// Gets the <see cref="AdornerLayer"/> for the <see cref="Backstage"/>. /// </summary> /// <remarks>This is exposed to make it possible to show content on the same <see cref="AdornerLayer"/> as the backstage is shown on.</remarks> public AdornerLayer? AdornerLayer { get; private set; } /// <summary> /// Gets or sets whether backstage is shown /// </summary> public bool IsOpen { get { return (bool)this.GetValue(IsOpenProperty); } set { this.SetValue(IsOpenProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="IsOpen"/> dependency property.</summary> public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register(nameof(IsOpen), typeof(bool), typeof(Backstage), new PropertyMetadata(BooleanBoxes.FalseBox, OnIsOpenChanged, CoerceIsOpen)); /// <summary> /// Gets or sets whether backstage can be openend or closed. /// </summary> public bool CanChangeIsOpen { get { return (bool)this.GetValue(CanChangeIsOpenProperty); } set { this.SetValue(CanChangeIsOpenProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="CanChangeIsOpen"/> dependency property.</summary> public static readonly DependencyProperty CanChangeIsOpenProperty = DependencyProperty.Register(nameof(CanChangeIsOpen), typeof(bool), typeof(Backstage), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether context tabs on the titlebar should be hidden when backstage is open /// </summary> public bool HideContextTabsOnOpen { get { return (bool)this.GetValue(HideContextTabsOnOpenProperty); } set { this.SetValue(HideContextTabsOnOpenProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="HideContextTabsOnOpen"/> dependency property.</summary> public static readonly DependencyProperty HideContextTabsOnOpenProperty = DependencyProperty.Register(nameof(HideContextTabsOnOpen), typeof(bool), typeof(Backstage), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether opening or closing should be animated. /// </summary> public bool AreAnimationsEnabled { get { return (bool)this.GetValue(AreAnimationsEnabledProperty); } set { this.SetValue(AreAnimationsEnabledProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="AreAnimationsEnabled"/> dependency property.</summary> public static readonly DependencyProperty AreAnimationsEnabledProperty = DependencyProperty.Register(nameof(AreAnimationsEnabled), typeof(bool), typeof(Backstage), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether to close the backstage when Esc is pressed /// </summary> public bool CloseOnEsc { get { return (bool)this.GetValue(CloseOnEscProperty); } set { this.SetValue(CloseOnEscProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="CloseOnEsc"/> dependency property.</summary> public static readonly DependencyProperty CloseOnEscProperty = DependencyProperty.Register(nameof(CloseOnEsc), typeof(bool), typeof(Backstage), new PropertyMetadata(BooleanBoxes.TrueBox)); private static object? CoerceIsOpen(DependencyObject d, object? baseValue) { var backstage = (Backstage)d; if (backstage.CanChangeIsOpen == false) { return BooleanBoxes.Box(backstage.IsOpen); } return baseValue; } private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (Backstage)d; var oldValue = (bool)e.OldValue; var newValue = (bool)e.NewValue; lock (syncIsOpen) { if ((bool)e.NewValue) { control.Show(); } else { control.Hide(); } // Invoke the event control.IsOpenChanged?.Invoke(control, e); } (UIElementAutomationPeer.FromElement(control) as Fluent.Automation.Peers.RibbonBackstageAutomationPeer)?.RaiseExpandCollapseAutomationEvent(oldValue, newValue); } /// <summary>Identifies the <see cref="UseHighestAvailableAdornerLayer"/> dependency property.</summary> public static readonly DependencyProperty UseHighestAvailableAdornerLayerProperty = DependencyProperty.Register(nameof(UseHighestAvailableAdornerLayer), typeof(bool), typeof(Backstage), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether the highest available adorner layer should be used for the <see cref="BackstageAdorner"/>. /// This means that we will try to look up the visual tree till we find the highest <see cref="AdornerDecorator"/>. /// </summary> public bool UseHighestAvailableAdornerLayer { get { return (bool)this.GetValue(UseHighestAvailableAdornerLayerProperty); } set { this.SetValue(UseHighestAvailableAdornerLayerProperty, BooleanBoxes.Box(value)); } } #region Content /// <summary> /// Gets or sets content of the backstage /// </summary> public UIElement? Content { get { return (UIElement?)this.GetValue(ContentProperty); } set { this.SetValue(ContentProperty, value); } } /// <summary>Identifies the <see cref="Content"/> dependency property.</summary> public static readonly DependencyProperty ContentProperty = DependencyProperty.Register(nameof(Content), typeof(UIElement), typeof(Backstage), new PropertyMetadata(OnContentChanged)); private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var backstage = (Backstage)d; if (e.OldValue is not null) { if (e.NewValue is DependencyObject dependencyObject) { BindingOperations.ClearBinding(dependencyObject, VisibilityProperty); } backstage.RemoveLogicalChild(e.OldValue); } if (e.NewValue is not null) { backstage.AddLogicalChild(e.NewValue); if (e.NewValue is DependencyObject dependencyObject) { BindingOperations.SetBinding(dependencyObject, VisibilityProperty, new Binding { Path = new PropertyPath(VisibilityProperty), Source = backstage }); } } } #endregion #region LogicalChildren /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var baseEnumerator = base.LogicalChildren; while (baseEnumerator?.MoveNext() == true) { yield return baseEnumerator.Current; } if (this.Content is not null) { yield return this.Content; } if (this.Icon is not null) { yield return this.Icon; } } } #endregion #endregion #region Initialization /// <summary> /// Static constructor /// </summary> static Backstage() { DefaultStyleKeyProperty.OverrideMetadata(typeof(Backstage), new FrameworkPropertyMetadata(typeof(Backstage))); // Disable QAT for this control CanAddToQuickAccessToolBarProperty.OverrideMetadata(typeof(Backstage), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(Backstage), new FrameworkPropertyMetadata(KeyboardNavigationMode.Cycle)); } /// <summary> /// Default constructor /// </summary> public Backstage() { this.Loaded += this.OnBackstageLoaded; this.Unloaded += this.OnBackstageUnloaded; this.DataContextChanged += this.Handle_DataContextChanged; } private void Handle_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (this.adorner is not null) { this.adorner.DataContext = e.NewValue; } } /// <summary> /// Called when this control receives the <see cref="PopupService.DismissPopupEvent"/>. /// </summary> protected virtual void OnDismissPopup(object? sender, DismissPopupEventArgs e) { // Don't close on dismiss popup event if application lost focus // or keytips should be shown. if (e.DismissReason == DismissPopupReason.ApplicationLostFocus || e.DismissReason == DismissPopupReason.ShowingKeyTips) { return; } // Only close backstage when popups should always be closed. // "Always" applies to controls marked with IsDefinitive for example. if (e.DismissMode != DismissPopupMode.Always) { return; } this.IsOpen = false; } #endregion #region Methods // Handles click event private void Click() { this.IsOpen = !this.IsOpen; } #region Show / Hide // We have to collapse WindowsFormsHost while Backstate is open private readonly Dictionary<FrameworkElement, Visibility> collapsedElements = new Dictionary<FrameworkElement, Visibility>(); // Saved window sizes private double savedWindowMinWidth = double.NaN; private double savedWindowMinHeight = double.NaN; private double savedWindowWidth = double.NaN; private double savedWindowHeight = double.NaN; private Window? ownerWindow; private Ribbon? parentRibbon; /// <summary> /// Shows the <see cref="Backstage"/> /// </summary> /// <returns> /// <c>true</c> if the <see cref="Backstage"/> was made visible. /// <c>false</c> if the <see cref="Backstage"/> was not made visible. /// </returns> protected virtual bool Show() { // don't open the backstage while in design mode if (DesignerProperties.GetIsInDesignMode(this)) { return false; } if (this.IsLoaded == false) { this.Loaded += this.OnDelayedShow; return false; } if (this.Content is null) { return false; } this.CreateAndAttachBackstageAdorner(); this.ShowAdorner(); this.parentRibbon = GetParentRibbon(this); if (this.parentRibbon is not null) { if (this.parentRibbon.TabControl is not null) { this.parentRibbon.TabControl.IsDropDownOpen = false; this.parentRibbon.TabControl.HighlightSelectedItem = false; this.parentRibbon.TabControl.RequestBackstageClose += this.HandleTabControlRequestBackstageClose; } if (this.parentRibbon.QuickAccessToolBar is not null) { this.parentRibbon.QuickAccessToolBar.IsEnabled = false; } if (this.parentRibbon.TitleBar is not null) { this.parentRibbon.TitleBar.HideContextTabs = this.HideContextTabsOnOpen; } } this.ownerWindow = Window.GetWindow(this); if (this.ownerWindow is null && this.Parent is not null) { this.ownerWindow = Window.GetWindow(this.Parent); } if (this.ownerWindow is not null) { this.SaveWindowSize(this.ownerWindow); this.SaveWindowMinSize(this.ownerWindow); } if (this.ownerWindow is not null) { this.ownerWindow.KeyDown += this.HandleOwnerWindowKeyDown; if (this.savedWindowMinWidth < 500) { this.ownerWindow.MinWidth = 500; } if (this.savedWindowMinHeight < 400) { this.ownerWindow.MinHeight = 400; } this.ownerWindow.SizeChanged += this.HandleOwnerWindowSizeChanged; // We have to collapse WindowsFormsHost while Backstage is open this.CollapseWindowsFormsHosts(this.ownerWindow); } var content = this.Content as IInputElement; content?.Focus(); return true; } /// <summary> /// Hides the <see cref="Backstage"/> /// </summary> protected virtual void Hide() { // potentially fixes https://github.com/fluentribbon/Fluent.Ribbon/issues/489 if (this.Dispatcher.HasShutdownStarted || this.Dispatcher.HasShutdownFinished) { return; } this.Loaded -= this.OnDelayedShow; if (this.Content is null) { return; } if (!this.IsLoaded || this.adorner is null) { return; } this.HideAdornerAndRestoreParentProperties(); } private void ShowAdorner() { if (this.adorner is null) { return; } if (this.AreAnimationsEnabled && this.TryFindResource("Fluent.Ribbon.Storyboards.Backstage.IsOpenTrueStoryboard") is Storyboard storyboard) { storyboard = storyboard.Clone(); storyboard.CurrentStateInvalidated += HandleStoryboardCurrentStateInvalidated; storyboard.Completed += HandleStoryboardOnCompleted; storyboard.Begin(this.adorner); } else { this.adorner.Visibility = Visibility.Visible; } void HandleStoryboardCurrentStateInvalidated(object? sender, EventArgs e) { this.adorner.Visibility = Visibility.Visible; storyboard.CurrentStateInvalidated -= HandleStoryboardCurrentStateInvalidated; } void HandleStoryboardOnCompleted(object? sender, EventArgs args) { this.AdornerLayer?.Update(); storyboard.Completed -= HandleStoryboardOnCompleted; } } private void HideAdornerAndRestoreParentProperties() { if (this.adorner is null) { return; } if (this.AreAnimationsEnabled && this.TryFindResource("Fluent.Ribbon.Storyboards.Backstage.IsOpenFalseStoryboard") is Storyboard storyboard) { storyboard = storyboard.Clone(); storyboard.Completed += HandleStoryboardOnCompleted; storyboard.Begin(this.adorner); } else { this.adorner.Visibility = Visibility.Collapsed; this.RestoreParentProperties(); } void HandleStoryboardOnCompleted(object? sender, EventArgs args) { if (this.adorner is not null) { this.adorner.Visibility = Visibility.Collapsed; } if (this.AdornerLayer is not null) { this.AdornerLayer.Visibility = Visibility.Visible; } this.RestoreParentProperties(); storyboard.Completed -= HandleStoryboardOnCompleted; } } private static void HandleOpenBackstageCommandCanExecute(object sender, CanExecuteRoutedEventArgs args) { var target = ((BackstageAdorner)args.Source).Backstage; args.CanExecute = target.CanChangeIsOpen; } private static void HandleOpenBackstageCommandExecuted(object sender, ExecutedRoutedEventArgs args) { var target = ((BackstageAdorner)args.Source).Backstage; target.IsOpen = !target.IsOpen; } private void CreateAndAttachBackstageAdorner() { // It's possible that we created an adorner but it's parent AdornerLayer got destroyed. // If that's the case we have to destroy our adorner. // This fixes #228 Backstage disappears when changing DontUseDwm if (this.adorner?.Parent is null) { this.DestroyAdorner(); } if (this.adorner is not null) { return; } FrameworkElement? elementToAdorn = UIHelper.GetParent<AdornerDecorator>(this) ?? UIHelper.GetParent<AdornerDecorator>(this.Parent); if (elementToAdorn is null) { return; } if (this.UseHighestAvailableAdornerLayer) { AdornerDecorator? currentAdornerDecorator; while ((currentAdornerDecorator = UIHelper.GetParent<AdornerDecorator>(elementToAdorn)) is not null) { elementToAdorn = currentAdornerDecorator; } } this.AdornerLayer = UIHelper.GetAdornerLayer(elementToAdorn); if (this.AdornerLayer is null) { throw new Exception($"AdornerLayer could not be found for {this}."); } this.adorner = new BackstageAdorner(elementToAdorn, this); BindingOperations.SetBinding(this.adorner, DataContextProperty, new Binding { Path = new PropertyPath(DataContextProperty), Source = this }); this.AdornerLayer.Add(this.adorner); this.AdornerLayer.CommandBindings.Add(new CommandBinding(RibbonCommands.OpenBackstage, HandleOpenBackstageCommandExecuted, HandleOpenBackstageCommandCanExecute)); } private void DestroyAdorner() { this.AdornerLayer?.CommandBindings.Clear(); if (this.adorner is not null) { this.AdornerLayer?.Remove(this.adorner); } if (this.adorner is not null) { BindingOperations.ClearAllBindings(this.adorner); } this.adorner?.Clear(); this.adorner = null; this.AdornerLayer = null; } private void RestoreParentProperties() { if (this.parentRibbon is not null) { if (this.parentRibbon.TabControl is not null) { this.parentRibbon.TabControl.HighlightSelectedItem = true; this.parentRibbon.TabControl.RequestBackstageClose -= this.HandleTabControlRequestBackstageClose; } if (this.parentRibbon.QuickAccessToolBar is not null) { this.parentRibbon.QuickAccessToolBar.IsEnabled = true; this.parentRibbon.QuickAccessToolBar.Refresh(); } if (this.parentRibbon.TitleBar is not null) { this.parentRibbon.TitleBar.HideContextTabs = false; } this.parentRibbon = null; } if (this.ownerWindow is not null) { this.ownerWindow.KeyDown -= this.HandleOwnerWindowKeyDown; this.ownerWindow.SizeChanged -= this.HandleOwnerWindowSizeChanged; if (double.IsNaN(this.savedWindowMinWidth) == false && double.IsNaN(this.savedWindowMinHeight) == false) { this.ownerWindow.MinWidth = this.savedWindowMinWidth; this.ownerWindow.MinHeight = this.savedWindowMinHeight; } if (double.IsNaN(this.savedWindowWidth) == false && double.IsNaN(this.savedWindowHeight) == false) { this.ownerWindow.Width = this.savedWindowWidth; this.ownerWindow.Height = this.savedWindowHeight; } this.savedWindowMinWidth = double.NaN; this.savedWindowMinHeight = double.NaN; this.savedWindowWidth = double.NaN; this.savedWindowHeight = double.NaN; this.ownerWindow = null; } // Uncollapse elements foreach (var element in this.collapsedElements) { element.Key.Visibility = element.Value; } this.collapsedElements.Clear(); } private void OnDelayedShow(object sender, EventArgs args) { this.Loaded -= this.OnDelayedShow; // Delaying show so everthing can load properly. // If we don't run this in the background setting IsOpen=true on application start we don't have access to the Bastage from the BackstageTabControl. this.RunInDispatcherAsync(() => this.Show(), DispatcherPriority.Background); } private void SaveWindowMinSize(Window? window) { if (window is null) { this.savedWindowMinWidth = double.NaN; this.savedWindowMinHeight = double.NaN; return; } this.savedWindowMinWidth = window.MinWidth; this.savedWindowMinHeight = window.MinHeight; } private void SaveWindowSize(Window? window) { if (window is null || window.WindowState == WindowState.Maximized) { this.savedWindowWidth = double.NaN; this.savedWindowHeight = double.NaN; return; } this.savedWindowWidth = window.ActualWidth; this.savedWindowHeight = window.ActualHeight; } private void HandleOwnerWindowSizeChanged(object sender, SizeChangedEventArgs e) { this.SaveWindowSize(Window.GetWindow(this)); } private void HandleTabControlRequestBackstageClose(object? sender, EventArgs e) { this.IsOpen = false; } // We have to collapse WindowsFormsHost while Backstage is open private void CollapseWindowsFormsHosts(DependencyObject parent) { switch (parent) { case null: case BackstageAdorner _: return; case FrameworkElement frameworkElement when parent is HwndHost && frameworkElement.Visibility != Visibility.Collapsed: this.collapsedElements.Add(frameworkElement, frameworkElement.Visibility); frameworkElement.Visibility = Visibility.Collapsed; return; } // Traverse visual tree for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { this.CollapseWindowsFormsHosts(VisualTreeHelper.GetChild(parent, i)); } } /// <inheritdoc /> protected override void OnKeyDown(KeyEventArgs e) { if (e.Handled) { return; } if (e.Key == Key.Enter || e.Key == Key.Space) { if (this.IsFocused) { this.IsOpen = !this.IsOpen; e.Handled = true; } } base.OnKeyDown(e); } // Handles backstage Esc key keydown private void HandleOwnerWindowKeyDown(object sender, KeyEventArgs e) { if (this.CloseOnEsc == false || e.Key != Key.Escape) { return; } // only handle ESC when the backstage is open e.Handled = this.IsOpen; this.IsOpen = false; } private void OnBackstageLoaded(object sender, RoutedEventArgs e) { this.AddHandler(PopupService.DismissPopupEvent, (EventHandler<DismissPopupEventArgs>)this.OnDismissPopup); } private void OnBackstageUnloaded(object sender, RoutedEventArgs e) { this.RemoveHandler(PopupService.DismissPopupEvent, (EventHandler<DismissPopupEventArgs>)this.OnDismissPopup); this.DestroyAdorner(); } #endregion #endregion #region Overrides /// <inheritdoc /> protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); if (ReferenceEquals(e.Source, this) == false) { return; } this.Click(); } /// <inheritdoc /> public override KeyTipPressedResult OnKeyTipPressed() { this.IsOpen = true; base.OnKeyTipPressed(); return KeyTipPressedResult.Empty; } /// <inheritdoc /> public override void OnKeyTipBack() { this.IsOpen = false; base.OnKeyTipBack(); } /// <inheritdoc /> public override void OnApplyTemplate() { base.OnApplyTemplate(); if (this.IsOpen) { this.Hide(); } this.DestroyAdorner(); if (this.IsOpen) { this.Show(); } } #endregion #region Quick Access Toolbar /// <inheritdoc /> public override FrameworkElement CreateQuickAccessItem() { throw new NotImplementedException(); } #endregion /// <inheritdoc /> protected override AutomationPeer OnCreateAutomationPeer() => new Fluent.Automation.Peers.RibbonBackstageAutomationPeer(this); } }
// 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 Xunit; namespace System.Reflection.Emit.Tests { public struct EmitStruct3 { } public class ILGeneratorEmit3 { [Fact] public void PosTest1() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder method = type.DefineMethod("meth1", MethodAttributes.Public | MethodAttributes.Static, typeof(bool), new Type[0]); ILGenerator ilGenerator = method.GetILGenerator(); LocalBuilder lb0 = ilGenerator.DeclareLocal(typeof(int)); LocalBuilder lb1 = ilGenerator.DeclareLocal(typeof(byte)); LocalBuilder lb2 = ilGenerator.DeclareLocal(typeof(double)); LocalBuilder lb3 = ilGenerator.DeclareLocal(typeof(bool)); LocalBuilder lb4 = ilGenerator.DeclareLocal(typeof(bool)); Label label1 = ilGenerator.DefineLabel(); Label label2 = ilGenerator.DefineLabel(); Label label3 = ilGenerator.DefineLabel(); Label label4 = ilGenerator.DefineLabel(); // emit the locals and check that we get correct values stored ilGenerator.Emit(OpCodes.Ldc_I4, 5); ilGenerator.Emit(OpCodes.Stloc, lb0); ilGenerator.Emit(OpCodes.Ldloc, lb0); ilGenerator.Emit(OpCodes.Ldc_I4, 5); ilGenerator.Emit(OpCodes.Ceq); ilGenerator.Emit(OpCodes.Stloc, lb4); ilGenerator.Emit(OpCodes.Ldloc, lb4); ilGenerator.Emit(OpCodes.Brtrue_S, label1); ilGenerator.Emit(OpCodes.Ldc_I4, 0); ilGenerator.Emit(OpCodes.Stloc, lb3); ilGenerator.Emit(OpCodes.Br_S, label4); ilGenerator.MarkLabel(label1); ilGenerator.Emit(OpCodes.Ldc_I4, 1); ilGenerator.Emit(OpCodes.Stloc, lb1); ilGenerator.Emit(OpCodes.Ldloc, lb1); ilGenerator.Emit(OpCodes.Ldc_I4, 1); ilGenerator.Emit(OpCodes.Ceq); ilGenerator.Emit(OpCodes.Stloc, lb4); ilGenerator.Emit(OpCodes.Ldloc, lb4); ilGenerator.Emit(OpCodes.Brtrue_S, label2); ilGenerator.Emit(OpCodes.Ldc_I4, 0); ilGenerator.Emit(OpCodes.Stloc, lb3); ilGenerator.Emit(OpCodes.Br_S, label4); ilGenerator.MarkLabel(label2); ilGenerator.Emit(OpCodes.Ldc_R8, 2.5); ilGenerator.Emit(OpCodes.Stloc, lb2); ilGenerator.Emit(OpCodes.Ldloc, lb2); ilGenerator.Emit(OpCodes.Ldc_R8, 2.5); ilGenerator.Emit(OpCodes.Ceq); ilGenerator.Emit(OpCodes.Stloc, lb4); ilGenerator.Emit(OpCodes.Ldloc, lb4); ilGenerator.Emit(OpCodes.Brtrue_S, label3); ilGenerator.Emit(OpCodes.Ldc_I4, 0); ilGenerator.Emit(OpCodes.Stloc, lb3); ilGenerator.Emit(OpCodes.Br_S, label4); // Should return true if all checks were correct ilGenerator.MarkLabel(label3); ilGenerator.Emit(OpCodes.Ldc_I4, 1); ilGenerator.Emit(OpCodes.Stloc, lb3); ilGenerator.Emit(OpCodes.Br_S, label4); ilGenerator.MarkLabel(label4); ilGenerator.Emit(OpCodes.Ldloc, lb3); ilGenerator.Emit(OpCodes.Ret); // Create the type where this method is in Type createdType = type.CreateTypeInfo().AsType(); MethodInfo createdMethod = createdType.GetMethod("meth1"); Assert.True((bool)createdMethod.Invoke(null, null)); } [Fact] public void PosTest2() { TypeBuilder tb = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder method = tb.DefineMethod("meth1", MethodAttributes.Public | MethodAttributes.Static, typeof(bool), new Type[0]); ILGenerator ilGenerator = method.GetILGenerator(); LocalBuilder lb0 = ilGenerator.DeclareLocal(typeof(EmitStruct3)); // Emit the locals ilGenerator.Emit(OpCodes.Ldloca, lb0); ilGenerator.Emit(OpCodes.Initobj, typeof(EmitStruct3)); ilGenerator.Emit(OpCodes.Ldc_I4, 1); ilGenerator.Emit(OpCodes.Ret); // Create the type where this method is in Type createdType = tb.CreateTypeInfo().AsType(); MethodInfo createdMethod = createdType.GetMethod("meth1"); Assert.True((bool)createdMethod.Invoke(null, null)); } [Fact] public void PosTest3() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder method = type.DefineMethod("meth1", MethodAttributes.Public | MethodAttributes.Static, typeof(bool), new Type[0]); ILGenerator ilGenerator = method.GetILGenerator(); // Emit locals LocalBuilder local = ilGenerator.DeclareLocal(typeof(int)); ilGenerator.Emit(OpCodes.Nop, local); ilGenerator.Emit(OpCodes.Ldc_I4, 1); ilGenerator.Emit(OpCodes.Ret); // create the type where this method is in Type createdType = type.CreateTypeInfo().AsType(); MethodInfo createdMethod = createdType.GetMethod("meth1"); Assert.True((bool)createdMethod.Invoke(null, null)); } [Fact] public void PosTest4() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder method = type.DefineMethod("meth1", MethodAttributes.Public | MethodAttributes.Static, typeof(bool), new Type[0]); ILGenerator ilGenerator = method.GetILGenerator(); LocalBuilder lb0 = ilGenerator.DeclareLocal(typeof(int)); LocalBuilder lb1 = ilGenerator.DeclareLocal(typeof(byte)); LocalBuilder lb2 = ilGenerator.DeclareLocal(typeof(double)); LocalBuilder lb3 = ilGenerator.DeclareLocal(typeof(bool)); LocalBuilder lb4 = ilGenerator.DeclareLocal(typeof(bool)); Label label1 = ilGenerator.DefineLabel(); Label label2 = ilGenerator.DefineLabel(); Label label3 = ilGenerator.DefineLabel(); Label label4 = ilGenerator.DefineLabel(); // Emit the locals using Stloc_0, Stloc_1, Stloc_2, Stloc_3, Stloc_S, // Ldloc_0, Ldloc_1, Ldloc_2, Ldloc_3, Ldloc_S, ilGenerator.Emit(OpCodes.Ldc_I4, 5); ilGenerator.Emit(OpCodes.Stloc_0, lb0); ilGenerator.Emit(OpCodes.Ldloc_0, lb0); ilGenerator.Emit(OpCodes.Ldc_I4, 5); ilGenerator.Emit(OpCodes.Ceq); ilGenerator.Emit(OpCodes.Stloc_S, lb4); ilGenerator.Emit(OpCodes.Ldloc_S, lb4); ilGenerator.Emit(OpCodes.Brtrue_S, label1); ilGenerator.Emit(OpCodes.Ldc_I4, 0); ilGenerator.Emit(OpCodes.Stloc_3, lb3); ilGenerator.Emit(OpCodes.Br_S, label4); ilGenerator.MarkLabel(label1); ilGenerator.Emit(OpCodes.Ldc_I4, 1); ilGenerator.Emit(OpCodes.Stloc_1, lb1); ilGenerator.Emit(OpCodes.Ldloc_1, lb1); ilGenerator.Emit(OpCodes.Ldc_I4, 1); ilGenerator.Emit(OpCodes.Ceq); ilGenerator.Emit(OpCodes.Stloc_S, lb4); ilGenerator.Emit(OpCodes.Ldloc_S, lb4); ilGenerator.Emit(OpCodes.Brtrue_S, label2); ilGenerator.Emit(OpCodes.Ldc_I4, 0); ilGenerator.Emit(OpCodes.Stloc_3, lb3); ilGenerator.Emit(OpCodes.Br_S, label4); ilGenerator.MarkLabel(label2); ilGenerator.Emit(OpCodes.Ldc_R8, 2.5); ilGenerator.Emit(OpCodes.Stloc_2, lb2); ilGenerator.Emit(OpCodes.Ldloc_2, lb2); ilGenerator.Emit(OpCodes.Ldc_R8, 2.5); ilGenerator.Emit(OpCodes.Ceq); ilGenerator.Emit(OpCodes.Stloc_S, lb4); ilGenerator.Emit(OpCodes.Ldloc_S, lb4); ilGenerator.Emit(OpCodes.Brtrue_S, label3); ilGenerator.Emit(OpCodes.Ldc_I4, 0); ilGenerator.Emit(OpCodes.Stloc_3, lb3); ilGenerator.Emit(OpCodes.Br_S, label4); ilGenerator.MarkLabel(label3); ilGenerator.Emit(OpCodes.Ldc_I4, 1); ilGenerator.Emit(OpCodes.Stloc_3, lb3); ilGenerator.Emit(OpCodes.Br_S, label4); ilGenerator.MarkLabel(label4); ilGenerator.Emit(OpCodes.Ldloc_3, lb3); ilGenerator.Emit(OpCodes.Ret); // Create the type where this method is in Type createdType = type.CreateTypeInfo().AsType(); MethodInfo createdMethod = createdType.GetMethod("meth1"); Assert.True((bool)createdMethod.Invoke(null, null)); } [Fact] public void Emit_OpCodes_LocalBuilder_NullLocal_ThrowsArgumentNullException() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.NotPublic); MethodBuilder method = type.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static); ILGenerator generator = method.GetILGenerator(); Assert.Throws<ArgumentNullException>("local", () => generator.Emit(OpCodes.Ldloc_0, (LocalBuilder)null)); } [Fact] public void Emit_OpCodes_LocalBuilder_LocalFromDifferentMethod_ThrowsArgumentException() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.NotPublic); MethodBuilder method1 = type.DefineMethod("Method1", MethodAttributes.Public | MethodAttributes.Static); MethodBuilder method2 = type.DefineMethod("Method2", MethodAttributes.Public | MethodAttributes.Static); ILGenerator generator = method1.GetILGenerator(); LocalBuilder local = method2.GetILGenerator().DeclareLocal(typeof(string)); Assert.Throws<ArgumentException>("local", () => generator.Emit(OpCodes.Ldloc_0, local)); } [Fact] public void Emit_OpCodes_LocalBuilder_TooManyLocals_ThrowsInvalidOperationException() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.NotPublic); MethodBuilder method = type.DefineMethod("NegTest3_Method", MethodAttributes.Public | MethodAttributes.Static); ILGenerator generator = method.GetILGenerator(); for (int i = 0; i <= byte.MaxValue; ++i) { generator.DeclareLocal(typeof(string)); } LocalBuilder arg = generator.DeclareLocal(typeof(string)); Assert.Throws<InvalidOperationException>(() => generator.Emit(OpCodes.Ldloc_S, arg)); } } }
using System.Collections.Generic; using Htc.Vita.Core.Json; using Htc.Vita.Core.Util; using Xunit; namespace Htc.Vita.Core.Tests { public static class IEnumerableExtensionTest { [Fact] public static void Default_0_ToJsonArray_bool() { var items = new List<bool> { true, false, true }; var jsonArray = items.ToJsonArray(); var jsonArraySize = jsonArray.Size(); Assert.Equal(items.Count, jsonArraySize); foreach (var item in items) { var matched = false; for (var i = 0; i < jsonArraySize; i++) { var item2 = jsonArray.ParseBool(i); if (!item.Equals(item2)) { continue; } matched = true; break; } Assert.True(matched); } } [Fact] public static void Default_0_ToJsonArray_double() { var items = new List<double> { 1.1d, 2.2d, 3.3d }; var jsonArray = items.ToJsonArray(); var jsonArraySize = jsonArray.Size(); Assert.Equal(items.Count, jsonArraySize); foreach (var item in items) { var matched = false; for (var i = 0; i < jsonArraySize; i++) { var item2 = jsonArray.ParseDouble(i); if (!item.Equals(item2)) { continue; } matched = true; break; } Assert.True(matched); } } [Fact] public static void Default_0_ToJsonArray_float() { var items = new List<float> { 1.1f, 2.2f, 3.3f }; var jsonArray = items.ToJsonArray(); var jsonArraySize = jsonArray.Size(); Assert.Equal(items.Count, jsonArraySize); foreach (var item in items) { var matched = false; for (var i = 0; i < jsonArraySize; i++) { var item2 = jsonArray.ParseFloat(i); if (!item.Equals(item2)) { continue; } matched = true; break; } Assert.True(matched); } } [Fact] public static void Default_0_ToJsonArray_int() { var items = new List<int> { 1, 2, 3 }; var jsonArray = items.ToJsonArray(); var jsonArraySize = jsonArray.Size(); Assert.Equal(items.Count, jsonArraySize); foreach (var item in items) { var matched = false; for (var i = 0; i < jsonArraySize; i++) { var item2 = jsonArray.ParseInt(i); if (!item.Equals(item2)) { continue; } matched = true; break; } Assert.True(matched); } } [Fact] public static void Default_0_ToJsonArray_long() { var items = new List<long> { 1L, 2L, 3L }; var jsonArray = items.ToJsonArray(); var jsonArraySize = jsonArray.Size(); Assert.Equal(items.Count, jsonArraySize); foreach (var item in items) { var matched = false; for (var i = 0; i < jsonArraySize; i++) { var item2 = jsonArray.ParseLong(i); if (!item.Equals(item2)) { continue; } matched = true; break; } Assert.True(matched); } } [Fact] public static void Default_0_ToJsonArray_string() { var items = new List<string> { "a", "b", "c" }; var jsonArray = items.ToJsonArray(); var jsonArraySize = jsonArray.Size(); Assert.Equal(items.Count, jsonArraySize); foreach (var item in items) { var matched = false; for (var i = 0; i < jsonArraySize; i++) { var item2 = jsonArray.ParseString(i); if (!item.Equals(item2)) { continue; } matched = true; break; } Assert.True(matched); } } [Fact] public static void Default_0_ToJsonArray_JsonArray() { var items = new List<JsonArray> { JsonFactory.GetInstance().GetJsonArray("[]"), JsonFactory.GetInstance().GetJsonArray("[1,2,3]"), JsonFactory.GetInstance().GetJsonArray("[\"1\",\"2\"]") }; var jsonArray = items.ToJsonArray(); var jsonArraySize = jsonArray.Size(); Assert.Equal(items.Count, jsonArraySize); foreach (var item in items) { var matched = false; for (var i = 0; i < jsonArraySize; i++) { var item1 = item.ToString(); var item2 = jsonArray.ParseJsonArray(i).ToString(); if (!item1.Equals(item2)) { continue; } matched = true; break; } Assert.True(matched); } } [Fact] public static void Default_0_ToJsonArray_JsonObject() { var items = new List<JsonObject> { JsonFactory.GetInstance().GetJsonObject("{}"), JsonFactory.GetInstance().GetJsonObject("{\"b\":\"2\"}"), JsonFactory.GetInstance().GetJsonObject("{\"c\":\"3\"}") }; var jsonArray = items.ToJsonArray(); var jsonArraySize = jsonArray.Size(); Assert.Equal(items.Count, jsonArraySize); foreach (var item in items) { var matched = false; for (var i = 0; i < jsonArraySize; i++) { var item1 = item.ToString(); var item2 = jsonArray.ParseJsonObject(i).ToString(); if (!item1.Equals(item2)) { continue; } matched = true; break; } Assert.True(matched); } } } }
//------------------------------------------------------------------------------ // <copyright file="ScrollProperties.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System.Runtime.InteropServices; using System.Diagnostics; using System; using System.Security.Permissions; using System.Runtime.Serialization.Formatters; using System.ComponentModel; using System.Drawing; using Microsoft.Win32; using System.Windows.Forms; using System.Globalization; /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties"]/*' /> /// <devdoc> /// <para> /// Basic Properties for Scrollbars. /// </para> /// </devdoc> public abstract class ScrollProperties { internal int minimum = 0; internal int maximum = 100; internal int smallChange = 1; internal int largeChange = 10; internal int value = 0; internal bool maximumSetExternally; internal bool smallChangeSetExternally; internal bool largeChangeSetExternally; /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.parent"]/*' /> private ScrollableControl parent; protected ScrollableControl ParentControl { get { return parent; } } /// <devdoc> /// Number of pixels to scroll the client region as a "line" for autoscroll. /// </devdoc> /// <internalonly/> private const int SCROLL_LINE = 5; internal bool visible = false; //Always Enabled private bool enabled = true; /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.ScrollProperties"]/*' /> protected ScrollProperties(ScrollableControl container) { this.parent = container; } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.Enabled"]/*' /> /// <devdoc> /// <para> /// Gets or sets a bool value controlling whether the scrollbar is enabled. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.ScrollBarEnableDescr) ] public bool Enabled { get { return enabled; } set { if (parent.AutoScroll) { return; } if (value != enabled) { enabled = value; EnableScroll(value); } } } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.LargeChange"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value to be added or subtracted to the <see cref='System.Windows.Forms.ScrollProperties.LargeChange'/> /// property when the scroll box is moved a large distance. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(10), SRDescription(SR.ScrollBarLargeChangeDescr), RefreshProperties(RefreshProperties.Repaint) ] public int LargeChange { get { // We preserve the actual large change value that has been set, but when we come to // get the value of this property, make sure it's within the maximum allowable value. // This way we ensure that we don't depend on the order of property sets when // code is generated at design-time. // return Math.Min(largeChange, maximum - minimum + 1); } set { if (largeChange != value ) { if (value < 0) { throw new ArgumentOutOfRangeException("LargeChange", SR.GetString(SR.InvalidLowBoundArgumentEx, "LargeChange", (value).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture))); } largeChange = value; largeChangeSetExternally = true; UpdateScrollInfo(); } } } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.Maximum"]/*' /> /// <devdoc> /// <para> /// Gets or sets the upper limit of values of the scrollable range. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(100), SRDescription(SR.ScrollBarMaximumDescr), RefreshProperties(RefreshProperties.Repaint) ] public int Maximum { get { return maximum; } set { if (parent.AutoScroll) { return; } if (maximum != value) { if (minimum > value) minimum = value; // bring this.value in line. if (value < this.value) Value = value; maximum = value; maximumSetExternally = true; UpdateScrollInfo(); } } } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.Minimum"]/*' /> /// <devdoc> /// <para> /// Gets or sets the lower limit of values of the scrollable range. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(0), SRDescription(SR.ScrollBarMinimumDescr), RefreshProperties(RefreshProperties.Repaint) ] public int Minimum { get { return minimum; } set { if (parent.AutoScroll) { return; } if (minimum != value) { if (value < 0) { throw new ArgumentOutOfRangeException("Minimum", SR.GetString(SR.InvalidLowBoundArgumentEx, "Minimum", (value).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture))); } if (maximum < value) maximum = value; // bring this.value in line. if (value > this.value) this.value = value; minimum = value; UpdateScrollInfo(); } } } internal abstract int PageSize { get; } internal abstract int Orientation { get; } internal abstract int HorizontalDisplayPosition { get; } internal abstract int VerticalDisplayPosition { get; } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.SmallChange"]/*' /> /// <devdoc> /// <para> /// Gets or sets the value to be added or subtracted to the /// <see cref='System.Windows.Forms.ScrollBar.Value'/> /// property when the scroll box is /// moved a small distance. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(1), SRDescription(SR.ScrollBarSmallChangeDescr) ] public int SmallChange { get { // We can't have SmallChange > LargeChange, but we shouldn't manipulate // the set values for these properties, so we just return the smaller // value here. // return Math.Min(smallChange, LargeChange); } set { if (smallChange != value) { if (value < 0) { throw new ArgumentOutOfRangeException("SmallChange", SR.GetString(SR.InvalidLowBoundArgumentEx, "SmallChange", (value).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture))); } smallChange = value; smallChangeSetExternally = true; UpdateScrollInfo(); } } } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.Value"]/*' /> /// <devdoc> /// <para> /// Gets or sets a numeric value that represents the current /// position of the scroll box /// on /// the scroll bar control. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(0), Bindable(true), SRDescription(SR.ScrollBarValueDescr) ] public int Value { get { return value; } set { if (this.value != value) { if (value < minimum || value > maximum) { throw new ArgumentOutOfRangeException("Value", SR.GetString(SR.InvalidBoundArgument, "Value", (value).ToString(CultureInfo.CurrentCulture), "'minimum'", "'maximum'")); } this.value = value; UpdateScrollInfo(); parent.SetDisplayFromScrollProps(HorizontalDisplayPosition, VerticalDisplayPosition); } } } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.Visible"]/*' /> /// <devdoc> /// <para> /// Gets or sets a bool value controlling whether the scrollbar is showing. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(false), SRDescription(SR.ScrollBarVisibleDescr) ] public bool Visible { get { return visible; } set { if (parent.AutoScroll) { return; } if (value != visible) { visible = value; parent.UpdateStylesCore (); UpdateScrollInfo(); parent.SetDisplayFromScrollProps(HorizontalDisplayPosition, VerticalDisplayPosition); } } } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.UpdateScrollInfo"]/*' /> /// <devdoc> /// Internal helper method /// </devdoc> /// <internalonly/> internal void UpdateScrollInfo() { if (parent.IsHandleCreated && visible) { NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); si.cbSize = Marshal.SizeOf(typeof(NativeMethods.SCROLLINFO)); si.fMask = NativeMethods.SIF_ALL; si.nMin = minimum; si.nMax = maximum; si.nPage = (parent.AutoScroll) ? PageSize : LargeChange; si.nPos = value; si.nTrackPos = 0; UnsafeNativeMethods.SetScrollInfo(new HandleRef(parent, parent.Handle), Orientation, si, true); } } /// <include file='doc\ScrollProperties.uex' path='docs/doc[@for="ScrollProperties.EnableScroll"]/*' /> /// <devdoc> /// Internal helper method for enabling or disabling the Vertical Scroll bar. /// </devdoc> /// <internalonly/> private void EnableScroll(bool enable) { if (enable) { UnsafeNativeMethods.EnableScrollBar(new HandleRef(parent, parent.Handle), Orientation, NativeMethods.ESB_ENABLE_BOTH); } else { UnsafeNativeMethods.EnableScrollBar(new HandleRef(parent, parent.Handle), Orientation, NativeMethods.ESB_DISABLE_BOTH); } } } }
// // ChangePhotoPathController.cs // // Author: // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2008-2009 Novell, Inc. // Copyright (C) 2008-2009 Stephane Delcroix // // 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. // // // ChangePhotoPath.IChangePhotoPathController.cs: The logic to change the photo path in photos.db // // Author: // Bengt Thuree (bengt@thuree.com) // // Copyright (C) 2007 // using FSpot; using FSpot.Core; using FSpot.Query; using System; using System.IO; using System.Collections; using System.Collections.Specialized; using Hyena; /* Need to 1) Find old base path, assuming starting /YYYY/MM/DD so look for /YY (/19 or /20) 2) Confirm old base path and display new base path 3) For each Photo, check each version, and change every instance of old base path to new path Consider!!! photo_store.Commit(photo) is using db.ExecuteNonQuery, which is not waiting for the command to finish. On my test set of 20.000 photos, it took SQLite another 1 hour or so to commit all rows after this extension had finished its execution. Consider 2!!! A bit of mixture between URI and path. Old and New base path are in String path. Rest in URI. */ namespace FSpot.Tools.ChangePhotoPath { public enum ProcessResult { Ok, Cancelled, Error, SamePath, NoPhotosFound, Processing } public class ChangePathController { PhotoStore photo_store = FSpot.App.Instance.Database.Photos; ArrayList photo_id_array, version_id_array; StringCollection old_path_array, new_path_array; int total_photos; string orig_base_path; private const string BASE2000 = "/20"; private const string BASE1900 = "/19"; private const string BASE1800 = "/18"; private IChangePhotoPathGui gui_controller; private bool user_cancelled; public bool UserCancelled { get {return user_cancelled;} set {user_cancelled = value;} } public ChangePathController (IChangePhotoPathGui gui) { gui_controller = gui; total_photos = photo_store.TotalPhotos; orig_base_path = EnsureEndsWithOneDirectorySeparator (FindOrigBasePath()); // NOT URI string new_base_path = EnsureEndsWithOneDirectorySeparator (FSpot.Core.Global.PhotoUri.LocalPath); // NOT URI gui_controller.DisplayDefaultPaths (orig_base_path, new_base_path); user_cancelled = false; } private string EnsureEndsWithOneDirectorySeparator (string tmp_str) { if ( (tmp_str == null) || (tmp_str.Length == 0) ) return String.Format ("{0}", Path.DirectorySeparatorChar); while (tmp_str.EndsWith(String.Format ("{0}", Path.DirectorySeparatorChar))) tmp_str = tmp_str.Remove (tmp_str.Length-1, 1); return String.Format ("{0}{1}", tmp_str, Path.DirectorySeparatorChar); } // Should always return TRUE, since path always ends with "/" public bool CanWeRun () { return (orig_base_path != null); } private string IsThisPhotoOnOrigBasePath (string check_this_path) { int i; i = check_this_path.IndexOf(BASE2000); if (i > 0) return (check_this_path.Substring(0, i)); i = check_this_path.IndexOf(BASE1900); if (i > 0) return (check_this_path.Substring(0, i)); i = check_this_path.IndexOf(BASE1800); if (i > 0) return (check_this_path.Substring(0, i)); return null; } private string FindOrigBasePath() { string res_path = null; foreach ( IPhoto photo in photo_store.Query ( "SELECT * FROM photos " ) ) { string tmp_path = (photo as Photo).DefaultVersion.Uri.AbsolutePath; res_path = IsThisPhotoOnOrigBasePath (tmp_path); if (res_path != null) break; } return res_path; } private void InitializeArrays() { photo_id_array = new ArrayList(); version_id_array = new ArrayList(); old_path_array = new StringCollection(); new_path_array = new StringCollection(); } private void AddVersionToArrays ( uint photo_id, uint version_id, string old_path, string new_path) { photo_id_array.Add (photo_id); version_id_array.Add (version_id); old_path_array.Add (old_path); new_path_array.Add (new_path); } private string CreateNewPath (string old_base, string new_base, PhotoVersion version) { return string.Format ("{0}{1}", new_base, version.Uri.AbsolutePath.Substring(old_base.Length)); } private bool ChangeThisVersionUri (PhotoVersion version, string old_base, string new_base) { // Change to path from URI, since easier to compare with old_base which is not in URI format. string tmp_path = System.IO.Path.GetDirectoryName (version.Uri.AbsolutePath); return ( tmp_path.StartsWith (old_base) ); } private void SearchVersionUriToChange (Photo photo, string old_base, string new_base) { foreach (uint version_id in photo.VersionIds) { PhotoVersion version = photo.GetVersion (version_id) as PhotoVersion; if ( ChangeThisVersionUri (version, old_base, new_base) ) AddVersionToArrays ( photo.Id, version_id, version.Uri.AbsolutePath, CreateNewPath (old_base, new_base, version)); // else // System.Console.WriteLine ("L : {0}", version.Uri.AbsolutePath); } } public bool SearchUrisToChange (string old_base, string new_base) { int count = 0; foreach ( IPhoto ibrows in photo_store.Query ( "SELECT * FROM photos " ) ) { count++; if (gui_controller.UpdateProgressBar ("Scanning through database", "Checking photo", total_photos)) return false; SearchVersionUriToChange ((ibrows as Photo), old_base, new_base); } return true; } public bool StillOnSamePhotoId (int old_index, int current_index, ArrayList array) { try { return (array[old_index] == array[current_index]); } catch { return true; // return true if out of index. } } public void UpdateThisUri (int index, string path, ref Photo photo) { if (photo == null) photo = photo_store.Get ( (uint) photo_id_array[index]) as Photo; PhotoVersion version = photo.GetVersion ( (uint) version_id_array[index]) as PhotoVersion; version.BaseUri = new SafeUri ( path ).GetBaseUri (); version.Filename = new SafeUri ( path ).GetFilename (); photo.Changes.UriChanged = true; photo.Changes.ChangeVersion ( (uint) version_id_array[index] ); } /// FIXME Refactor, try to use one common method.... public void RevertAllUris (int last_index) { gui_controller.remove_progress_dialog(); Photo photo = null; for (int k = last_index; k >= 0; k--) { if (gui_controller.UpdateProgressBar ("Reverting changes to database", "Reverting photo", last_index)) {} // do nothing, ignore trying to abort the revert... if ( (photo != null) && !StillOnSamePhotoId (k+1, k, photo_id_array) ) { photo_store.Commit (photo); photo = null; } UpdateThisUri (k, old_path_array[k], ref photo); Log.DebugFormat ("R : {0} - {1}", k, old_path_array[k]); } if (photo != null) photo_store.Commit (photo); Log.Debug ("Changing path failed due to above error. Have reverted any modification that took place."); } public ProcessResult ChangeAllUris ( ref int last_index) { gui_controller.remove_progress_dialog(); Photo photo = null; last_index = 0; try { photo = null; for (last_index = 0; last_index < photo_id_array.Count; last_index++) { if (gui_controller.UpdateProgressBar ("Changing photos base path", "Changing photo", photo_id_array.Count)) { Log.Debug("User aborted the change of paths..."); return ProcessResult.Cancelled; } if ( (photo != null) && !StillOnSamePhotoId (last_index-1, last_index, photo_id_array) ) { photo_store.Commit (photo); photo = null; } UpdateThisUri (last_index, new_path_array[last_index], ref photo); Log.DebugFormat ("U : {0} - {1}", last_index, new_path_array[last_index]); // DEBUG ONLY // Cause an TEST exception on 6'th URI to be changed. // float apa = last_index / (last_index-6); } if (photo != null) photo_store.Commit (photo); } catch (Exception e) { Log.Exception(e); return ProcessResult.Error; } return ProcessResult.Ok; } public ProcessResult ProcessArrays() { int last_index = 0; ProcessResult tmp_res; tmp_res = ChangeAllUris(ref last_index); if (!(tmp_res == ProcessResult.Ok)) RevertAllUris(last_index); return tmp_res; } /* public void CheckIfUpdated (int test_index, StringCollection path_array) { Photo photo = photo_store.Get ( (uint) photo_id_array[test_index]) as Photo; PhotoVersion version = photo.GetVersion ( (uint) version_id_array[test_index]) as PhotoVersion; if (version.Uri.AbsolutePath.ToString() == path_array[ test_index ]) Log.DebugFormat ("Test URI ({0}) matches --- Should be finished", test_index); else Log.DebugFormat ("Test URI ({0}) DO NOT match --- Should NOT BE finished", test_index); } */ /* Check paths are different If (Scan all photos) // user might cancel If (Check there are photos on old path) ChangePathsOnPhotos */ public bool NewOldPathSame (ref string newpath, ref string oldpath) { string p1 = EnsureEndsWithOneDirectorySeparator(newpath); string p2 = EnsureEndsWithOneDirectorySeparator(oldpath); return (p1 == p2); } public ProcessResult ChangePathOnPhotos (string old_base, string new_base) { ProcessResult tmp_res = ProcessResult.Processing; InitializeArrays(); if (NewOldPathSame (ref new_base, ref old_base)) tmp_res = ProcessResult.SamePath; if ( (tmp_res == ProcessResult.Processing) && (!SearchUrisToChange (old_base, new_base)) ) tmp_res = ProcessResult.Cancelled; if ( (tmp_res == ProcessResult.Processing) && (photo_id_array.Count == 0) ) tmp_res = ProcessResult.NoPhotosFound; if (tmp_res == ProcessResult.Processing) tmp_res = ProcessArrays(); // if (res) // CheckIfUpdated (photo_id_array.Count-1, new_path_array); // else // CheckIfUpdated (0, old_path_array); return tmp_res; } } }
#region File Description //----------------------------------------------------------------------------- // MessageBoxScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; using RolePlayingGameData; #endregion namespace RolePlaying { /// <summary> /// A popup message box screen, used to display "are you sure?" /// confirmation messages. /// </summary> /// <remarks> /// Similar to a class found in the Game State Management sample on the /// XNA Creators Club Online website (http://creators.xna.com). /// </remarks> class MessageBoxScreen : GameScreen { #region Fields string message; private Texture2D backgroundTexture; private Vector2 backgroundPosition; private Texture2D loadingBlackTexture; private Rectangle loadingBlackTextureDestination; private Texture2D backTexture; private Vector2 backPosition; private Texture2D selectTexture; private Vector2 selectPosition; private Vector2 confirmPosition, messagePosition; #endregion #region Events public event EventHandler<EventArgs> Accepted; public event EventHandler<EventArgs> Cancelled; #endregion #region Initialization /// <summary> /// Constructor lets the caller specify the message. /// </summary> public MessageBoxScreen(string message) { this.message = message; IsPopup = true; TransitionOnTime = TimeSpan.FromSeconds(0.2); TransitionOffTime = TimeSpan.FromSeconds(0.2); } /// <summary> /// Loads graphics content for this screen. This uses the shared ContentManager /// provided by the Game class, so the content will remain loaded forever. /// Whenever a subsequent MessageBoxScreen tries to load this same content, /// it will just get back another reference to the already loaded data. /// </summary> public override void LoadContent() { ContentManager content = ScreenManager.Game.Content; backgroundTexture = content.Load<Texture2D>(@"Textures\MainMenu\Confirm"); backTexture = content.Load<Texture2D>(@"Textures\Buttons\rpgbtn"); selectTexture = content.Load<Texture2D>(@"Textures\Buttons\rpgbtn"); loadingBlackTexture = content.Load<Texture2D>(@"Textures\GameScreens\FadeScreen"); Viewport viewport = ScreenManager.GraphicsDevice.Viewport; backgroundPosition = new Vector2( (viewport.Width - (backgroundTexture.Width * ScaledVector2.DrawFactor)) / 2, (viewport.Height - (backgroundTexture.Height * ScaledVector2.DrawFactor)) / 2); loadingBlackTextureDestination = new Rectangle(viewport.X, viewport.Y, viewport.Width, viewport.Height); backPosition = backgroundPosition + new Vector2(20f, backgroundTexture.Height * ScaledVector2.DrawFactor - 110 * ScaledVector2.ScaleFactor); selectPosition = backgroundPosition + new Vector2( backgroundTexture.Width * ScaledVector2.DrawFactor - 200 * ScaledVector2.ScaleFactor, backgroundTexture.Height * ScaledVector2.DrawFactor - 110 * ScaledVector2.ScaleFactor); confirmPosition.X = backgroundPosition.X + (backgroundTexture.Width * ScaledVector2.DrawFactor - Fonts.HeaderFont.MeasureString("Confirmation").X) / 2f; confirmPosition.Y = backgroundPosition.Y + 47 * ScaledVector2.ScaleFactor; message = Fonts.BreakTextIntoLines(message, 36, 10); messagePosition.X = backgroundPosition.X + (int)((backgroundTexture.Width * ScaledVector2.DrawFactor - Fonts.GearInfoFont.MeasureString(message).X) / 2); messagePosition.Y = (backgroundPosition.Y * 2) - 20 * ScaledVector2.ScaleFactor; } #endregion #region Handle Input /// <summary> /// Responds to user input, accepting or cancelling the message box. /// </summary> public override void HandleInput() { bool confirmationClicked = false; bool backClicked = false; if (InputManager.IsButtonClicked(new Rectangle( (int)selectPosition.X, (int)selectPosition.Y, (int)(backTexture.Width * ScaledVector2.DrawFactor ), (int)(backTexture.Height * ScaledVector2.DrawFactor )))) { confirmationClicked = true; } if (InputManager.IsButtonClicked(new Rectangle ((int)backPosition.X, (int)backPosition.Y, (int)(backTexture.Width * ScaledVector2.DrawFactor ), (int)(backTexture.Height * ScaledVector2.DrawFactor )))) { backClicked = true; } if (confirmationClicked) { // Raise the accepted event, then exit the message box. if (Accepted != null) Accepted(this, EventArgs.Empty); ExitScreen(); } else if (InputManager.IsActionTriggered(InputManager.Action.Back) || backClicked) { // Raise the cancelled event, then exit the message box. if (Cancelled != null) Cancelled(this, EventArgs.Empty); ExitScreen(); } } #endregion #region Draw /// <summary> /// Draws the message box. /// </summary> public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; spriteBatch.Begin(); var position = new Vector2(loadingBlackTextureDestination.X, loadingBlackTextureDestination.Y); spriteBatch.Draw(loadingBlackTexture, position, null,Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(backgroundTexture, backgroundPosition, null, Color.White, 0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(backTexture, backPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(selectTexture, selectPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); string noText = "No"; Vector2 noTextPosition = Fonts.GetCenterPositionInButton(Fonts.ButtonNamesFont, noText, new Rectangle((int)backPosition.X, (int)backPosition.Y, (int)(backTexture.Width), (int)(backTexture.Height ))); spriteBatch.DrawString(Fonts.ButtonNamesFont, noText,noTextPosition,Color.White); string yesText = "Yes"; Vector2 yesTextPosition = Fonts.GetCenterPositionInButton(Fonts.ButtonNamesFont, yesText, new Rectangle((int)selectPosition.X, (int)selectPosition.Y, (int)(selectTexture.Width ), (int)(selectTexture.Height ))); spriteBatch.DrawString(Fonts.ButtonNamesFont, yesText, yesTextPosition, Color.White); spriteBatch.DrawString(Fonts.HeaderFont, "Confirmation", confirmPosition, Fonts.CountColor); spriteBatch.DrawString(Fonts.GearInfoFont, message, messagePosition, Fonts.CountColor); spriteBatch.End(); } #endregion } }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Security.Cryptography; using Model=UnityEngine.AssetBundles.GraphTool.DataModel.Version2; namespace UnityEngine.AssetBundles.GraphTool { /// <summary> /// Asset reference. /// </summary> [System.Serializable] public class AssetReference { [SerializeField] private Guid m_guid; [SerializeField] private string m_assetDatabaseId; [SerializeField] private string m_importFrom; [SerializeField] private string m_exportTo; [SerializeField] private string m_variantName; [SerializeField] private string m_assetTypeString; private UnityEngine.Object[] m_data; private Type m_assetType; private Type m_filterType; /// <summary> /// Gets the identifier. /// </summary> /// <value>The identifier.</value> public string id { get { return m_guid.ToString(); } } /// <summary> /// Gets the asset database identifier. /// </summary> /// <value>The asset database identifier.</value> public string assetDatabaseId { get { return m_assetDatabaseId; } } /// <summary> /// Gets or sets the import from. /// </summary> /// <value>The import from.</value> public string importFrom { get { return m_importFrom; } set { m_importFrom = value; AssetReferenceDatabase.SetDBDirty(); } } /// <summary> /// Gets or sets the export to. /// </summary> /// <value>The export to.</value> public string exportTo { get { return m_exportTo; } set { m_exportTo = value; AssetReferenceDatabase.SetDBDirty(); } } /// <summary> /// Gets or sets the name of the variant. /// </summary> /// <value>The name of the variant.</value> public string variantName { get { return m_variantName; } set { m_variantName = value; AssetReferenceDatabase.SetDBDirty(); } } /// <summary> /// Gets the type of the asset. /// </summary> /// <value>The type of the asset.</value> public Type assetType { get { if(m_assetType == null) { m_assetType = Type.GetType(m_assetTypeString); if(m_assetType == null) { m_assetType = TypeUtility.GetTypeOfAsset(importFrom); m_assetTypeString = m_assetType.AssemblyQualifiedName; } } return m_assetType; } } /// <summary> /// Gets the type of the filter. /// </summary> /// <value>The type of the filter.</value> public Type filterType { get { if(m_filterType == null) { m_filterType = TypeUtility.FindAssetFilterType(m_importFrom); } return m_filterType; } } /// <summary> /// Gets the file name and extension. /// </summary> /// <value>The file name and extension.</value> public string fileNameAndExtension { get { if(m_importFrom != null) { return Path.GetFileName(m_importFrom); } if(m_exportTo != null) { return Path.GetFileName(m_exportTo); } return null; } } /// <summary> /// Gets extension. /// </summary> /// <value>The extension of the file name.</value> public string extension { get { if(m_importFrom != null) { return Path.GetExtension(m_importFrom); } if(m_exportTo != null) { return Path.GetExtension(m_exportTo); } return null; } } /// <summary> /// Gets the name of the file. /// </summary> /// <value>The name of the file.</value> public string fileName { get { if(m_importFrom != null) { return Path.GetFileNameWithoutExtension(m_importFrom); } if(m_exportTo != null) { return Path.GetFileNameWithoutExtension(m_exportTo); } return null; } } /// <summary> /// Gets the path. /// </summary> /// <value>The path.</value> public string path { get { if(m_importFrom != null) { return m_importFrom; } if(m_exportTo != null) { return m_exportTo; } return null; } } /// <summary> /// Gets the absolute path. /// </summary> /// <value>The absolute path.</value> public string absolutePath { get { return m_importFrom.Replace("Assets", Application.dataPath); } } /// <summary> /// Gets all data. /// </summary> /// <value>All data.</value> public UnityEngine.Object[] allData { get { if(m_data == null || m_data.Length == 0) { m_data = AssetDatabase.LoadAllAssetsAtPath(importFrom); } return m_data; } } /// <summary> /// Sets the dirty. /// </summary> public void SetDirty() { if(m_data != null) { foreach(var o in m_data) { EditorUtility.SetDirty(o); } } } /// <summary> /// Releases the data. /// </summary> public void ReleaseData() { if(m_data != null) { foreach(var o in m_data) { if(o is UnityEngine.GameObject || o is UnityEngine.Component) { // do nothing. // NOTE: DestroyImmediate() will destroy persistant GameObject in prefab. Do not call it. } else { LogUtility.Logger.LogFormat(LogType.Log, "Unloading {0} ({1})", importFrom, o.GetType().ToString()); Resources.UnloadAsset(o); } } m_data = null; } } /// <summary> /// Touchs the import asset. /// </summary> public void TouchImportAsset() { System.IO.File.SetLastWriteTime(importFrom, DateTime.UtcNow); } /// <summary> /// Creates the reference. /// </summary> /// <returns>The reference.</returns> /// <param name="importFrom">Import from.</param> public static AssetReference CreateReference (string importFrom) { return new AssetReference( guid: Guid.NewGuid(), assetDatabaseId:AssetDatabase.AssetPathToGUID(importFrom), importFrom:importFrom, assetType:TypeUtility.GetTypeOfAsset(importFrom) ); } /// <summary> /// Creates the reference. /// </summary> /// <returns>The reference.</returns> /// <param name="importFrom">Import from.</param> /// <param name="assetType">Asset type.</param> public static AssetReference CreateReference (string importFrom, Type assetType) { return new AssetReference( guid: Guid.NewGuid(), assetDatabaseId:AssetDatabase.AssetPathToGUID(importFrom), importFrom:importFrom, assetType:assetType ); } /// <summary> /// Creates the prefab reference. /// </summary> /// <returns>The prefab reference.</returns> /// <param name="importFrom">Import from.</param> public static AssetReference CreatePrefabReference (string importFrom) { return new AssetReference( guid: Guid.NewGuid(), assetDatabaseId:AssetDatabase.AssetPathToGUID(importFrom), importFrom:importFrom, assetType:typeof(GameObject) ); } /// <summary> /// Creates the asset bundle reference. /// </summary> /// <returns>The asset bundle reference.</returns> /// <param name="path">Path.</param> public static AssetReference CreateAssetBundleReference (string path) { return new AssetReference( guid: Guid.NewGuid(), assetDatabaseId:AssetDatabase.AssetPathToGUID(path), importFrom:path, assetType:typeof(AssetBundleReference) ); } /// <summary> /// Creates the asset bundle manifest reference. /// </summary> /// <returns>The asset bundle manifest reference.</returns> /// <param name="path">Path.</param> public static AssetReference CreateAssetBundleManifestReference (string path) { return new AssetReference( guid: Guid.NewGuid(), assetDatabaseId:AssetDatabase.AssetPathToGUID(path), importFrom:path, assetType:typeof(AssetBundleManifestReference) ); } /// <summary> /// Initializes a new instance of the <see cref="UnityEngine.AssetBundles.GraphTool.AssetReference"/> class. /// </summary> /// <param name="guid">GUID.</param> /// <param name="assetDatabaseId">Asset database identifier.</param> /// <param name="importFrom">Import from.</param> /// <param name="exportTo">Export to.</param> /// <param name="assetType">Asset type.</param> /// <param name="variantName">Variant name.</param> private AssetReference ( Guid guid, string assetDatabaseId = null, string importFrom = null, string exportTo = null, Type assetType = null, string variantName = null ) { if(assetType == null) { throw new AssetReferenceException(importFrom, "Invalid type of asset created:" + importFrom); } this.m_guid = guid; this.m_importFrom = importFrom; this.m_exportTo = exportTo; this.m_assetDatabaseId = assetDatabaseId; this.m_assetType = assetType; this.m_assetTypeString = assetType.AssemblyQualifiedName; this.m_variantName = variantName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; namespace Internal.Cryptography.Pal { /// <summary> /// Provides an implementation of an X509Store which is backed by files in a directory. /// </summary> internal sealed class DirectoryBasedStoreProvider : IStorePal { // {thumbprint}.1.pfx to {thumbprint}.9.pfx private const int MaxSaveAttempts = 9; private const string PfxExtension = ".pfx"; // *.pfx ({thumbprint}.pfx or {thumbprint}.{ordinal}.pfx) private const string PfxWildcard = "*" + PfxExtension; // .*.pfx ({thumbprint}.{ordinal}.pfx) private const string PfxOrdinalWildcard = "." + PfxWildcard; private static string s_userStoreRoot; private readonly string _storePath; private readonly bool _readOnly; #if DEBUG static DirectoryBasedStoreProvider() { Debug.Assert( 0 == OpenFlags.ReadOnly, "OpenFlags.ReadOnly is not zero, read-only detection will not work"); } #endif internal DirectoryBasedStoreProvider(string storeName, OpenFlags openFlags) { if (string.IsNullOrEmpty(storeName)) { throw new CryptographicException(SR.Arg_EmptyOrNullString); } string directoryName = GetDirectoryName(storeName); if (s_userStoreRoot == null) { // Do this here instead of a static field initializer so that // the static initializer isn't capable of throwing the "home directory not found" // exception. s_userStoreRoot = PersistedFiles.GetUserFeatureDirectory( X509Persistence.CryptographyFeatureName, X509Persistence.X509StoresSubFeatureName); } _storePath = Path.Combine(s_userStoreRoot, directoryName); if (0 != (openFlags & OpenFlags.OpenExistingOnly)) { if (!Directory.Exists(_storePath)) { throw new CryptographicException(SR.Cryptography_X509_StoreNotFound); } } // ReadOnly is 0x00, so it is implicit unless either ReadWrite or MaxAllowed // was requested. OpenFlags writeFlags = openFlags & (OpenFlags.ReadWrite | OpenFlags.MaxAllowed); if (writeFlags == OpenFlags.ReadOnly) { _readOnly = true; } } public void Dispose() { } public void CloneTo(X509Certificate2Collection collection) { Debug.Assert(collection != null); if (!Directory.Exists(_storePath)) { return; } foreach (string filePath in Directory.EnumerateFiles(_storePath, PfxWildcard)) { try { collection.Add(new X509Certificate2(filePath)); } catch (CryptographicException) { // The file wasn't a certificate, move on to the next one. } } } public void Add(ICertificatePal certPal) { if (_readOnly) { // Windows compatibility: Remove only throws when it needs to do work, add throws always. throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly); } // This may well be the first time that we've added something to this store. Directory.CreateDirectory(_storePath); uint userId = Interop.Sys.GetEUid(); EnsureDirectoryPermissions(_storePath, userId); OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal; using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles())) { string thumbprint = copy.Thumbprint; bool findOpenSlot; // The odds are low that we'd have a thumbprint collision, but check anyways. string existingFilename = FindExistingFilename(copy, _storePath, out findOpenSlot); if (existingFilename != null) { if (!copy.HasPrivateKey) { return; } try { using (X509Certificate2 fromFile = new X509Certificate2(existingFilename)) { if (fromFile.HasPrivateKey) { // We have a private key, the file has a private key, we're done here. return; } } } catch (CryptographicException) { // We can't read this file anymore, but a moment ago it was this certificate, // so go ahead and overwrite it. } } string destinationFilename; FileMode mode = FileMode.CreateNew; if (existingFilename != null) { destinationFilename = existingFilename; mode = FileMode.Create; } else if (findOpenSlot) { destinationFilename = FindOpenSlot(thumbprint); } else { destinationFilename = Path.Combine(_storePath, thumbprint + PfxExtension); } using (FileStream stream = new FileStream(destinationFilename, mode)) { EnsureFilePermissions(stream, userId); byte[] pkcs12 = copy.Export(X509ContentType.Pkcs12); stream.Write(pkcs12, 0, pkcs12.Length); } } } public void Remove(ICertificatePal certPal) { OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal; using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles())) { bool hadCandidates; string currentFilename = FindExistingFilename(copy, _storePath, out hadCandidates); if (currentFilename != null) { if (_readOnly) { // Windows compatibility, the readonly check isn't done until after a match is found. throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly); } File.Delete(currentFilename); } } } private static string FindExistingFilename(X509Certificate2 cert, string storePath, out bool hadCandidates) { hadCandidates = false; foreach (string maybeMatch in Directory.EnumerateFiles(storePath, cert.Thumbprint + PfxWildcard)) { hadCandidates = true; try { using (X509Certificate2 candidate = new X509Certificate2(maybeMatch)) { if (candidate.Equals(cert)) { return maybeMatch; } } } catch (CryptographicException) { // Contents weren't interpretable as a certificate, so it's not a match. } } return null; } private string FindOpenSlot(string thumbprint) { // We already know that {thumbprint}.pfx is taken, so start with {thumbprint}.1.pfx // We need space for {thumbprint} (thumbprint.Length) // And ".0.pfx" (6) // If MaxSaveAttempts is big enough to use more than one digit, we need that space, too (MaxSaveAttempts / 10) StringBuilder pathBuilder = new StringBuilder(thumbprint.Length + PfxOrdinalWildcard.Length + (MaxSaveAttempts / 10)); pathBuilder.Append(thumbprint); pathBuilder.Append('.'); int prefixLength = pathBuilder.Length; for (int i = 1; i <= MaxSaveAttempts; i++) { pathBuilder.Length = prefixLength; pathBuilder.Append(i); pathBuilder.Append(PfxExtension); string builtPath = Path.Combine(_storePath, pathBuilder.ToString()); if (!File.Exists(builtPath)) { return builtPath; } } throw new CryptographicException(SR.Cryptography_X509_StoreNoFileAvailable); } private static string GetDirectoryName(string storeName) { Debug.Assert(storeName != null); try { string fileName = Path.GetFileName(storeName); if (!StringComparer.Ordinal.Equals(storeName, fileName)) { throw new CryptographicException(SR.Format(SR.Security_InvalidValue, "storeName")); } } catch (IOException e) { throw new CryptographicException(e.Message, e); } return storeName.ToLowerInvariant(); } /// <summary> /// Checks the store directory has the correct permissions. /// </summary> /// <param name="path"> /// The path of the directory to check. /// </param> /// <param name="userId"> /// The current userId from GetEUid(). /// </param> private static void EnsureDirectoryPermissions(string path, uint userId) { Interop.Sys.FileStatus dirStat; if (Interop.Sys.Stat(path, out dirStat) != 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw new CryptographicException( SR.Cryptography_FileStatusError, new IOException(error.GetErrorMessage(), error.RawErrno)); } if (dirStat.Uid != userId) { throw new CryptographicException(SR.Format(SR.Cryptography_OwnerNotCurrentUser, path)); } if ((dirStat.Mode & (int)Interop.Sys.Permissions.S_IRWXU) != (int)Interop.Sys.Permissions.S_IRWXU) { throw new CryptographicException(SR.Format(SR.Cryptography_InvalidDirectoryPermissions, path)); } } /// <summary> /// Checks the file has the correct permissions and attempts to modify them if they're inappropriate. /// </summary> /// <param name="stream"> /// The file stream to check. /// </param> /// <param name="userId"> /// The current userId from GetEUid(). /// </param> private static void EnsureFilePermissions(FileStream stream, uint userId) { // Verify that we're creating files with u+rw and g-rw, o-rw. const Interop.Sys.Permissions requiredPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR; const Interop.Sys.Permissions forbiddenPermissions = Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; Interop.Sys.FileStatus stat; if (Interop.Sys.FStat(stream.SafeFileHandle, out stat) != 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw new CryptographicException( SR.Cryptography_FileStatusError, new IOException(error.GetErrorMessage(), error.RawErrno)); } if (stat.Uid != userId) { throw new CryptographicException(SR.Format(SR.Cryptography_OwnerNotCurrentUser, stream.Name)); } if ((stat.Mode & (int)requiredPermissions) != (int)requiredPermissions || (stat.Mode & (int)forbiddenPermissions) != 0) { if (Interop.Sys.FChMod(stream.SafeFileHandle, (int)requiredPermissions) < 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw new CryptographicException( SR.Format(SR.Cryptography_InvalidFilePermissions, stream.Name), new IOException(error.GetErrorMessage(), error.RawErrno)); } Debug.Assert(Interop.Sys.FStat(stream.SafeFileHandle, out stat) == 0); Debug.Assert((stat.Mode & (int)requiredPermissions) == (int)requiredPermissions); Debug.Assert((stat.Mode & (int)forbiddenPermissions) == 0); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; using Azure.Storage.Blobs.Models; using System.Threading; namespace Azure.Storage.Blobs.ChangeFeed { internal class ChangeFeed { /// <summary> /// BlobContainerClient for making List Blob requests and creating Segments. /// </summary> private readonly BlobContainerClient _containerClient; /// <summary> /// A <see cref="SegmentFactory"/> for creating new <see cref="Segment"/>s. /// </summary> private readonly SegmentFactory _segmentFactory; /// <summary> /// Queue of paths to years we haven't processed yet. /// </summary> private readonly Queue<string> _years; /// <summary> /// Paths to segments in the current year we haven't processed yet. /// </summary> private Queue<string> _segments; /// <summary> /// The Segment we are currently processing. /// </summary> private Segment _currentSegment; /// <summary> /// The latest time the Change Feed can safely be read from. /// </summary> public DateTimeOffset LastConsumable { get; private set; } /// <summary> /// User-specified start time. If the start time occurs before Change Feed was enabled /// for this account, we will start at the beginning of the Change Feed. /// </summary> private DateTimeOffset? _startTime; /// <summary> /// User-specified end time. If the end time occurs after _lastConsumable, we will /// end at _lastConsumable. /// </summary> private DateTimeOffset? _endTime; /// <summary> /// If this Change Feed has no events. /// </summary> private bool _empty; public ChangeFeed( BlobContainerClient containerClient, SegmentFactory segmentFactory, Queue<string> years, Queue<string> segments, Segment currentSegment, DateTimeOffset lastConsumable, DateTimeOffset? startTime, DateTimeOffset? endTime) { _containerClient = containerClient; _segmentFactory = segmentFactory; _years = years; _segments = segments; _currentSegment = currentSegment; LastConsumable = lastConsumable; _startTime = startTime; _endTime = endTime; _empty = false; } /// <summary> /// Constructor for mocking, and for creating a Change Feed with no Events. /// </summary> public ChangeFeed() { } // The last segment may still be adding chunks. public async Task<Page<BlobChangeFeedEvent>> GetPage( bool async, int pageSize = Constants.ChangeFeed.DefaultPageSize, CancellationToken cancellationToken = default) { if (!HasNext()) { throw new InvalidOperationException("Change feed doesn't have any more events"); } if (_currentSegment.DateTime >= _endTime) { return BlobChangeFeedEventPage.Empty(); } if (pageSize > Constants.ChangeFeed.DefaultPageSize) { pageSize = Constants.ChangeFeed.DefaultPageSize; } // Get next page List<BlobChangeFeedEvent> blobChangeFeedEvents = new List<BlobChangeFeedEvent>(); int remainingEvents = pageSize; while (blobChangeFeedEvents.Count < pageSize && HasNext()) { List<BlobChangeFeedEvent> newEvents = await _currentSegment.GetPage( async, remainingEvents, cancellationToken).ConfigureAwait(false); blobChangeFeedEvents.AddRange(newEvents); remainingEvents -= newEvents.Count; await AdvanceSegmentIfNecessary( async, cancellationToken).ConfigureAwait(false); } return new BlobChangeFeedEventPage(blobChangeFeedEvents, JsonSerializer.Serialize<ChangeFeedCursor>(GetCursor())); } public bool HasNext() { // [If Change Feed is empty], or [current segment is not finalized] // or ([segment count is 0] and [year count is 0] and [current segment doesn't have next]) if (_empty || _segments.Count == 0 && _years.Count == 0 && !_currentSegment.HasNext()) { return false; } if (_endTime.HasValue) { return _currentSegment.DateTime < _endTime; } return true; } internal ChangeFeedCursor GetCursor() => new ChangeFeedCursor( urlHost: _containerClient.Uri.Host, endDateTime: _endTime, currentSegmentCursor: _currentSegment.GetCursor()); private async Task AdvanceSegmentIfNecessary( bool async, CancellationToken cancellationToken) { // If the current segment has more Events, we don't need to do anything. if (_currentSegment.HasNext()) { return; } // If the current segment is completed, remove it if (_segments.Count > 0) { _currentSegment = await _segmentFactory.BuildSegment( async, _segments.Dequeue()).ConfigureAwait(false); } // If _segments is empty, refill it else if (_segments.Count == 0 && _years.Count > 0) { string yearPath = _years.Dequeue(); // Get Segments for first year _segments = await BlobChangeFeedExtensions.GetSegmentsInYearInternal( containerClient: _containerClient, yearPath: yearPath, startTime: _startTime, endTime: _endTime, async: async, cancellationToken: cancellationToken) .ConfigureAwait(false); if (_segments.Count > 0) { _currentSegment = await _segmentFactory.BuildSegment( async, _segments.Dequeue()) .ConfigureAwait(false); } } } public static ChangeFeed Empty() => new ChangeFeed { _empty = true }; } }
// ******************************************************************************************************** // Product Name: DotSpatial.Controls.dll // Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/25/2008 2:46:23 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using DotSpatial.Data; using DotSpatial.Symbology; using GeoAPI.Geometries; namespace DotSpatial.Controls { /// <summary> /// This is a specialized FeatureLayer that specifically handles raster drawing. /// </summary> public class MapRasterLayer : RasterLayer, IMapRasterLayer { #region Events /// <summary> /// Fires an event that indicates to the parent map-frame that it should first /// redraw the specified clip /// </summary> public event EventHandler<ClipArgs> BufferChanged; #endregion #region Private Variables private Image _backBuffer; // draw to the back buffer, and swap to the stencil when done. private Envelope _bufferExtent; // the geographic extent of the current buffer. private Rectangle _bufferRectangle; private bool _isInitialized; private Image _stencil; // draw features to the stencil #endregion #region Constructors /// <summary> /// Creates a new raster layer from the specified fileName /// </summary> /// <param name="fileName"></param> /// <param name="symbolizer"></param> public MapRasterLayer(string fileName, IRasterSymbolizer symbolizer) : base(fileName, symbolizer) { base.LegendText = Path.GetFileNameWithoutExtension(fileName); if ((long)DataSet.NumRows * DataSet.NumColumns > MaxCellsInMemory) { string pyrFile = Path.ChangeExtension(fileName, ".mwi"); BitmapGetter = File.Exists(pyrFile) && File.Exists(Path.ChangeExtension(pyrFile, ".mwh")) ? new PyramidImage(pyrFile) : CreatePyramidImage(pyrFile, DataManager.DefaultDataManager.ProgressHandler); } else { Bitmap bmp = new Bitmap(DataSet.NumColumns, DataSet.NumRows); symbolizer.Raster = DataSet; DataSet.DrawToBitmap(symbolizer, bmp); var id = new InRamImage(bmp) { Bounds = DataSet.Bounds }; BitmapGetter = id; } } /// <summary> /// Creates a new instance of a MapRasterLayer and the specified image data to use for rendering it. /// </summary> public MapRasterLayer(IRaster baseRaster, ImageData baseImage) : base(baseRaster) { base.LegendText = Path.GetFileNameWithoutExtension(baseRaster.Filename); BitmapGetter = baseImage; } /// <summary> /// Creates a new instance of a Raster layer, and will create a "FallLeaves" image based on the /// raster values. /// </summary> /// <param name="raster">The raster to use</param> public MapRasterLayer(IRaster raster) : base(raster) { base.LegendText = Path.GetFileNameWithoutExtension(raster.Filename); // string imageFile = Path.ChangeExtension(raster.Filename, ".png"); // if (File.Exists(imageFile)) File.Delete(imageFile); if ((long)raster.NumRows * raster.NumColumns > MaxCellsInMemory) { // For huge images, assume that GDAL or something was needed anyway, // and we would rather avoid having to re-create the pyramids if there is any chance // that the old values will work ok. string pyrFile = Path.ChangeExtension(raster.Filename, ".mwi"); if (File.Exists(pyrFile) && File.Exists(Path.ChangeExtension(pyrFile, ".mwh"))) { BitmapGetter = new PyramidImage(pyrFile); base.LegendText = Path.GetFileNameWithoutExtension(raster.Filename); } else { BitmapGetter = CreatePyramidImage(pyrFile, DataManager.DefaultDataManager.ProgressHandler); } } else { // Ensure smaller images match the scheme. Bitmap bmp = new Bitmap(raster.NumColumns, raster.NumRows); raster.PaintColorSchemeToBitmap(Symbolizer, bmp, raster.ProgressHandler); var id = new InRamImage(bmp) { Bounds = { AffineCoefficients = raster.Bounds.AffineCoefficients } }; BitmapGetter = id; } } #endregion #region Methods /// <summary> /// Call StartDrawing before using this. /// </summary> /// <param name="rectangles">The rectangular region in pixels to clear.</param> /// <param name= "color">The color to use when clearing. Specifying transparent /// will replace content with transparent pixels.</param> public void Clear(List<Rectangle> rectangles, Color color) { if (_backBuffer == null) return; Graphics g = Graphics.FromImage(_backBuffer); foreach (Rectangle r in rectangles) { if (r.IsEmpty == false) { g.Clip = new Region(r); g.Clear(color); } } g.Dispose(); } /// <summary> /// This will draw any features that intersect this region. To specify the features /// directly, use OnDrawFeatures. This will not clear existing buffer content. /// For that call Initialize instead. /// </summary> /// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param> /// <param name="regions">The geographic regions to draw</param> public void DrawRegions(MapArgs args, List<Extent> regions) { List<Rectangle> clipRects = args.ProjToPixel(regions); DrawWindows(args, regions, clipRects); } /// <summary> /// Indicates that the drawing process has been finalized and swaps the back buffer /// to the front buffer. /// </summary> public void FinishDrawing() { OnFinishDrawing(); if (_stencil != null && _stencil != _backBuffer) _stencil.Dispose(); _stencil = _backBuffer; } /// <summary> /// Copies any current content to the back buffer so that drawing should occur on the /// back buffer (instead of the fore-buffer). Calling draw methods without /// calling this may cause exceptions. /// </summary> /// <param name="preserve">Boolean, true if the front buffer content should be copied to the back buffer /// where drawing will be taking place.</param> public void StartDrawing(bool preserve) { Bitmap backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height); if (Buffer != null) { if (Buffer.Width == backBuffer.Width && Buffer.Height == backBuffer.Height) { if (preserve) { Graphics g = Graphics.FromImage(backBuffer); g.DrawImageUnscaled(Buffer, 0, 0); } } } if (BackBuffer != null && BackBuffer != Buffer) BackBuffer.Dispose(); BackBuffer = backBuffer; OnStartDrawing(); } #endregion #region Properties /// <summary> /// Gets or sets the back buffer that will be drawn to as part of the initialization process. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ShallowCopy] public Image BackBuffer { get { return _backBuffer; } set { _backBuffer = value; } } /// <summary> /// Gets the current buffer. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ShallowCopy] public Image Buffer { get { return _stencil; } set { _stencil = value; } } /// <summary> /// Gets or sets the geographic region represented by the buffer /// Calling Initialize will set this automatically. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ShallowCopy] public Envelope BufferEnvelope { get { return _bufferExtent; } set { _bufferExtent = value; } } /// <summary> /// Gets or sets the rectangle in pixels to use as the back buffer. /// Calling Initialize will set this automatically. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ShallowCopy] public Rectangle BufferRectangle { get { return _bufferRectangle; } set { _bufferRectangle = value; } } /// <summary> /// Gets or sets whether the image layer is initialized /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool IsInitialized { get { return _isInitialized; } set { _isInitialized = value; } } #endregion #region Protected Methods /// <summary> /// Fires the OnBufferChanged event /// </summary> /// <param name="clipRectangles">The Rectangle in pixels</param> protected virtual void OnBufferChanged(List<Rectangle> clipRectangles) { if (BufferChanged != null) { ClipArgs e = new ClipArgs(clipRectangles); BufferChanged(this, e); } } /// <summary> /// Indicates that whatever drawing is going to occur has finished and the contents /// are about to be flipped forward to the front buffer. /// </summary> protected virtual void OnFinishDrawing() { } ///// <summary> ///// This ensures that when the symbolic content for the layer is updated that we re-load the image. ///// </summary> //protected override void OnItemChanged() //{ // if (_baseImage == null) return; // string imgFile = _baseImage.Filename; // _baseImage.Open(imgFile); // base.OnItemChanged(); //} /// <summary> /// Occurs when a new drawing is started, but after the BackBuffer has been established. /// </summary> protected virtual void OnStartDrawing() { } protected override void Dispose(bool disposing) { if (disposing) { if (_stencil != _backBuffer && _stencil != null) { _stencil.Dispose(); _stencil = null; } if (_backBuffer != null) { _backBuffer.Dispose(); _backBuffer = null; } _bufferExtent = null; _bufferRectangle = Rectangle.Empty; _isInitialized = false; } base.Dispose(disposing); } #endregion #region Private Methods /// <summary> /// This draws to the back buffer. If the back buffer doesn't exist, this will create one. /// This will not flip the back buffer to the front. /// </summary> /// <param name="args"></param> /// <param name="regions"></param> /// <param name="clipRectangles"></param> private void DrawWindows(MapArgs args, IList<Extent> regions, IList<Rectangle> clipRectangles) { Graphics g; if (args.Device != null) { g = args.Device; // A device on the MapArgs is optional, but overrides the normal buffering behaviors. } else { if (_backBuffer == null) _backBuffer = new Bitmap(_bufferRectangle.Width, _bufferRectangle.Height); g = Graphics.FromImage(_backBuffer); } int numBounds = Math.Min(regions.Count, clipRectangles.Count); for (int i = 0; i < numBounds; i++) { using (Bitmap bmp = BitmapGetter.GetBitmap(regions[i], clipRectangles[i])) { if (bmp != null) g.DrawImage(bmp, clipRectangles[i]); } } if (args.Device == null) g.Dispose(); } #endregion } }
using System; using System.Collections.Generic; using System.Text; #if FRB_XNA || WINDOWS_PHONE || SILVERLIGHT || MONODROID using Microsoft.Xna.Framework; //using System.Windows.Forms; using Keys = Microsoft.Xna.Framework.Input.Keys; #elif FRB_MDX using Microsoft.DirectX; using Keys = Microsoft.DirectX.DirectInput.Key; #endif namespace FlatRedBall.Gui { public class Vector3Display : Window, IInputReceiver { #region Fields TextDisplay mXDisplay; TextDisplay mYDisplay; TextDisplay mZDisplay; TextDisplay mWDisplay; UpDown mXUpDown; UpDown mYUpDown; UpDown mZUpDown; UpDown mWUpDown; int mNumberOfComponents = 3; List<Keys> mIgnoredKeys = new List<Keys>(); #endregion #region Properties public Vector2 BeforeChangeVector2Value { get { return new Vector2(mXUpDown.BeforeChangeValue, mYUpDown.BeforeChangeValue); } } public Vector3 BeforeChangeVector3Value { get { return new Vector3(mXUpDown.BeforeChangeValue, mYUpDown.BeforeChangeValue, mZUpDown.BeforeChangeValue); } } public List<Keys> IgnoredKeys { get { return mIgnoredKeys; } } public bool IsUserEditingWindow { get { return mCursor.WindowPushed == mXUpDown.UpDownButton || mCursor.WindowPushed == mYUpDown.UpDownButton || mCursor.WindowPushed == mZUpDown.UpDownButton || mCursor.WindowPushed == mWUpDown.UpDownButton; } } private UpDown LastVisibleUpDown { get { if (mWUpDown.Visible) { return mWUpDown; } else if (mZUpDown.Visible) { return mZUpDown; } else if (mYUpDown.Visible) { return mYUpDown; } else if (mXUpDown.Visible) { return mXUpDown; } else { return null; } } } public int NumberOfComponents { get { return mNumberOfComponents; } set { mNumberOfComponents = value; #region Set the visibility of the components mXDisplay.Visible = mNumberOfComponents > 0; mXUpDown.Visible = mXDisplay.Visible; mYDisplay.Visible = mNumberOfComponents > 1; mYUpDown.Visible = mYDisplay.Visible; mZDisplay.Visible = mNumberOfComponents > 2; mZUpDown.Visible = mZDisplay.Visible; mWDisplay.Visible = mNumberOfComponents > 3; mWUpDown.Visible = mWDisplay.Visible; #endregion ScaleY = .5f + mNumberOfComponents; float border = .5f; mXUpDown.Y = border + 1; mYUpDown.Y = border + 3; mZUpDown.Y = border + 5; mWUpDown.Y = border + 7; mXDisplay.Y = mXUpDown.Y; mYDisplay.Y = mYUpDown.Y; mZDisplay.Y = mZUpDown.Y; mWDisplay.Y = mWUpDown.Y; if (mWUpDown.Visible) { mZUpDown.NextInTabSequence = mWUpDown; } if (mZUpDown.Visible) { mYUpDown.NextInTabSequence = mZUpDown; } if (mYUpDown.Visible) { mXUpDown.NextInTabSequence = mYUpDown; } } } public float Sensitivity { get { return mXUpDown.Sensitivity; } set { if (mXUpDown != null) mXUpDown.Sensitivity = value; if (mYUpDown != null) mYUpDown.Sensitivity = value; if (mZUpDown != null) mZUpDown.Sensitivity = value; if (mWUpDown != null) mWUpDown.Sensitivity = value; } } public Vector2 Vector2Value { get { return new Vector2(mXUpDown.CurrentValue, mYUpDown.CurrentValue); } set { mXUpDown.CurrentValue = value.X; mYUpDown.CurrentValue = value.Y; if (!mCursor.IsOn(mXUpDown as IWindow)) { mXUpDown.ForceUpdateBeforeChangedValue(); } if (!mCursor.IsOn(mYUpDown as IWindow)) { mYUpDown.ForceUpdateBeforeChangedValue(); } if (!mCursor.IsOn(mZUpDown as IWindow)) { mZUpDown.ForceUpdateBeforeChangedValue(); } if (!mCursor.IsOn(mWUpDown as IWindow)) { mWUpDown.ForceUpdateBeforeChangedValue(); } } } public Vector3 Vector3Value { get { return new Vector3(mXUpDown.CurrentValue, mYUpDown.CurrentValue, mZUpDown.CurrentValue); } set { mXUpDown.CurrentValue = value.X; mYUpDown.CurrentValue = value.Y; mZUpDown.CurrentValue = value.Z; if (!mCursor.IsOn(mXUpDown as IWindow)) { mXUpDown.ForceUpdateBeforeChangedValue(); } if (!mCursor.IsOn(mYUpDown as IWindow)) { mYUpDown.ForceUpdateBeforeChangedValue(); } if (!mCursor.IsOn(mZUpDown as IWindow)) { mZUpDown.ForceUpdateBeforeChangedValue(); } if (!mCursor.IsOn(mWUpDown as IWindow)) { mWUpDown.ForceUpdateBeforeChangedValue(); } } } #endregion #region Events public GuiMessage ValueChanged; public GuiMessage AfterValueChanged; #endregion #region Event and Delegate Methods // July 10, 2011 // These two methods // were previously not // implemented - the FocusUpdate // and GainFocus events were not being // used. I implemented them. Hopefully // this doesn't cause issues if the engine // raises these events...but I think it should // be okay. void OnFocusUpdateInternal(IInputReceiver inputReceiver) { if (this.FocusUpdate != null) { this.FocusUpdate(this); } } void OnGainFocusInternal(Window callingWindow) { if (this.GainFocus != null) { this.GainFocus(this); } } private void OnValueChanged(Window callingWindow) { if (ValueChanged != null) { ValueChanged(this); } } private void OnAfterValueChanged(Window callingWindow) { if(AfterValueChanged != null) { AfterValueChanged(this); } // The UpDown's BeforeChangeValue is only // set when the user pushes on the UpDown. // That means that if the user changes the X, // then Y, then Z, the BeforeChange value on all // three will remain the exact same. This forces // the BeforeChangeValue to be accurate so it can be // used in the BeforeChangeVector3Value property. //mXUpDown.ForceUpdateBeforeChangedValue(); //mYUpDown.ForceUpdateBeforeChangedValue(); //mZUpDown.ForceUpdateBeforeChangedValue(); //mWUpDown.ForceUpdateBeforeChangedValue(); } private void ComponentLosingFocus(Window callingWindow) { base.OnLosingFocus(); } #endregion #region Methods public Vector3Display(Cursor cursor) : base(cursor) { float border = .5f; this.ScaleX = 6f; this.ScaleY = 3.5f; #region Create the UpDowns and set their static properties mXUpDown = new UpDown(mCursor); AddWindow(mXUpDown); mYUpDown = new UpDown(mCursor); AddWindow(mYUpDown); mZUpDown = new UpDown(mCursor); AddWindow(mZUpDown); mWUpDown = new UpDown(mCursor); AddWindow(mWUpDown); mXUpDown.Y = border + 1; mYUpDown.Y = border + 3; mZUpDown.Y = border + 5; mWUpDown.Y = border + 7; mXUpDown.ValueChanged += OnValueChanged; mYUpDown.ValueChanged += OnValueChanged; mZUpDown.ValueChanged += OnValueChanged; mWUpDown.ValueChanged += OnValueChanged; mXUpDown.LosingFocus += ComponentLosingFocus; mYUpDown.LosingFocus += ComponentLosingFocus; mZUpDown.LosingFocus += ComponentLosingFocus; mWUpDown.LosingFocus += ComponentLosingFocus; mXUpDown.AfterValueChanged += OnAfterValueChanged; mYUpDown.AfterValueChanged += OnAfterValueChanged; mZUpDown.AfterValueChanged += OnAfterValueChanged; mWUpDown.AfterValueChanged += OnAfterValueChanged; mXUpDown.FocusUpdate += OnFocusUpdateInternal; mYUpDown.FocusUpdate += OnFocusUpdateInternal; mZUpDown.FocusUpdate += OnFocusUpdateInternal; mWUpDown.FocusUpdate += OnFocusUpdateInternal; mXUpDown.GainFocus += OnGainFocusInternal; mYUpDown.GainFocus += OnGainFocusInternal; mZUpDown.GainFocus += OnGainFocusInternal; mWUpDown.GainFocus += OnGainFocusInternal; #endregion #region Create the TextDisplays and set their static properties mXDisplay = new TextDisplay(mCursor); AddWindow(mXDisplay); mYDisplay = new TextDisplay(mCursor); AddWindow(mYDisplay); mZDisplay = new TextDisplay(mCursor); AddWindow(mZDisplay); mWDisplay = new TextDisplay(mCursor); AddWindow(mWDisplay); mXDisplay.Text = "X:"; mYDisplay.Text = "Y:"; mZDisplay.Text = "Z:"; mWDisplay.Text = "W:"; mXDisplay.X = 0f; mYDisplay.X = 0f; mZDisplay.X = 0f; mWDisplay.X = 0f; mXDisplay.Y = mXUpDown.Y; mYDisplay.Y = mYUpDown.Y; mZDisplay.Y = mZUpDown.Y; mWDisplay.Y = mWUpDown.Y; #endregion float spaceForDisplay = 1; #region Set the UpDown ScaleX values mXUpDown.ScaleX = this.ScaleX - border - spaceForDisplay; mYUpDown.ScaleX = this.ScaleX - border - spaceForDisplay; mZUpDown.ScaleX = this.ScaleX - border - spaceForDisplay; mWUpDown.ScaleX = this.ScaleX - border - spaceForDisplay; #endregion mXUpDown.X = border + spaceForDisplay * 2 + mXUpDown.ScaleX; mYUpDown.X = border + spaceForDisplay * 2 + mXUpDown.ScaleX; mZUpDown.X = border + spaceForDisplay * 2 + mXUpDown.ScaleX; mWUpDown.X = border + spaceForDisplay * 2 + mXUpDown.ScaleX; NumberOfComponents = 3; } #endregion #region IInputReceiver Members public bool TakingInput { get { return mXUpDown.TakingInput; } } public IInputReceiver NextInTabSequence { get { UpDown lastUpDown = LastVisibleUpDown; if (lastUpDown != null) { return lastUpDown.NextInTabSequence; } else { return null; } } set { UpDown lastUpDown = LastVisibleUpDown; if (lastUpDown != null) { lastUpDown.NextInTabSequence = value; } } } public event GuiMessage GainFocus; public event FocusUpdateDelegate FocusUpdate; public void OnFocusUpdate() { throw new InvalidOperationException("Vector3 should never have its OnFocusUpdate called"); } public void OnGainFocus() { FlatRedBall.Input.InputManager.ReceivingInput = mXUpDown; } public void LoseFocus() { // do nothing } public void ReceiveInput() { throw new InvalidOperationException("Vector3 should never have its ReceiveInput called"); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Composition.Convention; using System.Composition.Hosting.Core; using System.Diagnostics; using System.Reflection; using Xunit; namespace System.Composition.Hosting.Tests { public class ContainerConfigurationTests { [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WithProvider_ValidProvider_RegistersProvider() { var configuration = new ContainerConfiguration(); var provider = new ExportProvider { Result = 10 }; Assert.Same(configuration, configuration.WithProvider(provider)); CompositionHost container = configuration.CreateContainer(); Assert.Equal(0, provider.CalledGetExportDescriptors); Assert.Equal(0, provider.CalledGetExportDescriptors); Assert.Equal(10, container.GetExport<int>()); Assert.Equal(1, provider.CalledGetExportDescriptors); Assert.Equal(1, provider.CalledGetExportDescriptors); } public class ExportProvider : ExportDescriptorProvider { public object Result { get; set; } public int CalledGetExportDescriptors { get; set; } public int CalledCompositeActivator { get; set; } public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor) { CalledGetExportDescriptors++; return new[] { new ExportDescriptorPromise(contract, "origin", false, () => new CompositionDependency[0], dependencies => ExportDescriptor.Create(CompositeActivator, new Dictionary<string, object>())) }; } public object CompositeActivator(LifetimeContext context, CompositionOperation operation) { CalledCompositeActivator++; return Result; } } [Fact] public void WithProvider_NullProvider_ThrowsArgumentNullException() { var configuration = new ContainerConfiguration(); AssertExtensions.Throws<ArgumentNullException>("exportDescriptorProvider", () => configuration.WithProvider(null)); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WithDefaultConventions_PartWithNoMatchingConvention_Success() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); configuration.WithPart(typeof(ExportedProperty)); Assert.Same(configuration, configuration.WithDefaultConventions(conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport<string>()); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WithDefaultConventions_IEnumerablePartsWithNoMatchingConvention_Success() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); configuration.WithParts((IEnumerable<Type>)new Type[] { typeof(ExportedProperty) }); Assert.Same(configuration, configuration.WithDefaultConventions(conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport<string>()); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WithDefaultConventions_PartsArrayWithNoMatchingConvention_Success() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); configuration.WithParts(new Type[] { typeof(ExportedProperty) }); Assert.Same(configuration, configuration.WithDefaultConventions(conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport<string>()); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WithDefaultConventions_PartTNoMatchingConvention_Success() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); configuration.WithPart<ExportedProperty>(); Assert.Same(configuration, configuration.WithDefaultConventions(conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport<string>()); } public class ExportedProperty { [Export] public string Property => "A"; } [Fact] public void WithDefaultConventions_NullConventions_ThrowsArgumentNullException() { var configuration = new ContainerConfiguration(); AssertExtensions.Throws<ArgumentNullException>("conventions", () => configuration.WithDefaultConventions(null)); } [Fact] public void WithDefaultConventions_AlreadyHasDefaultConventions_ThrowsInvalidOperationException() { var configuration = new ContainerConfiguration(); configuration.WithDefaultConventions(new ConventionBuilder()); Assert.Throws<InvalidOperationException>(() => configuration.WithDefaultConventions(new ConventionBuilder())); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WithPartT_Convention_Success() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); Assert.Same(configuration, configuration.WithPart<ExportedProperty>(conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport<string>()); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WithPart_Convention_Success() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); Assert.Same(configuration, configuration.WithPart(typeof(ExportedProperty), conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport<string>()); } [Fact] public void WithPart_NullPartType_ThrowsArgumentNullException() { var configuration = new ContainerConfiguration(); AssertExtensions.Throws<ArgumentNullException>("partType", () => configuration.WithPart(null)); AssertExtensions.Throws<ArgumentNullException>("partType", () => configuration.WithPart(null, new ConventionBuilder())); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WithParts_Convention_Success() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); Assert.Same(configuration, configuration.WithParts(new Type[] { typeof(ExportedProperty) }, conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport<string>()); } [Fact] public void WithParts_NullPartTypes_ThrowsArgumentNullException() { var configuration = new ContainerConfiguration(); AssertExtensions.Throws<ArgumentNullException>("partTypes", () => configuration.WithParts(null)); AssertExtensions.Throws<ArgumentNullException>("partTypes", () => configuration.WithParts((IEnumerable<Type>)null)); AssertExtensions.Throws<ArgumentNullException>("partTypes", () => configuration.WithParts(null, new ConventionBuilder())); } [Fact] public void WithParts_NullItemInPartTypes_ThrowsArgumentNullExceptionOnCreation() { ContainerConfiguration configuration = new ContainerConfiguration().WithParts(new Type[] { null }); AssertExtensions.Throws<ArgumentNullException>("type", () => configuration.CreateContainer()); } [Fact] public void WithAssembly_Assembly_ThrowsCompositionFailedExceptionOnCreation() { var configuration = new ContainerConfiguration(); Assert.Same(configuration, configuration.WithAssembly(typeof(ExportedProperty).Assembly)); Assert.Throws<CompositionFailedException>(() => configuration.CreateContainer()); } [Fact] public void WithAssembly_AssemblyConventions_ThrowsCompositionFailedExceptionOnCreation() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); Assert.Same(configuration, configuration.WithAssembly(typeof(ExportedProperty).Assembly, conventions)); Assert.Throws<CompositionFailedException>(() => configuration.CreateContainer()); } [Fact] public void WithAssemblies_Assemblies_ThrowsCompositionFailedExceptionOnCreation() { var configuration = new ContainerConfiguration(); Assert.Same(configuration, configuration.WithAssemblies(new Assembly[] { typeof(ExportedProperty).Assembly })); Assert.Throws<CompositionFailedException>(() => configuration.CreateContainer()); } [Fact] public void WithAssemblies_AssembliesAndConvention_ThrowsCompositionFailedExceptionOnCreation() { var conventions = new ConventionBuilder(); conventions.ForType<ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); Assert.Same(configuration, configuration.WithAssemblies(new Assembly[] { typeof(ExportedProperty).Assembly }, conventions)); Assert.Throws<CompositionFailedException>(() => configuration.CreateContainer()); } [Fact] public void WithAssemblies_NullAssemblies_ThrowsArgumentNullException() { var configuration = new ContainerConfiguration(); AssertExtensions.Throws<ArgumentNullException>("assemblies", () => configuration.WithAssemblies(null)); AssertExtensions.Throws<ArgumentNullException>("assemblies", () => configuration.WithAssemblies(null, new ConventionBuilder())); } [Fact] public void WithAssemby_Null_ThrowsNullReferenceExceptionOnCreation() { ContainerConfiguration configuration = new ContainerConfiguration().WithAssembly(null); Assert.Throws<NullReferenceException>(() => configuration.CreateContainer()); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_ExportedSubClass_Success() { CompositionHost container = new ContainerConfiguration() .WithPart(typeof(Derived)) .CreateContainer(); Assert.Equal("Derived", container.GetExport<Derived>().Prop); } [Export] public class Derived : Base { public new string Prop { get; set; } = "Derived"; } public class Base { public object Prop { get; set; } = "Derived"; } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_OpenGenericTypes_Success() { var conventions = new ConventionBuilder(); conventions.ForTypesDerivedFrom<IContainer>() .Export<IContainer>(); conventions.ForTypesDerivedFrom(typeof(IRepository<>)) .Export(t => t.AsContractType(typeof(IRepository<>))); CompositionHost container = new ContainerConfiguration() .WithParts(new Type[] { typeof(EFRepository<>), typeof(Container) }, conventions) .CreateContainer(); Assert.Equal(0, container.GetExport<IRepository<int>>().Fetch()); } public interface IContainer { } public class Container : IContainer { } public interface IRepository<T> { T Fetch(); } public class EFRepository<T> : IRepository<T> { public EFRepository(IContainer test) { } public T Fetch() => default(T); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_ImportConventionsWithInheritedProperties_Success() { var conventions = new ConventionBuilder(); conventions.ForType<Imported>().Export(); conventions.ForType<DerivedFromBaseWithImport>() .ImportProperty(b => b.Imported) .Export(); CompositionHost container = new ContainerConfiguration() .WithDefaultConventions(conventions) .WithParts(typeof(Imported), typeof(DerivedFromBaseWithImport)) .CreateContainer(); DerivedFromBaseWithImport export = container.GetExport<DerivedFromBaseWithImport>(); Assert.IsAssignableFrom<Imported>(export.Imported); } public class Imported { } public class BaseWithImport { public virtual Imported Imported { get; set; } } public class DerivedFromBaseWithImport : BaseWithImport { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_ExportConventionsWithInheritedProperties_Success() { var conventions = new ConventionBuilder(); conventions.ForType<DerivedFromBaseWithExport>() .ExportProperty(b => b.Exported); CompositionHost container = new ContainerConfiguration() .WithDefaultConventions(conventions) .WithParts(typeof(DerivedFromBaseWithExport)) .CreateContainer(); Assert.Equal("A", container.GetExport<string>()); } public class BaseWithExport { public string Exported { get { return "A"; } } } public class DerivedFromBaseWithExport : BaseWithExport { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_ExportsToInheritedProperties_DontInterfereWithBase() { var conventions = new ConventionBuilder(); conventions.ForType<DerivedFromBaseWithExport2>() .ExportProperty(b => b.Exported); CompositionHost container = new ContainerConfiguration() .WithDefaultConventions(conventions) .WithParts(typeof(BaseWithExport2)) .WithParts(typeof(DerivedFromBaseWithExport2)) .CreateContainer(); Assert.Equal(new string[] { "A", "A" }, container.GetExports<string>()); } public class BaseWithExport2 { [Export] public virtual string Exported => "A"; } public class DerivedFromBaseWithExport2 : BaseWithExport { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_HasConventions_ClassExportsAreNotInherited() { CompositionHost container = new ContainerConfiguration() .WithPart<DerivedFromBaseWithDeclaredExports>(new ConventionBuilder()) .CreateContainer(); Assert.False(container.TryGetExport(out BaseWithDeclaredExports export)); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_HasConventions_PropertyExportsAreNotInherited() { CompositionHost container = new ContainerConfiguration() .WithPart<DerivedFromBaseWithDeclaredExports>(new ConventionBuilder()) .CreateContainer(); Assert.False(container.TryGetExport(out string export)); } [Export] public class BaseWithDeclaredExports { public BaseWithDeclaredExports() => Property = "foo"; [Export] public string Property { get; set; } } public class DerivedFromBaseWithDeclaredExports : BaseWithDeclaredExports { } public class CustomExport : ExportAttribute { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_HasConventions_CustomAttributesAreNotInherited() { CompositionHost container = new ContainerConfiguration() .WithPart<DerivedFromBaseWithCustomExport>(new ConventionBuilder()) .CreateContainer(); Assert.False(container.TryGetExport(out BaseWithCustomExport bce)); } [CustomExport] public class BaseWithCustomExport { } public class DerivedFromBaseWithCustomExport : BaseWithCustomExport { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_OpenGenericTypePart_Success() { ContainerConfiguration configuration = new ContainerConfiguration().WithParts(typeof(GenericExportedType<>)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("C", container.GetExport<GenericExportedType<int>>().Property); } [Export(typeof(GenericExportedType<>))] public class GenericExportedType<T> { public string Property => "C"; } [Theory] [InlineData(typeof(IncompatibleGenericExportedType<>))] [InlineData(typeof(IncompatibleGenericExportedType<int>))] [InlineData(typeof(IncompatibleGenericExportedTypeDerived<>))] public void CreateContainer_GenericTypeExport_ThrowsCompositionFailedException(Type partType) { ContainerConfiguration configuration = new ContainerConfiguration().WithParts(partType); Assert.Throws<CompositionFailedException>( () => configuration.CreateContainer()); } [Export(typeof(GenericExportedType<>))] public class IncompatibleGenericExportedType<T> { } [Export(typeof(GenericExportedType<>))] public class IncompatibleGenericExportedTypeDerived<T> : GenericExportedType<int> { } [Theory] [InlineData(typeof(NonGenericExportedType<>))] [InlineData(typeof(NonGenericExportedType<int>))] public void CreateContainer_NonGenericTypeExportWithGenericPart_ThrowsCompositionFailedException(Type partType) { ContainerConfiguration configuration = new ContainerConfiguration().WithParts(partType); Assert.Throws<CompositionFailedException>(() => configuration.CreateContainer()); } [Export(typeof(string))] public class NonGenericExportedType<T> { } [Fact] public void CreateContainer_UnassignableType_ThrowsCompositionFailedException() { ContainerConfiguration configuration = new ContainerConfiguration().WithParts(typeof(ContractExportedType)); Assert.Throws<CompositionFailedException>(() => configuration.CreateContainer()); } [Export(typeof(Derived))] public class ContractExportedType { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_AbstractOrStructType_Success() { ContainerConfiguration configuration = new ContainerConfiguration().WithParts(typeof(AbstractClass), typeof(StructType)); CompositionHost container = configuration.CreateContainer(); Assert.Throws<CompositionFailedException>(() => container.GetExport<AbstractClass>()); Assert.Throws<CompositionFailedException>(() => container.GetExport<StructType>()); } public abstract class AbstractClass { } public struct StructType { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_MetadataProperty_Success() { ContainerConfiguration configuration = new ContainerConfiguration().WithPart(typeof(MetadataProperty)); CompositionHost container = configuration.CreateContainer(); Assert.Throws<CompositionFailedException>(() => container.GetExport<MetadataProperty>()); } [MetadataAttribute] public class CustomMetadataExportAttribute : ExportAttribute { public object NullName { get; set; } = null; public string StringName { get; set; } = "value"; public int[] ArrayName { get; set; } = new int[] { 1, 2, 3 }; } public class MetadataProperty { [CustomMetadataExport] [ExportMetadata("NullName", null)] public object NullMetadata { get; set; } [CustomMetadataExport] [ExportMetadata("StringName", "value")] public string StringMetadata { get; set; } [CustomMetadataExport] [ExportMetadata("ArrayName", 4)] public int[] ArrayMetadata { get; set; } [CustomMetadataExport] [ExportMetadata("NewName", 1)] [Required] public int NewMetadata { get; set; } } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CreateContainer_MetadataClass_Success() { ContainerConfiguration configuration = new ContainerConfiguration().WithPart(typeof(MetadataClass)); CompositionHost container = configuration.CreateContainer(); Assert.Throws<CompositionFailedException>(() => container.GetExport<MetadataProperty>()); } [CustomMetadataExport] public class MetadataClass { } [Fact] public void CreateContainer_ExportIncompatibleNonGenericProperty_ThrowsCompositionFailedException() { ContainerConfiguration configuration = new ContainerConfiguration().WithPart(typeof(IncompatibleExportProperty)); Assert.Throws<CompositionFailedException>(() => configuration.CreateContainer()); } public class IncompatibleExportProperty { [Export(typeof(int))] public string Property { get; set; } } [Fact] public void CreateContainer_ExportGenericProperty_Success() { ContainerConfiguration configuration = new ContainerConfiguration().WithPart(typeof(GenericExportProperty<>)); Assert.NotNull(configuration.CreateContainer()); } public class GenericExportProperty<T> { [Export(typeof(List<>))] public List<T> Property { get; set; } = new List<T>(); } [Fact] public void CreateContainer_ExportIncompatibleGenericProperty_ThrowsCompositionFailedException() { ContainerConfiguration configuration = new ContainerConfiguration().WithPart(typeof(IncompatibleGenericExportProperty<>)); Assert.Throws<CompositionFailedException>(() => configuration.CreateContainer()); } public class IncompatibleGenericExportProperty<T> { [Export(typeof(List<string>))] public List<T> Property { get; set; } } public static IEnumerable<object[]> DebuggerAttributes_TestData() { yield return new object[] { new ContainerConfiguration() }; yield return new object[] { new ContainerConfiguration().WithPart(typeof(int)) }; yield return new object[] { new ContainerConfiguration().WithDefaultConventions(new ConventionBuilder()).WithPart(typeof(int)) }; yield return new object[] { new ContainerConfiguration().WithPart(typeof(int), new ConventionBuilder()) }; yield return new object[] { new ContainerConfiguration().WithPart(typeof(ExportedProperty)) }; } [Theory] [MemberData(nameof(DebuggerAttributes_TestData))] public void DebuggerAttributes_GetViaReflection_Success(ContainerConfiguration configuration) { DebuggerAttributeInfo debuggerAttributeInfo = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(configuration); foreach (PropertyInfo property in debuggerAttributeInfo.Properties) { Assert.NotNull(property.GetValue(debuggerAttributeInfo.Instance)); } } } }
// Copyright (C) 2004-2007 MySQL AB // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as published by // the Free Software Foundation // // There are special exceptions to the terms and conditions of the GPL // as it is applied to this software. View the full text of the // exception in file EXCEPTIONS in the directory of this software // distribution. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Data; using System.Data.Common; using MySql.Data.Types; using System.ComponentModel; using System.Globalization; using System.Reflection; namespace MySql.Data.MySqlClient { /// <summary> /// Represents a parameter to a <see cref="MySqlCommand"/>, and optionally, its mapping to <see cref="DataSet"/> columns. This class cannot be inherited. /// </summary> public sealed class MySqlParameter : DbParameter // , IDataParameter, IDbDataParameter { private const int UNSIGNED_MASK = 0x8000; private object paramValue; private ParameterDirection direction = ParameterDirection.Input; private bool isNullable = false; private string paramName; private string sourceColumn; private DataRowVersion sourceVersion = DataRowVersion.Current; private int size; private byte precision; private byte scale; private MySqlDbType mySqlDbType; private DbType dbType; private bool inferType; private bool sourceColumnNullMapping; private MySqlParameterCollection collection; #region Constructors /// <summary> /// Initializes a new instance of the MySqlParameter class. /// </summary> public MySqlParameter() { inferType = true; } /// <summary> /// Initializes a new instance of the <see cref="MySqlParameter"/> class with the parameter name and a value of the new MySqlParameter. /// </summary> /// <param name="parameterName">The name of the parameter to map. </param> /// <param name="value">An <see cref="Object"/> that is the value of the <see cref="MySqlParameter"/>. </param> public MySqlParameter(string parameterName, object value) : this() { ParameterName = parameterName; Value = value; } /// <summary> /// Initializes a new instance of the <see cref="MySqlParameter"/> class with the parameter name and the data type. /// </summary> /// <param name="parameterName">The name of the parameter to map. </param> /// <param name="dbType">One of the <see cref="MySqlDbType"/> values. </param> public MySqlParameter(string parameterName, MySqlDbType dbType) : this(parameterName, null) { MySqlDbType = dbType; } /// <summary> /// Initializes a new instance of the <see cref="MySqlParameter"/> class with the parameter name, the <see cref="MySqlDbType"/>, and the size. /// </summary> /// <param name="parameterName">The name of the parameter to map. </param> /// <param name="dbType">One of the <see cref="MySqlDbType"/> values. </param> /// <param name="size">The length of the parameter. </param> public MySqlParameter(string parameterName, MySqlDbType dbType, int size) : this(parameterName, dbType) { this.size = size; } /// <summary> /// Initializes a new instance of the <see cref="MySqlParameter"/> class with the parameter name, the <see cref="MySqlDbType"/>, the size, and the source column name. /// </summary> /// <param name="parameterName">The name of the parameter to map. </param> /// <param name="dbType">One of the <see cref="MySqlDbType"/> values. </param> /// <param name="size">The length of the parameter. </param> /// <param name="sourceColumn">The name of the source column. </param> public MySqlParameter(string parameterName, MySqlDbType dbType, int size, string sourceColumn) : this(parameterName, dbType) { this.size = size; direction = ParameterDirection.Input; this.sourceColumn = sourceColumn; sourceVersion = DataRowVersion.Current; } internal MySqlParameter(string name, MySqlDbType type, ParameterDirection dir, string col, DataRowVersion ver, object val) : this(name, type) { direction = dir; sourceColumn = col; sourceVersion = ver; Value = val; } /// <summary> /// Initializes a new instance of the <see cref="MySqlParameter"/> class with the parameter name, the type of the parameter, the size of the parameter, a <see cref="ParameterDirection"/>, the precision of the parameter, the scale of the parameter, the source column, a <see cref="DataRowVersion"/> to use, and the value of the parameter. /// </summary> /// <param name="parameterName">The name of the parameter to map. </param> /// <param name="dbType">One of the <see cref="MySqlDbType"/> values. </param> /// <param name="size">The length of the parameter. </param> /// <param name="direction">One of the <see cref="ParameterDirection"/> values. </param> /// <param name="isNullable">true if the value of the field can be null, otherwise false. </param> /// <param name="precision">The total number of digits to the left and right of the decimal point to which <see cref="MySqlParameter.Value"/> is resolved.</param> /// <param name="scale">The total number of decimal places to which <see cref="MySqlParameter.Value"/> is resolved. </param> /// <param name="sourceColumn">The name of the source column. </param> /// <param name="sourceVersion">One of the <see cref="DataRowVersion"/> values. </param> /// <param name="value">An <see cref="Object"/> that is the value of the <see cref="MySqlParameter"/>. </param> /// <exception cref="ArgumentException"/> public MySqlParameter(string parameterName, MySqlDbType dbType, int size, ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value) : this(parameterName, dbType, size, sourceColumn) { this.direction = direction; this.sourceVersion = sourceVersion; Value = value; } #endregion #region Properties internal MySqlParameterCollection Collection { get { return collection; } set { collection = value; } } internal bool TypeHasBeenSet { get { return inferType == false; } } /// <summary> /// Gets or sets the <see cref="DbType"/> of the parameter. /// </summary> public override DbType DbType { get { return dbType; } set { SetDbType(value); inferType = false; } } /// <summary> /// Gets or sets a value indicating whether the parameter is input-only, output-only, bidirectional, or a stored procedure return value parameter. /// As of MySql version 4.1 and earlier, input-only is the only valid choice. /// </summary> public override ParameterDirection Direction { get { return direction; } set { direction = value; } } /// <summary> /// Gets or sets a value indicating whether the parameter accepts null values. /// </summary> public override Boolean IsNullable { get { return isNullable; } set { isNullable = value; } } /// <summary> /// Gets or sets the MySqlDbType of the parameter. /// </summary> public MySqlDbType MySqlDbType { get { return mySqlDbType; } set { SetMySqlDbType(value); inferType = false; } } /// <summary> /// Gets or sets the name of the MySqlParameter. /// </summary> public override String ParameterName { get { return paramName; } set { if (collection != null) collection.ParameterNameChanged(this, paramName, value); paramName = value; } } /// <summary> /// Gets or sets the maximum number of digits used to represent the <see cref="Value"/> property. /// </summary> public byte Precision { get { return precision; } set { precision = value; } } /// <summary> /// Gets or sets the number of decimal places to which <see cref="Value"/> is resolved. /// </summary> public byte Scale { get { return scale; } set { scale = value; } } /// <summary> /// Gets or sets the maximum size, in bytes, of the data within the column. /// </summary> public override int Size { get { return size; } set { size = value; } } /// <summary> /// Gets or sets the name of the source column that is mapped to the <see cref="DataSet"/> and used for loading or returning the <see cref="Value"/>. /// </summary> public override String SourceColumn { get { return sourceColumn; } set { sourceColumn = value; } } /// <summary> /// Gets or sets the <see cref="DataRowVersion"/> to use when loading <see cref="Value"/>. /// </summary> public DataRowVersion SourceVersion { get { return sourceVersion; } set { sourceVersion = value; } } /// <summary> /// Gets or sets the value of the parameter. /// </summary> public override object Value { get { return paramValue; } set { paramValue = value; if (value is Byte[]) size = (value as Byte[]).Length; else if (value is String) size = (value as string).Length; if (inferType) SetTypeFromValue(); } } #endregion /// <summary> /// Overridden. Gets a string containing the <see cref="ParameterName"/>. /// </summary> /// <returns></returns> public override string ToString() { return paramName; } internal int GetPSType() { switch (mySqlDbType) { case MySqlDbType.Bit: return (int) MySqlDbType.Int64 | UNSIGNED_MASK; case MySqlDbType.UByte: return (int) MySqlDbType.Byte | UNSIGNED_MASK; case MySqlDbType.UInt64: return (int) MySqlDbType.Int64 | UNSIGNED_MASK; case MySqlDbType.UInt32: return (int) MySqlDbType.Int32 | UNSIGNED_MASK; case MySqlDbType.UInt24: return (int) MySqlDbType.Int32 | UNSIGNED_MASK; case MySqlDbType.UInt16: return (int) MySqlDbType.Int16 | UNSIGNED_MASK; default: return (int) mySqlDbType; } } internal void Serialize(MySqlStream stream, bool binary) { IMySqlValue v = MySqlField.GetIMySqlValue(mySqlDbType); if (!binary && (paramValue == null || paramValue == DBNull.Value)) stream.WriteStringNoNull("NULL"); else v.WriteValue(stream, binary, paramValue, size); } private void SetMySqlDbType(MySqlDbType mysql_dbtype) { mySqlDbType = mysql_dbtype; switch (mySqlDbType) { case MySqlDbType.Decimal: dbType = DbType.Decimal; break; case MySqlDbType.Byte: dbType = DbType.SByte; break; case MySqlDbType.UByte: dbType = DbType.Byte; break; case MySqlDbType.Int16: dbType = DbType.Int16; break; case MySqlDbType.UInt16: dbType = DbType.UInt16; break; case MySqlDbType.Int24: case MySqlDbType.Int32: dbType = DbType.Int32; break; case MySqlDbType.UInt24: case MySqlDbType.UInt32: dbType = DbType.UInt32; break; case MySqlDbType.Int64: dbType = DbType.Int64; break; case MySqlDbType.UInt64: dbType = DbType.UInt64; break; case MySqlDbType.Bit: dbType = DbType.UInt64; break; case MySqlDbType.Float: dbType = DbType.Single; break; case MySqlDbType.Double: dbType = DbType.Double; break; case MySqlDbType.Timestamp: case MySqlDbType.DateTime: dbType = DbType.DateTime; break; case MySqlDbType.Date: case MySqlDbType.Newdate: case MySqlDbType.Year: dbType = DbType.Date; break; case MySqlDbType.Time: dbType = DbType.Time; break; case MySqlDbType.Enum: case MySqlDbType.Set: case MySqlDbType.VarChar: dbType = DbType.String; break; case MySqlDbType.TinyBlob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Blob: dbType = DbType.Object; break; case MySqlDbType.String: dbType = DbType.StringFixedLength; break; } } private void SetDbType(DbType db_type) { dbType = db_type; switch (dbType) { case DbType.Guid: case DbType.AnsiString: case DbType.String: mySqlDbType = MySqlDbType.VarChar; break; case DbType.AnsiStringFixedLength: case DbType.StringFixedLength: mySqlDbType = MySqlDbType.String; break; case DbType.Boolean: case DbType.Byte: mySqlDbType = MySqlDbType.UByte; break; case DbType.SByte: mySqlDbType = MySqlDbType.Byte; break; case DbType.Date: mySqlDbType = MySqlDbType.Date; break; case DbType.DateTime: mySqlDbType = MySqlDbType.DateTime; break; case DbType.Time: mySqlDbType = MySqlDbType.Time; break; case DbType.Single: mySqlDbType = MySqlDbType.Float; break; case DbType.Double: mySqlDbType = MySqlDbType.Double; break; case DbType.Int16: mySqlDbType = MySqlDbType.Int16; break; case DbType.UInt16: mySqlDbType = MySqlDbType.UInt16; break; case DbType.Int32: mySqlDbType = MySqlDbType.Int32; break; case DbType.UInt32: mySqlDbType = MySqlDbType.UInt32; break; case DbType.Int64: mySqlDbType = MySqlDbType.Int64; break; case DbType.UInt64: mySqlDbType = MySqlDbType.UInt64; break; case DbType.Decimal: case DbType.Currency: mySqlDbType = MySqlDbType.Decimal; break; case DbType.Object: case DbType.VarNumeric: case DbType.Binary: default: mySqlDbType = MySqlDbType.Blob; break; } } private void SetTypeFromValue() { if (paramValue == null || paramValue == DBNull.Value) return; if (paramValue is Guid) DbType = DbType.String; else if (paramValue is TimeSpan) DbType = DbType.Time; else if (paramValue is bool) DbType = DbType.Byte; else { TypeCode tc = GetTypeCode(paramValue.GetType()); // Type.GetTypeCode(paramValue.GetType()); switch (tc) { case TypeCode.SByte: DbType = DbType.SByte; break; case TypeCode.Byte: DbType = DbType.Byte; break; case TypeCode.Int16: DbType = DbType.Int16; break; case TypeCode.UInt16: DbType = DbType.UInt16; break; case TypeCode.Int32: DbType = DbType.Int32; break; case TypeCode.UInt32: DbType = DbType.UInt32; break; case TypeCode.Int64: DbType = DbType.Int64; break; case TypeCode.UInt64: DbType = DbType.UInt64; break; case TypeCode.DateTime: DbType = DbType.DateTime; break; case TypeCode.String: DbType = DbType.String; break; case TypeCode.Single: DbType = DbType.Single; break; case TypeCode.Double: DbType = DbType.Double; break; case TypeCode.Decimal: DbType = DbType.Decimal; break; case TypeCode.Object: default: DbType = DbType.Object; break; } } } #region ICloneable internal object Clone() { MySqlParameter clone = new MySqlParameter(paramName, mySqlDbType, direction, sourceColumn, sourceVersion, paramValue); // if we have not had our type set yet then our clone should not either clone.inferType = inferType; return clone; } #endregion /// <summary> /// Resets the <b>DbType</b> property to its original settings. /// </summary> public override void ResetDbType() { inferType = true; } /// <summary> /// Sets or gets a value which indicates whether the source column is nullable. /// This allows <see cref="DbCommandBuilder"/> to correctly generate Update statements /// for nullable columns. /// </summary> public override bool SourceColumnNullMapping { get { return sourceColumnNullMapping; } set { sourceColumnNullMapping = value; } } // this method is pretty dumb but we want it to be fast. it doesn't return size based // on value and type but just on the value. internal long EstimatedSize() { if (Value == null || Value == DBNull.Value) return 4; // size of NULL if (Value is byte[]) return (Value as byte[]).Length; if (Value is string) return (Value as string).Length * 4; // account for UTF-8 (yeah I know) if (Value is decimal || Value is float) return 64; return 32; } private static TypeCode GetTypeCode(Type type) { if (type == null) { return TypeCode.Empty; } else if (type == typeof(Boolean)) { return TypeCode.Boolean; } else if (type == typeof(Char)) { return TypeCode.Char; } else if (type == typeof(SByte)) { return TypeCode.SByte; } else if (type == typeof(Byte)) { return TypeCode.Byte; } else if (type == typeof(Int16)) { return TypeCode.Int16; } else if (type == typeof(UInt16)) { return TypeCode.UInt16; } else if (type == typeof(Int32)) { return TypeCode.Int32; } else if (type == typeof(UInt32)) { return TypeCode.UInt32; } else if (type == typeof(Int64)) { return TypeCode.Int64; } else if (type == typeof(UInt64)) { return TypeCode.UInt64; } else if (type == typeof(Single)) { return TypeCode.Single; } else if (type == typeof(Double)) { return TypeCode.Double; } else if (type == typeof(Decimal)) { return TypeCode.Decimal; } else if (type == typeof(DateTime)) { return TypeCode.DateTime; } else if (type == typeof(String)) { return TypeCode.String; } else { return TypeCode.Object; } } } }
using System; using System.Collections; using System.Collections.Generic; using NServiceKit.IO; namespace NServiceKit.VirtualPath { /// <summary> /// Abstract base class for virtual directories. /// </summary> public abstract class AbstractVirtualDirectoryBase : IVirtualDirectory { /// <summary>The virtual path provider.</summary> protected IVirtualPathProvider VirtualPathProvider; /// <summary> /// Gets or sets the parent directory. /// </summary> /// <value> /// The parent directory. /// </value> public IVirtualDirectory ParentDirectory { get; set; } /// <summary> /// Gets the directory. /// </summary> /// <value> /// The directory. /// </value> public IVirtualDirectory Directory { get { return this; } } /// <summary> /// Gets the last modified. /// </summary> /// <value> /// The last modified. /// </value> public abstract DateTime LastModified { get; } /// <summary> /// Gets the virtual path. /// </summary> /// <value> /// The virtual path. /// </value> public virtual string VirtualPath { get { return GetVirtualPathToRoot(); } } /// <summary> /// Gets the real path. /// </summary> /// <value> /// The real path. /// </value> public virtual string RealPath { get { return GetRealPathToRoot(); } } /// <summary> /// Gets a value indicating whether this instance is directory. /// </summary> /// <value> /// <c>true</c> if this instance is directory; otherwise, <c>false</c>. /// </value> public virtual bool IsDirectory { get { return true; } } /// <summary> /// Gets a value indicating whether this instance is root. /// </summary> /// <value> /// <c>true</c> if this instance is root; otherwise, <c>false</c>. /// </value> public virtual bool IsRoot { get { return ParentDirectory == null; } } /// <summary> /// Gets the files. /// </summary> /// <value> /// The files. /// </value> public abstract IEnumerable<IVirtualFile> Files { get; } /// <summary> /// Gets the directories. /// </summary> /// <value> /// The directories. /// </value> public abstract IEnumerable<IVirtualDirectory> Directories { get; } /// <summary> /// Gets the name. /// </summary> /// <value> /// The name. /// </value> public abstract string Name { get; } /// <summary> /// Initializes a new instance of the <see cref="AbstractVirtualDirectoryBase"/> class. /// </summary> /// <param name="owningProvider">The owning provider.</param> protected AbstractVirtualDirectoryBase(IVirtualPathProvider owningProvider) : this(owningProvider, null) {} /// <summary> /// Initializes a new instance of the <see cref="AbstractVirtualDirectoryBase"/> class. /// </summary> /// <param name="owningProvider">The owning provider.</param> /// <param name="parentDirectory">The parent directory.</param> /// <exception cref="System.ArgumentNullException">owningProvider</exception> protected AbstractVirtualDirectoryBase(IVirtualPathProvider owningProvider, IVirtualDirectory parentDirectory) { if (owningProvider == null) throw new ArgumentNullException("owningProvider"); VirtualPathProvider = owningProvider; ParentDirectory = parentDirectory; } /// <summary> /// Gets the file. /// </summary> /// <param name="virtualPath">The virtual path.</param> /// <returns></returns> public virtual IVirtualFile GetFile(string virtualPath) { var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider); return GetFile(tokens); } /// <summary> /// Gets the directory. /// </summary> /// <param name="virtualPath">The virtual path.</param> /// <returns></returns> public virtual IVirtualDirectory GetDirectory(string virtualPath) { var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider); return GetDirectory(tokens); } /// <summary> /// Gets the file. /// </summary> /// <param name="virtualPath">The virtual path.</param> /// <returns></returns> public virtual IVirtualFile GetFile(Stack<string> virtualPath) { if (virtualPath.Count == 0) return null; var pathToken = virtualPath.Pop(); if (virtualPath.Count == 0) return GetFileFromBackingDirectoryOrDefault(pathToken); var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken); return virtDir != null ? virtDir.GetFile(virtualPath) : null; } /// <summary> /// Gets the directory. /// </summary> /// <param name="virtualPath">The virtual path.</param> /// <returns></returns> public virtual IVirtualDirectory GetDirectory(Stack<string> virtualPath) { if (virtualPath.Count == 0) return null; var pathToken = virtualPath.Pop(); var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken); if (virtDir == null) return null; return virtualPath.Count == 0 ? virtDir : virtDir.GetDirectory(virtualPath); } /// <summary> /// Gets all matching files. /// </summary> /// <param name="globPattern">The glob pattern.</param> /// <param name="maxDepth">The maximum depth.</param> /// <returns></returns> public virtual IEnumerable<IVirtualFile> GetAllMatchingFiles(string globPattern, int maxDepth = Int32.MaxValue) { if (maxDepth == 0) yield break; foreach (var f in GetMatchingFilesInDir(globPattern)) yield return f; foreach (var childDir in Directories) { var matchingFilesInChildDir = childDir.GetAllMatchingFiles(globPattern, maxDepth - 1); foreach (var f in matchingFilesInChildDir) yield return f; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets the virtual path to root. /// </summary> /// <returns></returns> protected virtual string GetVirtualPathToRoot() { if (IsRoot) return VirtualPathProvider.VirtualPathSeparator; return GetPathToRoot(VirtualPathProvider.VirtualPathSeparator, p => p.VirtualPath); } /// <summary> /// Gets the real path to root. /// </summary> /// <returns></returns> protected virtual string GetRealPathToRoot() { return GetPathToRoot(VirtualPathProvider.RealPathSeparator, p => p.RealPath); } /// <summary> /// Gets the path to root. /// </summary> /// <param name="separator">The separator.</param> /// <param name="pathSel">The path sel.</param> /// <returns></returns> protected virtual string GetPathToRoot(string separator, Func<IVirtualDirectory, string> pathSel) { var parentPath = ParentDirectory != null ? pathSel(ParentDirectory) : string.Empty; if (parentPath == separator) parentPath = string.Empty; return string.Concat(parentPath, separator, Name); } /// <summary>Determines whether the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />.</summary> /// /// <param name="obj">The <see cref="T:System.Object" /> to compare with the current <see cref="T:System.Object" />.</param> /// /// <returns>true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />; otherwise, false.</returns> public override bool Equals(object obj) { var other = obj as AbstractVirtualDirectoryBase; if (other == null) return false; return other.VirtualPath == VirtualPath; } /// <summary>Serves as a hash function for a particular type.</summary> /// /// <returns>A hash code for the current <see cref="T:System.Object" />.</returns> public override int GetHashCode() { return VirtualPath.GetHashCode(); } /// <summary>Returns a string that represents the current object.</summary> /// /// <returns>A string that represents the current object.</returns> public override string ToString() { return string.Format("{0} -> {1}", RealPath, VirtualPath); } /// <summary>Gets the enumerator.</summary> /// /// <returns>The enumerator.</returns> public abstract IEnumerator<IVirtualNode> GetEnumerator(); /// <summary> /// Gets the file from backing directory or default. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns></returns> protected abstract IVirtualFile GetFileFromBackingDirectoryOrDefault(string fileName); /// <summary> /// Gets the matching files in dir. /// </summary> /// <param name="globPattern">The glob pattern.</param> /// <returns></returns> protected abstract IEnumerable<IVirtualFile> GetMatchingFilesInDir(string globPattern); /// <summary> /// Gets the directory from backing directory or default. /// </summary> /// <param name="directoryName">Name of the directory.</param> /// <returns></returns> protected abstract IVirtualDirectory GetDirectoryFromBackingDirectoryOrDefault(string directoryName); } }
#if UNITY_2_6 || UNITY_2_6_1 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 // Coherent UI supports Linux for Unity3D 4.2+ #define COHERENT_UNITY_PRE_4_2 #endif using UnityEngine; using System.Collections; using System; using System.IO; using System.Text; using System.Reflection; using UnityEditor; using UnityEditor.Callbacks; public partial class CoherentPostProcessor { public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { DirectoryInfo dir = new DirectoryInfo(sourceDirName); DirectoryInfo[] dirs = dir.GetDirectories(); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, true); } if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } private static void DeleteFileIfExists(string path) { if (File.Exists(path)) { File.Delete(path); } } private static void CleanUpForWindows(BuildTarget target, string dataDirectory) { string sourceDll64Native = dataDirectory + "StreamingAssets/CoherentUI64_Native.dll"; string sourceDll64Managed = dataDirectory + "StreamingAssets/CoherentUINet.dll64"; string unneededManagedDllInPlugins = dataDirectory + "Plugins/CoherentUINet.dll"; DeleteFileIfExists(unneededManagedDllInPlugins); if (target == BuildTarget.StandaloneWindows64) { string targetDll64Native = dataDirectory + "Plugins/CoherentUI64_Native.dll"; string targetDllManaged = dataDirectory + "Managed/CoherentUINet.dll"; string unneededNativeDllInPlugins = dataDirectory + "Plugins/CoherentUI_Native.dll"; DeleteFileIfExists(unneededNativeDllInPlugins); DeleteFileIfExists(targetDll64Native); DeleteFileIfExists(targetDllManaged); if (!File.Exists(sourceDll64Native) || !File.Exists(sourceDll64Managed)) { Debug.LogError("Unable to copy essential files for Coherent UI x64 when postprocessing build!"); return; } File.Move(sourceDll64Native, targetDll64Native); File.Move(sourceDll64Managed, targetDllManaged); } else { // Delete the unneeded CoherentUI x64 DLLs DeleteFileIfExists(sourceDll64Native); DeleteFileIfExists(sourceDll64Managed); } if (Directory.Exists(dataDirectory + "StreamingAssets/CoherentUI_Host/macosx")) { Directory.Delete(dataDirectory + "StreamingAssets/CoherentUI_Host/macosx", true); } if (Directory.Exists(dataDirectory + "StreamingAssets/CoherentUI_Host/linux")) { Directory.Delete(dataDirectory + "StreamingAssets/CoherentUI_Host/linux", true); } } private static void CleanUpForMacOSX(string bundle) { var dataDirectory = bundle + "Contents/Data/StreamingAssets/"; var pluginsDirectory = bundle + "Contents/Plugins/"; string[] windowsDlls = { dataDirectory + "CoherentUI64_Native.dll", dataDirectory + "CoherentUINet.dll64", pluginsDirectory + "CoherentUI_Native.dll", pluginsDirectory + "CoherentUINet.dll", }; foreach (var file in windowsDlls) { DeleteFileIfExists(file); } if (Directory.Exists(dataDirectory + "CoherentUI_Host/windows")) { Directory.Delete(dataDirectory + "CoherentUI_Host/windows", true); } if (Directory.Exists(dataDirectory + "CoherentUI_Host/linux")) { Directory.Delete(dataDirectory + "CoherentUI_Host/linux", true); } } private static void CleanUpForLinux(string dataDirectory) { string[] windowsDlls = { dataDirectory + "StreamingAssets/CoherentUI64_Native.dll", dataDirectory + "StreamingAssets/CoherentUINet.dll64", }; foreach (var file in windowsDlls) { DeleteFileIfExists(file); } if (Directory.Exists(dataDirectory + "StreamingAssets/CoherentUI_Host/windows")) { Directory.Delete(dataDirectory + "StreamingAssets/CoherentUI_Host/windows", true); } if (Directory.Exists(dataDirectory + "StreamingAssets/CoherentUI_Host/macosx")) { Directory.Delete(dataDirectory + "StreamingAssets/CoherentUI_Host/macosx", true); } } private static void CleanUpForMobile(string dataFolder) { string[] dlls = { dataFolder + "CoherentUINet.dll64", dataFolder + "CoherentUI64_Native.dll", }; foreach (var file in dlls) { DeleteFileIfExists(file); } string hostDir = dataFolder + "CoherentUI_Host"; if(Directory.Exists(hostDir)) { Directory.Delete(hostDir, true); } } private static bool IsTargetPlatformSupported(BuildTarget target) { return target == BuildTarget.Android || target == BuildTarget.iPhone || #if !COHERENT_UNITY_PRE_4_2 target == BuildTarget.StandaloneLinux64 || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal || #endif target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneWindows || target == BuildTarget.StandaloneWindows64; } [PostProcessBuild] public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { if (!IsTargetPlatformSupported(target)) { if (Directory.Exists(Path.Combine(pathToBuiltProject, "StreamingAssets/CoherentUI_Host"))) { Directory.Delete(Path.Combine(pathToBuiltProject, "StreamingAssets/CoherentUI_Host"), true); } Debug.Log("Coherent UI package installed in a project targeting unsupported platfrom (" + target + ")!"); return; } var outDir = Path.GetDirectoryName(pathToBuiltProject); var projName = ""; if (target == BuildTarget.iPhone) { var slashDelim = pathToBuiltProject.LastIndexOf('/'); if(slashDelim != -1) { projName = pathToBuiltProject.Substring(slashDelim+1) ; } else { Debug.Log("Ivalid path to build project passed!"); return; } } else { projName = Path.GetFileNameWithoutExtension(pathToBuiltProject); } var resourcesFolder = PlayerPrefs.GetString("CoherentUIResources"); #if !COHERENT_UNITY_PRE_4_2 if (target == BuildTarget.Android) { outDir = pathToBuiltProject; projName = PlayerSettings.productName; } #endif // check for per-project override if(string.IsNullOrEmpty(resourcesFolder)) { FieldInfo projectUIResourcesStr = typeof(CoherentPostProcessor).GetField("ProjectUIResources", BindingFlags.Public | BindingFlags.Static); if(projectUIResourcesStr != null) { string projectResFolder = (string)projectUIResourcesStr.GetValue(null); Debug.Log(String.Format("[Coherent UI]: Found project resources folder: {0}", projectResFolder)); resourcesFolder = projectResFolder; } } bool buildingAndroidApk = false; string androidUnpackDir = Path.Combine(Application.dataPath, "../Temp/CouiApkRepack"); if (target == BuildTarget.Android && pathToBuiltProject.EndsWith(".apk")) { buildingAndroidApk = true; } if (buildingAndroidApk) { AndroidPostProcessor.FindAndCopySdkAaptAndZipalign(); AndroidPostProcessor.UnpackAPK(pathToBuiltProject, androidUnpackDir); } // copy the UI resources if(!string.IsNullOrEmpty(resourcesFolder)) { var lastDelim = resourcesFolder.LastIndexOf('/'); string folderName = lastDelim != -1 ? resourcesFolder.Substring(lastDelim+1) : resourcesFolder; StringBuilder outputDir = new StringBuilder(outDir); string uiResourcesFormat = null; switch(target) { #if !COHERENT_UNITY_PRE_4_2 case BuildTarget.StandaloneOSXIntel64: case BuildTarget.StandaloneOSXUniversal: #endif case BuildTarget.StandaloneOSXIntel: uiResourcesFormat = "/{0}.app/Contents/{1}"; break; case BuildTarget.StandaloneWindows: case BuildTarget.StandaloneWindows64: #if !COHERENT_UNITY_PRE_4_2 case BuildTarget.StandaloneLinux64: #endif uiResourcesFormat = "/{0}_Data/{1}"; break; case BuildTarget.iPhone: uiResourcesFormat = "/{0}/Data/{1}"; break; case BuildTarget.Android: uiResourcesFormat = "/{0}/assets/{1}"; // Format for exported Eclipse project break; default: new System.ApplicationException("Unsupported by Coherent UI build target"); break; } var inDir = Path.Combine(Application.dataPath, resourcesFolder); if (!Directory.Exists(inDir)) { resourcesFolder = Path.Combine("..", resourcesFolder); inDir = Path.Combine(Application.dataPath, resourcesFolder); } if (buildingAndroidApk) { outputDir = new StringBuilder(Path.Combine(androidUnpackDir, "assets/" + folderName)); } else { outputDir.AppendFormat(uiResourcesFormat, projName, folderName); } DirectoryCopy(inDir.ToString(), outputDir.ToString(), true); } switch (target) { case BuildTarget.StandaloneWindows: case BuildTarget.StandaloneWindows64: CleanUpForWindows(target, string.Format("{0}/{1}_Data/", outDir, projName)); break; #if !COHERENT_UNITY_PRE_4_2 case BuildTarget.StandaloneLinux64: CleanUpForLinux(string.Format("{0}/{1}_Data/", outDir, projName)); break; case BuildTarget.StandaloneOSXIntel64: case BuildTarget.StandaloneOSXUniversal: #endif case BuildTarget.StandaloneOSXIntel: CleanUpForMacOSX(string.Format("{0}/{1}.app/", outDir, projName)); break; case BuildTarget.iPhone: var outputFolder = string.Format("{0}/{1}/Data/Raw/", outDir, projName); IOSPostProcessor.PostProcess(pathToBuiltProject); CleanUpForMobile(outputFolder); break; case BuildTarget.Android: if (buildingAndroidApk) { AndroidPostProcessor.RepackAPK(pathToBuiltProject, androidUnpackDir); } else { bool apiLevel11OrGreater = (PlayerSettings.Android.minSdkVersion >= AndroidSdkVersions.AndroidApiLevel11); AndroidPostProcessor.ModifyManifestFile(string.Format("{0}/{1}/AndroidManifest.xml", outDir, projName), apiLevel11OrGreater); CleanUpForMobile(string.Format("{0}/{1}/assets/", outDir, projName)); AndroidPostProcessor.CleanUpForAndroid(string.Format("{0}/{1}/Plugins", outDir, projName)); AndroidPostProcessor.CopyMobileNetDll( string.Format("{0}/{1}/assets/bin/Data/Managed", outDir, projName), Path.Combine(Application.dataPath, "Plugins")); } break; default: new System.ApplicationException("Unsupported by Coherent UI build target"); break; } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using Aspectize.Core; using Aspectize; using Aspectize.Office; using Excel; using System.IO; using System.Linq; using System.Threading; namespace TranslationManager { public interface ITranslationManagerService { DataSet LoadTranslations(); [Command(BrowserCacheDuration = "30 Days")] DataSet LoadTranslationValues(Guid translationId, DateTime dateModified); DataSet ExtractLiterals(string applicationName); DataSet ImportTraductionFromExcel(UploadedFile excelFile); byte[] ExportTranslationToExcel(); [Command(IsSaveCommand = true)] DataSet SaveTranslations(DataSet dataSet); void ResetTranslationCache(); string GetPivotLanguage(); string[] GetLanguages(); string Translate(string term, string toLanguage); } [Service(Name = "TranslationManagerService", ConfigurationRequired = true)] public class TranslationManagerService : ITranslationManagerService, ILocalizationProvider, ISingleton, IApplicationDependent, IMustValidate, IServiceName//, ITranslationTerm { [Parameter(Optional = false)] string DataServiceName = ""; [Parameter(Optional = false)] string KeyLanguage = ""; [Parameter(Optional = false)] string Languages = ""; Application parentApp; string svcName; Dictionary<string, Dictionary<string, string>> dictionaries = new Dictionary<string, Dictionary<string, string>>(); Application IApplicationDependent.Parent { set { parentApp = value; } } DataSet ITranslationManagerService.LoadTranslations() { IDataManager dm = EntityManager.FromDataBaseService(DataServiceName); dm.LoadEntities<AspectizeTranslation>(); return dm.Data; } DataSet ITranslationManagerService.LoadTranslationValues(Guid translationId, DateTime dateModified) { IDataManager dm = EntityManager.FromDataBaseService(DataServiceName); dm.LoadEntityFields<AspectizeTranslation>(EntityLoadOption.AllFields, translationId); return dm.Data; } DataSet ITranslationManagerService.ExtractLiterals(string applicationName) { if (string.IsNullOrEmpty(applicationName)) applicationName = parentApp.Name; IDataManager dm = EntityManager.FromDataBaseService(DataServiceName); IEntityManager em = dm as IEntityManager; var dicoTranslations = new Dictionary<string, bool>(); List<AspectizeTranslation> translations = dm.GetEntities<AspectizeTranslation>(); foreach(AspectizeTranslation translation in em.GetAllInstances<AspectizeTranslation>()) { dicoTranslations.Add(translation.Key, translation.Ignore); } List<string> languages = Languages.Split(',').Select(p => p.Trim()).ToList(); List<string> literals = TranslationHelper.ExtractWebLiterals2(Context.HostHome, applicationName); var nbSaved = 0; foreach (string literal in literals) { var l = literal.Trim(); if (!dicoTranslations.ContainsKey(l)) { var t = em.CreateInstance<AspectizeTranslation>(); t.Key = l; t.IsNew = true; foreach (string language in languages) { TranslationValue tv = t.Values.Add(); tv.Language = language.Trim(); tv.Value = ""; } nbSaved++; } } dm.SaveTransactional(); return dm.Data; //return string.Format("{0} translations has been extracted, {1} translations has been saved in your storage {2}", literals.Count, nbSaved, DataServiceName); } DataSet ITranslationManagerService.ImportTraductionFromExcel(UploadedFile excelFile) { List<string> languages = Languages.Split(',').Select(p => p.Trim()).ToList(); IDataManager dm = EntityManager.FromDataBaseService(DataServiceName); IEntityManager em = dm as IEntityManager; IExcelDataReader excelReader = null; if (excelFile.ContentLength > 0) { string extension = Path.GetExtension(excelFile.Name); if (string.IsNullOrEmpty(extension) || extension.ToLower() == ".xlsx") { excelReader = ExcelReaderFactory.CreateOpenXmlReader(excelFile.Stream); } else throw new SmartException(100, @"File is not a valid Excel File, only valid Excel 2007 format (*.xlsx) is supported !"); excelReader.IsFirstRowAsColumnNames = true; DataSet result = null; try { result = excelReader.AsDataSet(); } catch (Exception e) { throw new SmartException(200, @"Import Error: {0}", e.Message); } if (result != null && result.Tables.Count == 1) { //List<AspectizeTranslation> translations = dm.GetEntities<AspectizeTranslation>(); List<AspectizeTranslation> translations = dm.GetEntitiesFields<AspectizeTranslation>(EntityLoadOption.AllFields); //, new QueryCriteria(AspectizeTranslation.Fields.Ignore, ComparisonOperator.Equal, false)); DataTable dt = result.Tables[0]; if (!dt.Columns.Contains(KeyLanguage)) throw new SmartException(100, "Invalid file, there should be a column named {0}", KeyLanguage); var nbLine = 1; foreach (DataRow dr in dt.Rows) { string key = dr[KeyLanguage].ToString(); AspectizeTranslation t = translations.Find(item => item.Key.Trim() == key.Trim()); if (t == null) { throw new SmartException(200, @"Invalid translation key {0} at line {1}", key, nbLine); } foreach(DataColumn dc in dt.Columns) { var langImport = dc.ColumnName; if (languages.Contains(langImport)) { TranslationValue tv = t.Values.GetList().Find(item => item.Language == langImport); if (tv == null) { tv = t.Values.Add(); tv.Language = langImport; } tv.Value = dr[dc].ToString(); } } t.IsNew = false; nbLine++; } dm.SaveTransactional(); } else throw new SmartException(200, @"File is not valid, should not have more than 1 sheet !"); } return dm.Data; } Dictionary<string, string> ILocalizationProvider.GetTranslator(string fromLanguage, string toLanguage) { var dictionaryName = String.Format("{0} {1}", fromLanguage, toLanguage); if (!dictionaries.ContainsKey(dictionaryName)) { List<string> languages = Languages.Split(',').Select(p => p.Trim()).ToList(); foreach (string language in languages) { Dictionary<string, string> dico = new Dictionary<string, string>(); string dicoName = string.Format("{0} {1}", KeyLanguage, language); if (!dictionaries.ContainsKey(dicoName)) { dictionaries.Add(dicoName, dico); } Dictionary<string, string> dicoReverse = new Dictionary<string, string>(); string dicoReverseName = string.Format("{0} {1}", language, KeyLanguage); if (!dictionaries.ContainsKey(dicoReverseName)) { dictionaries.Add(dicoReverseName, dicoReverse); } } IDataManager dm = EntityManager.FromDataBaseService(DataServiceName); IEntityManager em = dm as IEntityManager; List<AspectizeTranslation> translations = dm.GetEntitiesFields<AspectizeTranslation>(EntityLoadOption.AllFields, new QueryCriteria(AspectizeTranslation.Fields.Ignore, ComparisonOperator.Equal, false)); foreach (AspectizeTranslation translation in translations) { if (!translation.Ignore) { var key = translation.Key; var nbsp = '\u00a0'; key = key.Replace(nbsp, ' '); foreach (string language in languages) { var value = translation.Values.Find(item => item.Language == language); if (value != null && !string.IsNullOrWhiteSpace(value.Value)) { string dicoName = string.Format("{0} {1}", KeyLanguage, language); if (!dictionaries[dicoName].ContainsKey(key)) { dictionaries[dicoName].Add(key, value.Value); string dicoReverseName = string.Format("{0} {1}", language, KeyLanguage); if (!dictionaries[dicoReverseName].ContainsKey(value.Value)) { dictionaries[dicoReverseName].Add(value.Value, key); } } } } } } } return dictionaries[dictionaryName]; } byte[] ITranslationManagerService.ExportTranslationToExcel() { IDataManager dm = EntityManager.FromDataBaseService(DataServiceName); IEntityManager em = dm as IEntityManager; dm.LoadEntitiesFields<AspectizeTranslation>(EntityLoadOption.AllFields, new QueryCriteria(AspectizeTranslation.Fields.Ignore, ComparisonOperator.Equal, false)); IAspectizeExcel aspectizeExcel = ExecutingContext.GetService<IAspectizeExcel>("AspectizeExcel"); IEntityManager emExport = EntityManager.FromDataSet(new DataSet()); var dtTranslation = emExport.Data.Tables.Add(); dtTranslation.Columns.Add(KeyLanguage, typeof(string)); List<string> languages = Languages.Split(',').Select(p => p.Trim()).ToList(); foreach (string language in languages) { dtTranslation.Columns.Add(language, typeof(string)); } foreach(AspectizeTranslation translation in em.GetAllInstances<AspectizeTranslation>()) { var row = dtTranslation.NewRow(); row[KeyLanguage] = translation.Key; foreach (TranslationValue translationValue in translation.Values.GetList()) { row[translationValue.Language] = translationValue.Value; } dtTranslation.Rows.Add(row); } emExport.Data.AcceptChanges(); ExecutingContext.SetHttpDownloadFileName(string.Format("Translation_{0}_{1:ddMMyyyyHHmm}.xlsx", parentApp.Name, DateTime.Now)); var bytes = aspectizeExcel.ToExcel(emExport.Data, null); return bytes as byte[]; } DataSet ITranslationManagerService.SaveTranslations(DataSet dataSet) { IDataManager dm = EntityManager.FromDataSetAndBaseService(dataSet, DataServiceName); IEntityManager em = dm as IEntityManager; foreach (AspectizeTranslation translation in em.GetAllInstances<AspectizeTranslation>()) { if (translation.IsNew) { translation.IsNew = false; translation.data.AcceptChanges(); translation.data.SetAdded(); } } dm.SaveTransactional(); return dm.Data; } void ITranslationManagerService.ResetTranslationCache() { dictionaries.Clear(); } string IMustValidate.ValidateConfiguration() { if (String.IsNullOrWhiteSpace(KeyLanguage)) return String.Format("Parameter KeyLanguage can not be NullOrWhiteSpace on TranslationManagerService '{0}'. The parameter should be a .Net language culture name as 'en-US' !", svcName); if (String.IsNullOrWhiteSpace(DataServiceName)) return String.Format("Parameter DataServiceName can not be NullOrWhiteSpace on TranslationManagerService '{0}'. The parameter should be a valid Data Service Name !", svcName); if (String.IsNullOrWhiteSpace(Languages)) return String.Format("Parameter Languages can not be NullOrWhiteSpace on TranslationManagerService '{0}'. The parameter should be list of .Net language culture names separated by , !", svcName); var languages = Languages.Split(',').Select(p => p.Trim()).ToList(); foreach(string language in languages) { if (String.IsNullOrWhiteSpace(language)) return String.Format("Parameter Languages can not contains empty langauage on TranslationManagerService '{0}'. The parameter should be list of .Net language culture names separated by , !", svcName); } return null; } void IServiceName.SetServiceName(string name) { svcName = name; } string ITranslationManagerService.GetPivotLanguage() { return KeyLanguage; } string[] ITranslationManagerService.GetLanguages() { return Languages.Split(',').Select(p => p.Trim()).ToArray(); } string ITranslationManagerService.Translate(string term, string toLanguage) { if (string.IsNullOrWhiteSpace(toLanguage)) { toLanguage = Thread.CurrentThread.CurrentCulture.Name; } var dico = ((ILocalizationProvider)this).GetTranslator(KeyLanguage, toLanguage); if (dico != null && dico.ContainsKey(term)) { return dico[term]; } return term; } } }
// // ShadedContainer.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2010 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using Gtk; using MonoDevelop.Components; using Pinta.Core; namespace MonoDevelop.Components.Docking { public class ShadedContainer { struct Section { public int Offset; public int Size; } Gdk.Color lightColor; Gdk.Color darkColor; int shadowSize = 2; List<Widget> widgets = new List<Widget> (); Dictionary<Widget, Gdk.Rectangle[]> allocations = new Dictionary<Widget, Gdk.Rectangle[]> (); public ShadedContainer () { } public int ShadowSize { get { return this.shadowSize; } set { this.shadowSize = value; RedrawAll (); } } public Gdk.Color LightColor { get { return this.lightColor; } set { this.lightColor = value; RedrawAll (); } } public Gdk.Color DarkColor { get { return this.darkColor; } set { this.darkColor = value; RedrawAll (); } } public void Add (Gtk.Widget w) { widgets.Add (w); UpdateAllocation (w); w.Destroyed += HandleWDestroyed; w.Shown += HandleWShown; w.Hidden += HandleWHidden; w.SizeAllocated += HandleWSizeAllocated; w.Realized += HandleWRealized; IShadedWidget sw = w as IShadedWidget; if (sw != null) sw.AreasChanged += HandleSwAreasChanged; RedrawAll (); } public void Remove (Widget w) { widgets.Remove (w); allocations.Remove (w); w.Destroyed -= HandleWDestroyed; w.Shown -= HandleWShown; w.Hidden -= HandleWHidden; w.Realized -= HandleWRealized; IShadedWidget sw = w as IShadedWidget; if (sw != null) sw.AreasChanged -= HandleSwAreasChanged; RedrawAll (); } bool UpdateAllocation (Widget w) { if (w.IsRealized) { IShadedWidget sw = w as IShadedWidget; Gdk.Rectangle[] newAllocations; if (sw != null) { List<Gdk.Rectangle> rects = new List<Gdk.Rectangle> (); foreach (Gdk.Rectangle ar in sw.GetShadedAreas ()) rects.Add (ar); newAllocations = rects.ToArray (); } else { newAllocations = new Gdk.Rectangle [] { w.Allocation }; } Gdk.Rectangle[] oldAllocations; if (allocations.TryGetValue (w, out oldAllocations)) { if (oldAllocations.Length == newAllocations.Length) { bool changed = false; for (int n=0; n<oldAllocations.Length; n++) { if (newAllocations[n] != oldAllocations[n]) { changed = true; break; } } if (!changed) return false; } } allocations [w] = newAllocations; return true; } else { if (!allocations.ContainsKey (w)) return false; allocations.Remove (w); return true; } } void HandleWRealized (object sender, EventArgs e) { if (UpdateAllocation ((Widget) sender)) RedrawAll (); } void HandleSwAreasChanged (object sender, EventArgs e) { if (UpdateAllocation ((Gtk.Widget)sender)) RedrawAll (); } void HandleWSizeAllocated (object o, SizeAllocatedArgs args) { if (UpdateAllocation ((Widget) o)) RedrawAll (); } void HandleWHidden (object sender, EventArgs e) { RedrawAll (); } void HandleWShown (object sender, EventArgs e) { RedrawAll (); } void HandleWDestroyed (object sender, EventArgs e) { Remove ((Widget)sender); } void RedrawAll () { foreach (Widget w in widgets) { if (!w.Visible) continue; IShadedWidget sw = w as IShadedWidget; if (sw != null) { foreach (Gdk.Rectangle rect in sw.GetShadedAreas ()) w.QueueDrawArea (rect.X, rect.Y, rect.Width, rect.Height); } else w.QueueDraw (); } } public void DrawBackground (Gtk.Widget w) { DrawBackground (w, w.Allocation); } public void DrawBackground (Gtk.Widget w, Gdk.Rectangle allocation) { if (shadowSize == 0) { Gdk.Rectangle wr = new Gdk.Rectangle (allocation.X, allocation.Y, allocation.Width, allocation.Height); using (Cairo.Context ctx = Gdk.CairoHelper.Create (w.GdkWindow)) { ctx.Rectangle (wr.X, wr.Y, wr.Width, wr.Height); ctx.Color = lightColor.ToCairoColor (); ctx.Fill (); } return; } List<Section> secsT = new List<Section> (); List<Section> secsB = new List<Section> (); List<Section> secsR = new List<Section> (); List<Section> secsL = new List<Section> (); int x, y; w.GdkWindow.GetOrigin (out x, out y); Gdk.Rectangle rect = new Gdk.Rectangle (x + allocation.X, y + allocation.Y, allocation.Width, allocation.Height); Section s = new Section (); s.Size = rect.Width; secsT.Add (s); secsB.Add (s); s.Size = rect.Height; secsL.Add (s); secsR.Add (s); foreach (var rects in allocations) { int sx, sy; rects.Key.GdkWindow.GetOrigin (out sx, out sy); foreach (Gdk.Rectangle srt in rects.Value) { if (srt == rect) continue; Gdk.Rectangle sr = srt; sr.Offset (sx, sy); if (sr.Right == rect.X) RemoveSection (secsL, sr.Y - rect.Y, sr.Height); if (sr.Bottom == rect.Y) RemoveSection (secsT, sr.X - rect.X, sr.Width); if (sr.X == rect.Right) RemoveSection (secsR, sr.Y - rect.Y, sr.Height); if (sr.Y == rect.Bottom) RemoveSection (secsB, sr.X - rect.X, sr.Width); } } Gdk.Rectangle r = new Gdk.Rectangle (allocation.X, allocation.Y, allocation.Width, allocation.Height); using (Cairo.Context ctx = Gdk.CairoHelper.Create (w.GdkWindow)) { ctx.Rectangle (r.X, r.Y, r.Width, r.Height); ctx.Color = lightColor.ToCairoColor (); ctx.Fill (); DrawShadow (ctx, r, PositionType.Left, secsL); DrawShadow (ctx, r, PositionType.Top, secsT); DrawShadow (ctx, r, PositionType.Right, secsR); DrawShadow (ctx, r, PositionType.Bottom, secsB); } } void DrawShadow (Cairo.Context ctx, Gdk.Rectangle ar, PositionType pos, List<Section> secs) { foreach (Section s in secs) { Cairo.Gradient pat = null; Gdk.Rectangle r = ar; switch (pos) { case PositionType.Top: r.Height = shadowSize > r.Height ? r.Height / 2 : shadowSize; r.X += s.Offset; r.Width = s.Size; pat = new Cairo.LinearGradient (r.X, r.Y, r.X, r.Bottom); break; case PositionType.Bottom: r.Y = r.Bottom - shadowSize; r.Height = shadowSize > r.Height ? r.Height / 2 : shadowSize; r.X = r.X + s.Offset; r.Width = s.Size; pat = new Cairo.LinearGradient (r.X, r.Bottom, r.X, r.Y); break; case PositionType.Left: r.Width = shadowSize > r.Width ? r.Width / 2 : shadowSize; r.Y += s.Offset; r.Height = s.Size; pat = new Cairo.LinearGradient (r.X, r.Y, r.Right, r.Y); break; case PositionType.Right: r.X = r.Right - shadowSize; r.Width = shadowSize > r.Width ? r.Width / 2 : shadowSize; r.Y += s.Offset; r.Height = s.Size; pat = new Cairo.LinearGradient (r.Right, r.Y, r.X, r.Y); break; } Cairo.Color c = darkColor.ToCairoColor (); pat.AddColorStop (0, c); c.A = 0; pat.AddColorStop (1, c); ctx.NewPath (); ctx.Rectangle (r.X, r.Y, r.Width, r.Height); ctx.Pattern = pat; ctx.Fill (); pat.Destroy (); } } void RemoveSection (List<Section> secs, int offset, int size) { if (offset < 0) { size += offset; offset = 0; } if (size <= 0 || secs.Count == 0) return; Section last = secs [secs.Count - 1]; int rem = (last.Offset + last.Size) - (offset + size); if (rem < 0) { size += rem; if (size <= 0) return; } for (int n=0; n<secs.Count; n++) { Section s = secs [n]; if (s.Offset >= offset + size) continue; if (offset >= s.Offset + s.Size) continue; if (offset <= s.Offset && offset + size >= s.Offset + s.Size) { // Remove the whole section secs.RemoveAt (n); n--; continue; } if (offset <= s.Offset) { int newOfs = offset + size; s.Size = s.Size - (newOfs - s.Offset); s.Offset = newOfs; secs [n] = s; // Nothing else to remove return; } if (offset + size >= s.Offset + s.Size) { s.Size = offset - s.Offset; secs [n] = s; continue; } // Split section Section s2 = new Section (); s2.Offset = offset + size; s2.Size = (s.Offset + s.Size) - (offset + size); secs.Insert (n + 1, s2); s.Size = offset - s.Offset; secs [n] = s; } } } public interface IShadedWidget { IEnumerable<Gdk.Rectangle> GetShadedAreas (); event EventHandler AreasChanged; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// RoutesOperations operations. /// </summary> public partial interface IRoutesOperations { /// <summary> /// Deletes the specified route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Route>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a route in the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create or update route operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Route>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all routes in a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Route>>> ListWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a route in the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create or update route operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Route>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all routes in a route table. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Route>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Support; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Similarity = Lucene.Net.Search.Similarities.Similarity; internal sealed class ExactPhraseScorer : Scorer { private readonly int endMinus1; private const int CHUNK = 4096; private int gen; private readonly int[] counts = new int[CHUNK]; private readonly int[] gens = new int[CHUNK]; internal bool noDocs; private readonly long cost; private sealed class ChunkState { internal DocsAndPositionsEnum PosEnum { get; private set; } internal int Offset { get; private set; } internal bool UseAdvance { get; private set; } internal int PosUpto { get; set; } internal int PosLimit { get; set; } internal int Pos { get; set; } internal int LastPos { get; set; } public ChunkState(DocsAndPositionsEnum posEnum, int offset, bool useAdvance) { this.PosEnum = posEnum; this.Offset = offset; this.UseAdvance = useAdvance; } } private readonly ChunkState[] chunkStates; private int docID = -1; private int freq; private readonly Similarity.SimScorer docScorer; internal ExactPhraseScorer(Weight weight, PhraseQuery.PostingsAndFreq[] postings, Similarity.SimScorer docScorer) : base(weight) { this.docScorer = docScorer; chunkStates = new ChunkState[postings.Length]; endMinus1 = postings.Length - 1; // min(cost) cost = postings[0].postings.GetCost(); for (int i = 0; i < postings.Length; i++) { // Coarse optimization: advance(target) is fairly // costly, so, if the relative freq of the 2nd // rarest term is not that much (> 1/5th) rarer than // the first term, then we just use .nextDoc() when // ANDing. this buys ~15% gain for phrases where // freq of rarest 2 terms is close: bool useAdvance = postings[i].docFreq > 5 * postings[0].docFreq; chunkStates[i] = new ChunkState(postings[i].postings, -postings[i].position, useAdvance); if (i > 0 && postings[i].postings.NextDoc() == DocIdSetIterator.NO_MORE_DOCS) { noDocs = true; return; } } } public override int NextDoc() { while (true) { // first (rarest) term int doc = chunkStates[0].PosEnum.NextDoc(); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = doc; return doc; } // not-first terms int i = 1; while (i < chunkStates.Length) { ChunkState cs = chunkStates[i]; int doc2 = cs.PosEnum.DocID; if (cs.UseAdvance) { if (doc2 < doc) { doc2 = cs.PosEnum.Advance(doc); } } else { int iter = 0; while (doc2 < doc) { // safety net -- fallback to .advance if we've // done too many .nextDocs if (++iter == 50) { doc2 = cs.PosEnum.Advance(doc); break; } else { doc2 = cs.PosEnum.NextDoc(); } } } if (doc2 > doc) { break; } i++; } if (i == chunkStates.Length) { // this doc has all the terms -- now test whether // phrase occurs docID = doc; freq = PhraseFreq(); if (freq != 0) { return docID; } } } } public override int Advance(int target) { // first term int doc = chunkStates[0].PosEnum.Advance(target); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = DocIdSetIterator.NO_MORE_DOCS; return doc; } while (true) { // not-first terms int i = 1; while (i < chunkStates.Length) { int doc2 = chunkStates[i].PosEnum.DocID; if (doc2 < doc) { doc2 = chunkStates[i].PosEnum.Advance(doc); } if (doc2 > doc) { break; } i++; } if (i == chunkStates.Length) { // this doc has all the terms -- now test whether // phrase occurs docID = doc; freq = PhraseFreq(); if (freq != 0) { return docID; } } doc = chunkStates[0].PosEnum.NextDoc(); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = doc; return doc; } } } public override string ToString() { return "ExactPhraseScorer(" + m_weight + ")"; } public override int Freq => freq; public override int DocID => docID; public override float GetScore() { return docScorer.Score(docID, freq); } private int PhraseFreq() { freq = 0; // init chunks for (int i = 0; i < chunkStates.Length; i++) { ChunkState cs = chunkStates[i]; cs.PosLimit = cs.PosEnum.Freq; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); cs.PosUpto = 1; cs.LastPos = -1; } int chunkStart = 0; int chunkEnd = CHUNK; // process chunk by chunk bool end = false; // TODO: we could fold in chunkStart into offset and // save one subtract per pos incr while (!end) { gen++; if (gen == 0) { // wraparound Arrays.Fill(gens, 0); gen++; } // first term { ChunkState cs = chunkStates[0]; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; counts[posIndex] = 1; if (Debugging.AssertsEnabled) Debugging.Assert(gens[posIndex] != gen); gens[posIndex] = gen; } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } } // middle terms bool any = true; for (int t = 1; t < endMinus1; t++) { ChunkState cs = chunkStates[t]; any = false; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; if (posIndex >= 0 && gens[posIndex] == gen && counts[posIndex] == t) { // viable counts[posIndex]++; any = true; } } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } if (!any) { break; } } if (!any) { // petered out for this chunk chunkStart += CHUNK; chunkEnd += CHUNK; continue; } // last term { ChunkState cs = chunkStates[endMinus1]; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; if (posIndex >= 0 && gens[posIndex] == gen && counts[posIndex] == endMinus1) { freq++; } } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } } chunkStart += CHUNK; chunkEnd += CHUNK; } return freq; } public override long GetCost() { return cost; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Reflection; namespace AgentManagerNamespace { public class Layer: IComparable<Layer> { #region PUBLIC_MEMBER_VARIABLES #endregion // PUBLIC_MEMBER_VARIABLES #region PRIVATE_MEMBER_VARIABLES // Layer Id private int _id; private List<State> _states = new List<State> (); private State _currentState; private int _masked; private bool _enabled = false; private State _initialState; #endregion // PRIVATE_MEMBER_VARIABLES #region GETTERS_AND_SETTERS_METHODS //! Layer Id public int Id { get { return _id; } } //! Initial state in this Layer public State InitialState { get { return _initialState; } set { _initialState = value; } } /// Enables the Layer for working. public bool Enabled { get { return _enabled; } set { if (!_enabled && value) { CurrentState = InitialState; foreach (State state in _states) { state.Start (); } } if (_enabled && !value) { CurrentState = null; } _enabled = value; } } /// Agent that contains this state. public Agent Agent { get; set; } /// Current state public State CurrentState { get { return _currentState; } set { if (_currentState != value) { if (_currentState != null) _currentState.DeactivateState (); _currentState = value; if (_currentState != null) _currentState.ActivateState (); } } } /// Lock a state until its ended. public bool LockedState { get; set; } #endregion // GETTERS_AND_SETTERS_METHODS #region UNTIY_MONOBEHAVIOUR_METHODS #endregion // UNTIY_MONOBEHAVIOUR_METHODS #region PUBLIC_METHODS /** \brief Creates a Layer object. * * @param layerId Id of the Layer. */ public Layer (int layerId) { _id = layerId; } /** \brief Equality between Layer and Object. * * @param obj Object to compare with. */ public override bool Equals (object obj) { if (obj == null) return false; Layer layer = obj as Layer; if (layer == null) return false; else return Equals (layer); } /** \brief Equality between Layers. * * @param layer Layer to compare with. */ public bool Equals (Layer layer) { if (layer == null) return false; return (this.Id.Equals (layer.Id)); } /** \brief Comparation between Layers, sorted in decreassing order. * * @param layer Layer to compare with. */ public int CompareTo (Layer compareLayer) { // A null value means that this object is greater. if (compareLayer == null) return 1; else return compareLayer._id.CompareTo (this._id); } /** @brief Add an State to the Layer. * * @param state State object to be added. * @return Returns true if the addition has been successfully done. */ public bool AddState (State state) { // Check if this state alreary exists. if (_states.Contains (state)) { Debug.LogWarningFormat ("The state {0} does already exist in the layer {1}.", state.Name, _id); return false; } state.Layer = this; _states.Add (state); // By default the first state is the initial state. if (_states.Count == 1) { InitialState = state; } return true; } /** @brief Remove an State from the Layer. * * @param state State object to be removed. * @return Returns true if the state has been successfully removed. */ public bool RemoveState (State state) { if (state == InitialState) { if (_states.Count > 0) { if (_states [0] != state) InitialState = _states [0]; else if (_states.Count > 1) { InitialState = _states [1]; } else { InitialState = null; } } else { InitialState = null; } } return _states.Remove (state); } /** @brief Find an State by name * * @param stateName Name of the State to be found * @return The Agent found of null if this Layer has not the agent searched */ public State FindState (string stateName) { return _states.Find (state => state.Name.Equals (stateName)); } /** @brief Check if this Layer contains an State by name * * @param stateName Name of the State to be found. * @return True if this Layer contains this State. */ public bool ContainsState (string stateName) { return FindState (stateName) != null; } /** @brief Add a transition between two states. * * @param originStateName The name of the State to transitate from. * @param targetStateName The name of the State to transitate to. * @param trigget Trigger that determinates when to transitate. * @param priotity The prority to be actived. * @return A reference to the transition created. */ public Transition AddTransition (string originStateName, string targetStateName, TransitionTrigger trigger, int priority = 0) { // Check if the states exist. State originState = FindState (originStateName); if (originState == null) { Debug.LogWarningFormat ("The state {0} does not exist in layer {1}.", originStateName, _id); return null; } State targetState = FindState (targetStateName); if (targetState == null) { Debug.LogWarningFormat ("The state {0} does not exist in layer {1}.", targetStateName, _id); return null; } return originState.AddTransition (targetState, trigger, priority); } public void ActiveInterruptingState (State interruptingState, object value, Agent sender = null) { CurrentState = interruptingState; CurrentState.SendInterruptingMsg (value, sender); } public void SendStandarMessage (State state, object value, Agent sender = null) { state.SendStandardMsg (value, sender); } public void Mask () { if (_masked == 0) { foreach (State state in _states) { state.Mask (); } Enabled = false; } _masked++; } public void Unmask () { if (_masked == 1) { Enabled = true; foreach (State state in _states) { state.Unmask (); } } _masked--; } //! Updates the State of the Layer public void Update () { if (Enabled) { if (!LockedState) { Transition activedTransition = CurrentState.GetActivedTransition (); if (activedTransition != null) { CurrentState = activedTransition.TargetState; } } CurrentState.Update (); } } #endregion // PUBLIC_METHODS #region PRIVATE_METHODS #endregion // PRIVATE_METHODS } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Security.Permissions; using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StringInfo { [OptionalField(VersionAdded = 2)] private String m_str; // We allow this class to be serialized but there is no conceivable reason // for them to do so. Thus, we do not serialize the instance variables. [NonSerialized] private int[] m_indexes; // Legacy constructor public StringInfo() : this(""){} // Primary, useful constructor public StringInfo(String value) { this.String = value; } #region Serialization [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { m_str = String.Empty; } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (m_str.Length == 0) { m_indexes = null; } } #endregion Serialization [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals(Object value) { StringInfo that = value as StringInfo; if (that != null) { return (this.m_str.Equals(that.m_str)); } return (false); } [System.Runtime.InteropServices.ComVisible(false)] public override int GetHashCode() { return this.m_str.GetHashCode(); } // Our zero-based array of index values into the string. Initialize if // our private array is not yet, in fact, initialized. private int[] Indexes { get { if((null == this.m_indexes) && (0 < this.String.Length)) { this.m_indexes = StringInfo.ParseCombiningCharacters(this.String); } return(this.m_indexes); } } public String String { get { return(this.m_str); } set { if (null == value) { throw new ArgumentNullException(nameof(String), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); this.m_str = value; this.m_indexes = null; } } public int LengthInTextElements { get { if(null == this.Indexes) { // Indexes not initialized, so assume length zero return(0); } return(this.Indexes.Length); } } public String SubstringByTextElements(int startingTextElement) { // If the string is empty, no sense going further. if(null == this.Indexes) { // Just decide which error to give depending on the param they gave us.... if(startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } else { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } } return (this.SubstringByTextElements(startingTextElement, this.Indexes.Length - startingTextElement)); } public String SubstringByTextElements(int startingTextElement, int lengthInTextElements) { // // Parameter checking // if(startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } if(lengthInTextElements < 0) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(startingTextElement > this.Indexes.Length - lengthInTextElements) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } int start = this.Indexes[startingTextElement]; if(startingTextElement + lengthInTextElements == this.Indexes.Length) { // We are at the last text element in the string and because of that // must handle the call differently. return(this.String.Substring(start)); } else { return(this.String.Substring(start, (this.Indexes[lengthInTextElements + startingTextElement] - start))); } } public static String GetNextTextElement(String str) { return (GetNextTextElement(str, 0)); } //////////////////////////////////////////////////////////////////////// // // Get the code point count of the current text element. // // A combining class is defined as: // A character/surrogate that has the following Unicode category: // * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT) // * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA) // * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE) // // In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as: // // 1. If a character/surrogate is in the following category, it is a text element. // It can NOT further combine with characters in the combinging class to form a text element. // * one of the Unicode category in the combinging class // * UnicodeCategory.Format // * UnicodeCateogry.Control // * UnicodeCategory.OtherNotAssigned // 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element. // // Return: // The length of the current text element // // Parameters: // String str // index The starting index // len The total length of str (to define the upper boundary) // ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element. // currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element. // //////////////////////////////////////////////////////////////////////// internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. return (currentCharCount); } // Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not. int nextCharCount; UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount); if (CharUnicodeInfo.IsCombiningCategory(ucNext)) { // The next element is a combining class. // Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category, // not a format character, and not a control character). if (CharUnicodeInfo.IsCombiningCategory(ucCurrent) || (ucCurrent == UnicodeCategory.Format) || (ucCurrent == UnicodeCategory.Control) || (ucCurrent == UnicodeCategory.OtherNotAssigned) || (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate { // Will fall thru and return the currentCharCount } else { int startIndex = index; // Remember the current index. // We have a valid base characters, and we have a character (or surrogate) that is combining. // Check if there are more combining characters to follow. // Check if the next character is a nonspacing character. index += currentCharCount + nextCharCount; while (index < len) { ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount); if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) { ucCurrent = ucNext; currentCharCount = nextCharCount; break; } index += nextCharCount; } return (index - startIndex); } } // The return value will be the currentCharCount. int ret = currentCharCount; ucCurrent = ucNext; // Update currentCharCount. currentCharCount = nextCharCount; return (ret); } // Returns the str containing the next text element in str starting at // index index. If index is not supplied, then it will start at the beginning // of str. It recognizes a base character plus one or more combining // characters or a properly formed surrogate pair as a text element. See also // the ParseCombiningCharacters() and the ParseSurrogates() methods. public static String GetNextTextElement(String str, int index) { // // Validate parameters. // if (str==null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || index >= len) { if (index == len) { return (String.Empty); } throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } int charLen; UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen); return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen))); } public static TextElementEnumerator GetTextElementEnumerator(String str) { return (GetTextElementEnumerator(str, 0)); } public static TextElementEnumerator GetTextElementEnumerator(String str, int index) { // // Validate parameters. // if (str==null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || (index > len)) { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } return (new TextElementEnumerator(str, index, len)); } /* * Returns the indices of each base character or properly formed surrogate pair * within the str. It recognizes a base character plus one or more combining * characters or a properly formed surrogate pair as a text element and returns * the index of the base character or high surrogate. Each index is the * beginning of a text element within a str. The length of each element is * easily computed as the difference between successive indices. The length of * the array will always be less than or equal to the length of the str. For * example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would * return the indices: 0, 2, 4. */ public static int[] ParseCombiningCharacters(String str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; int[] result = new int[len]; if (len == 0) { return (result); } int resultCount = 0; int i = 0; int currentCharLen; UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen); while (i < len) { result[resultCount++] = i; i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen); } if (resultCount < len) { int[] returnArray = new int[resultCount]; Array.Copy(result, returnArray, resultCount); return (returnArray); } return (result); } } }
using System; using System.IO; using System.IO.Compression; using System.Threading.Tasks; using System.Collections; using ExcelDataReader.Portable.Async; using ExcelDataReader.Portable.IO; using ExcelDataReader.Portable.IO.PCLStorage; using ExcelDataReader.Portable.Log; using PCLStorage; namespace ExcelDataReader.Portable.Core { public class ZipWorker : IExcelWorker { private readonly IFileSystem fileSystem; private readonly IFileHelper fileHelper; #region Members and Properties private byte[] buffer; private bool disposed; private bool isCleaned; private const string TMP = "TMP_Z"; private const string FOLDER_xl = "xl"; private const string FOLDER_worksheets = "worksheets"; private const string FILE_sharedStrings = "sharedStrings.{0}"; private const string FILE_styles = "styles.{0}"; private const string FILE_workbook = "workbook.{0}"; private const string FILE_sheet = "sheet{0}.{1}"; private const string FOLDER_rels = "_rels"; private const string FILE_rels = "workbook.{0}.rels"; private string tempPath; private string exceptionMessage; private string xlPath; private string format = "xml"; private bool isValid; private string folderName; private IFolder rootFolder; //private bool _isBinary12Format; /// <summary> /// Gets a value indicating whether this instance is valid. /// </summary> /// <value><c>true</c> if this instance is valid; otherwise, <c>false</c>.</value> public bool IsValid { get { return isValid; } } /// <summary> /// Gets the temp path for extracted files. /// </summary> /// <value>The temp path for extracted files.</value> public string TempPath { get { return tempPath; } } /// <summary> /// Gets the exception message. /// </summary> /// <value>The exception message.</value> public string ExceptionMessage { get { return exceptionMessage; } } #endregion public ZipWorker(IFileSystem fileSystem, IFileHelper fileHelper) { this.fileSystem = fileSystem; this.fileHelper = fileHelper; } /// <summary> /// Extracts the specified zip file stream. /// </summary> /// <param name="fileStream">The zip file stream.</param> /// <returns></returns> public async Task<bool> Extract(Stream fileStream) { if (null == fileStream) return false; await CleanFromTempAsync(false); await NewTempPath(); isValid = true; ZipArchive zipFile = null; try { zipFile = new ZipArchive(fileStream); IEnumerator enumerator = zipFile.Entries.GetEnumerator(); while (enumerator.MoveNext()) { var entry = (ZipArchiveEntry) enumerator.Current; await ExtractZipEntry(zipFile, entry); } } catch (InvalidDataException ex) { isValid = false; exceptionMessage = ex.Message; CleanFromTemp(true); } catch (Exception ex) { CleanFromTemp(true); //true tells CleanFromTemp not to raise an IO Exception if this operation fails. If it did then the real error here would be masked throw; } finally { fileStream.Dispose(); if (null != zipFile) zipFile.Dispose(); } return isValid && await CheckFolderTree(); } /// <summary> /// Gets the shared strings stream. /// </summary> /// <returns></returns> public async Task<Stream> GetSharedStringsStream() { return await GetStream(Path.Combine(xlPath, string.Format(FILE_sharedStrings, format))); } /// <summary> /// Gets the styles stream. /// </summary> /// <returns></returns> public async Task<Stream> GetStylesStream() { return await GetStream(Path.Combine(xlPath, string.Format(FILE_styles, format))); } /// <summary> /// Gets the workbook stream. /// </summary> /// <returns></returns> public async Task<Stream> GetWorkbookStream() { return await GetStream(Path.Combine(xlPath, string.Format(FILE_workbook, format))); } /// <summary> /// Gets the worksheet stream. /// </summary> /// <param name="sheetId">The sheet id.</param> /// <returns></returns> public async Task<Stream> GetWorksheetStream(int sheetId) { return await GetStream(Path.Combine( Path.Combine(xlPath, FOLDER_worksheets), string.Format(FILE_sheet, sheetId, format))); } public async Task<Stream> GetWorksheetStream(string sheetPath) { //its possible sheetPath starts with /xl. in this case trim the /xl if (sheetPath.StartsWith("/xl/")) sheetPath = sheetPath.Substring(4); return await GetStream(Path.Combine(xlPath, sheetPath)); } /// <summary> /// Gets the workbook rels stream. /// </summary> /// <returns></returns> public async Task<Stream> GetWorkbookRelsStream() { return await GetStream(Path.Combine(xlPath, Path.Combine(FOLDER_rels, string.Format(FILE_rels, format)))); } private async Task CleanFromTempAsync(bool catchIoError) { if (string.IsNullOrEmpty(tempPath)) return; isCleaned = true; try { var exists = await fileSystem.LocalStorage.CheckExistsAsync(tempPath); if (exists == ExistenceCheckResult.FolderExists) { var dir = await fileSystem.GetFolderFromPathAsync(tempPath); await dir.DeleteFolderAndContentsAsync(); } } catch (IOException ex) { this.Log().Error(ex.Message); if (!catchIoError) throw; } } private void CleanFromTemp(bool catchIoError) { //todo: not sure about this because CleanFromTemp can get called in Exception handling and dispose //I think it's ok because we wait for it here AsyncHelper.RunSync(() => CleanFromTempAsync(catchIoError)); } private async Task ExtractZipEntry(ZipArchive zipFile, ZipArchiveEntry entry) { if (string.IsNullOrEmpty(entry.Name)) return; string tPath = Path.Combine(tempPath, entry.Name); //string path = entry..IsDirectory ? tPath : Path.GetDirectoryName(Path.GetFullPath(tPath)); var containingDirectoryName = Path.GetDirectoryName(entry.FullName); IFolder containingFolder = null; //get or create containing directory if (string.IsNullOrEmpty(containingDirectoryName)) { containingFolder = rootFolder; } else { //this is a sub folder so make sure it is created var folderExists = await rootFolder.CheckExistsAsync(containingDirectoryName); if (folderExists == ExistenceCheckResult.NotFound) { await rootFolder.CreateFolderAsync(containingDirectoryName, CreationCollisionOption.ReplaceExisting); } //get reference to the folder containingFolder = await rootFolder.GetFolderAsync(containingDirectoryName); } //create the file var fileExists = await containingFolder.CheckExistsAsync(entry.Name); if (fileExists == ExistenceCheckResult.NotFound) { await containingFolder.CreateFileAsync(entry.Name, CreationCollisionOption.ReplaceExisting); } var file = await containingFolder.GetFileAsync(entry.Name); using (var stream = await file.OpenAsync(FileAccess.ReadAndWrite)) { if (buffer == null) { buffer = new byte[0x1000]; } using(var inputStream = entry.Open()) { int count; while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, count); } } stream.Flush(); } } private async Task NewTempPath() { var tempID = Guid.NewGuid().ToString("N"); folderName = TMP + DateTime.Now.ToFileTimeUtc().ToString() + tempID; tempPath = Path.Combine(fileHelper.GetTempPath(), folderName); //ensure root folder created var rootExists = await fileSystem.LocalStorage.CheckExistsAsync(tempPath); if (rootExists == ExistenceCheckResult.NotFound) { await fileSystem.LocalStorage.CreateFolderAsync(tempPath, CreationCollisionOption.ReplaceExisting); } rootFolder = await fileSystem.GetFolderFromPathAsync(tempPath); isCleaned = false; this.Log().Debug("Using temp path {0}", tempPath); } private async Task<bool> CheckFolderTree() { xlPath = Path.Combine(tempPath, FOLDER_xl); var existsXlPath = await fileSystem.LocalStorage.CheckExistsAsync(xlPath) == ExistenceCheckResult.FolderExists; var existsWorksheetPath = await fileSystem.LocalStorage.CheckExistsAsync(Path.Combine(xlPath, FOLDER_worksheets)) == ExistenceCheckResult.FolderExists; var existsWorkbook = await fileSystem.LocalStorage.CheckExistsAsync(Path.Combine(xlPath, FILE_workbook)) == ExistenceCheckResult.FileExists; var existsStyles = await fileSystem.LocalStorage.CheckExistsAsync(Path.Combine(xlPath, FILE_styles)) == ExistenceCheckResult.FileExists; return existsXlPath && existsWorksheetPath && existsWorkbook && existsStyles; } private async Task<Stream> GetStream(string filePath) { var fileExists = await fileSystem.LocalStorage.CheckExistsAsync(filePath) == ExistenceCheckResult.FileExists; if (fileExists) { var file = await fileSystem.GetFileFromPathAsync(filePath); return await file.OpenAsync(FileAccess.Read); } else { return null; } } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { if (!isCleaned) CleanFromTemp(false); } buffer = null; disposed = true; } } ~ZipWorker() { Dispose(false); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text.RegularExpressions; using System.Windows.Forms; using bv.common; using bv.common.Configuration; using bv.common.Core; using bv.common.db; using bv.common.db.Core; using bv.common.Diagnostics; using bv.common.Enums; using bv.common.win; using bv.common.win.BaseForms; using bv.winclient.BasePanel; using bv.winclient.Core; using bv.winclient.Core.TranslationTool; using bv.winclient.Layout; using DevExpress.XtraBars; using DevExpress.XtraPivotGrid; using DevExpress.XtraPivotGrid.Localization; using DevExpress.XtraTab; using eidss.avr.BaseComponents; using eidss.avr.db.AvrEventArgs.AvrEventArgs; using eidss.avr.db.Common; using eidss.avr.db.Common.CommandProcessing.Commands.Export; using eidss.avr.db.DBService; using eidss.avr.db.Interfaces; using eidss.avr.Handlers.AvrEventArgs; using eidss.avr.LayoutForm; using eidss.avr.PivotComponents; using eidss.avr.QueryBuilder; using eidss.model.Avr.Commands; using eidss.model.Avr.Commands.Export; using eidss.model.Avr.Commands.Layout; using eidss.model.Avr.Commands.Models; using eidss.model.Avr.Commands.Print; using eidss.model.Avr.Commands.Refresh; using eidss.model.AVR.Db; using eidss.model.Avr.Tree; using eidss.model.Core; using eidss.model.Enums; using eidss.model.Reports.OperationContext; using eidss.model.Resources; using eidss.model.Schema; using eidss.winclient; namespace eidss.avr.MainForm { public partial class AvrMainForm : BaseAvrForm, IAvrMainFormView { private const int PublishQueryIndex = 74; private const int PublishLayoutIndex = 73; private const int PublishFolderIndex = 72; private const int UnpublishQueryIndex = 78; private const int UnpublishLayoutIndex = 77; private const int UnpublishFolderIndex = 76; private static readonly object m_SyncRoot = new object(); private bool m_QueryWasUpdated; private readonly BaseAvrDbService m_AvrDbService; public event EventHandler<CommandEventArgs> SendCommand; private AvrMainFormPresenter m_AvrMainFormPresenter; private SharedPresenter m_SharedPresenter; private readonly Dictionary<BarCheckItem, PivotGroupInterval> m_MenuGroupIntervals = new Dictionary<BarCheckItem, PivotGroupInterval>(); private TranslationButton m_TranslationButton; #region Construction & Dispose public AvrMainForm() { try { Trace.WriteLine(Trace.Kind.Info, "AvrMainForm(): AvrMainForm creating..."); // Note: [Ivan] init model factory for each copy of AvrMainForm. // when next copy of AvrMainForm created, //previous copy already inited so they does not need ModelFactory lock (m_SyncRoot) { PresenterFactory.Init(this); m_SharedPresenter = PresenterFactory.SharedPresenter; } m_AvrMainFormPresenter = (AvrMainFormPresenter) m_SharedPresenter[this]; InitializeComponent(); if (IsDesignMode()) { return; } if (BaseSettings.TranslationMode) { m_TranslationButton = new TranslationButton(); m_TranslationButton.Top = Height - m_TranslationButton.Height; m_TranslationButton.Left = Width - m_TranslationButton.Width - 4; m_TranslationButton.Parent = this; m_TranslationButton.Anchor = AnchorStyles.Right | AnchorStyles.Bottom; m_TranslationButton.BringToFront(); } m_AvrDbService = new BaseAvrDbService(); DbService = m_AvrDbService; RegisterChildObject(QueryLayoutTree, RelatedPostOrder.PostLast); QueryLayoutTree.OnElementSelect += QueryLayoutTree_OnElementSelect; QueryLayoutTree.OnElementEdit += QueryLayoutTree_OnElementEdit; QueryLayoutTree.OnElementPopup += QueryLayoutTree_OnElementPopup; biSettings.Visibility = AvrPermissions.AccessToAVRAdministrationPermission ? BarItemVisibility.Always : BarItemVisibility.Never; PivotGridFieldBase.DefaultTotalFormat.FormatString = PivotGridLocalizer.GetString(PivotGridStringId.TotalFormat); } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing"> true if managed resources should be disposed; otherwise, false. </param> protected override void Dispose(bool disposing) { try { LayoutCorrector.Reset(); DisposeLayoutDetails(); DisposeQueryDetails(); eventManager.ClearAllReferences(); if (disposing && (components != null)) { components.Dispose(); } if (m_AvrMainFormPresenter != null) { m_AvrMainFormPresenter.Dispose(); m_AvrMainFormPresenter = null; } if (m_SharedPresenter != null) { lock (m_SyncRoot) { PresenterFactory.RemovePresenterLink(m_SharedPresenter); } m_SharedPresenter.UnregisterView(this); m_SharedPresenter.Dispose(); m_SharedPresenter = null; } } finally { base.Dispose(disposing); } } #endregion #region Properties [Browsable(false)] public DataSet BaseDataSet { get { return baseDataSet; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] private bool TreeOpened { get { return TabControl.SelectedTabPage == TabPageTree; } set { TabControl.SelectedTabPage = value ? TabPageTree : TabPageEditor; } } [Browsable(false)] private bool IsQueryOpened { get { return queryDetail != null; } } [Browsable(false)] private bool IsLayoutOpened { get { return layoutDetail != null; } } [Browsable(false)] private bool IsViewPageSelected { get { return (IsLayoutOpened && layoutDetail.IsViewPageSelected); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override Dictionary<string, object> StartUpParameters { get { return base.StartUpParameters; } set { base.StartUpParameters = value; m_SharedPresenter.SharedModel.StartUpParameters = value; } } #endregion #region Init internal void InitLayoutDetail(bool isNewObject) { TabPageEditor.Text = EidssMessages.Get("msgPivotAndView", "Pivot and View"); if (layoutDetail != null) { return; } layoutDetail = new LayoutDetailPanel { Location = new Point(0, 0), Size = new Size(EditorPanel.Width, EditorPanel.Height), Dock = DockStyle.Fill, IgnoreAudit = true }; if (isNewObject) { layoutDetail.SelectInfoTabWithoutRefresh(); } layoutDetail.Appearance.Options.UseFont = true; EditorPanel.Controls.Add(layoutDetail); RegisterChildObject(layoutDetail, RelatedPostOrder.PostLast); layoutDetail.LayoutTabChanged += LayoutDetailLayoutTabChanged; layoutDetail.PivotFieldMouseRightClick += layoutDetail_PivotFieldMouseRightClick; } private void InitQueryDetail() { TabPageEditor.Text = EidssMessages.Get("msgQuery", "Query"); if (queryDetail != null) { return; } queryDetail = new QueryDetailPanel { Location = new Point(0, 0), Size = new Size(EditorPanel.Width, EditorPanel.Height), Dock = DockStyle.Fill, Visible = true, }; EditorPanel.Controls.Add(queryDetail); RegisterChildObject(queryDetail, RelatedPostOrder.PostLast); } private void DisposeLayoutDetails() { if (layoutDetail != null) { layoutDetail.Hide(); UnRegisterChildObject(layoutDetail); m_SharedPresenter.UnregisterView(layoutDetail); AvrPivotGridData oldDataSource = layoutDetail.PivotDetailView.DataSource; if (oldDataSource != null) { oldDataSource.Dispose(); } layoutDetail.Dispose(); layoutDetail = null; m_SharedPresenter.SharedModel.SelectedLayoutId = -1; ChangeFormCaption(new AvrTreeSelectedElementEventArgs()); } } private void DisposeQueryDetails() { if (queryDetail != null) { queryDetail.Hide(); UnRegisterChildObject(queryDetail); m_SharedPresenter.UnregisterView(queryDetail); queryDetail.Dispose(); queryDetail = null; m_SharedPresenter.SharedModel.SelectedQueryId = -1; ChangeFormCaption(new AvrTreeSelectedElementEventArgs()); } } protected override void AfterLoad() { try { if (BaseAvrPresenter.WinCheckAvrServiceAccessability()) { using (m_SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.AfterLoad)) { biExport.Enabled = EidssUserContext.User.HasPermission(PermissionHelper.ExecutePermission(EIDSSPermissionObject.CanImportExportData)); InitPopupMenu(); OpenStandardreportIfNeeded(); } } else { CloseTimer.Start(); } } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } private void CloseTimer_Tick(object sender, EventArgs e) { CloseTimer.Stop(); DoClose(); } private void InitPopupMenu() { int i = 1; foreach (KeyValuePair<long, string> pair in GroupIntervalHelper.GetGroupIntervalLookup()) { var groupDate = new BarCheckItem(); barManager.Items.Add(groupDate); bsGroupDate.LinksPersistInfo.Add(new LinkPersistInfo(groupDate)); groupDate.Caption = pair.Value; groupDate.Visibility = BarItemVisibility.Always; groupDate.Name = "bcGroupDate_" + i; i++; groupDate.CheckedChanged += bcGroupDate_CheckedChanged; PivotGroupInterval interval = GroupIntervalHelper.GetGroupInterval(pair.Key); m_MenuGroupIntervals.Add(groupDate, interval); } } private void OpenStandardreportIfNeeded() { if (StartUpParameters != null && StartUpParameters.ContainsKey(SharedProperty.StandardReports.ToString())) { m_SharedPresenter.SharedModel.StandardReports = true; TreeOpened = false; object layoutObjId; long layoutId; if (m_SharedPresenter.TryGetStartUpParameter("LayoutId", out layoutObjId) && long.TryParse(Utils.Str(layoutObjId), out layoutId)) { AvrLayoutLookup foundLayout = AvrLayoutLookup.GetAvrLayoutLookupById(layoutId); if (foundLayout != null) { var args = new AvrTreeSelectedElementEventArgs(foundLayout.idflQuery, foundLayout.idflLayout, foundLayout.idflFolder ?? foundLayout.idflQuery, foundLayout.idflFolder ?? -1, AvrTreeElementType.Layout, string.Empty); OpenLayoutEditor(args); // layoutDetail.SelectViewTabWithoutRefresh(); } } } } private void AVRReportControl_Load(object sender, EventArgs e) { UpdateFont(barMenu.LinksPersistInfo, WinClientContext.CurrentFont); if (Parent != null) { Parent.MinimumSize = new Size(600, 600); } } private static void UpdateFont(LinksInfo linksInfo, Font font) { foreach (LinkPersistInfo link in linksInfo) { link.Item.Appearance.Font = font; var container = link.Item as BarLinkContainerItem; if (container != null) { UpdateFont(container.LinksPersistInfo, font); } } } public override object GetChildKey(IRelatedObject child) { if (child is LayoutDetailPanel) { return ((LayoutDetailPanel) child).GetKey(); } if (child is QueryDetailPanel) { return ((QueryDetailPanel) child).GetKey(); } return null; } public override object GetKey(string tableName = null, string keyFieldName = null) { if (IsLayoutOpened) { return layoutDetail.GetKey(tableName, keyFieldName); } if (IsQueryOpened) { return queryDetail.GetKey(tableName, keyFieldName); } return null; } public static void Register(Control parentControl) { Utils.CheckNotNull(parentControl, "parentControl"); try { if (!BaseFormManager.ArchiveMode) { new MenuAction(ShowMe, MenuActionManager.Instance, MenuActionManager.Instance.AVR, "MenuLaunchRAM", 1000, false, (int) MenuIconsSmall.LaunchAVR) { Name = "btnRAM", SelectPermission = PermissionHelper.SelectPermission(EIDSSPermissionObject.AVRReport) }; WinMenuReportRegistrator.RegisterAllAvrReports(MenuActionManager.Instance, ShowStandardReport); } } catch (Exception ex) { Dbg.Debug("error during loading registering RAM menu, {0}", ex); if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } private static void ShowStandardReport(IMenuAction action) { try { using (CreateWaitDialog()) { var startupParams = new Dictionary<string, object> { {"StandardReports", true} }; //startupParams.Add("ShowAll", false); Match match = Regex.Match(action.Name, @"btnStandardReport_(?<QueryId>\d+)_(?<LayoutId>\d+)_"); Group queryGroup = match.Groups["QueryId"]; long queryId; if (queryGroup.Success && queryGroup.Captures.Count == 1 && Int64.TryParse(queryGroup.Captures[0].Value, out queryId)) { startupParams.Add("QueryId", queryId); } Group layoutGroup = match.Groups["LayoutId"]; long layoutId; object id = null; if (layoutGroup.Success && layoutGroup.Captures.Count == 1 && Int64.TryParse(layoutGroup.Captures[0].Value, out layoutId)) { startupParams.Add("LayoutId", layoutId); id = layoutId; } var avrForm = new AvrMainForm(); BaseFormManager.ShowNormal(avrForm, ref id, startupParams); if (avrForm.ParentForm != null) { avrForm.ParentForm.MinimumSize = avrForm.MinimumSize; } } } catch (Exception ex) { Dbg.Debug("error during showing RAM control for layout {0}: {1}", action.Caption, ex); if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } private static int CompareForm(IApplicationForm form, object x) { if (form.StartUpParameters == null || !form.StartUpParameters.ContainsKey(SharedProperty.StandardReports.ToString())) { return 0; } return -1; } private static void ShowMe() { try { using (CreateWaitDialog()) { var found = BaseFormManager.FindForm(typeof (AvrMainForm), null, CompareForm) as AvrMainForm; if (found == null) { object key = -1; var avrForm = new AvrMainForm(); BaseFormManager.ShowNormal(avrForm, ref key); if (avrForm.ParentForm != null) { avrForm.ParentForm.MinimumSize = avrForm.MinimumSize; } } } } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } private static WaitDialog CreateWaitDialog() { string title = EidssMessages.Get("msgPleaseWait"); string caption = EidssMessages.Get("msgAvrInitializing"); return new WaitDialog(caption, title); } #endregion #region Post protected override BaseAvrDetailPanel GetChildForPost() { if (IsLayoutOpened) { return layoutDetail; } if (IsQueryOpened) { return queryDetail; } return null; } public override bool Post(PostType postType = PostType.FinalPosting) { // if user hasn't update permission - no need to save if (!AvrPermissions.UpdatePermission) { return true; } try { bool isPost; using (m_SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.Post)) { if (Utils.IsCalledFromUnitTest()) { m_ClosingMode = BaseDetailForm.ClosingMode.Ok; } // No need to Post if call this code from unit-tests isPost = Utils.IsCalledFromUnitTest() || base.Post(postType); object key = GetKey(); if (isPost && key is long) { AvrTreeElementType type = IsLayoutOpened ? AvrTreeElementType.Layout : AvrTreeElementType.Query; QueryLayoutTree.ReloadQueryLayoutFolder((long) key, type); } } return isPost; } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); Trace.WriteLine(ex); return false; } } /// <summary> /// Call base post without any check. this method should be uses for debug purposes only /// </summary> /// <returns> </returns> internal bool ForcePost() { return base.Post(); } #endregion #region Delete query layout folder private void DeleteQueryLayoutFolder() { AvrTreeSelectedElementEventArgs args = QueryLayoutTree.GetTreeSelectedElementEventArgs(); switch (args.Type) { case AvrTreeElementType.Query: if (args.QueryId < 0) { throw new AvrException("Couldn't delete query because it's not selected"); } DeleteQueryLayout(args.QueryId, AvrTreeElementType.Query, true); break; case AvrTreeElementType.Layout: if (!args.ElementId.HasValue) { throw new AvrException("Couldn't delete layout because it's not selected"); } DeleteQueryLayout(args.ElementId.Value, AvrTreeElementType.Layout, true); //RaiseSendCommand(new LayoutCommand(this, LayoutOperation.Delete)); break; case AvrTreeElementType.Folder: QueryLayoutTree.DeleteFolder(); break; } } public void CloseQueryLayoutStart() { CloseQueryLayoutTimer.Start(); } private void CloseQueryLayoutTimer_Tick(object sender, EventArgs e) { CloseQueryLayoutTimer.Stop(); TreeOpened = true; DisposeLayoutDetails(); DisposeQueryDetails(); } public void DeleteQueryLayoutStart(QueryLayoutDeleteCommand deleteCommand) { DeleteQueryLayoutTimer.Tag = new QueryLayoutDeleteCommand(this, deleteCommand.ObjectId, deleteCommand.ObjectType); DeleteQueryLayoutTimer.Start(); } private void DeleteQueryLayoutTimer_Tick(object sender, EventArgs e) { DeleteQueryLayoutTimer.Stop(); var deleteCommand = DeleteQueryLayoutTimer.Tag as QueryLayoutDeleteCommand; if (deleteCommand != null && DeletePromptDialog() == DialogResult.Yes) { TreeOpened = true; DeleteQueryLayout(deleteCommand.ObjectId, deleteCommand.ObjectType); } } private void DeleteQueryLayout(long id, AvrTreeElementType objectType, bool needConfirmation = false) { try { if (needConfirmation && DeletePromptDialog() != DialogResult.Yes) { return; } string objectName = objectType == AvrTreeElementType.Query ? "Query" : "AsLayout"; if (m_AvrDbService.CanDelete(id, objectName)) { DisposeLayoutDetails(); DisposeQueryDetails(); if (!m_AvrDbService.Delete(id, objectName)) { ErrorMessage err = m_AvrDbService.LastError; throw new AvrException(err.Text + err.Exception); } if (objectType == AvrTreeElementType.Query) { LookupCache.NotifyDelete("Query", null, id); LookupCache.NotifyChange("Layout"); } else { LookupCache.NotifyDelete("Layout", null, id); } LookupCache.NotifyChange("LayoutFolder"); QueryLayoutTree.DeleteNodeWithId(id); } else { ErrorMessage err = m_AvrDbService.LastError; if (err != null) { throw new AvrException(err.Text + err.Exception); } ErrorForm.ShowMessage("msgCantDeleteRecord", "The record can't be deleted"); } } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } #endregion #region Tree Handlers private void TabControl_SelectedPageChanged(object sender, TabPageChangedEventArgs e) { QueryLayoutTree_OnElementSelect(sender, QueryLayoutTree.GetTreeSelectedElementEventArgs()); } private void QueryLayoutTree_OnElementSelect(object sender, AvrTreeSelectedElementEventArgs e) { try { bool insertPermission = AvrPermissions.InsertPermission; biNewQuery.Enabled = bbNewQuery.Enabled = bbPopupNewQuery.Enabled = insertPermission; biNewLayout.Enabled = bbNewLayout.Enabled = bbPopupNewLayout.Enabled = insertPermission && (TreeOpened || IsLayoutOpened); biNewFolder.Enabled = bbNewFolder.Enabled = bbPopupNewFolder.Enabled = insertPermission && TreeOpened; biCopyQueryLayout.Enabled = bbCopyQueryLayout.Enabled = bbPopupCopyQueryLayout.Enabled = insertPermission && (e.Type != AvrTreeElementType.Folder); biExportQuery.Enabled = true; biExportReport.Enabled = IsLayoutOpened; biPrintReport.Enabled = IsLayoutOpened; biEditQueryLayout.Enabled = bbEditQueryLayoutFolder.Enabled = bbPopupEditQueryLayoutFolder.Enabled = AvrPermissions.UpdatePermission && TreeOpened && !QueryLayoutTree.IsFocusedNodeReadOnly; biDeleteQueryLayoutFolder.Enabled = bbDeleteQueryLayoutFolder.Enabled = bbPopupDeleteQueryLayoutFolder.Enabled = AvrPermissions.DeletePermission && !QueryLayoutTree.IsFocusedNodeReadOnly; biPublishQueryLayoutFolder.Enabled = AvrPermissions.AccessToAVRAdministrationPermission && !QueryLayoutTree.IsFocusedNodeReadOnly; biUnpublishQueryLayoutFolder.Enabled = AvrPermissions.AccessToAVRAdministrationPermission && QueryLayoutTree.IsFocusedNodeReadOnly; switch (e.Type) { case AvrTreeElementType.Query: biPublishQueryLayoutFolder.ImageIndex = PublishQueryIndex; biUnpublishQueryLayoutFolder.ImageIndex = UnpublishQueryIndex; break; case AvrTreeElementType.Folder: biPublishQueryLayoutFolder.ImageIndex = PublishFolderIndex; biUnpublishQueryLayoutFolder.ImageIndex = UnpublishFolderIndex; break; case AvrTreeElementType.Layout: biPublishQueryLayoutFolder.ImageIndex = PublishLayoutIndex; biUnpublishQueryLayoutFolder.ImageIndex = UnpublishLayoutIndex; break; } } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } private void QueryLayoutTree_OnElementPopup(object sender, AvrTreeSelectedElementEventArgs e) { TreePopupMenu.ShowPopup(MousePosition); } private void QueryLayoutTree_OnElementEdit(object sender, AvrTreeSelectedElementEventArgs e) { OpenEditor(e); } internal void OpenEditor(AvrTreeSelectedElementEventArgs e, bool isNewObject = false) { try { if (!Loading && Post()) { using (m_SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.OpenEditor)) { m_AvrMainFormPresenter.SharedPresenter.SharedModel.SelectedFolderId = e.FolderId; if (e.Type == AvrTreeElementType.Folder) { QueryLayoutTree.EditFolder(e, isNewObject); } else { using (BaseAvrPresenter.CreateLoadingDialog()) { TreeOpened = false; if (e.Type == AvrTreeElementType.Query) { OpenQueryEditor(e, isNewObject); } else if (e.Type == AvrTreeElementType.Layout) { OpenLayoutEditor(e, isNewObject); } } } ChangeFormCaption(e); } if (BaseSettings.TranslationMode) { DesignControlManager.Create(this); } } } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } private void ChangeFormCaption(AvrTreeSelectedElementEventArgs e) { Form parentForm = FindForm(); if (parentForm != null) { var resources = new ComponentResourceManager(typeof (AvrMainForm)); string baseCaption = resources.GetString("$this.Caption"); parentForm.Text = string.IsNullOrEmpty(e.TreeElementPath) ? baseCaption : string.Format("{0} - {1}", baseCaption, e.TreeElementPath); } } private void OpenQueryEditor(AvrTreeSelectedElementEventArgs e, bool isNewObject = false) { DisposeQueryDetails(); InitQueryDetail(); queryDetail.OnAfterPost += queryDetail_OnAfterPost; object id = isNewObject ? null : (object) e.QueryId; queryDetail.LoadData(ref id); DisposeLayoutDetails(); m_SharedPresenter.SharedModel.SelectedLayoutId = -1; } private void queryDetail_OnAfterPost(object sender, EventArgs e) { queryDetail.OnAfterPost -= queryDetail_OnAfterPost; if (queryDetail.DbService != null && queryDetail.DbService.ID is long) { AvrMainFormPresenter.InvalidateQuery((long) queryDetail.DbService.ID); } m_QueryWasUpdated = true; } private void OpenLayoutEditor(AvrTreeSelectedElementEventArgs e, bool isNewObject = false) { bool newUseArchive = GetUseArchiveForOpeningLayout(e.ElementId, isNewObject); bool queryWasChanged = m_SharedPresenter.SharedModel.SelectedQueryId != e.QueryId; bool useArchiveChanged = newUseArchive != m_SharedPresenter.SharedModel.UseArchiveData; m_SharedPresenter.SharedModel.UseArchiveData = newUseArchive; DisposeLayoutDetails(); InitLayoutDetail(isNewObject); DisposeQueryDetails(); if ((m_QueryWasUpdated || queryWasChanged || useArchiveChanged) && e.QueryId > 0) { CheckAndTraceQuery(e); m_AvrMainFormPresenter.ExecQuery(e.QueryId); } m_QueryWasUpdated = false; m_SharedPresenter.SharedModel.SelectedQueryId = e.QueryId; if (isNewObject) { RaiseSendCommand(new QueryLayoutCommand(this, QueryLayoutOperation.NewLayout)); } else if (e.ElementId.HasValue) { m_SharedPresenter.SharedModel.SelectedLayoutId = e.ElementId.Value; } if (!isNewObject) { layoutDetail.SelectViewTabWithoutRefresh(); } } private static void CheckAndTraceQuery(AvrTreeSelectedElementEventArgs e) { AvrQueryLookup query = AvrQueryLookup.GetAvrQueryLookupById(e.QueryId); if (query == null) { throw new AvrDataException(string.Format("Could not find query with ID '{0}'", e.QueryId)); } Trace.WriteLine(Trace.Kind.Info, "Selected query item {0} with id {1} from list", query.QueryName, e.QueryId.ToString()); } private static bool GetUseArchiveForOpeningLayout(long? layoutId, bool isNewObject) { bool useArchive = false; if (!isNewObject && layoutId.HasValue) { AvrLayoutLookup foundLayout = AvrLayoutLookup.GetAvrLayoutLookupById(layoutId.Value); if (foundLayout != null) { useArchive = foundLayout.blnUseArchivedData; } } return useArchive; } #endregion #region Layout handlers private void LayoutDetailLayoutTabChanged(object sender, TabSelectionEventArgs e) { biNewQuery.Enabled = e.NewQueryEnabled && AvrPermissions.InsertPermission; bbNewQuery.Enabled = e.NewQueryEnabled && AvrPermissions.InsertPermission; /* biNewLayout.Enabled = e.NewEnabled && AvrPermissions.InsertPermission; bbNewLayout.Enabled = e.NewEnabled && AvrPermissions.InsertPermission; biCopyQueryLayout.Enabled = e.CopyEnabled && AvrPermissions.InsertPermission; bbCopyQueryLayout.Enabled = e.CopyEnabled && AvrPermissions.InsertPermission; biEditQueryLayout.Enabled = e.NewEnabled && AvrPermissions.UpdatePermission; bbEditQueryLayout.Enabled = e.NewEnabled && AvrPermissions.UpdatePermission; biDeleteQueryLayoutFolder.Enabled = e.LayoutDeleteEnabled && AvrPermissions.DeletePermission; biDeleteQuery.Enabled = e.QueryDeleteEnabled && AvrPermissions.DeletePermission; bbDeleteQueryLayoutFolder.Enabled = e.QueryDeleteEnabled && AvrPermissions.DeletePermission; biPublishQueryLayoutFolder.Enabled = e.LayoutDeleteEnabled && EidssUserContext.User.HasPermission( PermissionHelper.ExecutePermission(EIDSSPermissionObject.CanPublishLayout)); */ } private void layoutDetail_PivotFieldMouseRightClick(object sender, PivotFieldPopupMenuEventArgs e) { using (m_SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.PopupMenuRefreshing)) { IAvrPivotGridField field = e.Field; bbEditCaption.Tag = field; bbCopyField.Tag = field; bbDeleteCopyField.Tag = field; bbAddMissedValues.Tag = field; bbDeleteMissedValues.Tag = field; if (e.EnableGroupDate) { bcGroupDate_0.Checked = true; bcGroupDate_0.Tag = field; foreach (KeyValuePair<BarCheckItem, PivotGroupInterval> pair in m_MenuGroupIntervals) { BarCheckItem item = pair.Key; PivotGroupInterval interval = pair.Value; item.Tag = field; item.Checked = field.PrivateGroupInterval == interval; if (item.Checked) { bcGroupDate_0.Checked = false; } } } bool allowMissedValues = (e.EnableGroupDate || field.AllowMissedReferenceValues); bbAddMissedValues.Enabled = !field.AddMissedValues && allowMissedValues; bbDeleteMissedValues.Enabled = field.AddMissedValues && allowMissedValues; bbDeleteCopyField.Enabled = e.EnableDelete; bsGroupDate.Enabled = e.EnableGroupDate; PivotPopupMenu.ShowPopup(e.Location); } } #endregion #region Menu handlers private void biNewQuery_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { var args = new AvrTreeSelectedElementEventArgs(-1, -1, null, -1, AvrTreeElementType.Query, string.Empty); OpenEditor(args, true); }); } private void biNewLayout_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { AvrTreeSelectedElementEventArgs args = QueryLayoutTree.GetTreeSelectedElementEventArgs(); args.Type = AvrTreeElementType.Layout; args.ElementId = null; OpenEditor(args, true); }); } private void biNewFolder_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { AvrTreeSelectedElementEventArgs args = QueryLayoutTree.GetTreeSelectedElementEventArgs(); args.Type = AvrTreeElementType.Folder; OpenEditor(args, true); }); } private void biEditQueryLayoutFolder_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => OpenEditor(QueryLayoutTree.GetTreeSelectedElementEventArgs())); } private void biDeleteQueryLayoutFolder_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(DeleteQueryLayoutFolder); } private void biCopyQueryLayout_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { OpenEditor(QueryLayoutTree.GetTreeSelectedElementEventArgs()); RaiseSendCommand(new QueryLayoutCommand(sender, QueryLayoutOperation.CopyQueryLayout)); }); } private void biPublishQueryLayout_ItemClick(object sender, ItemClickEventArgs e) { PublishUnpublish(sender, true); } private void biUnpublishQueryLayoutFolder_ItemClick(object sender, ItemClickEventArgs e) { PublishUnpublish(sender, false); } private void PublishUnpublish(object sender, bool isPublish) { MenuHandlerWrapper(() => { if (TreeOpened) { if (Post()) { DisposeLayoutDetails(); DisposeQueryDetails(); AvrTreeSelectedElementEventArgs args = QueryLayoutTree.GetTreeSelectedElementEventArgs(); if (!args.ElementId.HasValue) { ErrorForm.ShowMessage("msgElementNotSelected", "Tree element is not selected"); } else if (BaseAvrDetailPresenterPanel.UserConfirmPublishUnpublish(args.Type, isPublish)) { long id = args.ElementId.Value; m_AvrDbService.PublishUnpublish(id, args.Type, isPublish); QueryLayoutTree.ReloadQueryLayoutFolder(id, args.Type); } } } else if (IsLayoutOpened || IsQueryOpened) { QueryLayoutOperation operation = isPublish ? QueryLayoutOperation.Publish : QueryLayoutOperation.Unpublish; AvrTreeElementType type = IsLayoutOpened ? AvrTreeElementType.Layout : AvrTreeElementType.Query; RaiseSendCommand(new QueryLayoutCommand(sender, operation)); QueryLayoutTree.ReloadQueryLayoutFolder((long) GetKey(), type); } }); } private void biExportReportToXls_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { if (!IsViewPageSelected) { RaiseSendCommand(new RefreshPivotCommand(sender)); } RaiseSendCommand(new ExportCommand(sender, ExportObject.View, ExportType.Xls)); }); } private void biExportReportToXlsx_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { if (!IsViewPageSelected) { RaiseSendCommand(new RefreshPivotCommand(sender)); } RaiseSendCommand(new ExportCommand(sender, ExportObject.View, ExportType.Xlsx)); }); } private void biExportReportToRtf_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { if (!IsViewPageSelected) { RaiseSendCommand(new RefreshPivotCommand(sender)); } RaiseSendCommand(new ExportCommand(sender, ExportObject.View, ExportType.Rtf)); }); } private void biExportReportToPdf_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { if (!IsViewPageSelected) { RaiseSendCommand(new RefreshPivotCommand(sender)); } RaiseSendCommand(new ExportCommand(sender, ExportObject.View, ExportType.Pdf)); }); } private void biExportReportToImage_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { if (!IsViewPageSelected) { RaiseSendCommand(new RefreshPivotCommand(sender)); } RaiseSendCommand(new ExportCommand(sender, ExportObject.View, ExportType.Image)); }); } private void biExportQueryLineListToXls_ItemClick(object sender, ItemClickEventArgs e) { ExportQueryLineListToExcelOrAccess(ExportType.Xls); } private void biExportQueryLineListToXlsx_ItemClick(object sender, ItemClickEventArgs e) { ExportQueryLineListToExcelOrAccess(ExportType.Xlsx); } private void biExportQueryLineListToMdb_ItemClick(object sender, ItemClickEventArgs e) { ExportQueryLineListToExcelOrAccess(ExportType.Mdb); } private void ExportQueryLineListToExcelOrAccess(ExportType type) { MenuHandlerWrapper(() => { if (!Loading && Post()) { AvrTreeSelectedElementEventArgs args = QueryLayoutTree.GetTreeSelectedElementEventArgs(); m_AvrMainFormPresenter.ExportQueryLineListToExcelOrAccess(args.QueryId, type); } }); } private void biPrintReport_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { if (!IsViewPageSelected) { RaiseSendCommand(new RefreshPivotCommand(sender)); } RaiseSendCommand(new PrintCommand(sender, PrintType.View)); }); } private void biShowToolBar_CheckedChanged(object sender, ItemClickEventArgs e) { barTools.Visible = biShowToolBar.Checked; } private void biSettings_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(() => { var form = new AvrSettingsForm(); BaseFormManager.ShowModal(form, ParentForm); }); } private void biInternalHelp_ItemClick(object sender, ItemClickEventArgs e) { MenuHandlerWrapper(ShowHelp); } private void biExit_ItemClick(object sender, ItemClickEventArgs e) { cmdClose_Click(); } private void MenuHandlerWrapper(Action action) { Utils.CheckNotNull(action, "action"); try { if (m_SharedPresenter.ContextKeeper.ContainsContext(ContextValue.ToolbarMenuClicked)) { return; } using (m_SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.ToolbarMenuClicked)) { action(); QueryLayoutTree.FocusedNodeReload(); } } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } #endregion #region Toolar handlers private void bbNewQuery_ItemClick(object sender, ItemClickEventArgs e) { biNewQuery_ItemClick(sender, e); } private void bbNewLayout_ItemClick(object sender, ItemClickEventArgs e) { biNewLayout_ItemClick(sender, e); } private void bbNewFolder_ItemClick(object sender, ItemClickEventArgs e) { biNewFolder_ItemClick(sender, e); } private void bbEditQueryLayout_ItemClick(object sender, ItemClickEventArgs e) { biEditQueryLayoutFolder_ItemClick(sender, e); } private void bbDeleteQueryLayoutFolder_ItemClick(object sender, ItemClickEventArgs e) { biDeleteQueryLayoutFolder_ItemClick(sender, e); } private void bbCopyQueryLayout_ItemClick(object sender, ItemClickEventArgs e) { biCopyQueryLayout_ItemClick(sender, e); } private void bbHelp_ItemClick(object sender, ItemClickEventArgs e) { biInternalHelp_ItemClick(sender, e); } #endregion #region Tree Popup Menu handlers private void bbPopupNewQuery_ItemClick(object sender, ItemClickEventArgs e) { biNewQuery_ItemClick(sender, e); } private void bbPopupNewLayout_ItemClick(object sender, ItemClickEventArgs e) { biNewLayout_ItemClick(sender, e); } private void bbPopupNewFolder_ItemClick(object sender, ItemClickEventArgs e) { biNewFolder_ItemClick(sender, e); } private void bbPopupEditQueryLayoutFolder_ItemClick(object sender, ItemClickEventArgs e) { biEditQueryLayoutFolder_ItemClick(sender, e); } private void bbPopupDeleteQueryLayoutFolder_ItemClick(object sender, ItemClickEventArgs e) { biDeleteQueryLayoutFolder_ItemClick(sender, e); } private void bbPopupCopyQueryLayout_ItemClick(object sender, ItemClickEventArgs e) { biCopyQueryLayout_ItemClick(sender, e); } #endregion #region Pivot Popup Menu handlers private void bbEditCaption_ItemClick(object sender, ItemClickEventArgs e) { PopupClickHandler(sender, e, PivotFieldOperation.Rename); } private void bcGroupDate_CheckedChanged(object sender, ItemClickEventArgs e) { if (m_SharedPresenter.ContextKeeper.ContainsContext(ContextValue.PopupMenuRefreshing)) { return; } IAvrPivotGridField field = FieldFromArgsSingleOrDefault(e); if (field != null && e.Item is BarCheckItem) { var item = (BarCheckItem) e.Item; PivotGroupInterval? groupInterval = null; bool containsCheckedItem = m_MenuGroupIntervals.ContainsKey(item); if (containsCheckedItem) { groupInterval = m_MenuGroupIntervals[item]; } if (item == bcGroupDate_0 || containsCheckedItem) { RaiseSendCommand(new PivotFieldGroupIntervalCommand(sender, field, groupInterval)); } } } private void bbCopyField_ItemClick(object sender, ItemClickEventArgs e) { PopupClickHandler(sender, e, PivotFieldOperation.Copy); } private void bbDeleteCopyField_ItemClick(object sender, ItemClickEventArgs e) { PopupClickHandler(sender, e, PivotFieldOperation.DeleteCopy); } private void bbAddMissedValues_ItemClick(object sender, ItemClickEventArgs e) { PopupClickHandler(sender, e, PivotFieldOperation.AddMissedValues); } private void bbDeleteMissedValues_ItemClick(object sender, ItemClickEventArgs e) { PopupClickHandler(sender, e, PivotFieldOperation.DeleteMissedValues); } private void PopupClickHandler(object sender, ItemClickEventArgs e, PivotFieldOperation operation) { if (m_SharedPresenter.ContextKeeper.ContainsContext(ContextValue.PopupMenuRefreshing)) { return; } IAvrPivotGridField field = FieldFromArgsSingleOrDefault(e); if (field != null) { RaiseSendCommand(new PivotFieldCommand(sender, field, operation)); } } private static IAvrPivotGridField FieldFromArgsSingleOrDefault(ItemClickEventArgs e) { return e.Item != null && !Utils.IsEmpty(e.Item.Tag) && (e.Item.Tag is IAvrPivotGridField) ? (IAvrPivotGridField) e.Item.Tag : null; } #endregion #region Command protected void RaiseSendCommand(Command command) { if (!IsDesignMode()) { SendCommand.SafeRaise(this, new CommandEventArgs(command)); } } #endregion #region HelpTopic Methods public override void ShowHelp() { //if (IsLayoutOpened) //{ if (TabControl.SelectedTabPage == TabPageTree) { ShowHelp("AVR_Getting_Started"); } else if (TabControl.SelectedTabPage == TabPageEditor) { switch (layoutDetail.SelectedTabPageName) { case "tabPagePivotInfo": ShowHelp("info_tab"); break; case "tabPagePivotGrid": ShowHelp("Pivot_Grid_Tab"); break; case "tabPageView": ShowHelp("view_tab"); break; //case "tabPageReport": // ShowHelp("AVR_Reports_Management"); // break; //case "tabPageChart": // ShowHelp("AVR_Chart_Management"); // break; //case "tabPageMap": // ShowHelp("AVR_in_Maps"); // break; default: base.ShowHelp(); break; } } //} //else if (IsQueryOpened) //{ // ShowHelp("AVR_Getting_Started"); //} //else //{ // ShowHelp("AVR_Getting_Started"); //} } #endregion #region ITranslationView #endregion } }
// // Mono.Xml.XPath.DTMXPathDocumentBuilder // // Author: // Atsushi Enomoto (ginga@kit.hi-ho.ne.jp) // // (C) 2003 Atsushi Enomoto // //#define DTM_CLASS // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; namespace Mono.Xml.XPath { #if OUTSIDE_SYSTEM_XML public #else internal #endif class DTMXPathDocumentBuilder { public DTMXPathDocumentBuilder (string url) : this (url, XmlSpace.None, 200) { } public DTMXPathDocumentBuilder (string url, XmlSpace space) : this (url, space, 200) { } public DTMXPathDocumentBuilder (string url, XmlSpace space, int defaultCapacity) { XmlReader r = null; try { r = new XmlTextReader (url); Init (r, space, defaultCapacity); } finally { if (r != null) r.Close (); } } public DTMXPathDocumentBuilder (XmlReader reader) : this (reader, XmlSpace.None, 200) { } public DTMXPathDocumentBuilder (XmlReader reader, XmlSpace space) : this (reader, space, 200) { } public DTMXPathDocumentBuilder (XmlReader reader, XmlSpace space, int defaultCapacity) { Init (reader, space, defaultCapacity); } private void Init (XmlReader reader, XmlSpace space, int defaultCapacity) { this.xmlReader = reader; this.validatingReader = reader as XmlValidatingReader; lineInfo = reader as IXmlLineInfo; this.xmlSpace = space; this.nameTable = reader.NameTable; nodeCapacity = defaultCapacity; attributeCapacity = nodeCapacity; nsCapacity = 10; idTable = new Hashtable (); nodes = new DTMXPathLinkedNode [nodeCapacity]; attributes = new DTMXPathAttributeNode [attributeCapacity]; namespaces = new DTMXPathNamespaceNode [nsCapacity]; Compile (); } XmlReader xmlReader; XmlValidatingReader validatingReader; XmlSpace xmlSpace; XmlNameTable nameTable; IXmlLineInfo lineInfo; int nodeCapacity; int attributeCapacity; int nsCapacity; // Linked Node DTMXPathLinkedNode [] nodes; // Attribute DTMXPathAttributeNode [] attributes; // NamespaceNode DTMXPathNamespaceNode [] namespaces; // idTable [string value] -> int nodeId Hashtable idTable; int nodeIndex; int attributeIndex; int nsIndex; // for attribute processing; should be reset per each element. bool hasAttributes; bool hasLocalNs; int attrIndexAtStart; int nsIndexAtStart; int lastNsInScope; bool skipRead = false; int [] parentStack = new int [10]; int parentStackIndex = 0; public DTMXPathDocument CreateDocument () { return new DTMXPathDocument (nameTable, nodes, attributes, namespaces, idTable ); } public void Compile () { // index 0 is dummy. No node (including Root) is assigned to this index // So that we can easily compare index != 0 instead of index < 0. // (Difference between jnz or jbe in 80x86.) AddNode (0, 0, 0, XPathNodeType.All, "", false, "", "", "", "", "", 0, 0, 0); nodeIndex++; AddAttribute (0, null, null, null, null, 0, 0); AddNsNode (0, null, null, 0); nsIndex++; AddNsNode (1, "xml", XmlNamespaces.XML, 0); // add root. AddNode (0, 0, 0, XPathNodeType.Root, xmlReader.BaseURI, false, "", "", "", "", "", 1, 0, 0); this.nodeIndex = 1; this.lastNsInScope = 1; parentStack [0] = nodeIndex; while (!xmlReader.EOF) Read (); SetNodeArrayLength (nodeIndex + 1); SetAttributeArrayLength (attributeIndex + 1); SetNsArrayLength (nsIndex + 1); xmlReader = null; // It is no more required. } public void Read () { if (!skipRead) if (!xmlReader.Read ()) return; skipRead = false; int parent = parentStack [parentStackIndex]; int prevSibling = nodeIndex; switch (xmlReader.NodeType) { case XmlNodeType.Element: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Comment: case XmlNodeType.Text: case XmlNodeType.ProcessingInstruction: if (parent == nodeIndex) prevSibling = 0; else while (nodes [prevSibling].Parent != parent) prevSibling = nodes [prevSibling].Parent; nodeIndex++; if (prevSibling != 0) nodes [prevSibling].NextSibling = nodeIndex; if (parentStack [parentStackIndex] == nodeIndex - 1) nodes [parent].FirstChild = nodeIndex; break; case XmlNodeType.Whitespace: if (xmlSpace == XmlSpace.Preserve) goto case XmlNodeType.Text; else goto default; case XmlNodeType.EndElement: parentStackIndex--; return; default: // No operations. Doctype, EntityReference, return; } string value = null; XPathNodeType nodeType = XPathNodeType.Text; switch (xmlReader.NodeType) { case XmlNodeType.Element: ProcessElement (parent, prevSibling); break; case XmlNodeType.SignificantWhitespace: nodeType = XPathNodeType.SignificantWhitespace; goto case XmlNodeType.Text; case XmlNodeType.Whitespace: nodeType = XPathNodeType.Whitespace; goto case XmlNodeType.Text; case XmlNodeType.CDATA: case XmlNodeType.Text: AddNode (parent, 0, prevSibling, nodeType, xmlReader.BaseURI, xmlReader.IsEmptyElement, xmlReader.LocalName, // for PI xmlReader.NamespaceURI, // for PI xmlReader.Prefix, value, xmlReader.XmlLang, nsIndex, lineInfo != null ? lineInfo.LineNumber : 0, lineInfo != null ? lineInfo.LinePosition : 0); // this code is tricky, but after sequential // Read() invokation, xmlReader is moved to // next node. if (value == null) { bool loop = true; value = String.Empty; XPathNodeType type = XPathNodeType.Whitespace; do { switch (xmlReader.NodeType) { case XmlNodeType.Text: case XmlNodeType.CDATA: type = XPathNodeType.Text; goto case XmlNodeType.Whitespace; case XmlNodeType.SignificantWhitespace: if (type == XPathNodeType.Whitespace) type = XPathNodeType.SignificantWhitespace; goto case XmlNodeType.Whitespace; case XmlNodeType.Whitespace: if (xmlReader.NodeType != XmlNodeType.Whitespace || xmlSpace == XmlSpace.Preserve) value += xmlReader.Value; loop = xmlReader.Read (); skipRead = true; continue; default: loop = false; break; } } while (loop); nodes [nodeIndex].Value = value; nodes [nodeIndex].NodeType = type; } break; case XmlNodeType.Comment: value = xmlReader.Value; nodeType = XPathNodeType.Comment; goto case XmlNodeType.Text; case XmlNodeType.ProcessingInstruction: value = xmlReader.Value; nodeType = XPathNodeType.ProcessingInstruction; goto case XmlNodeType.Text; } } private void ProcessElement (int parent, int previousSibling) { WriteStartElement (parent, previousSibling); // process namespaces and attributes. if (xmlReader.MoveToFirstAttribute ()) { do { string prefix = xmlReader.Prefix; string ns = xmlReader.NamespaceURI; if (ns == XmlNamespaces.XMLNS) ProcessNamespace ((prefix == null || prefix == String.Empty) ? "" : xmlReader.LocalName, xmlReader.Value); else ProcessAttribute (prefix, xmlReader.LocalName, ns, xmlReader.Value); } while (xmlReader.MoveToNextAttribute ()); xmlReader.MoveToElement (); } CloseStartElement (); } private void PrepareStartElement (int previousSibling) { hasAttributes = false; hasLocalNs = false; attrIndexAtStart = attributeIndex; nsIndexAtStart = nsIndex; while (namespaces [lastNsInScope].DeclaredElement == previousSibling) { lastNsInScope = namespaces [lastNsInScope].NextNamespace; } } private void WriteStartElement (int parent, int previousSibling) { PrepareStartElement (previousSibling); AddNode (parent, 0, // dummy:firstAttribute previousSibling, XPathNodeType.Element, xmlReader.BaseURI, xmlReader.IsEmptyElement, xmlReader.LocalName, xmlReader.NamespaceURI, xmlReader.Prefix, "", // Element has no internal value. xmlReader.XmlLang, lastNsInScope, lineInfo != null ? lineInfo.LineNumber : 0, lineInfo != null ? lineInfo.LinePosition : 0); } private void CloseStartElement () { if (attrIndexAtStart != attributeIndex) nodes [nodeIndex].FirstAttribute = attrIndexAtStart + 1; if (nsIndexAtStart != nsIndex) { nodes [nodeIndex].FirstNamespace = nsIndex; if (!xmlReader.IsEmptyElement) lastNsInScope = nsIndex; } if (!nodes [nodeIndex].IsEmptyElement) { parentStackIndex++; if (parentStack.Length == parentStackIndex) { int [] tmp = new int [parentStackIndex * 2]; Array.Copy (parentStack, tmp, parentStackIndex); parentStack = tmp; } parentStack [parentStackIndex] = nodeIndex; } } private void ProcessNamespace (string prefix, string ns) { int nextTmp = hasLocalNs ? nsIndex : nodes [nodeIndex].FirstNamespace; nsIndex++; this.AddNsNode (nodeIndex, prefix, ns, nextTmp); hasLocalNs = true; } private void ProcessAttribute (string prefix, string localName, string ns, string value) { attributeIndex ++; this.AddAttribute (nodeIndex, localName, ns, prefix != null ? prefix : String.Empty, value, lineInfo != null ? lineInfo.LineNumber : 0, lineInfo != null ? lineInfo.LinePosition : 0); if (hasAttributes) attributes [attributeIndex - 1].NextAttribute = attributeIndex; else hasAttributes = true; // Identity infoset if (validatingReader != null) { XmlSchemaDatatype dt = validatingReader.SchemaType as XmlSchemaDatatype; if (dt == null) { XmlSchemaType xsType = validatingReader.SchemaType as XmlSchemaType; if (xsType != null) dt = xsType.Datatype; } if (dt != null && dt.TokenizedType == XmlTokenizedType.ID) idTable.Add (value, nodeIndex); } } private void SetNodeArrayLength (int size) { DTMXPathLinkedNode [] newArr = new DTMXPathLinkedNode [size]; Array.Copy (nodes, newArr, System.Math.Min (size, nodes.Length)); nodes = newArr; } private void SetAttributeArrayLength (int size) { DTMXPathAttributeNode [] newArr = new DTMXPathAttributeNode [size]; Array.Copy (attributes, newArr, System.Math.Min (size, attributes.Length)); attributes = newArr; } private void SetNsArrayLength (int size) { DTMXPathNamespaceNode [] newArr = new DTMXPathNamespaceNode [size]; Array.Copy (namespaces, newArr, System.Math.Min (size, namespaces.Length)); namespaces = newArr; } // Here followings are skipped: firstChild, nextSibling, public void AddNode (int parent, int firstAttribute, int previousSibling, XPathNodeType nodeType, string baseUri, bool isEmptyElement, string localName, string ns, string prefix, string value, string xmlLang, int namespaceNode, int lineNumber, int linePosition) { if (nodes.Length < nodeIndex + 1) { nodeCapacity *= 4; SetNodeArrayLength (nodeCapacity); } #if DTM_CLASS nodes [nodeIndex] = new DTMXPathLinkedNode (); #endif nodes [nodeIndex].FirstChild = 0; // dummy nodes [nodeIndex].Parent = parent; nodes [nodeIndex].FirstAttribute = firstAttribute; nodes [nodeIndex].PreviousSibling = previousSibling; nodes [nodeIndex].NextSibling = 0; // dummy nodes [nodeIndex].NodeType = nodeType; nodes [nodeIndex].BaseURI = baseUri; nodes [nodeIndex].IsEmptyElement = isEmptyElement; nodes [nodeIndex].LocalName = localName; nodes [nodeIndex].NamespaceURI = ns; nodes [nodeIndex].Prefix = prefix; nodes [nodeIndex].Value = value; nodes [nodeIndex].XmlLang = xmlLang; nodes [nodeIndex].FirstNamespace = namespaceNode; nodes [nodeIndex].LineNumber = lineNumber; nodes [nodeIndex].LinePosition = linePosition; } // Followings are skipped: nextAttribute, public void AddAttribute (int ownerElement, string localName, string ns, string prefix, string value, int lineNumber, int linePosition) { if (attributes.Length < attributeIndex + 1) { attributeCapacity *= 4; SetAttributeArrayLength (attributeCapacity); } #if DTM_CLASS attributes [attributeIndex] = new DTMXPathAttributeNode (); #endif attributes [attributeIndex].OwnerElement = ownerElement; attributes [attributeIndex].LocalName = localName; attributes [attributeIndex].NamespaceURI = ns; attributes [attributeIndex].Prefix = prefix; attributes [attributeIndex].Value = value; attributes [attributeIndex].LineNumber = lineNumber; attributes [attributeIndex].LinePosition = linePosition; } // Followings are skipped: nextNsNode (may be next attribute in the same element, or ancestors' nsNode) public void AddNsNode (int declaredElement, string name, string ns, int nextNs) { if (namespaces.Length < nsIndex + 1) { nsCapacity *= 4; SetNsArrayLength (nsCapacity); } #if DTM_CLASS namespaces [nsIndex] = new DTMXPathNamespaceNode (); #endif namespaces [nsIndex].DeclaredElement = declaredElement; namespaces [nsIndex].Name = name; namespaces [nsIndex].Namespace = ns; namespaces [nsIndex].NextNamespace = nextNs; } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// UserSignature /// </summary> [DataContract] public partial class UserSignature : IEquatable<UserSignature>, IValidatableObject { public UserSignature() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="UserSignature" /> class. /// </summary> /// <param name="AdoptedDateTime">The date and time the user adopted their signature..</param> /// <param name="CreatedDateTime">Indicates the date and time the item was created..</param> /// <param name="DateStampProperties">DateStampProperties.</param> /// <param name="ErrorDetails">ErrorDetails.</param> /// <param name="ExternalID">.</param> /// <param name="ImageType">.</param> /// <param name="Initials150ImageId">.</param> /// <param name="InitialsImageUri">Contains the URI for an endpoint that you can use to retrieve the initials image..</param> /// <param name="IsDefault">.</param> /// <param name="PhoneticName">.</param> /// <param name="Signature150ImageId">.</param> /// <param name="SignatureFont">The font type for the signature, if the signature is not drawn. The supported font types are: \&quot;7_DocuSign\&quot;, \&quot;1_DocuSign\&quot;, \&quot;6_DocuSign\&quot;, \&quot;8_DocuSign\&quot;, \&quot;3_DocuSign\&quot;, \&quot;Mistral\&quot;, \&quot;4_DocuSign\&quot;, \&quot;2_DocuSign\&quot;, \&quot;5_DocuSign\&quot;, \&quot;Rage Italic\&quot; .</param> /// <param name="SignatureId">Specifies the signature ID associated with the signature name. You can use the signature ID in the URI in place of the signature name, and the value stored in the &#x60;signatureName&#x60; property in the body is used. This allows the use of special characters (such as \&quot;&amp;\&quot;, \&quot;&lt;\&quot;, \&quot;&gt;\&quot;) in a the signature name. Note that with each update to signatures, the returned signature ID might change, so the caller will need to trigger off the signature name to get the new signature ID..</param> /// <param name="SignatureImageUri">Contains the URI for an endpoint that you can use to retrieve the signature image..</param> /// <param name="SignatureInitials"> The initials associated with the signature..</param> /// <param name="SignatureName">Specifies the user signature name..</param> /// <param name="SignatureType">.</param> /// <param name="StampFormat">.</param> /// <param name="StampImageUri">.</param> /// <param name="StampSizeMM">.</param> /// <param name="StampType">.</param> public UserSignature(string AdoptedDateTime = default(string), string CreatedDateTime = default(string), DateStampProperties DateStampProperties = default(DateStampProperties), ErrorDetails ErrorDetails = default(ErrorDetails), string ExternalID = default(string), string ImageType = default(string), string Initials150ImageId = default(string), string InitialsImageUri = default(string), string IsDefault = default(string), string PhoneticName = default(string), string Signature150ImageId = default(string), string SignatureFont = default(string), string SignatureId = default(string), string SignatureImageUri = default(string), string SignatureInitials = default(string), string SignatureName = default(string), string SignatureType = default(string), string StampFormat = default(string), string StampImageUri = default(string), string StampSizeMM = default(string), string StampType = default(string)) { this.AdoptedDateTime = AdoptedDateTime; this.CreatedDateTime = CreatedDateTime; this.DateStampProperties = DateStampProperties; this.ErrorDetails = ErrorDetails; this.ExternalID = ExternalID; this.ImageType = ImageType; this.Initials150ImageId = Initials150ImageId; this.InitialsImageUri = InitialsImageUri; this.IsDefault = IsDefault; this.PhoneticName = PhoneticName; this.Signature150ImageId = Signature150ImageId; this.SignatureFont = SignatureFont; this.SignatureId = SignatureId; this.SignatureImageUri = SignatureImageUri; this.SignatureInitials = SignatureInitials; this.SignatureName = SignatureName; this.SignatureType = SignatureType; this.StampFormat = StampFormat; this.StampImageUri = StampImageUri; this.StampSizeMM = StampSizeMM; this.StampType = StampType; } /// <summary> /// The date and time the user adopted their signature. /// </summary> /// <value>The date and time the user adopted their signature.</value> [DataMember(Name="adoptedDateTime", EmitDefaultValue=false)] public string AdoptedDateTime { get; set; } /// <summary> /// Indicates the date and time the item was created. /// </summary> /// <value>Indicates the date and time the item was created.</value> [DataMember(Name="createdDateTime", EmitDefaultValue=false)] public string CreatedDateTime { get; set; } /// <summary> /// Gets or Sets DateStampProperties /// </summary> [DataMember(Name="dateStampProperties", EmitDefaultValue=false)] public DateStampProperties DateStampProperties { get; set; } /// <summary> /// Gets or Sets ErrorDetails /// </summary> [DataMember(Name="errorDetails", EmitDefaultValue=false)] public ErrorDetails ErrorDetails { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="externalID", EmitDefaultValue=false)] public string ExternalID { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="imageType", EmitDefaultValue=false)] public string ImageType { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="initials150ImageId", EmitDefaultValue=false)] public string Initials150ImageId { get; set; } /// <summary> /// Contains the URI for an endpoint that you can use to retrieve the initials image. /// </summary> /// <value>Contains the URI for an endpoint that you can use to retrieve the initials image.</value> [DataMember(Name="initialsImageUri", EmitDefaultValue=false)] public string InitialsImageUri { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="isDefault", EmitDefaultValue=false)] public string IsDefault { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="phoneticName", EmitDefaultValue=false)] public string PhoneticName { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="signature150ImageId", EmitDefaultValue=false)] public string Signature150ImageId { get; set; } /// <summary> /// The font type for the signature, if the signature is not drawn. The supported font types are: \&quot;7_DocuSign\&quot;, \&quot;1_DocuSign\&quot;, \&quot;6_DocuSign\&quot;, \&quot;8_DocuSign\&quot;, \&quot;3_DocuSign\&quot;, \&quot;Mistral\&quot;, \&quot;4_DocuSign\&quot;, \&quot;2_DocuSign\&quot;, \&quot;5_DocuSign\&quot;, \&quot;Rage Italic\&quot; /// </summary> /// <value>The font type for the signature, if the signature is not drawn. The supported font types are: \&quot;7_DocuSign\&quot;, \&quot;1_DocuSign\&quot;, \&quot;6_DocuSign\&quot;, \&quot;8_DocuSign\&quot;, \&quot;3_DocuSign\&quot;, \&quot;Mistral\&quot;, \&quot;4_DocuSign\&quot;, \&quot;2_DocuSign\&quot;, \&quot;5_DocuSign\&quot;, \&quot;Rage Italic\&quot; </value> [DataMember(Name="signatureFont", EmitDefaultValue=false)] public string SignatureFont { get; set; } /// <summary> /// Specifies the signature ID associated with the signature name. You can use the signature ID in the URI in place of the signature name, and the value stored in the &#x60;signatureName&#x60; property in the body is used. This allows the use of special characters (such as \&quot;&amp;\&quot;, \&quot;&lt;\&quot;, \&quot;&gt;\&quot;) in a the signature name. Note that with each update to signatures, the returned signature ID might change, so the caller will need to trigger off the signature name to get the new signature ID. /// </summary> /// <value>Specifies the signature ID associated with the signature name. You can use the signature ID in the URI in place of the signature name, and the value stored in the &#x60;signatureName&#x60; property in the body is used. This allows the use of special characters (such as \&quot;&amp;\&quot;, \&quot;&lt;\&quot;, \&quot;&gt;\&quot;) in a the signature name. Note that with each update to signatures, the returned signature ID might change, so the caller will need to trigger off the signature name to get the new signature ID.</value> [DataMember(Name="signatureId", EmitDefaultValue=false)] public string SignatureId { get; set; } /// <summary> /// Contains the URI for an endpoint that you can use to retrieve the signature image. /// </summary> /// <value>Contains the URI for an endpoint that you can use to retrieve the signature image.</value> [DataMember(Name="signatureImageUri", EmitDefaultValue=false)] public string SignatureImageUri { get; set; } /// <summary> /// The initials associated with the signature. /// </summary> /// <value> The initials associated with the signature.</value> [DataMember(Name="signatureInitials", EmitDefaultValue=false)] public string SignatureInitials { get; set; } /// <summary> /// Specifies the user signature name. /// </summary> /// <value>Specifies the user signature name.</value> [DataMember(Name="signatureName", EmitDefaultValue=false)] public string SignatureName { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="signatureType", EmitDefaultValue=false)] public string SignatureType { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="stampFormat", EmitDefaultValue=false)] public string StampFormat { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="stampImageUri", EmitDefaultValue=false)] public string StampImageUri { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="stampSizeMM", EmitDefaultValue=false)] public string StampSizeMM { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="stampType", EmitDefaultValue=false)] public string StampType { 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 UserSignature {\n"); sb.Append(" AdoptedDateTime: ").Append(AdoptedDateTime).Append("\n"); sb.Append(" CreatedDateTime: ").Append(CreatedDateTime).Append("\n"); sb.Append(" DateStampProperties: ").Append(DateStampProperties).Append("\n"); sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n"); sb.Append(" ExternalID: ").Append(ExternalID).Append("\n"); sb.Append(" ImageType: ").Append(ImageType).Append("\n"); sb.Append(" Initials150ImageId: ").Append(Initials150ImageId).Append("\n"); sb.Append(" InitialsImageUri: ").Append(InitialsImageUri).Append("\n"); sb.Append(" IsDefault: ").Append(IsDefault).Append("\n"); sb.Append(" PhoneticName: ").Append(PhoneticName).Append("\n"); sb.Append(" Signature150ImageId: ").Append(Signature150ImageId).Append("\n"); sb.Append(" SignatureFont: ").Append(SignatureFont).Append("\n"); sb.Append(" SignatureId: ").Append(SignatureId).Append("\n"); sb.Append(" SignatureImageUri: ").Append(SignatureImageUri).Append("\n"); sb.Append(" SignatureInitials: ").Append(SignatureInitials).Append("\n"); sb.Append(" SignatureName: ").Append(SignatureName).Append("\n"); sb.Append(" SignatureType: ").Append(SignatureType).Append("\n"); sb.Append(" StampFormat: ").Append(StampFormat).Append("\n"); sb.Append(" StampImageUri: ").Append(StampImageUri).Append("\n"); sb.Append(" StampSizeMM: ").Append(StampSizeMM).Append("\n"); sb.Append(" StampType: ").Append(StampType).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 UserSignature); } /// <summary> /// Returns true if UserSignature instances are equal /// </summary> /// <param name="other">Instance of UserSignature to be compared</param> /// <returns>Boolean</returns> public bool Equals(UserSignature other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AdoptedDateTime == other.AdoptedDateTime || this.AdoptedDateTime != null && this.AdoptedDateTime.Equals(other.AdoptedDateTime) ) && ( this.CreatedDateTime == other.CreatedDateTime || this.CreatedDateTime != null && this.CreatedDateTime.Equals(other.CreatedDateTime) ) && ( this.DateStampProperties == other.DateStampProperties || this.DateStampProperties != null && this.DateStampProperties.Equals(other.DateStampProperties) ) && ( this.ErrorDetails == other.ErrorDetails || this.ErrorDetails != null && this.ErrorDetails.Equals(other.ErrorDetails) ) && ( this.ExternalID == other.ExternalID || this.ExternalID != null && this.ExternalID.Equals(other.ExternalID) ) && ( this.ImageType == other.ImageType || this.ImageType != null && this.ImageType.Equals(other.ImageType) ) && ( this.Initials150ImageId == other.Initials150ImageId || this.Initials150ImageId != null && this.Initials150ImageId.Equals(other.Initials150ImageId) ) && ( this.InitialsImageUri == other.InitialsImageUri || this.InitialsImageUri != null && this.InitialsImageUri.Equals(other.InitialsImageUri) ) && ( this.IsDefault == other.IsDefault || this.IsDefault != null && this.IsDefault.Equals(other.IsDefault) ) && ( this.PhoneticName == other.PhoneticName || this.PhoneticName != null && this.PhoneticName.Equals(other.PhoneticName) ) && ( this.Signature150ImageId == other.Signature150ImageId || this.Signature150ImageId != null && this.Signature150ImageId.Equals(other.Signature150ImageId) ) && ( this.SignatureFont == other.SignatureFont || this.SignatureFont != null && this.SignatureFont.Equals(other.SignatureFont) ) && ( this.SignatureId == other.SignatureId || this.SignatureId != null && this.SignatureId.Equals(other.SignatureId) ) && ( this.SignatureImageUri == other.SignatureImageUri || this.SignatureImageUri != null && this.SignatureImageUri.Equals(other.SignatureImageUri) ) && ( this.SignatureInitials == other.SignatureInitials || this.SignatureInitials != null && this.SignatureInitials.Equals(other.SignatureInitials) ) && ( this.SignatureName == other.SignatureName || this.SignatureName != null && this.SignatureName.Equals(other.SignatureName) ) && ( this.SignatureType == other.SignatureType || this.SignatureType != null && this.SignatureType.Equals(other.SignatureType) ) && ( this.StampFormat == other.StampFormat || this.StampFormat != null && this.StampFormat.Equals(other.StampFormat) ) && ( this.StampImageUri == other.StampImageUri || this.StampImageUri != null && this.StampImageUri.Equals(other.StampImageUri) ) && ( this.StampSizeMM == other.StampSizeMM || this.StampSizeMM != null && this.StampSizeMM.Equals(other.StampSizeMM) ) && ( this.StampType == other.StampType || this.StampType != null && this.StampType.Equals(other.StampType) ); } /// <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.AdoptedDateTime != null) hash = hash * 59 + this.AdoptedDateTime.GetHashCode(); if (this.CreatedDateTime != null) hash = hash * 59 + this.CreatedDateTime.GetHashCode(); if (this.DateStampProperties != null) hash = hash * 59 + this.DateStampProperties.GetHashCode(); if (this.ErrorDetails != null) hash = hash * 59 + this.ErrorDetails.GetHashCode(); if (this.ExternalID != null) hash = hash * 59 + this.ExternalID.GetHashCode(); if (this.ImageType != null) hash = hash * 59 + this.ImageType.GetHashCode(); if (this.Initials150ImageId != null) hash = hash * 59 + this.Initials150ImageId.GetHashCode(); if (this.InitialsImageUri != null) hash = hash * 59 + this.InitialsImageUri.GetHashCode(); if (this.IsDefault != null) hash = hash * 59 + this.IsDefault.GetHashCode(); if (this.PhoneticName != null) hash = hash * 59 + this.PhoneticName.GetHashCode(); if (this.Signature150ImageId != null) hash = hash * 59 + this.Signature150ImageId.GetHashCode(); if (this.SignatureFont != null) hash = hash * 59 + this.SignatureFont.GetHashCode(); if (this.SignatureId != null) hash = hash * 59 + this.SignatureId.GetHashCode(); if (this.SignatureImageUri != null) hash = hash * 59 + this.SignatureImageUri.GetHashCode(); if (this.SignatureInitials != null) hash = hash * 59 + this.SignatureInitials.GetHashCode(); if (this.SignatureName != null) hash = hash * 59 + this.SignatureName.GetHashCode(); if (this.SignatureType != null) hash = hash * 59 + this.SignatureType.GetHashCode(); if (this.StampFormat != null) hash = hash * 59 + this.StampFormat.GetHashCode(); if (this.StampImageUri != null) hash = hash * 59 + this.StampImageUri.GetHashCode(); if (this.StampSizeMM != null) hash = hash * 59 + this.StampSizeMM.GetHashCode(); if (this.StampType != null) hash = hash * 59 + this.StampType.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) 2017 Jan Pluskal // //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.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Netfox.Core.Helpers { public class NotifyTaskCompletion<TResult> : NotifyTaskCompletion { private readonly Action _notifyPropertyChange; protected TResult DefaultResult = default(TResult); private readonly Func<Task<TResult>> _resultBody; public NotifyTaskCompletion(Task<TResult> task, bool @await = false) { this.RunTask(task, @await ); } private void RunTask(Task<TResult> task, bool await) { this.Task = task; this.TaskLocal = task; if(@await) this.Await(); } public void ReRun() { this.RunTask(this._resultBody(),false); this.TaskLocal.ContinueWith(t => { this._notifyPropertyChange(); }); } public NotifyTaskCompletion(Task<TResult> task, Action notifyPropertyChange, bool await = false) : this(task, @await) { this._notifyPropertyChange = notifyPropertyChange; this.TaskLocal.ContinueWith(t => { notifyPropertyChange(); }); } public NotifyTaskCompletion(Func<Task<TResult>> resultBody, Action notifyPropertyChange, bool await = false) : this(resultBody(), notifyPropertyChange, @await) { this._resultBody = resultBody; } public NotifyTaskCompletion(Func<Task<TResult>> resultBody, Action notifyPropertyChange, TResult @default, bool await = false) : this(resultBody, notifyPropertyChange, @await) { this.DefaultResult = @default; } public NotifyTaskCompletion(Func<Task<TResult>> resultBody, bool await = false) : this(resultBody(), @await) { } protected NotifyTaskCompletion() { } public Task<TResult> TaskLocal { get; set; } public new TResult Result { get { if(this.IsNotCompleted) this.Await(); return (this.Status == TaskStatus.RanToCompletion)? this.TaskLocal.Result : this.DefaultResult; } } public new TaskAwaiter<TResult> GetAwaiter() { return this.WatchTaskAsync().GetAwaiter(); } public static implicit operator TResult(NotifyTaskCompletion<TResult> notifyTaskCompletion) { return notifyTaskCompletion.Result; } public static implicit operator Task<TResult>(NotifyTaskCompletion<TResult> notifyTaskCompletion) { return notifyTaskCompletion.TaskLocal; } private new async Task<TResult> WatchTaskAsync() { await base.WatchTaskAsync(); return this.Result; } #region Overrides of Object public override string ToString() {return this.Result?.ToString() ?? base.ToString(); } #endregion } public class NotifyTaskCompletion : INotifyPropertyChanged { private bool _isTaskStateNotified; public NotifyTaskCompletion(Task task, bool await = false) { this.Task = task; if (@await) this.Await(); } public NotifyTaskCompletion(Task task, Action notifyPropertyChange, bool await = false):this(task,@await) { this.Task.ContinueWith(t => { notifyPropertyChange(); }); } protected NotifyTaskCompletion() { } public TaskStatus Status => this.Task?.Status ?? TaskStatus.Created; public bool IsCompleted => this.Task?.IsCompleted ?? false; public bool IsNotCompleted => !this.IsCompleted; public bool IsSuccessfullyCompleted => this.Status == TaskStatus.RanToCompletion; public bool IsCanceled => this.Task?.IsCanceled ?? false; public bool IsFaulted => this.Task?.IsFaulted ?? false; public AggregateException Exception => this.Task?.Exception; public Exception InnerException => this.Exception?.InnerException; public string ErrorMessage => this.InnerException?.Message; public string ErrorMessagesAll { get { var sb = new StringBuilder(); this.InnerExceptionPrinter(this.Exception, sb); return sb.ToString(); } } protected Task Task { get; set; } protected object Result => null; public event PropertyChangedEventHandler PropertyChanged; public TaskAwaiter GetAwaiter() { return this.Task.GetAwaiter(); } protected void Await() { if((this.IsNotCompleted)) { var _ = this.WatchTaskAsync(); } } protected async Task WatchTaskAsync() { try { await this.Task; } catch {} if(!this._isTaskStateNotified) { this._isTaskStateNotified = true; this.NotifyTaskStateChanged(); } } private void InnerExceptionPrinter(Exception ex, StringBuilder sb) { if(ex == null) { return; } sb.AppendLine(ex.GetType().ToString()); sb.AppendLine(ex.Message); this.InnerExceptionPrinter(ex.InnerException, sb); var readOnlyCollection = (ex as AggregateException)?.InnerExceptions; if(readOnlyCollection != null) { foreach(var innerException in readOnlyCollection) { this.InnerExceptionPrinter(innerException, sb); } } } private void NotifyTaskStateChanged() { var propertyChanged = this.PropertyChanged; if(propertyChanged == null) { return; } propertyChanged(this, new PropertyChangedEventArgs(nameof(this.Status))); propertyChanged(this, new PropertyChangedEventArgs(nameof(this.IsCompleted))); propertyChanged(this, new PropertyChangedEventArgs(nameof(this.IsNotCompleted))); if(this.Task.IsCanceled) { propertyChanged(this, new PropertyChangedEventArgs(nameof(this.IsCanceled))); } else if(this.Task.IsFaulted) { propertyChanged(this, new PropertyChangedEventArgs(nameof(this.IsFaulted))); propertyChanged(this, new PropertyChangedEventArgs(nameof(this.Exception))); propertyChanged(this, new PropertyChangedEventArgs(nameof(this.InnerException))); propertyChanged(this, new PropertyChangedEventArgs(nameof(this.ErrorMessage))); propertyChanged(this, new PropertyChangedEventArgs(nameof(this.ErrorMessagesAll))); } else { propertyChanged(this, new PropertyChangedEventArgs(nameof(this.IsSuccessfullyCompleted))); propertyChanged(this, new PropertyChangedEventArgs(nameof(this.Result))); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Streams.Core; using Orleans.Providers; namespace Orleans.Streams { [Serializable] internal class PubSubGrainState { public HashSet<PubSubPublisherState> Producers { get; set; } = new HashSet<PubSubPublisherState>(); public HashSet<PubSubSubscriptionState> Consumers { get; set; } = new HashSet<PubSubSubscriptionState>(); } [StorageProvider(ProviderName = "PubSubStore")] internal class PubSubRendezvousGrain : Grain<PubSubGrainState>, IPubSubRendezvousGrain { private Logger logger; private const bool DEBUG_PUB_SUB = false; private static readonly CounterStatistic counterProducersAdded; private static readonly CounterStatistic counterProducersRemoved; private static readonly CounterStatistic counterProducersTotal; private static readonly CounterStatistic counterConsumersAdded; private static readonly CounterStatistic counterConsumersRemoved; private static readonly CounterStatistic counterConsumersTotal; private readonly ISiloStatusOracle siloStatusOracle; static PubSubRendezvousGrain() { counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED); counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED); counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL); counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED); counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED); counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL); } public PubSubRendezvousGrain(ISiloStatusOracle siloStatusOracle) { this.siloStatusOracle = siloStatusOracle; } public override Task OnActivateAsync() { logger = GetLogger(GetType().Name + "-" + RuntimeIdentity + "-" + IdentityString); LogPubSubCounts("OnActivateAsync"); return Task.CompletedTask; } public override Task OnDeactivateAsync() { LogPubSubCounts("OnDeactivateAsync"); return Task.CompletedTask; } public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, IStreamProducerExtension streamProducer) { counterProducersAdded.Increment(); try { var publisherState = new PubSubPublisherState(streamId, streamProducer); State.Producers.Add(publisherState); LogPubSubCounts("RegisterProducer {0}", streamProducer); await WriteStateAsync(); counterProducersTotal.Increment(); } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterProducerFailed, $"Failed to register a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } return State.Consumers.Where(c => !c.IsFaulted).ToSet(); } public async Task UnregisterProducer(StreamId streamId, IStreamProducerExtension streamProducer) { counterProducersRemoved.Increment(); try { int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer)); LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved); if (numRemoved > 0) { Task updateStorageTask = State.Producers.Count == 0 && State.Consumers.Count == 0 ? ClearStateAsync() //State contains no producers or consumers, remove it from storage : WriteStateAsync(); await updateStorageTask; } counterProducersTotal.DecrementBy(numRemoved); } catch (Exception exc) { logger.Error(ErrorCode.Stream_UnegisterProducerFailed, $"Failed to unregister a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } if (State.Producers.Count == 0 && State.Consumers.Count == 0) { DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation } } public async Task RegisterConsumer( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { counterConsumersAdded.Increment(); PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId)); if (pubSubState != null && pubSubState.IsFaulted) throw new FaultedSubscriptionException(subscriptionId, streamId); try { if (pubSubState == null) { pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer); State.Consumers.Add(pubSubState); } if (filter != null) pubSubState.AddFilter(filter); LogPubSubCounts("RegisterConsumer {0}", streamConsumer); await WriteStateAsync(); counterConsumersTotal.Increment(); } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterConsumerFailed, $"Failed to register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } int numProducers = State.Producers.Count; if (numProducers <= 0) return; if (logger.IsVerbose) logger.Info("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}", numProducers, streamConsumer, Utils.EnumerableToString(State.Producers)); // Notify producers about a new streamConsumer. var tasks = new List<Task>(); var producers = State.Producers.ToList(); int initialProducerCount = producers.Count; try { foreach (PubSubPublisherState producerState in producers) { tasks.Add(ExecuteProducerTask(producerState, producerState.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filter))); } Exception exception = null; try { await Task.WhenAll(tasks); } catch (Exception exc) { exception = exc; } // if the number of producers has been changed, resave state. if (State.Producers.Count != initialProducerCount) { await WriteStateAsync(); counterConsumersTotal.DecrementBy(initialProducerCount - State.Producers.Count); } if (exception != null) { throw exception; } } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterConsumerFailed, $"Failed to update producers while register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } private void RemoveProducer(PubSubPublisherState producer) { logger.Warn(ErrorCode.Stream_ProducerIsDead, "Producer {0} on stream {1} is no longer active - permanently removing producer.", producer, producer.Stream); State.Producers.Remove(producer); } public async Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId) { counterConsumersRemoved.Increment(); try { int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId)); LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved); if (await TryClearState()) { // If state was cleared expedite Deactivation DeactivateOnIdle(); } else { if (numRemoved != 0) { await WriteStateAsync(); } await NotifyProducersOfRemovedSubscription(subscriptionId, streamId); } counterConsumersTotal.DecrementBy(numRemoved); } catch (Exception exc) { logger.Error(ErrorCode.Stream_UnregisterConsumerFailed, $"Failed to unregister a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } public Task<int> ProducerCount(StreamId streamId) { return Task.FromResult(State.Producers.Count); } public Task<int> ConsumerCount(StreamId streamId) { return Task.FromResult(GetConsumersForStream(streamId).Length); } public Task<PubSubSubscriptionState[]> DiagGetConsumers(StreamId streamId) { return Task.FromResult(GetConsumersForStream(streamId)); } private PubSubSubscriptionState[] GetConsumersForStream(StreamId streamId) { return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray(); } private void LogPubSubCounts(string fmt, params object[] args) { if (logger.IsVerbose || DEBUG_PUB_SUB) { int numProducers = 0; int numConsumers = 0; if (State?.Producers != null) numProducers = State.Producers.Count; if (State?.Consumers != null) numConsumers = State.Consumers.Count; string when = args != null && args.Length != 0 ? string.Format(fmt, args) : fmt; logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}", when, numProducers, numConsumers, Utils.EnumerableToString(State?.Consumers), Utils.EnumerableToString(State?.Producers)); } } // Check that what we have cached locally matches what is in the persistent table. public async Task Validate() { var captureProducers = State.Producers; var captureConsumers = State.Consumers; await ReadStateAsync(); if (captureProducers.Count != State.Producers.Count) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={captureProducers.Count}, State.Producers.Count={State.Producers.Count}"); } if (captureProducers.Any(producer => !State.Producers.Contains(producer))) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={Utils.EnumerableToString(captureProducers)}, State.Producers={Utils.EnumerableToString(State.Producers)}"); } if (captureConsumers.Count != State.Consumers.Count) { LogPubSubCounts("Validate: Consumer count mismatch"); throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={captureConsumers.Count}, State.Consumers.Count={State.Consumers.Count}"); } if (captureConsumers.Any(consumer => !State.Consumers.Contains(consumer))) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={Utils.EnumerableToString(captureConsumers)}, State.Consumers={Utils.EnumerableToString(State.Consumers)}"); } } public Task<List<StreamSubscription>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer) { var grainRef = streamConsumer as GrainReference; if (grainRef != null) { List<StreamSubscription> subscriptions = State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer)) .Select( c => new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId, grainRef.GrainId)).ToList(); return Task.FromResult(subscriptions); } else { List<StreamSubscription> subscriptions = State.Consumers.Where(c => !c.IsFaulted) .Select( c => new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId, c.consumerReference.GrainId)).ToList(); return Task.FromResult(subscriptions); } } public async Task FaultSubscription(GuidId subscriptionId) { PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId)); if (pubSubState == null) { return; } try { pubSubState.Fault(); if (logger.IsVerbose) logger.Verbose("Setting subscription {0} to a faulted state.", subscriptionId.Guid); await WriteStateAsync(); await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream); } catch (Exception exc) { logger.Error(ErrorCode.Stream_SetSubscriptionToFaultedFailed, $"Failed to set subscription state to faulted. SubscriptionId {subscriptionId}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, StreamId streamId) { int numProducersBeforeNotify = State.Producers.Count; if (numProducersBeforeNotify > 0) { if (logger.IsVerbose) logger.Verbose("Notifying {0} existing producers about unregistered consumer.", numProducersBeforeNotify); // Notify producers about unregistered consumer. List<Task> tasks = State.Producers .Select(producerState => ExecuteProducerTask(producerState, producerState.Producer.RemoveSubscriber(subscriptionId, streamId))) .ToList(); await Task.WhenAll(tasks); //if producers got removed if (State.Producers.Count < numProducersBeforeNotify) await this.WriteStateAsync(); } } /// <summary> /// Try clear state will only clear the state if there are no producers or consumers. /// </summary> /// <returns></returns> private async Task<bool> TryClearState() { if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause { await ClearStateAsync(); //State contains no producers or consumers, remove it from storage return true; } return false; } private async Task ExecuteProducerTask(PubSubPublisherState producer, Task producerTask) { try { await producerTask; } catch (GrainExtensionNotInstalledException) { RemoveProducer(producer); } catch (ClientNotAvailableException) { RemoveProducer(producer); } catch (OrleansMessageRejectionException) { var grainRef = producer.Producer as GrainReference; // if producer is a system target on and unavailable silo, remove it. if (grainRef == null || grainRef.GrainId.IsSystemTarget && siloStatusOracle.GetApproximateSiloStatus(grainRef.SystemTargetSilo).IsUnavailable()) { RemoveProducer(producer); } else // otherwise, throw { throw; } } } } }
namespace AngleSharp.Dom { using AngleSharp.Dom.Collections; using AngleSharp.Extensions; using AngleSharp.Html; using System; using System.IO; /// <summary> /// Represents a node in the generated tree. /// </summary> abstract class Node : EventTarget, INode, IEquatable<INode> { #region Fields readonly NodeType _type; readonly String _name; readonly NodeFlags _flags; Url _baseUri; Node _parent; NodeList _children; private Document _owner; #endregion #region ctor internal Node(Document owner, String name, NodeType type = NodeType.Element, NodeFlags flags = NodeFlags.None) { _owner = owner; _name = name ?? String.Empty; _type = type; _children = this.CreateChildren(); _flags = flags; } #endregion #region Public Properties public Boolean HasChildNodes { get { return _children.Length != 0; } } public String BaseUri { get { return BaseUrl?.Href ?? String.Empty; } } public Url BaseUrl { get { if (_baseUri != null) { return _baseUri; } else if (_parent != null) { foreach (var ancestor in this.Ancestors<Node>()) { if (ancestor._baseUri != null) { return ancestor._baseUri; } } } var document = Owner; if (document != null) { return document._baseUri ?? document.DocumentUrl; } else if (_type == NodeType.Document) { document = (Document)this; return document.DocumentUrl; } return null; } set { _baseUri = value; } } public NodeType NodeType { get { return _type; } } public virtual String NodeValue { get { return null; } set { } } public virtual String TextContent { get { return null; } set { } } INode INode.PreviousSibling { get { return PreviousSibling; } } INode INode.NextSibling { get { return NextSibling; } } INode INode.FirstChild { get { return FirstChild; } } INode INode.LastChild { get { return LastChild; } } IDocument INode.Owner { get { return Owner; } } INode INode.Parent { get { return _parent; } } public IElement ParentElement { get { return _parent as IElement; } } INodeList INode.ChildNodes { get { return _children; } } public String NodeName { get { return _name; } } #endregion #region Internal Properties internal Node PreviousSibling { get { if (_parent != null) { var n = _parent._children.Length; for (var i = 1; i < n; i++) { if (Object.ReferenceEquals(_parent._children[i], this)) { return _parent._children[i - 1]; } } } return null; } } internal Node NextSibling { get { if (_parent != null) { var n = _parent._children.Length - 1; for (var i = 0; i < n; i++) { if (Object.ReferenceEquals(_parent._children[i], this)) { return _parent._children[i + 1]; } } } return null; } } internal Node FirstChild { get { return _children.Length > 0 ? _children[0] : null; } } internal Node LastChild { get { return _children.Length > 0 ? _children[_children.Length - 1] : null; } } internal NodeFlags Flags { get { return _flags; } } internal NodeList ChildNodes { get { return _children; } set { _children = value; } } internal Node Parent { get { return _parent; } set { _parent = value; } } internal Document Owner { get { if (_type == NodeType.Document) { return default(Document); } return _owner; } set { foreach (var descendentAndSelf in this.DescendentsAndSelf<Node>()) { var oldDocument = descendentAndSelf.Owner; if (!Object.ReferenceEquals(oldDocument, value)) { descendentAndSelf._owner = value; if (oldDocument != null) { NodeIsAdopted(oldDocument); } } } } } #endregion #region Internal Methods internal void AppendText(String s) { var lastChild = LastChild as TextNode; if (lastChild == null) { AddNode(new TextNode(Owner, s)); } else { lastChild.Append(s); } } internal void InsertText(Int32 index, String s) { if (index > 0 && index <= _children.Length && _children[index - 1].NodeType == NodeType.Text) { var node = (IText)_children[index - 1]; node.Append(s); } else if (index >= 0 && index < _children.Length && _children[index].NodeType == NodeType.Text) { var node = (IText)_children[index]; node.Insert(0, s); } else { var node = new TextNode(Owner, s); InsertNode(index, node); } } #endregion #region Public Methods public virtual void ToHtml(TextWriter writer, IMarkupFormatter formatter) { writer.Write(TextContent); } public INode AppendChild(INode child) { return this.PreInsert(child, null); } public INode InsertChild(Int32 index, INode child) { var reference = index < _children.Length ? _children[index] : null; return this.PreInsert(child, reference); } public INode InsertBefore(INode newElement, INode referenceElement) { return this.PreInsert(newElement, referenceElement); } public INode ReplaceChild(INode newChild, INode oldChild) { return this.ReplaceChild(newChild as Node, oldChild as Node, false); } public INode RemoveChild(INode child) { return this.PreRemove(child); } public abstract INode Clone(Boolean deep = true); public DocumentPositions CompareDocumentPosition(INode otherNode) { if (Object.ReferenceEquals(this, otherNode)) { return DocumentPositions.Same; } else if (!Object.ReferenceEquals(Owner, otherNode.Owner)) { var relative = otherNode.GetHashCode() > GetHashCode() ? DocumentPositions.Following : DocumentPositions.Preceding; return DocumentPositions.Disconnected | DocumentPositions.ImplementationSpecific | relative; } else if (otherNode.IsAncestorOf(this)) { return DocumentPositions.Contains | DocumentPositions.Preceding; } else if (otherNode.IsDescendantOf(this)) { return DocumentPositions.ContainedBy | DocumentPositions.Following; } else if (otherNode.IsPreceding(this)) { return DocumentPositions.Preceding; } return DocumentPositions.Following; } public Boolean Contains(INode otherNode) { return this.IsInclusiveAncestorOf(otherNode); } public void Normalize() { for (var i = 0; i < _children.Length; i++) { var text = _children[i] as TextNode; if (text != null) { var length = text.Length; if (length == 0) { RemoveChild(text, false); i--; } else { var sb = Pool.NewStringBuilder(); var sibling = text; var end = i; var owner = Owner; while ((sibling = sibling.NextSibling as TextNode) != null) { sb.Append(sibling.Data); end++; owner.ForEachRange(m => m.Head == sibling, m => m.StartWith(text, length)); owner.ForEachRange(m => m.Tail == sibling, m => m.EndWith(text, length)); owner.ForEachRange(m => m.Head == sibling.Parent && m.Start == end, m => m.StartWith(text, length)); owner.ForEachRange(m => m.Tail == sibling.Parent && m.End == end, m => m.EndWith(text, length)); length += sibling.Length; } text.Replace(text.Length, 0, sb.ToPool()); for (var j = end; j > i; j--) { RemoveChild(_children[j], false); } } } else if (_children[i].HasChildNodes) { _children[i].Normalize(); } } } public String LookupNamespaceUri(String prefix) { if (String.IsNullOrEmpty(prefix)) { prefix = null; } return LocateNamespace(prefix); } public String LookupPrefix(String namespaceUri) { if (String.IsNullOrEmpty(namespaceUri)) { return null; } return LocatePrefix(namespaceUri); } public Boolean IsDefaultNamespace(String namespaceUri) { if (String.IsNullOrEmpty(namespaceUri)) { namespaceUri = null; } var defaultNamespace = LocateNamespace(null); return namespaceUri.Is(defaultNamespace); } public virtual Boolean Equals(INode otherNode) { if (BaseUri.Is(otherNode.BaseUri) && NodeName.Is(otherNode.NodeName) && ChildNodes.Length == otherNode.ChildNodes.Length) { for (var i = 0; i < _children.Length; i++) { if (!_children[i].Equals(otherNode.ChildNodes[i])) { return false; } } return true; } return false; } #endregion #region Helpers /// <summary> /// For more information, see: /// https://dom.spec.whatwg.org/#validate-and-extract /// </summary> protected static void GetPrefixAndLocalName(String qualifiedName, ref String namespaceUri, out String prefix, out String localName) { if (!qualifiedName.IsXmlName()) throw new DomException(DomError.InvalidCharacter); if (!qualifiedName.IsQualifiedName()) throw new DomException(DomError.Namespace); if (String.IsNullOrEmpty(namespaceUri)) { namespaceUri = null; } var index = qualifiedName.IndexOf(Symbols.Colon); if (index > 0) { prefix = qualifiedName.Substring(0, index); localName = qualifiedName.Substring(index + 1); } else { prefix = null; localName = qualifiedName; } if (IsNamespaceError(prefix, namespaceUri, qualifiedName)) throw new DomException(DomError.Namespace); } protected static Boolean IsNamespaceError(String prefix, String namespaceUri, String qualifiedName) { return (prefix != null && namespaceUri == null) || (prefix.Is(NamespaceNames.XmlPrefix) && !namespaceUri.Is(NamespaceNames.XmlUri)) || ((qualifiedName.Is(NamespaceNames.XmlNsPrefix) || prefix.Is(NamespaceNames.XmlNsPrefix)) && !namespaceUri.Is(NamespaceNames.XmlNsUri)) || (namespaceUri.Is(NamespaceNames.XmlNsUri) && (!qualifiedName.Is(NamespaceNames.XmlNsPrefix) && !prefix.Is(NamespaceNames.XmlNsPrefix))); } protected virtual String LocateNamespace(String prefix) { return _parent?.LocateNamespace(prefix); } protected virtual String LocatePrefix(String namespaceUri) { return _parent?.LocatePrefix(namespaceUri); } internal void ChangeOwner(Document document) { var oldDocument = Owner; _parent?.RemoveChild(this, false); Owner = document; NodeIsAdopted(oldDocument); } internal void InsertNode(Int32 index, Node node) { node.Parent = this; _children.Insert(index, node); } internal void AddNode(Node node) { node.Parent = this; _children.Add(node); } internal void RemoveNode(Int32 index, Node node) { node.Parent = null; _children.RemoveAt(index); } internal void ReplaceAll(Node node, Boolean suppressObservers) { var document = Owner; if (node != null) { document.AdoptNode(node); } var removedNodes = new NodeList(); var addedNodes = new NodeList(); removedNodes.AddRange(_children); if (node != null) { if (node.NodeType == NodeType.DocumentFragment) { addedNodes.AddRange(node._children); } else { addedNodes.Add(node); } } for (var i = 0; i < removedNodes.Length; i++) { RemoveChild(removedNodes[i], true); } for (var i = 0; i < addedNodes.Length; i++) { InsertBefore(addedNodes[i], null, true); } if (!suppressObservers) { document.QueueMutation(MutationRecord.ChildList( target: this, addedNodes: addedNodes, removedNodes: removedNodes)); } } internal INode InsertBefore(Node newElement, Node referenceElement, Boolean suppressObservers) { var document = Owner; var count = newElement.NodeType == NodeType.DocumentFragment ? newElement.ChildNodes.Length : 1; if (referenceElement != null && document != null) { var childIndex = referenceElement.Index(); document.ForEachRange(m => m.Head == this && m.Start > childIndex, m => m.StartWith(this, m.Start + count)); document.ForEachRange(m => m.Tail == this && m.End > childIndex, m => m.EndWith(this, m.End + count)); } if (newElement.NodeType == NodeType.Document || newElement.Contains(this)) throw new DomException(DomError.HierarchyRequest); var addedNodes = new NodeList(); var n = _children.Index(referenceElement); if (n == -1) { n = _children.Length; } if (newElement._type == NodeType.DocumentFragment) { var end = n; var start = n; while (newElement.HasChildNodes) { var child = newElement.ChildNodes[0]; newElement.RemoveChild(child, true); InsertNode(end, child); end++; } while (start < end) { var child = _children[start]; addedNodes.Add(child); NodeIsInserted(child); start++; } } else { addedNodes.Add(newElement); InsertNode(n, newElement); NodeIsInserted(newElement); } if (!suppressObservers && document != null) { document.QueueMutation(MutationRecord.ChildList( target: this, addedNodes: addedNodes, previousSibling: n > 0 ? _children[n - 1] : null, nextSibling: referenceElement)); } return newElement; } internal void RemoveChild(Node node, Boolean suppressObservers) { var document = Owner; var index = _children.Index(node); if (document != null) { document.ForEachRange(m => m.Head.IsInclusiveDescendantOf(node), m => m.StartWith(this, index)); document.ForEachRange(m => m.Tail.IsInclusiveDescendantOf(node), m => m.EndWith(this, index)); document.ForEachRange(m => m.Head == this && m.Start > index, m => m.StartWith(this, m.Start - 1)); document.ForEachRange(m => m.Tail == this && m.End > index, m => m.EndWith(this, m.End - 1)); } var oldPreviousSibling = index > 0 ? _children[index - 1] : null; if (!suppressObservers && document != null) { var removedNodes = new NodeList { node }; document.QueueMutation(MutationRecord.ChildList( target: this, removedNodes: removedNodes, previousSibling: oldPreviousSibling, nextSibling: node.NextSibling)); document.AddTransientObserver(node); } RemoveNode(index, node); NodeIsRemoved(node, oldPreviousSibling); } internal INode ReplaceChild(Node node, Node child, Boolean suppressObservers) { if (this.IsEndPoint() || node.IsHostIncludingInclusiveAncestor(this)) throw new DomException(DomError.HierarchyRequest); if (child.Parent != this) throw new DomException(DomError.NotFound); if (node.IsInsertable()) { var parent = _parent as IDocument; var referenceChild = child.NextSibling; var document = Owner; var addedNodes = new NodeList(); var removedNodes = new NodeList(); if (parent != null) { var forbidden = false; switch (node._type) { case NodeType.DocumentType: forbidden = parent.Doctype != child || child.IsPrecededByElement(); break; case NodeType.Element: forbidden = parent.DocumentElement != child || child.IsFollowedByDoctype(); break; case NodeType.DocumentFragment: var elements = node.GetElementCount(); forbidden = elements > 1 || node.HasTextNodes() || (elements == 1 && (parent.DocumentElement != child || child.IsFollowedByDoctype())); break; } if (forbidden) throw new DomException(DomError.HierarchyRequest); } if (referenceChild == node) { referenceChild = node.NextSibling; } document?.AdoptNode(node); RemoveChild(child, true); InsertBefore(node, referenceChild, true); removedNodes.Add(child); if (node._type == NodeType.DocumentFragment) { addedNodes.AddRange(node._children); } else { addedNodes.Add(node); } if (!suppressObservers && document != null) { document.QueueMutation(MutationRecord.ChildList( target: this, addedNodes: addedNodes, removedNodes: removedNodes, previousSibling: child.PreviousSibling, nextSibling: referenceChild)); } return child; } throw new DomException(DomError.HierarchyRequest); } /// <summary> /// Run any adopting steps defined for node in other applicable /// specifications and pass node and oldDocument as parameters. /// </summary> internal virtual void NodeIsAdopted(Document oldDocument) { } /// <summary> /// Specifications may define insertion steps for all or some nodes. /// </summary> internal virtual void NodeIsInserted(Node newNode) { newNode.OnParentChanged(); } /// <summary> /// Specifications may define removing steps for all or some nodes. /// </summary> internal virtual void NodeIsRemoved(Node removedNode, Node oldPreviousSibling) { removedNode.OnParentChanged(); } protected virtual void OnParentChanged() { //TODO } protected void CloneNode(Node target, Boolean deep) { target._baseUri = _baseUri; if (deep) { foreach (var child in _children) { target.AddNode((Node)child.Clone(true)); } } } #endregion } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * PageSpeed Insights API Version v2 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/speed/docs/insights/v2/getting-started'>PageSpeed Insights API</a> * <tr><th>API Version<td>v2 * <tr><th>API Rev<td>20190129 (1489) * <tr><th>API Docs * <td><a href='https://developers.google.com/speed/docs/insights/v2/getting-started'> * https://developers.google.com/speed/docs/insights/v2/getting-started</a> * <tr><th>Discovery Name<td>pagespeedonline * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using PageSpeed Insights API can be found at * <a href='https://developers.google.com/speed/docs/insights/v2/getting-started'>https://developers.google.com/speed/docs/insights/v2/getting-started</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Pagespeedonline.v2 { /// <summary>The Pagespeedonline Service.</summary> public class PagespeedonlineService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v2"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public PagespeedonlineService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PagespeedonlineService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { pagespeedapi = new PagespeedapiResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "pagespeedonline"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/pagespeedonline/v2/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "pagespeedonline/v2/"; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://www.googleapis.com/batch/pagespeedonline/v2"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch/pagespeedonline/v2"; } } #endif private readonly PagespeedapiResource pagespeedapi; /// <summary>Gets the Pagespeedapi resource.</summary> public virtual PagespeedapiResource Pagespeedapi { get { return pagespeedapi; } } } ///<summary>A base abstract class for Pagespeedonline requests.</summary> public abstract class PagespeedonlineBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new PagespeedonlineBaseServiceRequest instance.</summary> protected PagespeedonlineBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>An opaque string that represents a user for quota purposes. Must not exceed 40 /// characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Deprecated. Please use quotaUser instead.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Pagespeedonline parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "pagespeedapi" collection of methods.</summary> public class PagespeedapiResource { private const string Resource = "pagespeedapi"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PagespeedapiResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of /// suggestions to make that page faster, and other information.</summary> /// <param name="url">The URL to fetch and analyze</param> public virtual RunpagespeedRequest Runpagespeed(string url) { return new RunpagespeedRequest(service, url); } /// <summary>Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of /// suggestions to make that page faster, and other information.</summary> public class RunpagespeedRequest : PagespeedonlineBaseServiceRequest<Google.Apis.Pagespeedonline.v2.Data.Result> { /// <summary>Constructs a new Runpagespeed request.</summary> public RunpagespeedRequest(Google.Apis.Services.IClientService service, string url) : base(service) { Url = url; InitParameters(); } /// <summary>The URL to fetch and analyze</summary> [Google.Apis.Util.RequestParameterAttribute("url", Google.Apis.Util.RequestParameterType.Query)] public virtual string Url { get; private set; } /// <summary>Indicates if third party resources should be filtered out before PageSpeed analysis.</summary> /// [default: false] [Google.Apis.Util.RequestParameterAttribute("filter_third_party_resources", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> FilterThirdPartyResources { get; set; } /// <summary>The locale used to localize formatted results</summary> [Google.Apis.Util.RequestParameterAttribute("locale", Google.Apis.Util.RequestParameterType.Query)] public virtual string Locale { get; set; } /// <summary>A PageSpeed rule to run; if none are given, all rules are run</summary> [Google.Apis.Util.RequestParameterAttribute("rule", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Rule { get; set; } /// <summary>Indicates if binary data containing a screenshot should be included</summary> /// [default: false] [Google.Apis.Util.RequestParameterAttribute("screenshot", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Screenshot { get; set; } /// <summary>The analysis strategy to use</summary> [Google.Apis.Util.RequestParameterAttribute("strategy", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<StrategyEnum> Strategy { get; set; } /// <summary>The analysis strategy to use</summary> public enum StrategyEnum { /// <summary>Fetch and analyze the URL for desktop browsers</summary> [Google.Apis.Util.StringValueAttribute("desktop")] Desktop, /// <summary>Fetch and analyze the URL for mobile devices</summary> [Google.Apis.Util.StringValueAttribute("mobile")] Mobile, } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "runpagespeed"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "runPagespeed"; } } /// <summary>Initializes Runpagespeed parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "url", new Google.Apis.Discovery.Parameter { Name = "url", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = @"(?i)http(s)?://.*", }); RequestParameters.Add( "filter_third_party_resources", new Google.Apis.Discovery.Parameter { Name = "filter_third_party_resources", IsRequired = false, ParameterType = "query", DefaultValue = "false", Pattern = null, }); RequestParameters.Add( "locale", new Google.Apis.Discovery.Parameter { Name = "locale", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"[a-zA-Z]+(_[a-zA-Z]+)?", }); RequestParameters.Add( "rule", new Google.Apis.Discovery.Parameter { Name = "rule", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"[a-zA-Z]+", }); RequestParameters.Add( "screenshot", new Google.Apis.Discovery.Parameter { Name = "screenshot", IsRequired = false, ParameterType = "query", DefaultValue = "false", Pattern = null, }); RequestParameters.Add( "strategy", new Google.Apis.Discovery.Parameter { Name = "strategy", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Pagespeedonline.v2.Data { public class PagespeedApiFormatStringV2 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>List of arguments for the format string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("args")] public virtual System.Collections.Generic.IList<PagespeedApiFormatStringV2.ArgsData> Args { get; set; } /// <summary>A localized format string with {{FOO}} placeholders, where 'FOO' is the key of the argument whose /// value should be substituted. For HYPERLINK arguments, the format string will instead contain {{BEGIN_FOO}} /// and {{END_FOO}} for the argument with key 'FOO'.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } public class ArgsData { /// <summary>The placeholder key for this arg, as a string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("key")] public virtual string Key { get; set; } /// <summary>The screen rectangles being referred to, with dimensions measured in CSS pixels. This is only /// ever used for SNAPSHOT_RECT arguments. If this is absent for a SNAPSHOT_RECT argument, it means that /// that argument refers to the entire snapshot.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rects")] public virtual System.Collections.Generic.IList<ArgsData.RectsData> Rects { get; set; } /// <summary>Secondary screen rectangles being referred to, with dimensions measured in CSS pixels. This is /// only ever used for SNAPSHOT_RECT arguments.</summary> [Newtonsoft.Json.JsonPropertyAttribute("secondary_rects")] public virtual System.Collections.Generic.IList<ArgsData.SecondaryRectsData> SecondaryRects { get; set; } /// <summary>Type of argument. One of URL, STRING_LITERAL, INT_LITERAL, BYTES, DURATION, VERBATIM_STRING, /// PERCENTAGE, HYPERLINK, or SNAPSHOT_RECT.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>Argument value, as a localized string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } public class RectsData { /// <summary>The height of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>The left coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("left")] public virtual System.Nullable<int> Left { get; set; } /// <summary>The top coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("top")] public virtual System.Nullable<int> Top { get; set; } /// <summary>The width of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } } public class SecondaryRectsData { /// <summary>The height of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>The left coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("left")] public virtual System.Nullable<int> Left { get; set; } /// <summary>The top coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("top")] public virtual System.Nullable<int> Top { get; set; } /// <summary>The width of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } } } } public class PagespeedApiImageV2 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Image data base64 encoded.</summary> [Newtonsoft.Json.JsonPropertyAttribute("data")] public virtual string Data { get; set; } /// <summary>Height of screenshot in pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>Unique string key, if any, identifying this image.</summary> [Newtonsoft.Json.JsonPropertyAttribute("key")] public virtual string Key { get; set; } /// <summary>Mime type of image data (e.g. "image/jpeg").</summary> [Newtonsoft.Json.JsonPropertyAttribute("mime_type")] public virtual string MimeType { get; set; } /// <summary>The region of the page that is captured by this image, with dimensions measured in CSS /// pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("page_rect")] public virtual PagespeedApiImageV2.PageRectData PageRect { get; set; } /// <summary>Width of screenshot in pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>The region of the page that is captured by this image, with dimensions measured in CSS /// pixels.</summary> public class PageRectData { /// <summary>The height of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>The left coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("left")] public virtual System.Nullable<int> Left { get; set; } /// <summary>The top coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("top")] public virtual System.Nullable<int> Top { get; set; } /// <summary>The width of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } } } public class Result : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The captcha verify result</summary> [Newtonsoft.Json.JsonPropertyAttribute("captchaResult")] public virtual string CaptchaResult { get; set; } /// <summary>Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and /// run by the server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("formattedResults")] public virtual Result.FormattedResultsData FormattedResults { get; set; } /// <summary>Canonicalized and final URL for the document, after following page redirects (if any).</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>List of rules that were specified in the request, but which the server did not know how to /// instantiate.</summary> [Newtonsoft.Json.JsonPropertyAttribute("invalidRules")] public virtual System.Collections.Generic.IList<string> InvalidRules { get; set; } /// <summary>Kind of result.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, /// etc.</summary> [Newtonsoft.Json.JsonPropertyAttribute("pageStats")] public virtual Result.PageStatsData PageStats { get; set; } /// <summary>Response code for the document. 200 indicates a normal page load. 4xx/5xx indicates an /// error.</summary> [Newtonsoft.Json.JsonPropertyAttribute("responseCode")] public virtual System.Nullable<int> ResponseCode { get; set; } /// <summary>A map with one entry for each rule group in these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ruleGroups")] public virtual System.Collections.Generic.IDictionary<string,Result.RuleGroupsDataElement> RuleGroups { get; set; } /// <summary>Base64-encoded screenshot of the page that was analyzed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("screenshot")] public virtual PagespeedApiImageV2 Screenshot { get; set; } /// <summary>Title of the page, as displayed in the browser's title bar.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The version of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual Result.VersionData Version { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and /// run by the server.</summary> public class FormattedResultsData { /// <summary>The locale of the formattedResults, e.g. "en_US".</summary> [Newtonsoft.Json.JsonPropertyAttribute("locale")] public virtual string Locale { get; set; } /// <summary>Dictionary of formatted rule results, with one entry for each PageSpeed rule instantiated and /// run by the server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ruleResults")] public virtual System.Collections.Generic.IDictionary<string,FormattedResultsData.RuleResultsDataElement> RuleResults { get; set; } /// <summary>The enum-like identifier for this rule. For instance "EnableKeepAlive" or "AvoidCssImport". Not /// localized.</summary> public class RuleResultsDataElement { /// <summary>List of rule groups that this rule belongs to. Each entry in the list is one of "SPEED" or /// "USABILITY".</summary> [Newtonsoft.Json.JsonPropertyAttribute("groups")] public virtual System.Collections.Generic.IList<string> Groups { get; set; } /// <summary>Localized name of the rule, intended for presentation to a user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("localizedRuleName")] public virtual string LocalizedRuleName { get; set; } /// <summary>The impact (unbounded floating point value) that implementing the suggestions for this rule /// would have on making the page faster. Impact is comparable between rules to determine which rule's /// suggestions would have a higher or lower impact on making a page faster. For instance, if enabling /// compression would save 1MB, while optimizing images would save 500kB, the enable compression rule /// would have 2x the impact of the image optimization rule, all other things being equal.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ruleImpact")] public virtual System.Nullable<double> RuleImpact { get; set; } /// <summary>A brief summary description for the rule, indicating at a high level what should be done to /// follow the rule and what benefit can be gained by doing so.</summary> [Newtonsoft.Json.JsonPropertyAttribute("summary")] public virtual PagespeedApiFormatStringV2 Summary { get; set; } /// <summary>List of blocks of URLs. Each block may contain a heading and a list of URLs. Each URL may /// optionally include additional details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("urlBlocks")] public virtual System.Collections.Generic.IList<RuleResultsDataElement.UrlBlocksData> UrlBlocks { get; set; } public class UrlBlocksData { /// <summary>Heading to be displayed with the list of URLs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("header")] public virtual PagespeedApiFormatStringV2 Header { get; set; } /// <summary>List of entries that provide information about URLs in the url block. /// Optional.</summary> [Newtonsoft.Json.JsonPropertyAttribute("urls")] public virtual System.Collections.Generic.IList<UrlBlocksData.UrlsData> Urls { get; set; } public class UrlsData { /// <summary>List of entries that provide additional details about a single URL. /// Optional.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<PagespeedApiFormatStringV2> Details { get; set; } /// <summary>A format string that gives information about the URL, and a list of arguments for /// that format string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("result")] public virtual PagespeedApiFormatStringV2 Result { get; set; } } } } } /// <summary>Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, /// etc.</summary> public class PageStatsData { /// <summary>Number of uncompressed response bytes for CSS resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("cssResponseBytes")] public virtual System.Nullable<long> CssResponseBytes { get; set; } /// <summary>Number of response bytes for flash resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("flashResponseBytes")] public virtual System.Nullable<long> FlashResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for the main HTML document and all iframes on the /// page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("htmlResponseBytes")] public virtual System.Nullable<long> HtmlResponseBytes { get; set; } /// <summary>Number of response bytes for image resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("imageResponseBytes")] public virtual System.Nullable<long> ImageResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for JS resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("javascriptResponseBytes")] public virtual System.Nullable<long> JavascriptResponseBytes { get; set; } /// <summary>Number of CSS resources referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberCssResources")] public virtual System.Nullable<int> NumberCssResources { get; set; } /// <summary>Number of unique hosts referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberHosts")] public virtual System.Nullable<int> NumberHosts { get; set; } /// <summary>Number of JavaScript resources referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberJsResources")] public virtual System.Nullable<int> NumberJsResources { get; set; } /// <summary>Number of HTTP resources loaded by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberResources")] public virtual System.Nullable<int> NumberResources { get; set; } /// <summary>Number of static (i.e. cacheable) resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberStaticResources")] public virtual System.Nullable<int> NumberStaticResources { get; set; } /// <summary>Number of response bytes for other resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("otherResponseBytes")] public virtual System.Nullable<long> OtherResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for text resources not covered by other statistics (i.e /// non-HTML, non-script, non-CSS resources) on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("textResponseBytes")] public virtual System.Nullable<long> TextResponseBytes { get; set; } /// <summary>Total size of all request bytes sent by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("totalRequestBytes")] public virtual System.Nullable<long> TotalRequestBytes { get; set; } } /// <summary>The name of this rule group: one of "SPEED" or "USABILITY".</summary> public class RuleGroupsDataElement { /// <summary>The score (0-100) for this rule group, which indicates how much better a page could be in that /// category (e.g. how much faster, or how much more usable). A high score indicates little room for /// improvement, while a lower score indicates more room for improvement.</summary> [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual System.Nullable<int> Score { get; set; } } /// <summary>The version of PageSpeed used to generate these results.</summary> public class VersionData { /// <summary>The major version number of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("major")] public virtual System.Nullable<int> Major { get; set; } /// <summary>The minor version number of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("minor")] public virtual System.Nullable<int> Minor { get; set; } } } }
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; namespace ZXing.Common { /// <summary> /// Common string-related functions. /// </summary> /// <author>Sean Owen</author> /// <author>Alex Dupre</author> public static class StringUtils { #if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || WINDOWS_PHONE80 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE) private static String PLATFORM_DEFAULT_ENCODING = "UTF-8"; #else private static String PLATFORM_DEFAULT_ENCODING = Encoding.Default.WebName; #endif public static String SHIFT_JIS = "SJIS"; public static String GB2312 = "GB2312"; private const String EUC_JP = "EUC-JP"; private const String UTF8 = "UTF-8"; private const String ISO88591 = "ISO-8859-1"; private static readonly bool ASSUME_SHIFT_JIS = String.Compare(SHIFT_JIS, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(EUC_JP, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0; /// <summary> /// Guesses the encoding. /// </summary> /// <param name="bytes">bytes encoding a string, whose encoding should be guessed</param> /// <param name="hints">decode hints if applicable</param> /// <returns>name of guessed encoding; at the moment will only guess one of: /// {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform /// default encoding if none of these can possibly be correct</returns> public static String guessEncoding(byte[] bytes, IDictionary<DecodeHintType, object> hints) { if (hints != null && hints.ContainsKey(DecodeHintType.CHARACTER_SET)) { String characterSet = (String)hints[DecodeHintType.CHARACTER_SET]; if (characterSet != null) { return characterSet; } } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. int length = bytes.Length; bool canBeISO88591 = true; bool canBeShiftJIS = true; bool canBeUTF8 = true; int utf8BytesLeft = 0; //int utf8LowChars = 0; int utf2BytesChars = 0; int utf3BytesChars = 0; int utf4BytesChars = 0; int sjisBytesLeft = 0; //int sjisLowChars = 0; int sjisKatakanaChars = 0; //int sjisDoubleBytesChars = 0; int sjisCurKatakanaWordLength = 0; int sjisCurDoubleBytesWordLength = 0; int sjisMaxKatakanaWordLength = 0; int sjisMaxDoubleBytesWordLength = 0; //int isoLowChars = 0; //int isoHighChars = 0; int isoHighOther = 0; bool utf8bom = bytes.Length > 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); i++) { int value = bytes[i] & 0xFF; // UTF-8 stuff if (canBeUTF8) { if (utf8BytesLeft > 0) { if ((value & 0x80) == 0) { canBeUTF8 = false; } else { utf8BytesLeft--; } } else if ((value & 0x80) != 0) { if ((value & 0x40) == 0) { canBeUTF8 = false; } else { utf8BytesLeft++; if ((value & 0x20) == 0) { utf2BytesChars++; } else { utf8BytesLeft++; if ((value & 0x10) == 0) { utf3BytesChars++; } else { utf8BytesLeft++; if ((value & 0x08) == 0) { utf4BytesChars++; } else { canBeUTF8 = false; } } } } } //else { //utf8LowChars++; //} } // ISO-8859-1 stuff if (canBeISO88591) { if (value > 0x7F && value < 0xA0) { canBeISO88591 = false; } else if (value > 0x9F) { if (value < 0xC0 || value == 0xD7 || value == 0xF7) { isoHighOther++; } //else { //isoHighChars++; //} } //else { //isoLowChars++; //} } // Shift_JIS stuff if (canBeShiftJIS) { if (sjisBytesLeft > 0) { if (value < 0x40 || value == 0x7F || value > 0xFC) { canBeShiftJIS = false; } else { sjisBytesLeft--; } } else if (value == 0x80 || value == 0xA0 || value > 0xEF) { canBeShiftJIS = false; } else if (value > 0xA0 && value < 0xE0) { sjisKatakanaChars++; sjisCurDoubleBytesWordLength = 0; sjisCurKatakanaWordLength++; if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) { sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength; } } else if (value > 0x7F) { sjisBytesLeft++; //sjisDoubleBytesChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength++; if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) { sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength; } } else { //sjisLowChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength = 0; } } } if (canBeUTF8 && utf8BytesLeft > 0) { canBeUTF8 = false; } if (canBeShiftJIS && sjisBytesLeft > 0) { canBeShiftJIS = false; } // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) { return UTF8; } // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done if (canBeShiftJIS && (ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) { return SHIFT_JIS; } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is: // - If we saw // - only two consecutive katakana chars in the whole text, or // - at least 10% of bytes that could be "upper" not-alphanumeric Latin1, // - then we conclude Shift_JIS, else ISO-8859-1 if (canBeISO88591 && canBeShiftJIS) { return (sjisMaxKatakanaWordLength == 2 && sjisKatakanaChars == 2) || isoHighOther * 10 >= length ? SHIFT_JIS : ISO88591; } // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding if (canBeISO88591) { return ISO88591; } if (canBeShiftJIS) { return SHIFT_JIS; } if (canBeUTF8) { return UTF8; } // Otherwise, we take a wild guess with platform encoding return PLATFORM_DEFAULT_ENCODING; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace FSL.XFApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Groups { public class GroupsModule : IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<UUID, GroupMembershipData> m_GroupMap = new Dictionary<UUID, GroupMembershipData>(); private Dictionary<UUID, IClientAPI> m_ClientMap = new Dictionary<UUID, IClientAPI>(); private UUID opensimulatorGroupID = new UUID("00000000-68f9-1111-024e-222222111123"); private List<Scene> m_SceneList = new List<Scene>(); private static GroupMembershipData osGroup = new GroupMembershipData(); #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { m_log.Info("[GROUPS]: No configuration found. Using defaults"); } else { if (!groupsConfig.GetBoolean("Enabled", false)) { m_log.Info("[GROUPS]: Groups disabled in configuration"); return; } if (groupsConfig.GetString("Module", "Default") != "Default") return; } lock (m_SceneList) { if (!m_SceneList.Contains(scene)) { if (m_SceneList.Count == 0) { osGroup.GroupID = opensimulatorGroupID; osGroup.GroupName = "OpenSimulator Testing"; osGroup.GroupPowers = (uint)(GroupPowers.AllowLandmark | GroupPowers.AllowSetHome); m_GroupMap[opensimulatorGroupID] = osGroup; } m_SceneList.Add(scene); } } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClientClosed += OnClientClosed; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; } public void PostInitialise() { } public void Close() { // m_log.Debug("[GROUPS]: Shutting down group module."); lock (m_ClientMap) { m_ClientMap.Clear(); } lock (m_GroupMap) { m_GroupMap.Clear(); } } public string Name { get { return "GroupsModule"; } } public bool IsSharedModule { get { return true; } } #endregion private void OnNewClient(IClientAPI client) { // Subscribe to instant messages client.OnInstantMessage += OnInstantMessage; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; lock (m_ClientMap) { if (!m_ClientMap.ContainsKey(client.AgentId)) { m_ClientMap.Add(client.AgentId, client); } } GroupMembershipData[] updateGroups = new GroupMembershipData[1]; updateGroups[0] = osGroup; client.SendGroupMembership(updateGroups); } private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID AgentID, UUID SessionID) { UUID ActiveGroupID; string ActiveGroupName; ulong ActiveGroupPowers; string firstname = remoteClient.FirstName; string lastname = remoteClient.LastName; string ActiveGroupTitle = "I IZ N0T"; ActiveGroupID = osGroup.GroupID; ActiveGroupName = osGroup.GroupName; ActiveGroupPowers = osGroup.GroupPowers; remoteClient.SendAgentDataUpdate(AgentID, ActiveGroupID, firstname, lastname, ActiveGroupPowers, ActiveGroupName, ActiveGroupTitle); } private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { } private void OnGridInstantMessage(GridInstantMessage msg) { // Trigger the above event handler OnInstantMessage(null, msg); } private void HandleUUIDGroupNameRequest(UUID id,IClientAPI remote_client) { string groupnamereply = "Unknown"; UUID groupUUID = UUID.Zero; lock (m_GroupMap) { if (m_GroupMap.ContainsKey(id)) { GroupMembershipData grp = m_GroupMap[id]; groupnamereply = grp.GroupName; groupUUID = grp.GroupID; } } remote_client.SendGroupNameReply(groupUUID, groupnamereply); } private void OnClientClosed(UUID agentID, Scene scene) { lock (m_ClientMap) { if (m_ClientMap.ContainsKey(agentID)) { // IClientAPI cli = m_ClientMap[agentID]; // if (cli != null) // { // //m_log.Info("[GROUPS]: Removing all reference to groups for " + cli.Name); // } // else // { // //m_log.Info("[GROUPS]: Removing all reference to groups for " + agentID.ToString()); // } m_ClientMap.Remove(agentID); } } } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace tk2dEditor.SpriteCollectionEditor { // As nasty as this is, its a necessary evil for backwards compatibility public class SpriteCollectionProxy { public SpriteCollectionProxy() { } public SpriteCollectionProxy(tk2dSpriteCollection obj) { this.obj = obj; CopyFromSource(); } public void CopyFromSource() { this.obj.Upgrade(); // make sure its up to date textureParams = new List<tk2dSpriteCollectionDefinition>(obj.textureParams.Length); foreach (var v in obj.textureParams) { if (v == null) textureParams.Add(null); else { var t = new tk2dSpriteCollectionDefinition(); t.CopyFrom(v); textureParams.Add(t); } } spriteSheets = new List<tk2dSpriteSheetSource>(); if (obj.spriteSheets != null) { foreach (var v in obj.spriteSheets) { if (v == null) spriteSheets.Add(null); else { var t = new tk2dSpriteSheetSource(); t.CopyFrom(v); spriteSheets.Add(t); } } } fonts = new List<tk2dSpriteCollectionFont>(); if (obj.fonts != null) { foreach (var v in obj.fonts) { if (v == null) fonts.Add(null); else { var t = new tk2dSpriteCollectionFont(); t.CopyFrom(v); fonts.Add(t); } } } UpgradeLegacySpriteSheets(); var target = this; var source = obj; target.platforms = new List<tk2dSpriteCollectionPlatform>(); foreach (tk2dSpriteCollectionPlatform plat in source.platforms) { tk2dSpriteCollectionPlatform p = new tk2dSpriteCollectionPlatform(); p.CopyFrom(plat); target.platforms.Add(p); } if (target.platforms.Count == 0) { tk2dSpriteCollectionPlatform plat = new tk2dSpriteCollectionPlatform(); // add a null platform target.platforms.Add(plat); } target.assetName = source.assetName; target.loadable = source.loadable; target.maxTextureSize = source.maxTextureSize; target.forceTextureSize = source.forceTextureSize; target.forcedTextureWidth = source.forcedTextureWidth; target.forcedTextureHeight = source.forcedTextureHeight; target.textureCompression = source.textureCompression; target.atlasWidth = source.atlasWidth; target.atlasHeight = source.atlasHeight; target.forceSquareAtlas = source.forceSquareAtlas; target.atlasWastage = source.atlasWastage; target.allowMultipleAtlases = source.allowMultipleAtlases; target.spriteCollection = source.spriteCollection; target.premultipliedAlpha = source.premultipliedAlpha; CopyArray(ref target.altMaterials, source.altMaterials); CopyArray(ref target.atlasMaterials, source.atlasMaterials); CopyArray(ref target.atlasTextures, source.atlasTextures); target.useTk2dCamera = source.useTk2dCamera; target.targetHeight = source.targetHeight; target.targetOrthoSize = source.targetOrthoSize; target.globalScale = source.globalScale; target.physicsDepth = source.physicsDepth; target.disableTrimming = source.disableTrimming; target.normalGenerationMode = source.normalGenerationMode; target.padAmount = source.padAmount; target.autoUpdate = source.autoUpdate; target.editorDisplayScale = source.editorDisplayScale; // Texture settings target.filterMode = source.filterMode; target.wrapMode = source.wrapMode; target.userDefinedTextureSettings = source.userDefinedTextureSettings; target.mipmapEnabled = source.mipmapEnabled; target.anisoLevel = source.anisoLevel; } void CopyArray<T>(ref T[] dest, T[] source) { if (source == null) { dest = new T[0]; } else { dest = new T[source.Length]; for (int i = 0; i < source.Length; ++i) dest[i] = source[i]; } } void UpgradeLegacySpriteSheets() { if (spriteSheets != null) { for (int i = 0; i < spriteSheets.Count; ++i) { var spriteSheet = spriteSheets[i]; if (spriteSheet != null && spriteSheet.version == 0) { if (spriteSheet.texture == null) { spriteSheet.active = false; } else { spriteSheet.tileWidth = spriteSheet.texture.width / spriteSheet.tilesX; spriteSheet.tileHeight = spriteSheet.texture.height / spriteSheet.tilesY; spriteSheet.active = true; for (int j = 0; j < textureParams.Count; ++j) { var param = textureParams[j]; if (param.fromSpriteSheet && param.texture == spriteSheet.texture) { param.fromSpriteSheet = false; param.hasSpriteSheetId = true; param.spriteSheetId = i; param.spriteSheetX = param.regionId % spriteSheet.tilesX; param.spriteSheetY = param.regionId / spriteSheet.tilesX; } } } spriteSheet.version = tk2dSpriteSheetSource.CURRENT_VERSION; } } } } public void DeleteUnusedData() { foreach (tk2dSpriteCollectionFont font in obj.fonts) { bool found = false; foreach (tk2dSpriteCollectionFont f in fonts) { if (f.data == font.data && f.editorData == font.editorData) { found = true; break; } } if (!found) { tk2dEditorUtility.DeleteAsset(font.data); tk2dEditorUtility.DeleteAsset(font.editorData); } } if (obj.altMaterials != null) { foreach (Material material in obj.altMaterials) { bool found = false; if (altMaterials != null) { foreach (Material m in altMaterials) { if (m == material) { found = true; break; } } } if (!found) tk2dEditorUtility.DeleteAsset(material); } } List<tk2dSpriteCollectionPlatform> platformsToDelete = new List<tk2dSpriteCollectionPlatform>(); if (obj.HasPlatformData && !this.HasPlatformData) { platformsToDelete = new List<tk2dSpriteCollectionPlatform>(obj.platforms); atlasTextures = new Texture2D[0]; // clear all references atlasMaterials = new Material[0]; } else if (this.HasPlatformData && !obj.HasPlatformData) { // delete old sprite collection atlases and materials foreach (Material material in obj.atlasMaterials) tk2dEditorUtility.DeleteAsset(material); foreach (Texture2D texture in obj.atlasTextures) tk2dEditorUtility.DeleteAsset(texture); } else if (obj.HasPlatformData && this.HasPlatformData) { foreach (tk2dSpriteCollectionPlatform platform in obj.platforms) { bool found = false; foreach (tk2dSpriteCollectionPlatform p in platforms) { if (p.spriteCollection == platform.spriteCollection) { found = true; break; } } if (!found) // platform existed previously, but does not any more platformsToDelete.Add(platform); } } foreach (tk2dSpriteCollectionPlatform platform in platformsToDelete) { if (platform.spriteCollection == null) continue; tk2dSpriteCollection sc = platform.spriteCollection; string path = AssetDatabase.GetAssetPath(sc.spriteCollection); tk2dEditorUtility.DeleteAsset(sc.spriteCollection); foreach (Material material in sc.atlasMaterials) tk2dEditorUtility.DeleteAsset(material); foreach (Texture2D texture in sc.atlasTextures) tk2dEditorUtility.DeleteAsset(texture); foreach (tk2dSpriteCollectionFont font in sc.fonts) { tk2dEditorUtility.DeleteAsset(font.editorData); tk2dEditorUtility.DeleteAsset(font.data); } tk2dEditorUtility.DeleteAsset(sc); string dataDirName = System.IO.Path.GetDirectoryName(path); if (System.IO.Directory.Exists(dataDirName) && System.IO.Directory.GetFiles(dataDirName).Length == 0) AssetDatabase.DeleteAsset(dataDirName); } } public void CopyToTarget() { CopyToTarget(obj); } public void CopyToTarget(tk2dSpriteCollection target) { target.textureParams = textureParams.ToArray(); target.spriteSheets = spriteSheets.ToArray(); target.fonts = fonts.ToArray(); var source = this; target.platforms = new List<tk2dSpriteCollectionPlatform>(); foreach (tk2dSpriteCollectionPlatform plat in source.platforms) { tk2dSpriteCollectionPlatform p = new tk2dSpriteCollectionPlatform(); p.CopyFrom(plat); target.platforms.Add(p); } target.assetName = source.assetName; target.loadable = source.loadable; target.maxTextureSize = source.maxTextureSize; target.forceTextureSize = source.forceTextureSize; target.forcedTextureWidth = source.forcedTextureWidth; target.forcedTextureHeight = source.forcedTextureHeight; target.textureCompression = source.textureCompression; target.atlasWidth = source.atlasWidth; target.atlasHeight = source.atlasHeight; target.forceSquareAtlas = source.forceSquareAtlas; target.atlasWastage = source.atlasWastage; target.allowMultipleAtlases = source.allowMultipleAtlases; target.spriteCollection = source.spriteCollection; target.premultipliedAlpha = source.premultipliedAlpha; CopyArray(ref target.altMaterials, source.altMaterials); CopyArray(ref target.atlasMaterials, source.atlasMaterials); CopyArray(ref target.atlasTextures, source.atlasTextures); target.useTk2dCamera = source.useTk2dCamera; target.targetHeight = source.targetHeight; target.targetOrthoSize = source.targetOrthoSize; target.globalScale = source.globalScale; target.physicsDepth = source.physicsDepth; target.disableTrimming = source.disableTrimming; target.normalGenerationMode = source.normalGenerationMode; target.padAmount = source.padAmount; target.autoUpdate = source.autoUpdate; target.editorDisplayScale = source.editorDisplayScale; // Texture settings target.filterMode = source.filterMode; target.wrapMode = source.wrapMode; target.userDefinedTextureSettings = source.userDefinedTextureSettings; target.mipmapEnabled = source.mipmapEnabled; target.anisoLevel = source.anisoLevel; } public bool AllowAltMaterials { get { return !allowMultipleAtlases; } } public int FindOrCreateEmptySpriteSlot() { for (int index = 0; index < textureParams.Count; ++index) { if (textureParams[index].texture == null && textureParams[index].name.Length == 0) return index; } textureParams.Add(new tk2dSpriteCollectionDefinition()); return textureParams.Count - 1; } public int FindOrCreateEmptyFontSlot() { for (int index = 0; index < fonts.Count; ++index) { if (!fonts[index].active) { fonts[index].active = true; return index; } } var font = new tk2dSpriteCollectionFont(); font.active = true; fonts.Add(font); return fonts.Count - 1; } public int FindOrCreateEmptySpriteSheetSlot() { for (int index = 0; index < spriteSheets.Count; ++index) { if (!spriteSheets[index].active) { spriteSheets[index].active = true; spriteSheets[index].version = tk2dSpriteSheetSource.CURRENT_VERSION; return index; } } var spriteSheet = new tk2dSpriteSheetSource(); spriteSheet.active = true; spriteSheet.version = tk2dSpriteSheetSource.CURRENT_VERSION; spriteSheets.Add(spriteSheet); return spriteSheets.Count - 1; } public string FindUniqueTextureName(string name) { int at = name.LastIndexOf('@'); if (at != -1) { name = name.Substring(0, at); } List<string> textureNames = new List<string>(); foreach (var entry in textureParams) { textureNames.Add(entry.name); } if (textureNames.IndexOf(name) == -1) return name; int count = 1; do { string currName = name + " " + count.ToString(); if (textureNames.IndexOf(currName) == -1) return currName; ++count; } while(count < 1024); // arbitrary large number return name; // failed to find a name } public bool Empty { get { return textureParams.Count == 0 && fonts.Count == 0 && spriteSheets.Count == 0; } } // Call after deleting anything public void Trim() { int lastIndex = textureParams.Count - 1; while (lastIndex >= 0) { if (textureParams[lastIndex].texture != null || textureParams[lastIndex].name.Length > 0) break; lastIndex--; } int count = textureParams.Count - 1 - lastIndex; if (count > 0) { textureParams.RemoveRange( lastIndex + 1, count ); } lastIndex = fonts.Count - 1; while (lastIndex >= 0) { if (fonts[lastIndex].active) break; lastIndex--; } count = fonts.Count - 1 - lastIndex; if (count > 0) fonts.RemoveRange(lastIndex + 1, count); lastIndex = spriteSheets.Count - 1; while (lastIndex >= 0) { if (spriteSheets[lastIndex].active) break; lastIndex--; } count = spriteSheets.Count - 1 - lastIndex; if (count > 0) spriteSheets.RemoveRange(lastIndex + 1, count); lastIndex = atlasMaterials.Length - 1; while (lastIndex >= 0) { if (atlasMaterials[lastIndex] != null) break; lastIndex--; } count = atlasMaterials.Length - 1 - lastIndex; if (count > 0) System.Array.Resize(ref atlasMaterials, lastIndex + 1); } public int GetSpriteSheetId(tk2dSpriteSheetSource spriteSheet) { for (int index = 0; index < spriteSheets.Count; ++index) if (spriteSheets[index] == spriteSheet) return index; return 0; } // Delete all sprites from a spritesheet public void DeleteSpriteSheet(tk2dSpriteSheetSource spriteSheet) { int index = GetSpriteSheetId(spriteSheet); for (int i = 0; i < textureParams.Count; ++i) { if (textureParams[i].hasSpriteSheetId && textureParams[i].spriteSheetId == index) { textureParams[i] = new tk2dSpriteCollectionDefinition(); } } spriteSheets[index] = new tk2dSpriteSheetSource(); Trim(); } public string GetAssetPath() { return AssetDatabase.GetAssetPath(obj); } public string GetOrCreateDataPath() { return tk2dSpriteCollectionBuilder.GetOrCreateDataPath(obj); } public bool Ready { get { return obj != null; } } tk2dSpriteCollection obj; // Mirrored data objects public List<tk2dSpriteCollectionDefinition> textureParams = new List<tk2dSpriteCollectionDefinition>(); public List<tk2dSpriteSheetSource> spriteSheets = new List<tk2dSpriteSheetSource>(); public List<tk2dSpriteCollectionFont> fonts = new List<tk2dSpriteCollectionFont>(); // Mirrored from sprite collection public string assetName; public int maxTextureSize; public tk2dSpriteCollection.TextureCompression textureCompression; public int atlasWidth, atlasHeight; public bool forceSquareAtlas; public float atlasWastage; public bool allowMultipleAtlases; public tk2dSpriteCollectionData spriteCollection; public bool premultipliedAlpha; public List<tk2dSpriteCollectionPlatform> platforms = new List<tk2dSpriteCollectionPlatform>(); public bool HasPlatformData { get { return platforms.Count > 1; } } public Material[] altMaterials; public Material[] atlasMaterials; public Texture2D[] atlasTextures; public bool useTk2dCamera; public int targetHeight; public float targetOrthoSize; public float globalScale; // Texture settings public FilterMode filterMode; public TextureWrapMode wrapMode; public bool userDefinedTextureSettings; public bool mipmapEnabled = true; public int anisoLevel = 1; public float physicsDepth; public bool disableTrimming; public bool forceTextureSize = false; public int forcedTextureWidth = 1024; public int forcedTextureHeight = 1024; public tk2dSpriteCollection.NormalGenerationMode normalGenerationMode; public int padAmount; public bool autoUpdate; public bool loadable; public float editorDisplayScale; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using Material.Application.Helpers; using Material.Application.Infrastructure; using Material.Application.Properties; namespace Material.Application.Routing { internal class RouteStack : IRouteStack { private readonly Stack<RouteItem> stack; private readonly object syncRoot = new object(); private bool locked; private RouteItem routeHead; private object menuHeader; public RouteStack(ObservableCollection<Route> menuRoutes, IRouteFactory routeFactory, IRouteErrorListener routeErrorListener, IContext synchronizationContext) { if (routeFactory == null || routeErrorListener == null || synchronizationContext == null) { throw new ArgumentNullException(); } MenuRoutes = menuRoutes ?? new ObservableCollection<Route>(); RouteFactory = routeFactory; RouteErrorListener = routeErrorListener; SynchronizationContext = synchronizationContext; stack = new Stack<RouteItem>(); } private RouteItem RouteHead { set { if (routeHead == value) return; var previous = routeHead; routeHead = value; if (value.Route != null) { value.Route.IsTransitioning = false; } OnPropertyChanged(nameof(Current)); OnPropertyChanged(nameof(CurrentView)); OnHeadChanged(); previous?.Route.NotifyPropertyChanged(nameof(Route.IsActive)); routeHead?.Route.NotifyPropertyChanged(nameof(Route.IsActive)); } } private LockManager Lock => new LockManager(this, true); private LockManager SoftLock => new LockManager(this, false); public event EventHandler RouteHeadChanged; public IRouteFactory RouteFactory { get; } public object MenuHeader { get { return menuHeader; } set { if (Equals(value, menuHeader)) return; menuHeader = value; OnPropertyChanged(); } } public ObservableCollection<Route> MenuRoutes { get; } public IRouteErrorListener RouteErrorListener { get; } public IContext SynchronizationContext { get; } public int Count => stack.Count; public Route Current => routeHead?.Route; public object CurrentView { get { if (routeHead == null) { return null; } return routeHead.CachedView ?? routeHead.Route; } } public async Task<object> Push(Route route, bool cacheCurrentView) { SynchronizationContext.VerifyAccess(); if (route == null) { throw new ArgumentNullException(nameof(route)); } if (route.Routes != null && route.Routes != this) { throw new ArgumentException(ErrorMessages.RoutesAssociatedWithOtherStack); } if (route is TransientRoute) { throw new ArgumentException("Cannot push a transient route."); } if (stack.Any(item => item.Route == route)) { throw new InvalidOperationException("Cannot push same route instance multiple times."); } List<RouteEventError> errors; Task<object> result; using (Lock) { errors = new List<RouteEventError>(); result = (await PushRoute(route, cacheCurrentView, false, errors)).Task; } await OnRouteReady(route, RouteActivationMethod.Pushed, errors); return await result; } public async Task Change(Route route) { SynchronizationContext.VerifyAccess(); if (route == null) { throw new ArgumentNullException(nameof(route)); } if (route == Current) { return; } if (route.Routes != null && route.Routes != this) { throw new ArgumentException(ErrorMessages.RoutesAssociatedWithOtherStack); } var completionSources = new List<TaskCompletionSource<object>>(stack.Count); var errors = new List<RouteEventError>(); using (Lock) { await ChangeRoute(route, completionSources, errors); } await OnRouteReady(route, RouteActivationMethod.Changed, errors); foreach (var completionSource in completionSources) { completionSource.SetCanceled(); } } public async Task<Route> Pop(object result) { SynchronizationContext.VerifyAccess(); if (stack.Count <= 1) { throw new InvalidOperationException("Cannot pop base route."); } RouteItem poppedRoute; RouteItem nextRoute; List<RouteEventError> errors; using (Lock) { poppedRoute = stack.Pop(); nextRoute = stack.Peek(); errors = new List<RouteEventError>(); try { await poppedRoute.Route.OnRouteDeactivating(false); } catch (Exception ex) { RouteErrorListener.TryOnRouteEventException(poppedRoute.Route, RouteEventType.Deactivating, ex); } try { await nextRoute.Route.OnRouteRestoring(result); } catch (Exception ex) { errors.Add(new RouteEventError(RouteEventType.Restoring, ex)); RouteErrorListener.TryOnRouteEventException(nextRoute.Route, RouteEventType.Restoring, ex); } poppedRoute.CachedView = null; var route = nextRoute.Route; if (nextRoute.CachedView == null) { try { var view = route.CreateView(false); nextRoute.CachedView = view; var frameworkElement = view as FrameworkElement; if (frameworkElement != null && frameworkElement.DataContext == null) { frameworkElement.DataContext = route; } } catch (Exception ex) { errors.Add(new RouteEventError(RouteEventType.ViewCreation, ex)); RouteErrorListener.TryOnRouteEventException(route, RouteEventType.ViewCreation, ex); } } RouteHead = nextRoute; try { await poppedRoute.Route.OnRouteDeactivated(false); } catch (Exception ex) { RouteErrorListener.TryOnRouteEventException(poppedRoute.Route, RouteEventType.Deactivated, ex); } try { await nextRoute.Route.OnRouteRestored(result); } catch (Exception ex) { errors.Add(new RouteEventError(RouteEventType.Restored, ex)); RouteErrorListener.TryOnRouteEventException(nextRoute.Route, RouteEventType.Restored, ex); } } await OnRouteReady(nextRoute.Route, RouteActivationMethod.Restored, errors); poppedRoute.CompletionSource.SetResult(result); return nextRoute.Route; } public void ReloadView(Route route) { if (route == null) { return; } using (SoftLock) { if (routeHead == null) { return; } if (SynchronizationContext.IsSynchronized) { ReloadViewInternal(route); } else { SynchronizationContext.Invoke(() => ReloadViewInternal(route)); } } } public event PropertyChangedEventHandler PropertyChanged; private void ReloadViewInternal(Route route) { if (routeHead.Route == route) { try { var view = route.CreateView(true); routeHead.CachedView = view; var frameworkElement = view as FrameworkElement; if (frameworkElement != null && frameworkElement.DataContext == null) { frameworkElement.DataContext = route; } OnPropertyChanged(nameof(CurrentView)); } catch (Exception ex) { RouteErrorListener.TryOnRouteEventException(route, RouteEventType.ViewCreation, ex); } } else { var routeItem = stack.FirstOrDefault(item => item.Route == route); if (routeItem != null) { routeItem.CachedView = null; } } } private async Task ChangeRoute(Route route, List<TaskCompletionSource<object>> completionSources, List<RouteEventError> errors) { var sentinel = 0; while (true) { if (++sentinel == 32) { throw new RouteTransitionException("Detected possible loop with transient routes."); } var transientRoute = route as TransientRoute; if (transientRoute != null) { transientRoute.Routes = this; var transientRouteErrors = new List<RouteEventError>(); try { await transientRoute.OnRouteInitializing(); } catch (Exception ex) { transientRouteErrors.Add(new RouteEventError(RouteEventType.Initializing, ex)); } try { await transientRoute.OnRouteActivating(); } catch (Exception ex) { transientRouteErrors.Add(new RouteEventError(RouteEventType.Activating, ex)); } try { route = transientRoute.GetNextRoute(transientRouteErrors); } catch (Exception ex) { throw new RouteTransitionException( "A transient route threw an exception while switching to next route.", ex); } if (route == null) { throw new RouteTransitionException("A transient route resulted in a dead end."); } if (route.Routes != null && route.Routes != this) { throw new RouteTransitionException(ErrorMessages.RoutesAssociatedWithOtherStack); } continue; } while (stack.Count != 0) { var item = stack.Pop(); completionSources.Add(item.CompletionSource); try { await item.Route.OnRouteDeactivating(true); } catch (Exception ex) { RouteErrorListener.TryOnRouteEventException(item.Route, RouteEventType.Deactivating, ex); } item.CachedView = null; try { await item.Route.OnRouteDeactivated(true); } catch (Exception ex) { RouteErrorListener.TryOnRouteEventException(item.Route, RouteEventType.Deactivated, ex); } } await PushRoute(route, false, true, errors); break; } } private async Task<TaskCompletionSource<object>> PushRoute(Route route, bool cacheCurrentView, bool ignoreCurrent, List<RouteEventError> errors) { route.Routes = this; var currentRoute = Current; if (currentRoute != null && !cacheCurrentView) { routeHead.CachedView = null; } if (!ignoreCurrent && currentRoute != null) { try { await currentRoute.OnRouteHiding(); } catch (Exception ex) { RouteErrorListener.TryOnRouteEventException(currentRoute, RouteEventType.Hiding, ex); } } try { await route.OnRouteInitializing(); } catch (Exception ex) { errors.Add(new RouteEventError(RouteEventType.Initializing, ex)); RouteErrorListener.TryOnRouteEventException(route, RouteEventType.Initializing, ex); } try { await route.OnRouteActivating(); } catch (Exception ex) { errors.Add(new RouteEventError(RouteEventType.Activating, ex)); RouteErrorListener.TryOnRouteEventException(route, RouteEventType.Activating, ex); } var item = new RouteItem(route); try { var view = route.CreateView(false); item.CachedView = view; var frameworkElement = view as FrameworkElement; if (frameworkElement != null && frameworkElement.DataContext == null) { frameworkElement.DataContext = route; } } catch (Exception ex) { errors.Add(new RouteEventError(RouteEventType.ViewCreation, ex)); RouteErrorListener.TryOnRouteEventException(route, RouteEventType.ViewCreation, ex); } stack.Push(item); RouteHead = item; if (!ignoreCurrent && currentRoute != null) { try { await currentRoute.OnRouteHidden(); } catch (Exception ex) { RouteErrorListener.TryOnRouteEventException(currentRoute, RouteEventType.Hidden, ex); } } try { await route.OnRouteInitialized(); } catch (Exception ex) { errors.Add(new RouteEventError(RouteEventType.Initialized, ex)); RouteErrorListener.TryOnRouteEventException(route, RouteEventType.Initialized, ex); } try { await route.OnRouteActivated(); } catch (Exception ex) { errors.Add(new RouteEventError(RouteEventType.Activated, ex)); RouteErrorListener.TryOnRouteEventException(route, RouteEventType.Activated, ex); } return item.CompletionSource; } private async Task OnRouteReady(Route route, RouteActivationMethod method, List<RouteEventError> errors) { try { await route.OnRouteReady(method, errors); } catch (Exception ex) { RouteErrorListener.TryOnRouteEventException(route, RouteEventType.Ready, ex); } } private void EnterLock(bool hardLock) { // This is old code because locking isn't necessary since we're synchronized. lock (syncRoot) { if (locked) { throw new InvalidOperationException("A route change is already in progress."); } if (hardLock) { Current?.BeginTransition(); } locked = true; } } private void ExitLock() { lock (syncRoot) { locked = false; } } [NotifyPropertyChangedInvocator] private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void OnHeadChanged() { try { RouteHeadChanged?.Invoke(this, EventArgs.Empty); } catch { // ignored } } private class LockManager : IDisposable { private readonly RouteStack routeStack; public LockManager(RouteStack routeStack, bool hardLock) { routeStack.EnterLock(hardLock); this.routeStack = routeStack; } public void Dispose() { routeStack.ExitLock(); } } } }
using UnityEngine; using UnityEngine.Rendering; using System.Collections; using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; [ExecuteInEditMode] #if UNITY_5_4_OR_NEWER [ImageEffectAllowedInSceneView] #endif [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Sonic Ether/SEGI (Cascaded)")] public class SEGICascaded : MonoBehaviour { #region Parameters [Serializable] public enum VoxelResolution { low = 64, high = 128 } public VoxelResolution voxelResolution = VoxelResolution.high; public bool visualizeSunDepthTexture = false; public bool visualizeGI = false; public Light sun; public LayerMask giCullingMask = 2147483647; public float shadowSpaceSize = 50.0f; [Range(0.01f, 1.0f)] public float temporalBlendWeight = 0.1f; public bool visualizeVoxels = false; public bool updateGI = true; public Color skyColor; public float voxelSpaceSize = 25.0f; public bool useBilateralFiltering = false; [Range(0, 2)] public int innerOcclusionLayers = 1; public bool halfResolution = false; public bool stochasticSampling = true; public bool infiniteBounces = false; public Transform followTransform; [Range(1, 128)] public int cones = 4; [Range(1, 32)] public int coneTraceSteps = 10; [Range(0.1f, 2.0f)] public float coneLength = 1.0f; [Range(0.5f, 6.0f)] public float coneWidth = 3.9f; [Range(0.0f, 2.0f)] public float occlusionStrength = 0.15f; [Range(0.0f, 4.0f)] public float nearOcclusionStrength = 0.5f; [Range(0.001f, 4.0f)] public float occlusionPower = 0.65f; [Range(0.0f, 4.0f)] public float coneTraceBias = 2.8f; [Range(0.0f, 4.0f)] public float nearLightGain = 0.36f; [Range(0.0f, 4.0f)] public float giGain = 1.0f; [Range(0.0f, 4.0f)] public float secondaryBounceGain = 0.9f; [Range(0.0f, 16.0f)] public float softSunlight = 0.0f; [Range(0.0f, 8.0f)] public float skyIntensity = 1.0f; [HideInInspector] public bool doReflections { get { return false; //Locked to keep reflections disabled since they're in a broken state with cascades at the moment } set { value = false; } } [Range(12, 128)] public int reflectionSteps = 64; [Range(0.001f, 4.0f)] public float reflectionOcclusionPower = 1.0f; [Range(0.0f, 1.0f)] public float skyReflectionIntensity = 1.0f; [Range(0.1f, 4.0f)] public float farOcclusionStrength = 1.0f; [Range(0.1f, 4.0f)] public float farthestOcclusionStrength = 1.0f; [Range(3, 16)] public int secondaryCones = 6; [Range(0.1f, 2.0f)] public float secondaryOcclusionStrength = 0.27f; public bool sphericalSkylight = false; #endregion #region InternalVariables object initChecker; Material material; Camera attachedCamera; Transform shadowCamTransform; Camera shadowCam; GameObject shadowCamGameObject; Texture2D[] blueNoise; int sunShadowResolution = 128; int prevSunShadowResolution; Shader sunDepthShader; float shadowSpaceDepthRatio = 10.0f; int frameCounter = 0; RenderTexture sunDepthTexture; RenderTexture previousGIResult; RenderTexture previousDepth; ///<summary>This is a volume texture that is immediately written to in the voxelization shader. The RInt format enables atomic writes to avoid issues where multiple fragments are trying to write to the same voxel in the volume.</summary> RenderTexture integerVolume; ///<summary>A 2D texture with the size of [voxel resolution, voxel resolution] that must be used as the active render texture when rendering the scene for voxelization. This texture scales depending on whether Voxel AA is enabled to ensure correct voxelization.</summary> RenderTexture dummyVoxelTextureAAScaled; ///<summary>A 2D texture with the size of [voxel resolution, voxel resolution] that must be used as the active render texture when rendering the scene for voxelization. This texture is always the same size whether Voxel AA is enabled or not.</summary> RenderTexture dummyVoxelTextureFixed; ///<summary>The main GI data clipmaps that hold GI data referenced during GI tracing</summary> Clipmap[] clipmaps; ///<summary>The secondary clipmaps that hold irradiance data for infinite bounces</summary> Clipmap[] irradianceClipmaps; bool notReadyToRender = false; Shader voxelizationShader; Shader voxelTracingShader; ComputeShader clearCompute; ComputeShader transferIntsCompute; ComputeShader mipFilterCompute; const int numClipmaps = 6; int clipmapCounter = 0; int currentClipmapIndex = 0; Camera voxelCamera; GameObject voxelCameraGO; GameObject leftViewPoint; GameObject topViewPoint; float voxelScaleFactor { get { return (float)voxelResolution / 256.0f; } } Quaternion rotationFront = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f); Quaternion rotationLeft = new Quaternion(0.0f, 0.7f, 0.0f, 0.7f); Quaternion rotationTop = new Quaternion(0.7f, 0.0f, 0.0f, 0.7f); int giRenderRes { get { return halfResolution ? 2 : 1; } } enum RenderState { Voxelize, Bounce } RenderState renderState = RenderState.Voxelize; #endregion #region SupportingObjectsAndProperties struct Pass { public static int DiffuseTrace = 0; public static int BilateralBlur = 1; public static int BlendWithScene = 2; public static int TemporalBlend = 3; public static int SpecularTrace = 4; public static int GetCameraDepthTexture = 5; public static int GetWorldNormals = 6; public static int VisualizeGI = 7; public static int WriteBlack = 8; public static int VisualizeVoxels = 10; public static int BilateralUpsample = 11; } public struct SystemSupported { public bool hdrTextures; public bool rIntTextures; public bool dx11; public bool volumeTextures; public bool postShader; public bool sunDepthShader; public bool voxelizationShader; public bool tracingShader; public bool fullFunctionality { get { return hdrTextures && rIntTextures && dx11 && volumeTextures && postShader && sunDepthShader && voxelizationShader && tracingShader; } } } /// <summary> /// Contains info on system compatibility of required hardware functionality /// </summary> public SystemSupported systemSupported; /// <summary> /// Estimates the VRAM usage of all the render textures used to render GI. /// </summary> public float vramUsage //TODO: Update vram usage calculation { get { if (!enabled) { return 0.0f; } long v = 0; if (sunDepthTexture != null) v += sunDepthTexture.width * sunDepthTexture.height * 16; if (previousGIResult != null) v += previousGIResult.width * previousGIResult.height * 16 * 4; if (previousDepth != null) v += previousDepth.width * previousDepth.height * 32; if (integerVolume != null) v += integerVolume.width * integerVolume.height * integerVolume.volumeDepth * 32; if (dummyVoxelTextureAAScaled != null) v += dummyVoxelTextureAAScaled.width * dummyVoxelTextureAAScaled.height * 8; if (dummyVoxelTextureFixed != null) v += dummyVoxelTextureFixed.width * dummyVoxelTextureFixed.height * 8; if (clipmaps != null) { for (int i = 0; i < numClipmaps; i++) { if (clipmaps[i] != null) { v += clipmaps[i].volumeTexture0.width * clipmaps[i].volumeTexture0.height * clipmaps[i].volumeTexture0.volumeDepth * 16 * 4; } } } if (irradianceClipmaps != null) { for (int i = 0; i < numClipmaps; i++) { if (irradianceClipmaps[i] != null) { v += irradianceClipmaps[i].volumeTexture0.width * irradianceClipmaps[i].volumeTexture0.height * irradianceClipmaps[i].volumeTexture0.volumeDepth * 16 * 4; } } } float vram = (v / 8388608.0f); return vram; } } class Clipmap { public Vector3 origin; public Vector3 originDelta; public Vector3 previousOrigin; public float localScale; public int resolution; public RenderTexture volumeTexture0; public FilterMode filterMode = FilterMode.Bilinear; public RenderTextureFormat renderTextureFormat = RenderTextureFormat.ARGBHalf; public void UpdateTextures() { if (volumeTexture0) { volumeTexture0.DiscardContents(); volumeTexture0.Release(); DestroyImmediate(volumeTexture0); } volumeTexture0 = new RenderTexture(resolution, resolution, 0, renderTextureFormat, RenderTextureReadWrite.Linear); volumeTexture0.wrapMode = TextureWrapMode.Clamp; #if UNITY_5_4_OR_NEWER volumeTexture0.dimension = TextureDimension.Tex3D; #else volumeTexture0.isVolume = true; #endif volumeTexture0.volumeDepth = resolution; volumeTexture0.enableRandomWrite = true; volumeTexture0.filterMode = filterMode; #if UNITY_5_4_OR_NEWER volumeTexture0.autoGenerateMips = false; #else volumeTexture0.generateMips = false; #endif volumeTexture0.useMipMap = false; volumeTexture0.Create(); volumeTexture0.hideFlags = HideFlags.HideAndDontSave; } public void CleanupTextures() { if (volumeTexture0) { volumeTexture0.DiscardContents(); volumeTexture0.Release(); DestroyImmediate(volumeTexture0); } } } public bool gaussianMipFilter { get { return false; } set { value = false; } } int mipFilterKernel { get { return gaussianMipFilter ? 1 : 0; } } public bool voxelAA = false; int dummyVoxelResolution { get { return (int)voxelResolution * (voxelAA ? 4 : 1); } } #endregion public void ApplyPreset(SEGICascadedPreset preset) { voxelResolution = preset.voxelResolution; voxelAA = preset.voxelAA; innerOcclusionLayers = preset.innerOcclusionLayers; infiniteBounces = preset.infiniteBounces; temporalBlendWeight = preset.temporalBlendWeight; useBilateralFiltering = preset.useBilateralFiltering; halfResolution = preset.halfResolution; stochasticSampling = preset.stochasticSampling; doReflections = preset.doReflections; cones = preset.cones; coneTraceSteps = preset.coneTraceSteps; coneLength = preset.coneLength; coneWidth = preset.coneWidth; coneTraceBias = preset.coneTraceBias; occlusionStrength = preset.occlusionStrength; nearOcclusionStrength = preset.nearOcclusionStrength; occlusionPower = preset.occlusionPower; nearLightGain = preset.nearLightGain; giGain = preset.giGain; secondaryBounceGain = preset.secondaryBounceGain; reflectionSteps = preset.reflectionSteps; reflectionOcclusionPower = preset.reflectionOcclusionPower; skyReflectionIntensity = preset.skyReflectionIntensity; gaussianMipFilter = preset.gaussianMipFilter; farOcclusionStrength = preset.farOcclusionStrength; farthestOcclusionStrength = preset.farthestOcclusionStrength; secondaryCones = preset.secondaryCones; secondaryOcclusionStrength = preset.secondaryOcclusionStrength; } void Start() { InitCheck(); } void InitCheck() { if (initChecker == null) { Init(); } } void CreateVolumeTextures() { if (integerVolume) { integerVolume.DiscardContents(); integerVolume.Release(); DestroyImmediate(integerVolume); } integerVolume = new RenderTexture((int)voxelResolution, (int)voxelResolution, 0, RenderTextureFormat.RInt, RenderTextureReadWrite.Linear); #if UNITY_5_4_OR_NEWER integerVolume.dimension = TextureDimension.Tex3D; #else integerVolume.isVolume = true; #endif integerVolume.volumeDepth = (int)voxelResolution; integerVolume.enableRandomWrite = true; integerVolume.filterMode = FilterMode.Point; integerVolume.Create(); integerVolume.hideFlags = HideFlags.HideAndDontSave; ResizeDummyTexture(); } void BuildClipmaps() { if (clipmaps != null) { for (int i = 0; i < numClipmaps; i++) { if (clipmaps[i] != null) { clipmaps[i].CleanupTextures(); } } } clipmaps = new Clipmap[numClipmaps]; for (int i = 0; i < numClipmaps; i++) { clipmaps[i] = new Clipmap(); clipmaps[i].localScale = Mathf.Pow(2.0f, (float)i); clipmaps[i].resolution = (int)voxelResolution; clipmaps[i].filterMode = FilterMode.Bilinear; clipmaps[i].renderTextureFormat = RenderTextureFormat.ARGBHalf; clipmaps[i].UpdateTextures(); } if (irradianceClipmaps != null) { for (int i = 0; i < numClipmaps; i++) { if (irradianceClipmaps[i] != null) { irradianceClipmaps[i].CleanupTextures(); } } } irradianceClipmaps = new Clipmap[numClipmaps]; for (int i = 0; i < numClipmaps; i++) { irradianceClipmaps[i] = new Clipmap(); irradianceClipmaps[i].localScale = Mathf.Pow(2.0f, i); irradianceClipmaps[i].resolution = (int)voxelResolution; irradianceClipmaps[i].filterMode = FilterMode.Point; irradianceClipmaps[i].renderTextureFormat = RenderTextureFormat.ARGBHalf; irradianceClipmaps[i].UpdateTextures(); } } void ResizeDummyTexture() { if (dummyVoxelTextureAAScaled) { dummyVoxelTextureAAScaled.DiscardContents(); dummyVoxelTextureAAScaled.Release(); DestroyImmediate(dummyVoxelTextureAAScaled); } dummyVoxelTextureAAScaled = new RenderTexture(dummyVoxelResolution, dummyVoxelResolution, 0, RenderTextureFormat.R8); dummyVoxelTextureAAScaled.Create(); dummyVoxelTextureAAScaled.hideFlags = HideFlags.HideAndDontSave; if (dummyVoxelTextureFixed) { dummyVoxelTextureFixed.DiscardContents(); dummyVoxelTextureFixed.Release(); DestroyImmediate(dummyVoxelTextureFixed); } dummyVoxelTextureFixed = new RenderTexture((int)voxelResolution, (int)voxelResolution, 0, RenderTextureFormat.R8); dummyVoxelTextureFixed.Create(); dummyVoxelTextureFixed.hideFlags = HideFlags.HideAndDontSave; } void GetBlueNoiseTextures() { blueNoise = null; blueNoise = new Texture2D[64]; for (int i = 0; i < 64; i++) { string filename = "LDR_RGBA_" + i.ToString(); Texture2D blueNoiseTexture = Resources.Load("Noise Textures/" + filename) as Texture2D; if (blueNoiseTexture == null) { Debug.LogWarning("Unable to find noise texture \"Assets/SEGI/Resources/Noise Textures/" + filename + "\" for SEGI!"); } blueNoise[i] = blueNoiseTexture; } } void Init() { //Setup shaders and materials sunDepthShader = Shader.Find("Hidden/SEGIRenderSunDepth_C"); clearCompute = Resources.Load("SEGIClear_C") as ComputeShader; transferIntsCompute = Resources.Load("SEGITransferInts_C") as ComputeShader; mipFilterCompute = Resources.Load("SEGIMipFilter_C") as ComputeShader; voxelizationShader = Shader.Find("Hidden/SEGIVoxelizeScene_C"); voxelTracingShader = Shader.Find("Hidden/SEGITraceScene_C"); if (!material) { material = new Material(Shader.Find("Hidden/SEGI_C")); material.hideFlags = HideFlags.HideAndDontSave; } //Get the camera attached to this game object attachedCamera = this.GetComponent<Camera>(); attachedCamera.depthTextureMode |= DepthTextureMode.Depth; attachedCamera.depthTextureMode |= DepthTextureMode.DepthNormals; #if UNITY_5_4_OR_NEWER attachedCamera.depthTextureMode |= DepthTextureMode.MotionVectors; #endif //Find the proxy shadow rendering camera if it exists GameObject scgo = GameObject.Find("SEGI_SHADOWCAM"); //If not, create it if (!scgo) { shadowCamGameObject = new GameObject("SEGI_SHADOWCAM"); shadowCam = shadowCamGameObject.AddComponent<Camera>(); shadowCamGameObject.hideFlags = HideFlags.HideAndDontSave; shadowCam.enabled = false; shadowCam.depth = attachedCamera.depth - 1; shadowCam.orthographic = true; shadowCam.orthographicSize = shadowSpaceSize; shadowCam.clearFlags = CameraClearFlags.SolidColor; shadowCam.backgroundColor = new Color(0.0f, 0.0f, 0.0f, 1.0f); shadowCam.farClipPlane = shadowSpaceSize * 2.0f * shadowSpaceDepthRatio; shadowCam.cullingMask = giCullingMask; shadowCam.useOcclusionCulling = false; shadowCamTransform = shadowCamGameObject.transform; } else //Otherwise, it already exists, just get it { shadowCamGameObject = scgo; shadowCam = scgo.GetComponent<Camera>(); shadowCamTransform = shadowCamGameObject.transform; } //Create the proxy camera objects responsible for rendering the scene to voxelize the scene. If they already exist, destroy them GameObject vcgo = GameObject.Find("SEGI_VOXEL_CAMERA"); if (!vcgo) { voxelCameraGO = new GameObject("SEGI_VOXEL_CAMERA"); voxelCameraGO.hideFlags = HideFlags.HideAndDontSave; voxelCamera = voxelCameraGO.AddComponent<Camera>(); voxelCamera.enabled = false; voxelCamera.orthographic = true; voxelCamera.orthographicSize = voxelSpaceSize * 0.5f; voxelCamera.nearClipPlane = 0.0f; voxelCamera.farClipPlane = voxelSpaceSize; voxelCamera.depth = -2; voxelCamera.renderingPath = RenderingPath.Forward; voxelCamera.clearFlags = CameraClearFlags.Color; voxelCamera.backgroundColor = Color.black; voxelCamera.useOcclusionCulling = false; } else { voxelCameraGO = vcgo; voxelCamera = vcgo.GetComponent<Camera>(); } GameObject lvp = GameObject.Find("SEGI_LEFT_VOXEL_VIEW"); if (!lvp) { leftViewPoint = new GameObject("SEGI_LEFT_VOXEL_VIEW"); leftViewPoint.hideFlags = HideFlags.HideAndDontSave; } else { leftViewPoint = lvp; } GameObject tvp = GameObject.Find("SEGI_TOP_VOXEL_VIEW"); if (!tvp) { topViewPoint = new GameObject("SEGI_TOP_VOXEL_VIEW"); topViewPoint.hideFlags = HideFlags.HideAndDontSave; } else { topViewPoint = tvp; } //Setup sun depth texture if (sunDepthTexture) { sunDepthTexture.DiscardContents(); sunDepthTexture.Release(); DestroyImmediate(sunDepthTexture); } sunDepthTexture = new RenderTexture(sunShadowResolution, sunShadowResolution, 16, RenderTextureFormat.RHalf, RenderTextureReadWrite.Linear); sunDepthTexture.wrapMode = TextureWrapMode.Clamp; sunDepthTexture.filterMode = FilterMode.Point; sunDepthTexture.Create(); sunDepthTexture.hideFlags = HideFlags.HideAndDontSave; CreateVolumeTextures(); BuildClipmaps(); GetBlueNoiseTextures(); initChecker = new object(); } void CheckSupport() { systemSupported.hdrTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf); systemSupported.rIntTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RInt); systemSupported.dx11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; systemSupported.volumeTextures = SystemInfo.supports3DTextures; systemSupported.postShader = material.shader.isSupported; systemSupported.sunDepthShader = sunDepthShader.isSupported; systemSupported.voxelizationShader = voxelizationShader.isSupported; systemSupported.tracingShader = voxelTracingShader.isSupported; if (!systemSupported.fullFunctionality) { Debug.LogWarning("SEGI is not supported on the current platform. Check for shader compile errors in SEGI/Resources"); enabled = false; } } void OnDrawGizmosSelected() { if (!enabled) return; Color prevColor = Gizmos.color; Gizmos.color = new Color(1.0f, 0.25f, 0.0f, 0.5f); float scale = clipmaps[numClipmaps - 1].localScale; Gizmos.DrawCube(clipmaps[0].origin, new Vector3(voxelSpaceSize * scale, voxelSpaceSize * scale, voxelSpaceSize * scale)); Gizmos.color = new Color(1.0f, 0.0f, 0.0f, 0.1f); Gizmos.color = prevColor; } void CleanupTexture(ref RenderTexture texture) { if (texture) { texture.DiscardContents(); texture.Release(); DestroyImmediate(texture); } } void CleanupTextures() { CleanupTexture(ref sunDepthTexture); CleanupTexture(ref previousGIResult); CleanupTexture(ref previousDepth); CleanupTexture(ref integerVolume); CleanupTexture(ref dummyVoxelTextureAAScaled); CleanupTexture(ref dummyVoxelTextureFixed); if (clipmaps != null) { for (int i = 0; i < numClipmaps; i++) { if (clipmaps[i] != null) { clipmaps[i].CleanupTextures(); } } } if (irradianceClipmaps != null) { for (int i = 0; i < numClipmaps; i++) { if (irradianceClipmaps[i] != null) { irradianceClipmaps[i].CleanupTextures(); } } } } void Cleanup() { DestroyImmediate(material); DestroyImmediate(voxelCameraGO); DestroyImmediate(leftViewPoint); DestroyImmediate(topViewPoint); DestroyImmediate(shadowCamGameObject); initChecker = null; CleanupTextures(); } void OnEnable() { InitCheck(); ResizeRenderTextures(); CheckSupport(); } void OnDisable() { Cleanup(); } void ResizeRenderTextures() { if (previousGIResult) { previousGIResult.DiscardContents(); previousGIResult.Release(); DestroyImmediate(previousGIResult); } int width = attachedCamera.pixelWidth == 0 ? 2 : attachedCamera.pixelWidth; int height = attachedCamera.pixelHeight == 0 ? 2 : attachedCamera.pixelHeight; previousGIResult = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBHalf); previousGIResult.wrapMode = TextureWrapMode.Clamp; previousGIResult.filterMode = FilterMode.Bilinear; previousGIResult.Create(); previousGIResult.hideFlags = HideFlags.HideAndDontSave; if (previousDepth) { previousDepth.DiscardContents(); previousDepth.Release(); DestroyImmediate(previousDepth); } previousDepth = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); previousDepth.wrapMode = TextureWrapMode.Clamp; previousDepth.filterMode = FilterMode.Bilinear; previousDepth.Create(); previousDepth.hideFlags = HideFlags.HideAndDontSave; } void ResizeSunShadowBuffer() { if (sunDepthTexture) { sunDepthTexture.DiscardContents(); sunDepthTexture.Release(); DestroyImmediate(sunDepthTexture); } sunDepthTexture = new RenderTexture(sunShadowResolution, sunShadowResolution, 16, RenderTextureFormat.RHalf, RenderTextureReadWrite.Linear); sunDepthTexture.wrapMode = TextureWrapMode.Clamp; sunDepthTexture.filterMode = FilterMode.Point; sunDepthTexture.Create(); sunDepthTexture.hideFlags = HideFlags.HideAndDontSave; } void Update() { if (notReadyToRender) return; if (previousGIResult == null) { ResizeRenderTextures(); } if (previousGIResult.width != attachedCamera.pixelWidth || previousGIResult.height != attachedCamera.pixelHeight) { ResizeRenderTextures(); } if ((int)sunShadowResolution != prevSunShadowResolution) { ResizeSunShadowBuffer(); } prevSunShadowResolution = (int)sunShadowResolution; if (clipmaps[0].resolution != (int)voxelResolution) { clipmaps[0].resolution = (int)voxelResolution; clipmaps[0].UpdateTextures(); } if (dummyVoxelTextureAAScaled.width != dummyVoxelResolution) { ResizeDummyTexture(); } } Matrix4x4 TransformViewMatrix(Matrix4x4 mat) { #if UNITY_5_5_OR_NEWER if (SystemInfo.usesReversedZBuffer) { mat[2, 0] = -mat[2, 0]; mat[2, 1] = -mat[2, 1]; mat[2, 2] = -mat[2, 2]; mat[2, 3] = -mat[2, 3]; // mat[3, 2] += 0.0f; } #endif return mat; } int SelectCascadeBinary(int c) { float counter = c + 0.01f; int result = 0; for (int i = 1; i < numClipmaps; i++) { float level = Mathf.Pow(2.0f, i); result += Mathf.CeilToInt( ((counter / level) % 1.0f) - ((level - 1.0f) / level) ); } return result; } void OnPreRender() { //Force reinitialization to make sure that everything is working properly if one of the cameras was unexpectedly destroyed if (!voxelCamera || !shadowCam) initChecker = null; InitCheck(); if (notReadyToRender) return; if (!updateGI) { return; } //Cache the previous active render texture to avoid issues with other Unity rendering going on RenderTexture previousActive = RenderTexture.active; Shader.SetGlobalInt("SEGIVoxelAA", voxelAA ? 3 : 0); //Temporarily disable rendering of shadows on the directional light during voxelization pass. Cache the result to set it back to what it was after voxelization is done LightShadows prevSunShadowSetting = LightShadows.None; if (sun != null) { prevSunShadowSetting = sun.shadows; sun.shadows = LightShadows.None; } //Main voxelization work if (renderState == RenderState.Voxelize) { currentClipmapIndex = SelectCascadeBinary(clipmapCounter); //Determine which clipmap to update during this frame Clipmap activeClipmap = clipmaps[currentClipmapIndex]; //Set the active clipmap based on which one is determined to render this frame //If we're not updating the base level 0 clipmap, get the previous clipmap Clipmap prevClipmap = null; if (currentClipmapIndex != 0) { prevClipmap = clipmaps[currentClipmapIndex - 1]; } float clipmapShadowSize = shadowSpaceSize * activeClipmap.localScale; float clipmapSize = voxelSpaceSize * activeClipmap.localScale; //Determine the current clipmap's size in world units based on its scale //float voxelTexel = (1.0f * clipmapSize) / activeClipmap.resolution * 0.5f; //Calculate the size of a voxel texel in world-space units //Setup the voxel volume origin position float interval = (clipmapSize) / 8.0f; //The interval at which the voxel volume will be "locked" in world-space Vector3 origin; if (followTransform) { origin = followTransform.position; } else { //GI is still flickering a bit when the scene view and the game view are opened at the same time origin = transform.position + transform.forward * clipmapSize / 4.0f; } //Lock the voxel volume origin based on the interval activeClipmap.previousOrigin = activeClipmap.origin; activeClipmap.origin = new Vector3(Mathf.Round(origin.x / interval) * interval, Mathf.Round(origin.y / interval) * interval, Mathf.Round(origin.z / interval) * interval); //Clipmap delta movement for scrolling secondary bounce irradiance volume when this clipmap has changed origin activeClipmap.originDelta = activeClipmap.origin - activeClipmap.previousOrigin; Shader.SetGlobalVector("SEGIVoxelSpaceOriginDelta", activeClipmap.originDelta / (voxelSpaceSize * activeClipmap.localScale)); //Calculate the relative origin and overlap/size of the previous cascade as compared to the active cascade. This is used to avoid voxelizing areas that have already been voxelized by previous (smaller) cascades Vector3 prevClipmapRelativeOrigin = Vector3.zero; float prevClipmapOccupance = 0.0f; if (currentClipmapIndex != 0) { prevClipmapRelativeOrigin = (prevClipmap.origin - activeClipmap.origin) / clipmapSize; prevClipmapOccupance = prevClipmap.localScale / activeClipmap.localScale; } Shader.SetGlobalVector("SEGIClipmapOverlap", new Vector4(prevClipmapRelativeOrigin.x, prevClipmapRelativeOrigin.y, prevClipmapRelativeOrigin.z, prevClipmapOccupance)); //Calculate the relative origin and scale of this cascade as compared to the first (level 0) cascade. This is used during GI tracing/data lookup to ensure tracing is done in the correct space for (int i = 1; i < numClipmaps; i++) { Vector3 clipPosFromMaster = Vector3.zero; float clipScaleFromMaster = 1.0f; clipPosFromMaster = (clipmaps[i].origin - clipmaps[0].origin) / (voxelSpaceSize * clipmaps[i].localScale); clipScaleFromMaster = clipmaps[0].localScale / clipmaps[i].localScale; Shader.SetGlobalVector("SEGIClipTransform" + i.ToString(), new Vector4(clipPosFromMaster.x, clipPosFromMaster.y, clipPosFromMaster.z, clipScaleFromMaster)); } //Set the voxel camera (proxy camera used to render the scene for voxelization) parameters voxelCamera.enabled = false; voxelCamera.orthographic = true; voxelCamera.orthographicSize = clipmapSize * 0.5f; voxelCamera.nearClipPlane = 0.0f; voxelCamera.farClipPlane = clipmapSize; voxelCamera.depth = -2; voxelCamera.renderingPath = RenderingPath.Forward; voxelCamera.clearFlags = CameraClearFlags.Color; voxelCamera.backgroundColor = Color.black; voxelCamera.cullingMask = giCullingMask; //Move the voxel camera game object and other related objects to the above calculated voxel space origin voxelCameraGO.transform.position = activeClipmap.origin - Vector3.forward * clipmapSize * 0.5f; voxelCameraGO.transform.rotation = rotationFront; leftViewPoint.transform.position = activeClipmap.origin + Vector3.left * clipmapSize * 0.5f; leftViewPoint.transform.rotation = rotationLeft; topViewPoint.transform.position = activeClipmap.origin + Vector3.up * clipmapSize * 0.5f; topViewPoint.transform.rotation = rotationTop; //Set matrices needed for voxelization //Shader.SetGlobalMatrix("WorldToGI", shadowCam.worldToCameraMatrix); //Shader.SetGlobalMatrix("GIToWorld", shadowCam.cameraToWorldMatrix); //Shader.SetGlobalMatrix("GIProjection", shadowCam.projectionMatrix); //Shader.SetGlobalMatrix("GIProjectionInverse", shadowCam.projectionMatrix.inverse); Shader.SetGlobalMatrix("WorldToCamera", attachedCamera.worldToCameraMatrix); Shader.SetGlobalFloat("GIDepthRatio", shadowSpaceDepthRatio); Matrix4x4 frontViewMatrix = TransformViewMatrix(voxelCamera.transform.worldToLocalMatrix); Matrix4x4 leftViewMatrix = TransformViewMatrix(leftViewPoint.transform.worldToLocalMatrix); Matrix4x4 topViewMatrix = TransformViewMatrix(topViewPoint.transform.worldToLocalMatrix); Shader.SetGlobalMatrix("SEGIVoxelViewFront", frontViewMatrix); Shader.SetGlobalMatrix("SEGIVoxelViewLeft", leftViewMatrix); Shader.SetGlobalMatrix("SEGIVoxelViewTop", topViewMatrix); Shader.SetGlobalMatrix("SEGIWorldToVoxel", voxelCamera.worldToCameraMatrix); Shader.SetGlobalMatrix("SEGIVoxelProjection", voxelCamera.projectionMatrix); Shader.SetGlobalMatrix("SEGIVoxelProjectionInverse", voxelCamera.projectionMatrix.inverse); Shader.SetGlobalMatrix("SEGIVoxelVPFront", GL.GetGPUProjectionMatrix(voxelCamera.projectionMatrix, true) * frontViewMatrix); Shader.SetGlobalMatrix("SEGIVoxelVPLeft", GL.GetGPUProjectionMatrix(voxelCamera.projectionMatrix, true) * leftViewMatrix); Shader.SetGlobalMatrix("SEGIVoxelVPTop", GL.GetGPUProjectionMatrix(voxelCamera.projectionMatrix, true) * topViewMatrix); Shader.SetGlobalMatrix("SEGIWorldToVoxel" + currentClipmapIndex.ToString(), voxelCamera.worldToCameraMatrix); Shader.SetGlobalMatrix("SEGIVoxelProjection" + currentClipmapIndex.ToString(), voxelCamera.projectionMatrix); Matrix4x4 voxelToGIProjection = shadowCam.projectionMatrix * shadowCam.worldToCameraMatrix * voxelCamera.cameraToWorldMatrix; Shader.SetGlobalMatrix("SEGIVoxelToGIProjection", voxelToGIProjection); Shader.SetGlobalVector("SEGISunlightVector", sun ? Vector3.Normalize(sun.transform.forward) : Vector3.up); //Set paramteters Shader.SetGlobalInt("SEGIVoxelResolution", (int)voxelResolution); Shader.SetGlobalColor("GISunColor", sun == null ? Color.black : new Color(Mathf.Pow(sun.color.r, 2.2f), Mathf.Pow(sun.color.g, 2.2f), Mathf.Pow(sun.color.b, 2.2f), Mathf.Pow(sun.intensity, 2.2f))); Shader.SetGlobalColor("SEGISkyColor", new Color(Mathf.Pow(skyColor.r * skyIntensity * 0.5f, 2.2f), Mathf.Pow(skyColor.g * skyIntensity * 0.5f, 2.2f), Mathf.Pow(skyColor.b * skyIntensity * 0.5f, 2.2f), Mathf.Pow(skyColor.a, 2.2f))); Shader.SetGlobalFloat("GIGain", giGain); Shader.SetGlobalFloat("SEGISecondaryBounceGain", infiniteBounces ? secondaryBounceGain : 0.0f); Shader.SetGlobalFloat("SEGISoftSunlight", softSunlight); Shader.SetGlobalInt("SEGISphericalSkylight", sphericalSkylight ? 1 : 0); Shader.SetGlobalInt("SEGIInnerOcclusionLayers", innerOcclusionLayers); //Render the depth texture from the sun's perspective in order to inject sunlight with shadows during voxelization if (sun != null) { shadowCam.cullingMask = giCullingMask; Vector3 shadowCamPosition = activeClipmap.origin + Vector3.Normalize(-sun.transform.forward) * clipmapShadowSize * 0.5f * shadowSpaceDepthRatio; shadowCamTransform.position = shadowCamPosition; shadowCamTransform.LookAt(activeClipmap.origin, Vector3.up); shadowCam.renderingPath = RenderingPath.Forward; shadowCam.depthTextureMode |= DepthTextureMode.None; shadowCam.orthographicSize = clipmapShadowSize; shadowCam.farClipPlane = clipmapShadowSize * 2.0f * shadowSpaceDepthRatio; //Shader.SetGlobalMatrix("WorldToGI", shadowCam.worldToCameraMatrix); //Shader.SetGlobalMatrix("GIToWorld", shadowCam.cameraToWorldMatrix); //Shader.SetGlobalMatrix("GIProjection", shadowCam.projectionMatrix); //Shader.SetGlobalMatrix("GIProjectionInverse", shadowCam.projectionMatrix.inverse); voxelToGIProjection = shadowCam.projectionMatrix * shadowCam.worldToCameraMatrix * voxelCamera.cameraToWorldMatrix; Shader.SetGlobalMatrix("SEGIVoxelToGIProjection", voxelToGIProjection); Graphics.SetRenderTarget(sunDepthTexture); shadowCam.SetTargetBuffers(sunDepthTexture.colorBuffer, sunDepthTexture.depthBuffer); shadowCam.RenderWithShader(sunDepthShader, ""); Shader.SetGlobalTexture("SEGISunDepth", sunDepthTexture); } //Clear the volume texture that is immediately written to in the voxelization scene shader clearCompute.SetTexture(0, "RG0", integerVolume); clearCompute.SetInt("Res", activeClipmap.resolution); clearCompute.Dispatch(0, activeClipmap.resolution / 16, activeClipmap.resolution / 16, 1); //Set irradiance "secondary bounce" texture Shader.SetGlobalTexture("SEGICurrentIrradianceVolume", irradianceClipmaps[currentClipmapIndex].volumeTexture0); Graphics.SetRandomWriteTarget(1, integerVolume); voxelCamera.targetTexture = dummyVoxelTextureAAScaled; voxelCamera.RenderWithShader(voxelizationShader, ""); Graphics.ClearRandomWriteTargets(); //Transfer the data from the volume integer texture to the main volume texture used for GI tracing. transferIntsCompute.SetTexture(0, "Result", activeClipmap.volumeTexture0); transferIntsCompute.SetTexture(0, "RG0", integerVolume); transferIntsCompute.SetInt("VoxelAA", voxelAA ? 3 : 0); transferIntsCompute.SetInt("Resolution", activeClipmap.resolution); transferIntsCompute.Dispatch(0, activeClipmap.resolution / 16, activeClipmap.resolution / 16, 1); //Push current voxelization result to higher levels for (int i = 0 + 1; i < numClipmaps; i++) { Clipmap sourceClipmap = clipmaps[i - 1]; Clipmap targetClipmap = clipmaps[i]; Vector3 sourceRelativeOrigin = Vector3.zero; float sourceOccupance = 0.0f; sourceRelativeOrigin = (sourceClipmap.origin - targetClipmap.origin) / (targetClipmap.localScale * voxelSpaceSize); sourceOccupance = sourceClipmap.localScale / targetClipmap.localScale; mipFilterCompute.SetTexture(0, "Source", sourceClipmap.volumeTexture0); mipFilterCompute.SetTexture(0, "Destination", targetClipmap.volumeTexture0); mipFilterCompute.SetVector("ClipmapOverlap", new Vector4(sourceRelativeOrigin.x, sourceRelativeOrigin.y, sourceRelativeOrigin.z, sourceOccupance)); mipFilterCompute.SetInt("destinationRes", targetClipmap.resolution); mipFilterCompute.Dispatch(0, targetClipmap.resolution / 16, targetClipmap.resolution / 16, 1); } for (int i = 0; i < numClipmaps; i++) { Shader.SetGlobalTexture("SEGIVolumeLevel" + i.ToString(), clipmaps[i].volumeTexture0); } if (infiniteBounces) { renderState = RenderState.Bounce; } else { //Increment clipmap counter clipmapCounter++; if (clipmapCounter >= (int)Mathf.Pow(2.0f, numClipmaps)) { clipmapCounter = 0; } } } else if (renderState == RenderState.Bounce) { //Calculate the relative position and scale of the current clipmap as compared to the first (level 0) clipmap. Used to ensure tracing is performed in the correct space Vector3 translateToZero = Vector3.zero; translateToZero = (clipmaps[currentClipmapIndex].origin - clipmaps[0].origin) / (voxelSpaceSize * clipmaps[currentClipmapIndex].localScale); float scaleToZero = 1.0f / clipmaps[currentClipmapIndex].localScale; Shader.SetGlobalVector("SEGICurrentClipTransform", new Vector4(translateToZero.x, translateToZero.y, translateToZero.z, scaleToZero)); //Clear the volume texture that is immediately written to in the voxelization scene shader clearCompute.SetTexture(0, "RG0", integerVolume); clearCompute.SetInt("Res", clipmaps[currentClipmapIndex].resolution); clearCompute.Dispatch(0, (int)voxelResolution / 16, (int)voxelResolution / 16, 1); //Only render infinite bounces for clipmaps 0, 1, and 2 if (currentClipmapIndex <= 2) { Shader.SetGlobalInt("SEGISecondaryCones", secondaryCones); Shader.SetGlobalFloat("SEGISecondaryOcclusionStrength", secondaryOcclusionStrength); Graphics.SetRandomWriteTarget(1, integerVolume); voxelCamera.targetTexture = dummyVoxelTextureFixed; voxelCamera.RenderWithShader(voxelTracingShader, ""); Graphics.ClearRandomWriteTargets(); transferIntsCompute.SetTexture(1, "Result", irradianceClipmaps[currentClipmapIndex].volumeTexture0); transferIntsCompute.SetTexture(1, "RG0", integerVolume); transferIntsCompute.SetInt("Resolution", (int)voxelResolution); transferIntsCompute.Dispatch(1, (int)voxelResolution / 16, (int)voxelResolution / 16, 1); } //Increment clipmap counter clipmapCounter++; if (clipmapCounter >= (int)Mathf.Pow(2.0f, numClipmaps)) { clipmapCounter = 0; } renderState = RenderState.Voxelize; } Matrix4x4 giToVoxelProjection = voxelCamera.projectionMatrix * voxelCamera.worldToCameraMatrix * shadowCam.cameraToWorldMatrix; Shader.SetGlobalMatrix("GIToVoxelProjection", giToVoxelProjection); RenderTexture.active = previousActive; //Set the sun's shadow setting back to what it was before voxelization if (sun != null) { sun.shadows = prevSunShadowSetting; } } [ImageEffectOpaque] void OnRenderImage(RenderTexture source, RenderTexture destination) { if (notReadyToRender) { Graphics.Blit(source, destination); return; } //Set parameters Shader.SetGlobalFloat("SEGIVoxelScaleFactor", voxelScaleFactor); material.SetMatrix("CameraToWorld", attachedCamera.cameraToWorldMatrix); material.SetMatrix("WorldToCamera", attachedCamera.worldToCameraMatrix); material.SetMatrix("ProjectionMatrixInverse", attachedCamera.projectionMatrix.inverse); material.SetMatrix("ProjectionMatrix", attachedCamera.projectionMatrix); material.SetInt("FrameSwitch", frameCounter); Shader.SetGlobalInt("SEGIFrameSwitch", frameCounter); material.SetVector("CameraPosition", transform.position); material.SetFloat("DeltaTime", Time.deltaTime); material.SetInt("StochasticSampling", stochasticSampling ? 1 : 0); material.SetInt("TraceDirections", cones); material.SetInt("TraceSteps", coneTraceSteps); material.SetFloat("TraceLength", coneLength); material.SetFloat("ConeSize", coneWidth); material.SetFloat("OcclusionStrength", occlusionStrength); material.SetFloat("OcclusionPower", occlusionPower); material.SetFloat("ConeTraceBias", coneTraceBias); material.SetFloat("GIGain", giGain); material.SetFloat("NearLightGain", nearLightGain); material.SetFloat("NearOcclusionStrength", nearOcclusionStrength); material.SetInt("DoReflections", doReflections ? 1 : 0); material.SetInt("HalfResolution", halfResolution ? 1 : 0); material.SetInt("ReflectionSteps", reflectionSteps); material.SetFloat("ReflectionOcclusionPower", reflectionOcclusionPower); material.SetFloat("SkyReflectionIntensity", skyReflectionIntensity); material.SetFloat("FarOcclusionStrength", farOcclusionStrength); material.SetFloat("FarthestOcclusionStrength", farthestOcclusionStrength); material.SetTexture("NoiseTexture", blueNoise[frameCounter]); material.SetFloat("BlendWeight", temporalBlendWeight); //If Visualize Voxels is enabled, just render the voxel visualization shader pass and return if (visualizeVoxels) { Graphics.Blit(source, destination, material, Pass.VisualizeVoxels); return; } //Setup temporary textures RenderTexture gi1 = RenderTexture.GetTemporary(source.width / giRenderRes, source.height / giRenderRes, 0, RenderTextureFormat.ARGBHalf); RenderTexture gi2 = RenderTexture.GetTemporary(source.width / giRenderRes, source.height / giRenderRes, 0, RenderTextureFormat.ARGBHalf); RenderTexture reflections = null; //If reflections are enabled, create a temporary render buffer to hold them if (doReflections) { reflections = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf); } //Get the camera depth and normals RenderTexture currentDepth = RenderTexture.GetTemporary(source.width / giRenderRes, source.height / giRenderRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); currentDepth.filterMode = FilterMode.Point; RenderTexture currentNormal = RenderTexture.GetTemporary(source.width / giRenderRes, source.height / giRenderRes, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear); currentNormal.filterMode = FilterMode.Point; //Get the camera depth and normals Graphics.Blit(source, currentDepth, material, Pass.GetCameraDepthTexture); material.SetTexture("CurrentDepth", currentDepth); Graphics.Blit(source, currentNormal, material, Pass.GetWorldNormals); material.SetTexture("CurrentNormal", currentNormal); //Set the previous GI result and camera depth textures to access them in the shader material.SetTexture("PreviousGITexture", previousGIResult); Shader.SetGlobalTexture("PreviousGITexture", previousGIResult); material.SetTexture("PreviousDepth", previousDepth); //Render diffuse GI tracing result Graphics.Blit(source, gi2, material, Pass.DiffuseTrace); if (doReflections) { //Render GI reflections result Graphics.Blit(source, reflections, material, Pass.SpecularTrace); material.SetTexture("Reflections", reflections); } //Perform bilateral filtering if (useBilateralFiltering && temporalBlendWeight >= 0.99999f) { material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); Graphics.Blit(gi2, gi1, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(gi1, gi2, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); Graphics.Blit(gi2, gi1, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(gi1, gi2, material, Pass.BilateralBlur); } //If Half Resolution tracing is enabled if (giRenderRes == 2) { RenderTexture.ReleaseTemporary(gi1); //Setup temporary textures RenderTexture gi3 = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf); RenderTexture gi4 = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf); //Prepare the half-resolution diffuse GI result to be bilaterally upsampled gi2.filterMode = FilterMode.Point; Graphics.Blit(gi2, gi4); RenderTexture.ReleaseTemporary(gi2); gi4.filterMode = FilterMode.Point; gi3.filterMode = FilterMode.Point; //Perform bilateral upsampling on half-resolution diffuse GI result material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(gi4, gi3, material, Pass.BilateralUpsample); material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); //Perform a bilateral blur to be applied in newly revealed areas that are still noisy due to not having previous data blended with it RenderTexture blur0 = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf); RenderTexture blur1 = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf); material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); Graphics.Blit(gi3, blur1, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(blur1, blur0, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(0.0f, 2.0f)); Graphics.Blit(blur0, blur1, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(2.0f, 0.0f)); Graphics.Blit(blur1, blur0, material, Pass.BilateralBlur); material.SetTexture("BlurredGI", blur0); //Perform temporal reprojection and blending if (temporalBlendWeight < 1.0f) { Graphics.Blit(gi3, gi4); Graphics.Blit(gi4, gi3, material, Pass.TemporalBlend); Graphics.Blit(gi3, previousGIResult); Graphics.Blit(source, previousDepth, material, Pass.GetCameraDepthTexture); //Perform bilateral filtering on temporally blended result if (useBilateralFiltering) { material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); Graphics.Blit(gi3, gi4, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(gi4, gi3, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); Graphics.Blit(gi3, gi4, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(gi4, gi3, material, Pass.BilateralBlur); } } //Set the result to be accessed in the shader material.SetTexture("GITexture", gi3); //Actually apply the GI to the scene using gbuffer data Graphics.Blit(source, destination, material, visualizeGI ? Pass.VisualizeGI : Pass.BlendWithScene); //Release temporary textures RenderTexture.ReleaseTemporary(blur0); RenderTexture.ReleaseTemporary(blur1); RenderTexture.ReleaseTemporary(gi3); RenderTexture.ReleaseTemporary(gi4); } else //If Half Resolution tracing is disabled { if (temporalBlendWeight < 1.0f) { //Perform a bilateral blur to be applied in newly revealed areas that are still noisy due to not having previous data blended with it RenderTexture blur0 = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf); RenderTexture blur1 = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf); material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); Graphics.Blit(gi2, blur1, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(blur1, blur0, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(0.0f, 2.0f)); Graphics.Blit(blur0, blur1, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(2.0f, 0.0f)); Graphics.Blit(blur1, blur0, material, Pass.BilateralBlur); material.SetTexture("BlurredGI", blur0); //Perform temporal reprojection and blending Graphics.Blit(gi2, gi1, material, Pass.TemporalBlend); Graphics.Blit(gi1, previousGIResult); Graphics.Blit(source, previousDepth, material, Pass.GetCameraDepthTexture); //Perform bilateral filtering on temporally blended result if (useBilateralFiltering) { material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); Graphics.Blit(gi1, gi2, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(gi2, gi1, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(0.0f, 1.0f)); Graphics.Blit(gi1, gi2, material, Pass.BilateralBlur); material.SetVector("Kernel", new Vector2(1.0f, 0.0f)); Graphics.Blit(gi2, gi1, material, Pass.BilateralBlur); } RenderTexture.ReleaseTemporary(blur0); RenderTexture.ReleaseTemporary(blur1); } //Actually apply the GI to the scene using gbuffer data material.SetTexture("GITexture", temporalBlendWeight < 1.0f ? gi1 : gi2); Graphics.Blit(source, destination, material, visualizeGI ? Pass.VisualizeGI : Pass.BlendWithScene); //Release temporary textures RenderTexture.ReleaseTemporary(gi1); RenderTexture.ReleaseTemporary(gi2); } //Release temporary textures RenderTexture.ReleaseTemporary(currentDepth); RenderTexture.ReleaseTemporary(currentNormal); if (visualizeSunDepthTexture) Graphics.Blit(sunDepthTexture, destination); //Release the temporary reflections result texture if (doReflections) { RenderTexture.ReleaseTemporary(reflections); } //Set matrices/vectors for use during temporal reprojection material.SetMatrix("ProjectionPrev", attachedCamera.projectionMatrix); material.SetMatrix("ProjectionPrevInverse", attachedCamera.projectionMatrix.inverse); material.SetMatrix("WorldToCameraPrev", attachedCamera.worldToCameraMatrix); material.SetMatrix("CameraToWorldPrev", attachedCamera.cameraToWorldMatrix); material.SetVector("CameraPositionPrev", transform.position); //Advance the frame counter frameCounter = (frameCounter + 1) % (64); } }
//#define ASTARDEBUG using UnityEngine; using System.Collections; namespace Pathfinding { /** \astarpro */ public class DebugUtility : MonoBehaviour { public Material defaultMaterial; public new static DebugUtility active; public float offset = 0.2F; public bool optimizeMeshes = false; public void Awake () { active = this; } public static void DrawCubes (Vector3[] topVerts, Vector3[] bottomVerts, Color[] vertexColors, float width) { if (active == null) { active = GameObject.FindObjectOfType(typeof(DebugUtility)) as DebugUtility; } if (active == null) throw new System.NullReferenceException (); if (topVerts.Length != bottomVerts.Length || topVerts.Length != vertexColors.Length) { Debug.LogError ("Array Lengths are not the same"); return; } //65000 limit divided by 4*6 = 24 if (topVerts.Length > 2708) { Vector3[] topVerts2 = new Vector3[topVerts.Length-2708]; Vector3[] bottomVerts2 = new Vector3[topVerts.Length-2708]; Color[] vertexColors2 = new Color[topVerts.Length-2708]; for (int i=2708;i<topVerts.Length;i++) { topVerts2[i-2708] = topVerts[i]; bottomVerts2[i-2708] = bottomVerts[i]; vertexColors2[i-2708] = vertexColors[i]; } Vector3[] topVerts3 = new Vector3[2708]; Vector3[] bottomVerts3 = new Vector3[2708]; Color[] vertexColors3 = new Color[2708]; for (int i=0;i<2708;i++) { topVerts3[i] = topVerts[i]; bottomVerts3[i] = bottomVerts[i]; vertexColors3[i] = vertexColors[i]; } DrawCubes (topVerts2,bottomVerts2,vertexColors2, width); topVerts = topVerts3; bottomVerts = bottomVerts3; vertexColors = vertexColors3; } width /= 2F; Vector3[] vertices = new Vector3[topVerts.Length*4*6]; int[] tris = new int[topVerts.Length*6*6]; Color[] colors = new Color[topVerts.Length*4*6]; for (int i=0;i<topVerts.Length;i++) { Vector3 top = topVerts[i] + new Vector3 (0,active.offset,0); Vector3 bottom = bottomVerts[i] - new Vector3 (0,active.offset,0);; Vector3 top1 = top + new Vector3 (-width,0,-width); Vector3 top2 = top + new Vector3 (width,0,-width); Vector3 top3 = top + new Vector3 (width,0,width); Vector3 top4 = top + new Vector3 (-width,0,width); Vector3 bottom1 = bottom + new Vector3 (-width,0,-width); Vector3 bottom2 = bottom + new Vector3 (width,0,-width); Vector3 bottom3 = bottom + new Vector3 (width,0,width); Vector3 bottom4 = bottom + new Vector3 (-width,0,width); int vIndex = i*4*6; Color col = vertexColors[i]; //Color.Lerp (Color.green,Color.red,topVerts[i].y*0.06F); // for (int c=vIndex;c<vIndex+24;c++) { colors[c] = col; } //Top vertices[vIndex] = top1; vertices[vIndex+1] = top4; vertices[vIndex+2] = top3; vertices[vIndex+3] = top2; int tIndex = i*6*6; tris[tIndex] = vIndex; tris[tIndex+1] = vIndex+1; tris[tIndex+2] = vIndex+2; tris[tIndex+3] = vIndex; tris[tIndex+4] = vIndex+2; tris[tIndex+5] = vIndex+3; //Bottom vIndex += 4; vertices[vIndex+3] = bottom1; vertices[vIndex+2] = bottom4; vertices[vIndex+1] = bottom3; vertices[vIndex] = bottom2; tIndex += 6; tris[tIndex] = vIndex; tris[tIndex+1] = vIndex+1; tris[tIndex+2] = vIndex+2; tris[tIndex+3] = vIndex; tris[tIndex+4] = vIndex+2; tris[tIndex+5] = vIndex+3; //Right vIndex += 4; vertices[vIndex] = bottom2; vertices[vIndex+1] = top2; vertices[vIndex+2] = top3; vertices[vIndex+3] = bottom3; tIndex += 6; tris[tIndex] = vIndex; tris[tIndex+1] = vIndex+1; tris[tIndex+2] = vIndex+2; tris[tIndex+3] = vIndex; tris[tIndex+4] = vIndex+2; tris[tIndex+5] = vIndex+3; //Left vIndex += 4; vertices[vIndex+3] = bottom1; vertices[vIndex+2] = top1; vertices[vIndex+1] = top4; vertices[vIndex] = bottom4; tIndex += 6; tris[tIndex] = vIndex; tris[tIndex+1] = vIndex+1; tris[tIndex+2] = vIndex+2; tris[tIndex+3] = vIndex; tris[tIndex+4] = vIndex+2; tris[tIndex+5] = vIndex+3; //Forward vIndex += 4; vertices[vIndex+3] = bottom3; vertices[vIndex+2] = bottom4; vertices[vIndex+1] = top4; vertices[vIndex] = top3; tIndex += 6; tris[tIndex] = vIndex; tris[tIndex+1] = vIndex+1; tris[tIndex+2] = vIndex+2; tris[tIndex+3] = vIndex; tris[tIndex+4] = vIndex+2; tris[tIndex+5] = vIndex+3; //Back vIndex += 4; vertices[vIndex] = bottom2; vertices[vIndex+1] = bottom1; vertices[vIndex+2] = top1; vertices[vIndex+3] = top2; tIndex += 6; tris[tIndex] = vIndex; tris[tIndex+1] = vIndex+1; tris[tIndex+2] = vIndex+2; tris[tIndex+3] = vIndex; tris[tIndex+4] = vIndex+2; tris[tIndex+5] = vIndex+3; } Mesh mesh = new Mesh (); mesh.vertices = vertices; mesh.triangles = tris; mesh.colors = colors; mesh.name = "VoxelMesh"; mesh.RecalculateNormals (); mesh.RecalculateBounds (); if (active.optimizeMeshes) { mesh.Optimize (); } GameObject go = new GameObject ("DebugMesh"); MeshRenderer rend = go.AddComponent (typeof(MeshRenderer)) as MeshRenderer; rend.material = active.defaultMaterial; (go.AddComponent (typeof(MeshFilter)) as MeshFilter).mesh = mesh; } public static void DrawQuads (Vector3[] verts, float width) { //65000 limit divided by 4 if (verts.Length >= 16250) { Vector3[] verts2 = new Vector3[verts.Length-16250]; for (int i=16250;i<verts.Length;i++) { verts2[i-16250] = verts[i]; } Vector3[] verts3 = new Vector3[16250]; for (int i=0;i<16250;i++) { verts3[i] = verts[i]; } DrawQuads (verts2, width); verts = verts3; } width /= 2F; Vector3[] vertices = new Vector3[verts.Length*4]; int[] tris = new int[verts.Length*6]; for (int i=0;i<verts.Length;i++) { Vector3 p = verts[i]; int vIndex = i*4; vertices[vIndex] = p + new Vector3 (-width,0,-width); vertices[vIndex+1] = p + new Vector3 (-width,0,width); vertices[vIndex+2] = p + new Vector3 (width,0,width); vertices[vIndex+3] = p + new Vector3 (width,0,-width); int tIndex = i*6; tris[tIndex] = vIndex; tris[tIndex+1] = vIndex+1; tris[tIndex+2] = vIndex+2; tris[tIndex+3] = vIndex; tris[tIndex+4] = vIndex+2; tris[tIndex+5] = vIndex+3; } Mesh mesh = new Mesh (); mesh.vertices = vertices; mesh.triangles = tris; mesh.RecalculateNormals (); mesh.RecalculateBounds (); GameObject go = new GameObject ("DebugMesh"); MeshRenderer rend = go.AddComponent (typeof(MeshRenderer)) as MeshRenderer; rend.material = active.defaultMaterial; (go.AddComponent (typeof(MeshFilter)) as MeshFilter).mesh = mesh; } public static void TestMeshLimit () { Vector3[] vertices = new Vector3[16000*4]; int[] tris = new int[16000*6]; for (int i=0;i<16000;i++) { Vector3 p = Random.onUnitSphere*10; int vIndex = i*4; vertices[vIndex] = p + new Vector3 (-0.1F,0,-0.1F); vertices[vIndex+1] = p + new Vector3 (-0.1F,0,0.1F); vertices[vIndex+2] = p + new Vector3 (0.1F,0,0.1F); vertices[vIndex+3] = p + new Vector3 (0.1F,0,-0.1F); int tIndex = i*6; tris[tIndex] = vIndex; tris[tIndex+1] = vIndex+1; tris[tIndex+2] = vIndex+2; tris[tIndex+3] = vIndex; tris[tIndex+4] = vIndex+2; tris[tIndex+5] = vIndex+3; } Mesh mesh = new Mesh (); mesh.vertices = vertices; mesh.triangles = tris; mesh.RecalculateNormals (); mesh.RecalculateBounds (); GameObject go = new GameObject ("DebugMesh"); go.AddComponent (typeof(MeshRenderer)); (go.AddComponent (typeof(MeshFilter)) as MeshFilter).mesh = mesh; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Resources; using System.Text; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Runtime.Serialization; namespace System.Xml { /// <devdoc> /// <para>Returns detailed information about the last parse error, including the error /// number, line number, character position, and a text description.</para> /// </devdoc> public class XmlException : SystemException { private string _res; private string[] _args; // this field is not used, it's here just V1.1 serialization compatibility private int _lineNumber; private int _linePosition; private string _sourceUri; // message != null for V1 exceptions deserialized in Whidbey // message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message) private string _message; protected XmlException(SerializationInfo info, StreamingContext context) : base(info, context) { _res = (string)info.GetValue("_res", typeof(string)); _args = (string[])info.GetValue("_args", typeof(string[])); _lineNumber = (int)info.GetValue("_lineNumber", typeof(int)); _linePosition = (int)info.GetValue("_linePosition", typeof(int)); // deserialize optional members _sourceUri = string.Empty; string version = null; foreach (SerializationEntry e in info) { switch (e.Name) { case "sourceUri": _sourceUri = (string)e.Value; break; case "version": version = (string)e.Value; break; } } if (version == null) { // deserializing V1 exception _message = CreateMessage(_res, _args, _lineNumber, _linePosition); } else { // deserializing V2 or higher exception -> exception message is serialized by the base class (Exception._message) _message = null; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("res", _res); info.AddValue("args", _args); info.AddValue("lineNumber", _lineNumber); info.AddValue("linePosition", _linePosition); info.AddValue("sourceUri", _sourceUri); info.AddValue("version", "2.0"); } //provided to meet the ECMA standards public XmlException() : this(null) { } //provided to meet the ECMA standards public XmlException(String message) : this(message, ((Exception)null), 0, 0) { #if DEBUG Debug.Assert(message == null || !message.StartsWith("Xml_", StringComparison.Ordinal), "Do not pass a resource here!"); #endif } //provided to meet ECMA standards public XmlException(String message, Exception innerException) : this(message, innerException, 0, 0) { } //provided to meet ECMA standards public XmlException(String message, Exception innerException, int lineNumber, int linePosition) : this(message, innerException, lineNumber, linePosition, null) { } internal XmlException(String message, Exception innerException, int lineNumber, int linePosition, string sourceUri) : base(FormatUserMessage(message, lineNumber, linePosition), innerException) { HResult = HResults.Xml; _res = (message == null ? SR.Xml_DefaultException : SR.Xml_UserException); _args = new string[] { message }; _sourceUri = sourceUri; _lineNumber = lineNumber; _linePosition = linePosition; } internal XmlException(string res, string[] args) : this(res, args, null, 0, 0, null) { } internal XmlException(string res, string arg) : this(res, new string[] { arg }, null, 0, 0, null) { } internal XmlException(string res, string arg, string sourceUri) : this(res, new string[] { arg }, null, 0, 0, sourceUri) { } internal XmlException(string res, String arg, IXmlLineInfo lineInfo) : this(res, new string[] { arg }, lineInfo, null) { } internal XmlException(string res, String arg, Exception innerException, IXmlLineInfo lineInfo) : this(res, new string[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null) { } internal XmlException(string res, string[] args, IXmlLineInfo lineInfo) : this(res, args, lineInfo, null) { } internal XmlException(string res, string[] args, IXmlLineInfo lineInfo, string sourceUri) : this(res, args, null, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), sourceUri) { } internal XmlException(string res, string arg, int lineNumber, int linePosition) : this(res, new string[] { arg }, null, lineNumber, linePosition, null) { } internal XmlException(string res, string arg, int lineNumber, int linePosition, string sourceUri) : this(res, new string[] { arg }, null, lineNumber, linePosition, sourceUri) { } internal XmlException(string res, string[] args, int lineNumber, int linePosition) : this(res, args, null, lineNumber, linePosition, null) { } internal XmlException(string res, string[] args, int lineNumber, int linePosition, string sourceUri) : this(res, args, null, lineNumber, linePosition, sourceUri) { } internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition) : this(res, args, innerException, lineNumber, linePosition, null) { } internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition, string sourceUri) : base(CreateMessage(res, args, lineNumber, linePosition), innerException) { HResult = HResults.Xml; _res = res; _args = args; _sourceUri = sourceUri; _lineNumber = lineNumber; _linePosition = linePosition; } private static string FormatUserMessage(string message, int lineNumber, int linePosition) { if (message == null) { return CreateMessage(SR.Xml_DefaultException, null, lineNumber, linePosition); } else { if (lineNumber == 0 && linePosition == 0) { // do not reformat the message when not needed return message; } else { // add line information return CreateMessage(SR.Xml_UserException, new string[] { message }, lineNumber, linePosition); } } } private static string CreateMessage(string res, string[] args, int lineNumber, int linePosition) { try { string message; // No line information -> get resource string and return if (lineNumber == 0) { message = (args == null) ? res : string.Format(res, args); } // Line information is available -> we need to append it to the error message else { string lineNumberStr = lineNumber.ToString(CultureInfo.InvariantCulture); string linePositionStr = linePosition.ToString(CultureInfo.InvariantCulture); message = string.Format(res, args); message = SR.Format(SR.Xml_MessageWithErrorPosition, new string[] { message, lineNumberStr, linePositionStr }); } return message; } catch (MissingManifestResourceException) { return "UNKNOWN(" + res + ")"; } } internal static string[] BuildCharExceptionArgs(string data, int invCharIndex) { return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < data.Length ? data[invCharIndex + 1] : '\0'); } internal static string[] BuildCharExceptionArgs(char[] data, int length, int invCharIndex) { Debug.Assert(invCharIndex < data.Length); Debug.Assert(invCharIndex < length); Debug.Assert(length <= data.Length); return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < length ? data[invCharIndex + 1] : '\0'); } internal static string[] BuildCharExceptionArgs(char invChar, char nextChar) { string[] aStringList = new string[2]; // for surrogate characters include both high and low char in the message so that a full character is displayed if (XmlCharType.IsHighSurrogate(invChar) && nextChar != 0) { int combinedChar = XmlCharType.CombineSurrogateChar(nextChar, invChar); aStringList[0] = new string(new char[] { invChar, nextChar }); aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", combinedChar); } else { // don't include 0 character in the string - in means eof-of-string in native code, where this may bubble up to if ((int)invChar == 0) { aStringList[0] = "."; } else { aStringList[0] = invChar.ToString(); } aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", (int)invChar); } return aStringList; } public int LineNumber { get { return _lineNumber; } } public int LinePosition { get { return _linePosition; } } public string SourceUri { get { return _sourceUri; } } public override string Message { get { return (_message == null) ? base.Message : _message; } } internal string ResString { get { return _res; } } internal static bool IsCatchableException(Exception e) { Debug.Assert(e != null, "Unexpected null exception"); return !( e is OutOfMemoryException || e is NullReferenceException ); } }; }
using System; using NUnit.Framework; using PeanutButter.RandomGenerators; using PeanutButter.TempDb.LocalDb; namespace PeanutButter.TestUtils.Entity.Tests { [TestFixture] public class TestDbSchemaImporter { private TempDBLocalDb _migratedDb; [OneTimeSetUp] public void TestFixtureSetUp() { _migratedDb = CreateMigratedDb(); } [OneTimeTearDown] public void TestFixtureTearDown() { _migratedDb.Dispose(); } private TempDBLocalDb CreateMigratedDb() { var db = CreateTempDb(); var migrator = Create(db.ConnectionString); migrator.MigrateToLatest(); return db; } [Test] public void CleanCommentsFrom_GivenStringWithoutComments_ShouldReturnIt() { //---------------Set up test pack------------------- var sut = Create(); var input = "create table foo (id int primary key identity);"; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.CleanCommentsFrom(input); //---------------Test Result ----------------------- Assert.AreEqual(input, result); } [Test] public void CleanCommentsFrom_GivenStringWithSingleLineComment_ShouldRemoveIt() { //---------------Set up test pack------------------- var sut = Create(); var expected = "create table foo (id int primary key identity);"; var input = string.Join("\r\n", "-- this is a single line comment", expected); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.CleanCommentsFrom(input); //---------------Test Result ----------------------- Assert.AreEqual(expected, result); } [Test] public void CleanCommentsFrom_GivenStringWithMultilineComment_ShouldRemoveIt() { //---------------Set up test pack------------------- var sut = Create(); var expected = "create table foo (id int primary key identity);"; var input = string.Join("\r\n", "/* this is the start of a multiline comment", "and here is some more comment */", expected); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.CleanCommentsFrom(input); //---------------Test Result ----------------------- Assert.AreEqual(expected, result); } [Test] public void MigrateToLatest_ShouldNotThrow() { using (var db = CreateTempDb()) { //---------------Set up test pack------------------- var migrator = new DbSchemaImporter(db.ConnectionString, TestResources.dbscript); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- migrator.MigrateToLatest(); //---------------Test Result ----------------------- } } [Test] public void MakeATempDb() { //---------------Set up test pack------------------- var db = CreateTempDb(); var migrator = new DbSchemaImporter(db.ConnectionString, TestResources.dbscript); migrator.MigrateToLatest(); Console.WriteLine(db.DatabasePath); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- //---------------Test Result ----------------------- } [TestCase("COMBlockList")] [TestCase("COMBlockListReason")] [TestCase("COMMessagePlatformOption")] [TestCase("COMMessageRequestLog")] [TestCase("COMNotificationCustomer")] [TestCase("COMNotificationCustomerHistory")] [TestCase("COMNotificationMember")] [TestCase("COMNotificationMemberHistory")] [TestCase("COMNotificationRestriction")] [TestCase("COMPromotionCustomer")] [TestCase("COMPromotionCustomerHistory")] [TestCase("COMPromotionMember")] [TestCase("COMPromotionMemberHistory")] [TestCase("COMProtocol")] [TestCase("COMProtocolOption")] [TestCase("COMSubscriptionOption")] public void ShouldHaveTableAfterMigration_(string tableName) { //---------------Set up test pack------------------- using (var connection = _migratedDb.OpenConnection()) { //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- using (var cmd = connection.CreateCommand()) { cmd.CommandText = "select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = '" + tableName + "';"; using (var reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); } } //---------------Test Result ----------------------- } } [Test] public void SplitPartsOutOf_GivenStringWithNo_GO_ShouldReturnIt() { //---------------Set up test pack------------------- var sut = Create(); var input = RandomValueGen.GetRandomString(); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.SplitPartsOutOf(input); //---------------Test Result ----------------------- Assert.IsNotNull(result); Assert.AreEqual(1, result.Length); Assert.AreEqual(input, result[0]); } [Test] public void SplitPartsOutOf_GivenStringWithA_GO_ShouldReturnTheParts() { //---------------Set up test pack------------------- var sut = Create(); var first = RandomValueGen.GetRandomString(); var second = RandomValueGen.GetRandomString(); var input = first + "\r\nGO\r\n" + second; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.SplitPartsOutOf(input); //---------------Test Result ----------------------- Assert.IsNotNull(result); Assert.AreEqual(2, result.Length); Assert.AreEqual(first, result[0]); Assert.AreEqual(second, result[1]); } private DbSchemaImporter Create(string connectionString = null, string schema = null) { return new DbSchemaImporter(connectionString ?? RandomValueGen.GetRandomString(1), schema ?? TestResources.dbscript); } private static TempDBLocalDb CreateTempDb() { return new TempDBLocalDb(); } } }
// Copyright 2007-2010 Portland State University, University of Wisconsin-Madison // Author: Robert Scheller, Ben Sulman using Edu.Wisc.Forest.Flel.Util; using Landis.SpatialModeling; using Landis.Core; using System.Collections.Generic; namespace Landis.Extension.Succession.NetEcosystemCN { public interface IFunctionalType { double PPDF1{get;set;} double PPDF2{get;set;} double PPDF3{get;set;} double PPDF4{get;set;} double FCFRACleaf{get;set;} double BTOLAI{get;set;} double KLAI{get;set;} double MAXLAI{get;set;} double PPRPTS2 {get;set;} double PPRPTS3 {get;set;} double MonthlyWoodMortality{get;set;} double WoodDecayRate{get;set;} double MortCurveShape{get;set;} int LeafNeedleDrop{get;set;} double CoarseRootFraction { get; set; } double FineRootFraction { get; set; } } public class FunctionalType : IFunctionalType { private double ppdf1; private double ppdf2; private double ppdf3; private double ppdf4; private double fcfracLeaf; private double btolai; private double klai; private double maxlai; private double pprpts2; private double pprpts3; private double monthlyWoodMortality; private double woodDecayRate; private double mortCurveShape; private int leafNeedleDrop; private double coarseRootFraction; private double fineRootFraction; public static FunctionalTypeTable Table; //--------------------------------------------------------------------- /// <summary> /// Optimum temperature for production for parameterization of a Poisson Density Function /// curve to simulate temperature effect on growth. /// Century Model Interface Help - Colorado State University, Fort Collins, CO 80523 /// </summary> public double PPDF1 { get { return ppdf1; } set { if (value < 10.0 || value > 40.0) throw new InputValueException(value.ToString(), "Decay rate must be between 10 and 40.0"); ppdf1 = value; } } //--------------------------------------------------------------------- /// <summary> /// Maximum temperature for production for parameterization of a Poisson Density Function /// curve to simulate temperature effect on growth. /// Century Model Interface Help - Colorado State University, Fort Collins, CO 80523 /// </summary> public double PPDF2 { get { return ppdf2; } set { if (value < 20.0 || value > 100.0) throw new InputValueException(value.ToString(), "Decay rate must be between 20 and 100.0"); ppdf2 = value; } } //--------------------------------------------------------------------- /// <summary> /// Left curve shape for parameterization of a Poisson Density Function curve to /// simulate temperature effect on growth. /// Century Model Interface Help - Colorado State University, Fort Collins, CO 80523 /// </summary> public double PPDF3 { get { return ppdf3; } set { if (value < 0.0 || value > 5.0) throw new InputValueException(value.ToString(), "Decay rate must be between 0 and 5.0"); ppdf3 = value; } } //--------------------------------------------------------------------- /// <summary> /// Right curve shape for parameterization of a Poisson Density Function /// curve to simulate temperature effect on growth. /// Century Model Interface Help - Colorado State University, Fort Collins, CO 80523 /// </summary> public double PPDF4 { get { return ppdf4; } set { if (value < 0.0 || value > 10.0) throw new InputValueException(value.ToString(), "Decay rate must be between 0 and 10.0"); ppdf4 = value; } } //--------------------------------------------------------------------- /// <summary> /// C allocation fraction of old leaves for mature forest. /// Century Model Interface Help - Colorado State University, Fort Collins, CO 80523 /// </summary> public double FCFRACleaf { get { return fcfracLeaf; } set { if (value < 0.1 || value > 1.0) throw new InputValueException(value.ToString(), "The fraction of NPP allocated to leaves must be between 0.1 and 1.0"); fcfracLeaf = value; } } //--------------------------------------------------------------------- /// <summary> /// Biomass to leaf area index (LAI) conversion factor for trees. This is a biome-specific parameters. /// Century Model Interface Help - Colorado State University, Fort Collins, CO 80523 /// </summary> public double BTOLAI { get { return btolai; } set { if (value < -3.0 || value > 1000.0) throw new InputValueException(value.ToString(), "BTOLAI must be between -3 and 1000"); btolai = value; } } //--------------------------------------------------------------------- /// <summary> /// Large wood mass in grams per square meter (g C /m2) at which half of the /// theoretical maximum leaf area (MAXLAI) is achieved. /// Century Model Interface Help - Colorado State University, Fort Collins, CO 80523 /// </summary> public double KLAI { get { return klai; } set { if (value < 1.0 || value > 50000.0) throw new InputValueException(value.ToString(), "K LAI must be between 1 and 50000"); klai = value; } } //--------------------------------------------------------------------- /// <summary> /// The Century manual recommends a maximum of 20 (?) /// </summary> public double MAXLAI { get { return maxlai; } set { if (value < 0 || value > 50.0) throw new InputValueException(value.ToString(), "Max LAI must be between 1 and 100"); maxlai = value; } } //--------------------------------------------------------------------- // 'PPRPTS(2)': The effect of water content on the intercept, allows the user to // increase the value of the intercept and thereby increase the slope of the line. public double PPRPTS2 { get { return pprpts2; } set { pprpts2 = value; } } //--------------------------------------------------------------------- // 'PPRPTS(3)': The lowest ratio of available water to PET at which there is no restriction on production. public double PPRPTS3 { get { return pprpts3; } set { pprpts3 = value; } } //--------------------------------------------------------------------- public double MonthlyWoodMortality { get { return monthlyWoodMortality; } set { if (value < 0.0 || value > 1.0) throw new InputValueException(value.ToString(), "Monthly Wood Mortality is a fraction and must be between 0.0 and 1.0"); monthlyWoodMortality = value; } } //--------------------------------------------------------------------- public double WoodDecayRate { get { return woodDecayRate; } set { if (value <= 0.0 || value > 2.0) throw new InputValueException(value.ToString(), "Decay rate must be between 0.0 and 2.0"); woodDecayRate = value; } } //--------------------------------------------------------------------- /// <summary> /// Determines the shape of the age-related mortality curve. Ranges from a gradual senescence (5) /// to a steep senescence (15). /// </summary> public double MortCurveShape { get { return mortCurveShape; } set { if (value <= 2 || value > 25) throw new InputValueException(value.ToString(), "Mortality shape curve parameters must be between 5 and 15"); mortCurveShape = value; } } //--------------------------------------------------------------------- /// <summary> /// Determines at what month of the year needles or leaves are dropped. /// </summary> public int LeafNeedleDrop { get { return leafNeedleDrop; } set { if (value < 1 || value > 12) throw new InputValueException(value.ToString(), "Leaf/Needle Drop must be a month of the year, 1-12"); leafNeedleDrop = value; } } //--------------------------------------------------------------------- /// <summary> /// Determines the fraction of woody biomass that is coarse roots /// </summary> public double CoarseRootFraction { get { return coarseRootFraction; } set { if (value < 0 || value > 1) throw new InputValueException(value.ToString(), "Coarse Roots must be expressed as a fraction, 0-1"); coarseRootFraction = value; } } //--------------------------------------------------------------------- /// <summary> /// Determines the fraction of leaf biomass that is fine roots /// </summary> public double FineRootFraction { get { return fineRootFraction; } set { if (value < 0 || value > 1) throw new InputValueException(value.ToString(), "Fine Roots must be expressed as a fraction, 0-1"); fineRootFraction = value; } } //--------------------------------------------------------------------- public FunctionalType() { } //--------------------------------------------------------------------- public static void Initialize(IInputParameters parameters) { Table = parameters.FunctionalTypes; //PlugIn.ModelCore.UI.WriteLine(" Functional Table [1].PPDF1={0}.", parameters.FunctionalTypeTable[1].PPDF1); } //--------------------------------------------------------------------- } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.IDictionary.TryGetValue(TKey,out TValue) /// </summary> public class IDictionaryTryGetValue { private int c_MINI_STRING_LENGTH = 1; private int c_MAX_STRING_LENGTH = 20; public static int Main(string[] args) { IDictionaryTryGetValue testObj = new IDictionaryTryGetValue(); TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.IDictionary.TryGetValue(TKey,out TValue)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Netativ]"); retVal = NegTest1() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using Dictionary<TKey,TValue> which implemented the TryGetValue method in IDictionay<TKey,TValue> and TKey is int..."; const string c_TEST_ID = "P001"; Dictionary<int, int> dictionary = new Dictionary<int, int>(); int key = TestLibrary.Generator.GetInt32(-55); int value = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); int outValue; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { bool result = ((IDictionary<int, int>)dictionary).TryGetValue(key, out outValue); if (outValue != value) { string errorDesc = "Value is not " + outValue + " as expected: Actual(" + value + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!result) { string errorDesc = "Value is not false as expected: Actual is true"; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using Dictionary<TKey,TValue> which implemented the TryGetValue method in IDictionay<TKey,TValue> and TKey is String..."; const string c_TEST_ID = "P002"; Dictionary<String, String> dictionary = new Dictionary<String, String>(); String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); String value = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); dictionary.Add(key, value); String outValue; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { bool result = ((IDictionary<String, String>)dictionary).TryGetValue(key, out outValue); if (outValue != value) { string errorDesc = "Value is not " + outValue + " as expected: Actual(" + value + ")"; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!result) { string errorDesc = "Value is not false as expected: Actual is true"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using Dictionary<TKey,TValue> which implemented the TryGetValue method in IDictionay<TKey,TValue> and TKey is customer class..."; const string c_TEST_ID = "P003"; Dictionary<MyClass, MyClass> dictionary = new Dictionary<MyClass, MyClass>(); MyClass key = new MyClass(); MyClass value = new MyClass(); dictionary.Add(key, value); MyClass outValue; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { bool result = ((IDictionary<MyClass, MyClass>)dictionary).TryGetValue(key, out outValue); if (!outValue.Equals(value)) { string errorDesc = "Value is not object as expected"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!result) { string errorDesc = "Value is not false as expected: Actual is true"; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Using Dictionary<TKey,TValue> which implemented the TryGetValue method in IDictionay<TKey,TValue> and TKey isn't exists in Dictionayr..."; const string c_TEST_ID = "P004"; Dictionary<String, String> dictionary = new Dictionary<String, String>(); String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); String outValue; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { bool result = ((IDictionary<String, String>)dictionary).TryGetValue(key, out outValue); if (outValue != null) { string errorDesc = "Value is not null as expected: Actual(" + outValue + ")"; TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (result) { string errorDesc = "Value is not false as expected: Actual is true"; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_DESC = "PosTest5: Using user-defined class which implemented the add method in IDictionay<TKey,TValue>..."; const string c_TEST_ID = "P005"; MyDictionary<int, int> dictionary = new MyDictionary<int, int>(); int key = TestLibrary.Generator.GetInt32(-55); int value = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int outValue = 0; bool result = ((IDictionary<int, int>)dictionary).TryGetValue(key, out outValue); if (outValue != value) { string errorDesc = "Value is not null as expected: Actual(" + outValue + ")"; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!result) { string errorDesc = "Value is not false as expected: Actual is true"; TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("015", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: Using Dictionary<TKey,TValue> which implemented the TryGetValue method in IDictionay<TKey,TValue> and Key is a null reference..."; const string c_TEST_ID = "N001"; Dictionary<String, int> dictionary = new Dictionary<String, int>(); String key = null; int value; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IDictionary<String, int>)dictionary).TryGetValue(key, out value); TestLibrary.TestFramework.LogError("016" + "TestId-" + c_TEST_ID, "The ArgumentNullException was not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("017", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private int count; private int capacity = 10; public bool readOnly = false; private KeyValuePair<TKey, TValue>[] keyvaluePair; public MyDictionary() { count = 0; keyvaluePair = new KeyValuePair<TKey, TValue>[capacity]; } #region IDictionary<TKey,TValue> Members public void Add(TKey key, TValue value) { if (readOnly) throw new NotSupportedException(); if (ContainsKey(key)) throw new ArgumentException(); try { KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value); keyvaluePair[count] = pair; count++; } catch (Exception en) { throw en; } } public bool ContainsKey(TKey key) { bool exist = false; if (key == null) throw new ArgumentNullException(); foreach (KeyValuePair<TKey, TValue> pair in keyvaluePair) { if (pair.Key != null && pair.Key.Equals(key)) { exist = true; } } return exist; } public ICollection<TKey> Keys { get { throw new Exception("The method or operation is not implemented."); } } public bool Remove(TKey key) { if (readOnly) { throw new NotSupportedException(); } bool contains = ContainsKey(key); if (!contains) { return false; } else { int index = -1; for (int j = 0; j < count; j++) { KeyValuePair<TKey, TValue> pair = keyvaluePair[j]; if (pair.Key.Equals(key)) { index = j; break; } } count--; if (index < count) { Array.Copy(keyvaluePair, index + 1, keyvaluePair, index, count - index); } keyvaluePair[count] = new KeyValuePair<TKey, TValue>(default(TKey), default(TValue)); return true; } } public bool TryGetValue(TKey key, out TValue value) { bool result = false; value = default(TValue); if (ContainsKey(key)) { for (int j = 0; j < count; j++) { KeyValuePair<TKey, TValue> pair = keyvaluePair[j]; if (pair.Key.Equals(key)) { result = true; value = pair.Value; break; } } } return result; } public ICollection<TValue> Values { get { throw new Exception("The method or operation is not implemented."); } } public TValue this[TKey key] { get { if (!ContainsKey(key)) throw new KeyNotFoundException(); int index = -1; for (int j = 0; j < count; j++) { KeyValuePair<TKey, TValue> pair = keyvaluePair[j]; if (pair.Key.Equals(key)) { index = j; break; } } return keyvaluePair[index].Value; } set { if (readOnly) throw new NotSupportedException(); if (ContainsKey(key)) { int index = -1; for (int j = 0; j < count; j++) { KeyValuePair<TKey, TValue> pair = keyvaluePair[j]; if (pair.Key.Equals(key)) { index = j; break; } } KeyValuePair<TKey, TValue> newpair = new KeyValuePair<TKey, TValue>(key, value); keyvaluePair[index] = newpair; } else { KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value); keyvaluePair[count] = pair; count++; } } } #endregion #region ICollection<KeyValuePair<TKey,TValue>> Members public void Add(KeyValuePair<TKey, TValue> item) { throw new Exception("The method or operation is not implemented."); } public void Clear() { throw new Exception("The method or operation is not implemented."); } public bool Contains(KeyValuePair<TKey, TValue> item) { throw new Exception("The method or operation is not implemented."); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new Exception("The method or operation is not implemented."); } public int Count { get { return count; } } public bool IsReadOnly { get { throw new Exception("The method or operation is not implemented."); } } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable<KeyValuePair<TKey,TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion } public class MyClass { } #endregion }
using System; using System.Collections.Generic; using System.Reflection; using Assman.ContentFiltering; using Assman.DependencyManagement; using Assman.PreCompilation; namespace Assman.Configuration { public class AssmanContext { public static AssmanContext Create(ResourceMode resourceMode) { return new AssmanContext(resourceMode); } private static AssmanContext _current; public static AssmanContext Current { get { if(_current == null) { var resourceMode = ResourceModeProvider.Instance.GetCurrentResourceMode(); _current = AssmanConfiguration.Current.BuildContext(resourceMode); } return _current; } set { _current = value; } } private readonly IResourceFinder _finder; private readonly CompositeResourceFinder _compositeFinder; private readonly ContentFilterPipelineMap _filterPipelineMap; private IResourceGroupManager _scriptGroups; private IResourceGroupManager _styleGroups; private IResourcePathResolver _scriptPathResolver; private IResourcePathResolver _stylePathResolver; private readonly List<Assembly> _assemblies; private readonly DependencyManager _dependencyManager; private readonly ResourceMode _resourceMode; internal AssmanContext(ResourceMode resourceMode) { var resourceCache = ResourceCacheFactory.GetCache(resourceMode); _scriptGroups = ResourceGroupManager.GetInstance(resourceMode, resourceCache); _styleGroups = ResourceGroupManager.GetInstance(resourceMode, resourceCache); _compositeFinder = new CompositeResourceFinder(); _compositeFinder.Exclude(new ConsolidatedResourceExcluder(_scriptGroups)); _compositeFinder.Exclude(new ConsolidatedResourceExcluder(_styleGroups)); _compositeFinder.Exclude(new PreCompiledResourceExcluder()); _compositeFinder.Exclude(new VsDocResourceExcluder()); _finder = new ResourceModeFilteringFinder(resourceMode, new CachingResourceFinder(resourceCache, _compositeFinder)); _filterPipelineMap = new ContentFilterPipelineMap(); _assemblies = new List<Assembly>(); _dependencyManager = DependencyManagerFactory.GetDependencyManager(_finder, _scriptGroups, _styleGroups, resourceMode); _resourceMode = resourceMode; _scriptPathResolver = new ResourcePathResolver(_scriptGroups, _dependencyManager, _finder); _stylePathResolver = new ResourcePathResolver(_styleGroups, _dependencyManager, _finder); } public DateTime ConfigurationLastModified { get; set; } public bool PreCompiled { get; private set; } public bool GZip { get; set; } public bool ConsolidateScripts { get { return _scriptGroups.Consolidate; } set { _scriptGroups.Consolidate = value; } } public bool ConsolidateStylesheets { get { return _styleGroups.Consolidate; } set { _styleGroups.Consolidate = value; } } //TODO: Remove this. Have the config flag simply clear out all default dependency resolvers if set public bool ManageDependencies { get; set; } public bool MutuallyExclusiveGroups { get { return _scriptGroups.MutuallyExclusiveGroups && _styleGroups.MutuallyExclusiveGroups; } set { _scriptGroups.MutuallyExclusiveGroups = value; _styleGroups.MutuallyExclusiveGroups = value; } } public string Version { get; set; } public void MapExtensionToContentPipeline(string fileExtension, ContentFilterPipeline filterPipeline) { _filterPipelineMap.MapExtension(fileExtension, filterPipeline); } public IResourceGroupManager ScriptGroups { get { return _scriptGroups; } } public IResourceGroupManager StyleGroups { get { return _styleGroups; } } public IResourcePathResolver ScriptPathResolver { get { return _scriptPathResolver; } } public IResourcePathResolver StylePathResolver { get { return _stylePathResolver; } } public ContentFilterPipeline GetContentPipelineForExtension(string fileExtension) { return _filterPipelineMap.GetPipelineForExtension(fileExtension); } public void AddFinder(IResourceFinder finder) { _compositeFinder.AddFinder(finder); } public void AddFinders(IEnumerable<IResourceFinder> finders) { _compositeFinder.AddFinders(finders); } public void AddExcluder(IFinderExcluder excluder) { _compositeFinder.Exclude(excluder); } public void AddAssembly(Assembly assembly) { _assemblies.Add(assembly); _compositeFinder.AddFinder(ResourceFinderFactory.GetInstance(assembly)); } public void AddAssemblies(IEnumerable<Assembly> assemblies) { foreach (var assembly in assemblies) { AddAssembly(assembly); } } public IEnumerable<Assembly> GetAssemblies() { return _assemblies; } public GroupTemplateContext FindGroupTemplate(string consolidatedUrl) { var resourceType = ResourceType.FromPath(consolidatedUrl); return GroupManagerOfType(resourceType).GetGroupTemplateOrDefault(consolidatedUrl); } [Obsolete("Please use GetCompiler instead")] public ResourceCompiler GetConsolidator() { return GetCompiler(); } public ResourceCompiler GetCompiler() { return new ResourceCompiler(_filterPipelineMap, _dependencyManager, _scriptGroups, _styleGroups, _finder, _resourceMode); } public IEnumerable<string> GetResourceDependencies(string virtualPath) { return _dependencyManager.GetDependencies(virtualPath); } public void MapExtensionToDependencyProvider(string fileExtension, IDependencyProvider dependencyProvider) { _dependencyManager.MapProvider(fileExtension, dependencyProvider); } public void LoadPreCompilationReport(PreCompilationReport preCompilationReport) { _scriptGroups = new PreCompiledGroupManager(preCompilationReport.Scripts, _scriptGroups); _styleGroups = new PreCompiledGroupManager(preCompilationReport.Stylesheets, _styleGroups); _dependencyManager.SetCache(new PreCompiledDependencyCache(preCompilationReport.Dependencies)); _scriptPathResolver = new ResourcePathResolver(_scriptGroups, _dependencyManager, _finder); _stylePathResolver = new ResourcePathResolver(_styleGroups, _dependencyManager, _finder); Version = preCompilationReport.Version; PreCompiled = true; } internal IResourceFinder Finder { get { return _finder; } } private IResourceGroupManager GroupManagerOfType(ResourceType resourceType) { if (resourceType == ResourceType.Script) return _scriptGroups; else return _styleGroups; } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileDNSBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDNSProfileDNSStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDNSProfileDNS64AdditionalSectionRewrite))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDNSProfileDNS64Mode))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileIPAddress))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileString))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDNSProfileDNSLastAction))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDNSProfileDNSRapidResponseLastAction))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))] public partial class LocalLBProfileDNS : iControlInterface { public LocalLBProfileDNS() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void create( string [] profile_names ) { this.Invoke("create", new object [] { profile_names}); } public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { profile_names}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_profiles //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void delete_all_profiles( ) { this.Invoke("delete_all_profiles", new object [0]); } public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState); } public void Enddelete_all_profiles(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void delete_profile( string [] profile_names ) { this.Invoke("delete_profile", new object [] { profile_names}); } public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_profile", new object[] { profile_names}, callback, asyncState); } public void Enddelete_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileDNSProfileDNSStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBProfileDNSProfileDNSStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBProfileDNSProfileDNSStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileDNSProfileDNSStatistics)(results[0])); } //----------------------------------------------------------------------- // get_avr_dnsstat_sample_rate //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_avr_dnsstat_sample_rate( string [] profile_names ) { object [] results = this.Invoke("get_avr_dnsstat_sample_rate", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_avr_dnsstat_sample_rate(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_avr_dnsstat_sample_rate", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_avr_dnsstat_sample_rate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_default_profile( string [] profile_names ) { object [] results = this.Invoke("get_default_profile", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_profile", new object[] { profile_names}, callback, asyncState); } public string [] Endget_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] profile_names ) { object [] results = this.Invoke("get_description", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { profile_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_dns64_additional_section_rewrite //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileDNSProfileDNS64AdditionalSectionRewrite [] get_dns64_additional_section_rewrite( string [] profile_names ) { object [] results = this.Invoke("get_dns64_additional_section_rewrite", new object [] { profile_names}); return ((LocalLBProfileDNSProfileDNS64AdditionalSectionRewrite [])(results[0])); } public System.IAsyncResult Beginget_dns64_additional_section_rewrite(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns64_additional_section_rewrite", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileDNSProfileDNS64AdditionalSectionRewrite [] Endget_dns64_additional_section_rewrite(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileDNSProfileDNS64AdditionalSectionRewrite [])(results[0])); } //----------------------------------------------------------------------- // get_dns64_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileDNSProfileDNS64Mode [] get_dns64_mode( string [] profile_names ) { object [] results = this.Invoke("get_dns64_mode", new object [] { profile_names}); return ((LocalLBProfileDNSProfileDNS64Mode [])(results[0])); } public System.IAsyncResult Beginget_dns64_mode(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns64_mode", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileDNSProfileDNS64Mode [] Endget_dns64_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileDNSProfileDNS64Mode [])(results[0])); } //----------------------------------------------------------------------- // get_dns64_prefix //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileIPAddress [] get_dns64_prefix( string [] profile_names ) { object [] results = this.Invoke("get_dns64_prefix", new object [] { profile_names}); return ((LocalLBProfileIPAddress [])(results[0])); } public System.IAsyncResult Beginget_dns64_prefix(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns64_prefix", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileIPAddress [] Endget_dns64_prefix(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileIPAddress [])(results[0])); } //----------------------------------------------------------------------- // get_dns_cache //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_dns_cache( string [] profile_names ) { object [] results = this.Invoke("get_dns_cache", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_dns_cache(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_cache", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_dns_cache(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_dns_cache_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_dns_cache_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_dns_cache_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_dns_cache_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_cache_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_dns_cache_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_dns_express_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_dns_express_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_dns_express_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_dns_express_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_express_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_dns_express_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_dns_firewall_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_dns_firewall_state( string [] profile_names ) { object [] results = this.Invoke("get_dns_firewall_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_dns_firewall_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_firewall_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_dns_firewall_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_dns_last_action //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileDNSProfileDNSLastAction [] get_dns_last_action( string [] profile_names ) { object [] results = this.Invoke("get_dns_last_action", new object [] { profile_names}); return ((LocalLBProfileDNSProfileDNSLastAction [])(results[0])); } public System.IAsyncResult Beginget_dns_last_action(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_last_action", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileDNSProfileDNSLastAction [] Endget_dns_last_action(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileDNSProfileDNSLastAction [])(results[0])); } //----------------------------------------------------------------------- // get_dns_logging_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_dns_logging_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_dns_logging_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_dns_logging_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_logging_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_dns_logging_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_dns_logging_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_dns_logging_profile( string [] profile_names ) { object [] results = this.Invoke("get_dns_logging_profile", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_dns_logging_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_logging_profile", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_dns_logging_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_dns_rapid_response_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_dns_rapid_response_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_dns_rapid_response_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_dns_rapid_response_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_rapid_response_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_dns_rapid_response_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_dns_rapid_response_last_action //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileDNSProfileDNSRapidResponseLastAction [] get_dns_rapid_response_last_action( string [] profile_names ) { object [] results = this.Invoke("get_dns_rapid_response_last_action", new object [] { profile_names}); return ((LocalLBProfileDNSProfileDNSRapidResponseLastAction [])(results[0])); } public System.IAsyncResult Beginget_dns_rapid_response_last_action(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_rapid_response_last_action", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileDNSProfileDNSRapidResponseLastAction [] Endget_dns_rapid_response_last_action(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileDNSProfileDNSRapidResponseLastAction [])(results[0])); } //----------------------------------------------------------------------- // get_dns_security_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_dns_security_profile( string [] profile_names ) { object [] results = this.Invoke("get_dns_security_profile", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_dns_security_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dns_security_profile", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_dns_security_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_dnssec_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_dnssec_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_dnssec_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_dnssec_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dnssec_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_dnssec_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_gtm_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_gtm_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_gtm_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_gtm_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_gtm_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_gtm_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_hardware_caching_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_hardware_caching_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_hardware_caching_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_hardware_caching_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_hardware_caching_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_hardware_caching_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_hardware_validation_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_hardware_validation_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_hardware_validation_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_hardware_validation_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_hardware_validation_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_hardware_validation_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileDNSProfileDNSStatistics get_statistics( string [] profile_names ) { object [] results = this.Invoke("get_statistics", new object [] { profile_names}); return ((LocalLBProfileDNSProfileDNSStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileDNSProfileDNSStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileDNSProfileDNSStatistics)(results[0])); } //----------------------------------------------------------------------- // get_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { object [] results = this.Invoke("get_statistics_by_virtual", new object [] { profile_names, virtual_names}); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } //----------------------------------------------------------------------- // get_use_local_bind_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_use_local_bind_state( string [] profile_names ) { object [] results = this.Invoke("get_use_local_bind_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_use_local_bind_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_use_local_bind_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_use_local_bind_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_zone_transfer_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_zone_transfer_state( string [] profile_names ) { object [] results = this.Invoke("get_zone_transfer_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_zone_transfer_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_zone_transfer_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_zone_transfer_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // is_base_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_base_profile( string [] profile_names ) { object [] results = this.Invoke("is_base_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_base_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_base_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_system_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_system_profile( string [] profile_names ) { object [] results = this.Invoke("is_system_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_system_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_system_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void reset_statistics( string [] profile_names ) { this.Invoke("reset_statistics", new object [] { profile_names}); } public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { profile_names}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void reset_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { this.Invoke("reset_statistics_by_virtual", new object [] { profile_names, virtual_names}); } public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_avr_dnsstat_sample_rate //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_avr_dnsstat_sample_rate( string [] profile_names, LocalLBProfileULong [] rates ) { this.Invoke("set_avr_dnsstat_sample_rate", new object [] { profile_names, rates}); } public System.IAsyncResult Beginset_avr_dnsstat_sample_rate(string [] profile_names,LocalLBProfileULong [] rates, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_avr_dnsstat_sample_rate", new object[] { profile_names, rates}, callback, asyncState); } public void Endset_avr_dnsstat_sample_rate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_default_profile( string [] profile_names, string [] defaults ) { this.Invoke("set_default_profile", new object [] { profile_names, defaults}); } public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_profile", new object[] { profile_names, defaults}, callback, asyncState); } public void Endset_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_description( string [] profile_names, string [] descriptions ) { this.Invoke("set_description", new object [] { profile_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { profile_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns64_additional_section_rewrite //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns64_additional_section_rewrite( string [] profile_names, LocalLBProfileDNSProfileDNS64AdditionalSectionRewrite [] values ) { this.Invoke("set_dns64_additional_section_rewrite", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_dns64_additional_section_rewrite(string [] profile_names,LocalLBProfileDNSProfileDNS64AdditionalSectionRewrite [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns64_additional_section_rewrite", new object[] { profile_names, values}, callback, asyncState); } public void Endset_dns64_additional_section_rewrite(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns64_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns64_mode( string [] profile_names, LocalLBProfileDNSProfileDNS64Mode [] modes ) { this.Invoke("set_dns64_mode", new object [] { profile_names, modes}); } public System.IAsyncResult Beginset_dns64_mode(string [] profile_names,LocalLBProfileDNSProfileDNS64Mode [] modes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns64_mode", new object[] { profile_names, modes}, callback, asyncState); } public void Endset_dns64_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns64_prefix //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns64_prefix( string [] profile_names, LocalLBProfileIPAddress [] values ) { this.Invoke("set_dns64_prefix", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_dns64_prefix(string [] profile_names,LocalLBProfileIPAddress [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns64_prefix", new object[] { profile_names, values}, callback, asyncState); } public void Endset_dns64_prefix(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_cache //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_cache( string [] profile_names, LocalLBProfileString [] caches ) { this.Invoke("set_dns_cache", new object [] { profile_names, caches}); } public System.IAsyncResult Beginset_dns_cache(string [] profile_names,LocalLBProfileString [] caches, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_cache", new object[] { profile_names, caches}, callback, asyncState); } public void Endset_dns_cache(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_cache_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_cache_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_dns_cache_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_dns_cache_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_cache_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_dns_cache_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_express_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_express_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_dns_express_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_dns_express_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_express_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_dns_express_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_firewall_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_firewall_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_dns_firewall_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_dns_firewall_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_firewall_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_dns_firewall_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_last_action //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_last_action( string [] profile_names, LocalLBProfileDNSProfileDNSLastAction [] actions ) { this.Invoke("set_dns_last_action", new object [] { profile_names, actions}); } public System.IAsyncResult Beginset_dns_last_action(string [] profile_names,LocalLBProfileDNSProfileDNSLastAction [] actions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_last_action", new object[] { profile_names, actions}, callback, asyncState); } public void Endset_dns_last_action(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_logging_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_logging_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_dns_logging_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_dns_logging_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_logging_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_dns_logging_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_logging_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_logging_profile( string [] profile_names, LocalLBProfileString [] logging_profile_names ) { this.Invoke("set_dns_logging_profile", new object [] { profile_names, logging_profile_names}); } public System.IAsyncResult Beginset_dns_logging_profile(string [] profile_names,LocalLBProfileString [] logging_profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_logging_profile", new object[] { profile_names, logging_profile_names}, callback, asyncState); } public void Endset_dns_logging_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_rapid_response_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_rapid_response_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_dns_rapid_response_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_dns_rapid_response_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_rapid_response_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_dns_rapid_response_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_rapid_response_last_action //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_rapid_response_last_action( string [] profile_names, LocalLBProfileDNSProfileDNSRapidResponseLastAction [] actions ) { this.Invoke("set_dns_rapid_response_last_action", new object [] { profile_names, actions}); } public System.IAsyncResult Beginset_dns_rapid_response_last_action(string [] profile_names,LocalLBProfileDNSProfileDNSRapidResponseLastAction [] actions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_rapid_response_last_action", new object[] { profile_names, actions}, callback, asyncState); } public void Endset_dns_rapid_response_last_action(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dns_security_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dns_security_profile( string [] profile_names, LocalLBProfileString [] security_profile_names ) { this.Invoke("set_dns_security_profile", new object [] { profile_names, security_profile_names}); } public System.IAsyncResult Beginset_dns_security_profile(string [] profile_names,LocalLBProfileString [] security_profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dns_security_profile", new object[] { profile_names, security_profile_names}, callback, asyncState); } public void Endset_dns_security_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dnssec_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_dnssec_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_dnssec_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_dnssec_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dnssec_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_dnssec_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_gtm_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_gtm_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_gtm_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_gtm_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_gtm_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_gtm_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_hardware_caching_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_hardware_caching_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_hardware_caching_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_hardware_caching_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_hardware_caching_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_hardware_caching_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_hardware_validation_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_hardware_validation_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_hardware_validation_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_hardware_validation_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_hardware_validation_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_hardware_validation_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_use_local_bind_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_use_local_bind_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_use_local_bind_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_use_local_bind_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_use_local_bind_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_use_local_bind_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_zone_transfer_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDNS", RequestNamespace="urn:iControl:LocalLB/ProfileDNS", ResponseNamespace="urn:iControl:LocalLB/ProfileDNS")] public void set_zone_transfer_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_zone_transfer_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_zone_transfer_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_zone_transfer_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_zone_transfer_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.DNS64AdditionalSectionRewrite", Namespace = "urn:iControl")] public enum LocalLBProfileDNSDNS64AdditionalSectionRewrite { DNS64_ADDITIONAL_SECTION_REWRITE_UNKNOWN, DNS64_ADDITIONAL_SECTION_REWRITE_DISABLE, DNS64_ADDITIONAL_SECTION_REWRITE_V6ONLY, DNS64_ADDITIONAL_SECTION_REWRITE_V4ONLY, DNS64_ADDITIONAL_SECTION_REWRITE_ANY, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.DNS64Mode", Namespace = "urn:iControl")] public enum LocalLBProfileDNSDNS64Mode { DNS64_MODE_UNKNOWN, DNS64_MODE_DISABLE, DNS64_MODE_SECONDARY, DNS64_MODE_IMMEDIATE, DNS64_MODE_V4ONLY, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.DNSLastAction", Namespace = "urn:iControl")] public enum LocalLBProfileDNSDNSLastAction { DNS_LAST_ACTION_UNKNOWN, DNS_LAST_ACTION_ALLOW, DNS_LAST_ACTION_DROP, DNS_LAST_ACTION_REJECT, DNS_LAST_ACTION_HINT, DNS_LAST_ACTION_NOERROR, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.DNSRapidResponseLastAction", Namespace = "urn:iControl")] public enum LocalLBProfileDNSDNSRapidResponseLastAction { DNS_RAPID_RESPONSE_ACTION_UNKNOWN, DNS_RAPID_RESPONSE_ACTION_ALLOW, DNS_RAPID_RESPONSE_ACTION_DROP, DNS_RAPID_RESPONSE_ACTION_RESPOND_TC, DNS_RAPID_RESPONSE_ACTION_RESPOND_NXDOMAIN, DNS_RAPID_RESPONSE_ACTION_RESPOND_NOERROR, DNS_RAPID_RESPONSE_ACTION_RESPOND_REFUSED, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.ProfileDNS64AdditionalSectionRewrite", Namespace = "urn:iControl")] public partial class LocalLBProfileDNSProfileDNS64AdditionalSectionRewrite { private LocalLBProfileDNSDNS64AdditionalSectionRewrite valueField; public LocalLBProfileDNSDNS64AdditionalSectionRewrite value { get { return this.valueField; } set { this.valueField = value; } } private bool default_flagField; public bool default_flag { get { return this.default_flagField; } set { this.default_flagField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.ProfileDNS64Mode", Namespace = "urn:iControl")] public partial class LocalLBProfileDNSProfileDNS64Mode { private LocalLBProfileDNSDNS64Mode valueField; public LocalLBProfileDNSDNS64Mode value { get { return this.valueField; } set { this.valueField = value; } } private bool default_flagField; public bool default_flag { get { return this.default_flagField; } set { this.default_flagField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.ProfileDNSLastAction", Namespace = "urn:iControl")] public partial class LocalLBProfileDNSProfileDNSLastAction { private LocalLBProfileDNSDNSLastAction valueField; public LocalLBProfileDNSDNSLastAction value { get { return this.valueField; } set { this.valueField = value; } } private bool default_flagField; public bool default_flag { get { return this.default_flagField; } set { this.default_flagField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.ProfileDNSRapidResponseLastAction", Namespace = "urn:iControl")] public partial class LocalLBProfileDNSProfileDNSRapidResponseLastAction { private LocalLBProfileDNSDNSRapidResponseLastAction valueField; public LocalLBProfileDNSDNSRapidResponseLastAction value { get { return this.valueField; } set { this.valueField = value; } } private bool default_flagField; public bool default_flag { get { return this.default_flagField; } set { this.default_flagField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.ProfileDNSStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBProfileDNSProfileDNSStatisticEntry { private string profile_nameField; public string profile_name { get { return this.profile_nameField; } set { this.profile_nameField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDNS.ProfileDNSStatistics", Namespace = "urn:iControl")] public partial class LocalLBProfileDNSProfileDNSStatistics { private LocalLBProfileDNSProfileDNSStatisticEntry [] statisticsField; public LocalLBProfileDNSProfileDNSStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Peddler { public class StringGeneratorTests { private const int numberOfAttempts = 100; private static ISet<Char> empty { get; } private static ISet<Char> alphabet { get; } static StringGeneratorTests() { empty = ImmutableHashSet<Char>.Empty; var lowerCaseAlphabet = new HashSet<Char> { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; alphabet = lowerCaseAlphabet.ToImmutableHashSet(); } [Fact] public void Constructor_WithLength_RequiresNonNegative() { Assert.Throws<ArgumentOutOfRangeException>( () => new StringGenerator(-1) ); } [Fact] public void Constructor_WithLengthAndCharacters_RequiresNonNullChars() { Assert.Throws<ArgumentNullException>( () => new StringGenerator(10, null) ); } [Fact] public void Constructor_WithLengthAndCharacters_RequiresNonNegative() { Assert.Throws<ArgumentOutOfRangeException>( () => new StringGenerator(-1, alphabet) ); } [Fact] public void Constructor_WithLengthAndCharacters_RequiresCharsWhenNotEmpty() { Assert.Throws<ArgumentException>( () => new StringGenerator(5, empty) ); } [Fact] public void Constructor_WithLengthAndCharacters_AllowsEmptyCharsWithLengthOfZero() { var generator = new StringGenerator(0, empty); Assert.Equal(String.Empty, generator.Next()); } [Fact] public void Constructor_WithRange_RequiresNonNegative() { Assert.Throws<ArgumentOutOfRangeException>( () => new StringGenerator(-1, 10) ); } [Fact] public void Constructor_WithRange_RequiresLowerMinimum() { Assert.Throws<ArgumentException>( () => new StringGenerator(10, 9) ); } [Fact] public void Constructor_WithRangeAndCharacters_RequiresNonNullChars() { Assert.Throws<ArgumentNullException>( () => new StringGenerator(1, 10, null) ); } [Fact] public void Constructor_WithRangeAndCharacters_RequiresNonNegative() { Assert.Throws<ArgumentOutOfRangeException>( () => new StringGenerator(-1, 10, alphabet) ); } [Fact] public void Constructor_WithRangeAndCharacters_RequiresLowerMinimum() { Assert.Throws<ArgumentException>( () => new StringGenerator(5, 4, alphabet) ); } [Fact] public void Constructor_WithRangeAndCharacters_RequiresCharsWhenNotEmpty() { Assert.Throws<ArgumentException>( () => new StringGenerator(1, 5, empty) ); } [Fact] public void Constructor_WithRangeAndCharacters_AllowsEmptyCharsWithMaximumIsZero() { var generator = new StringGenerator(0, 0, empty); Assert.Equal(String.Empty, generator.Next()); } [Fact] public void Next_Defaults() { var characters = CharacterSets.AsciiPrintable; var generator = new StringGenerator(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.Next(); Assert.InRange(value.Length, 0, 255); Assert.DoesNotContain(value, character => !characters.Contains(character)); Assert.True(generator.EqualityComparer.Equals(value, value)); } } public static IEnumerable<object[]> NextDistinct_Defaults_Data { get { yield return ToArray(String.Empty); yield return ToArray(" "); yield return ToArray("foo"); yield return ToArray(new String('a', 256)); yield return ToArray(new String('a', 10000)); yield return ToArray(new String(CharacterSets.AsciiExtended.First(), 5)); } } [Theory] [MemberData(nameof(NextDistinct_Defaults_Data))] public void NextDistinct_Defaults(String other) { var characters = CharacterSets.AsciiPrintable; var generator = new StringGenerator(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextDistinct(other); Assert.NotEqual(value, other); Assert.InRange(value.Length, 0, 255); Assert.DoesNotContain(value, character => !characters.Contains(character)); Assert.False(generator.EqualityComparer.Equals(other, value)); } } [Fact] public void NextDistinct_NullOther() { const string other = null; var generator = new StringGenerator(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextDistinct(other); Assert.NotEqual(value, other); Assert.InRange(value.Length, 0, 255); Assert.False(generator.EqualityComparer.Equals(other, value)); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void Next_WithLength(int length) { var characters = CharacterSets.AsciiPrintable; var generator = new StringGenerator(length); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.Next(); Assert.Equal(length, value.Length); Assert.DoesNotContain(value, character => !characters.Contains(character)); Assert.True(generator.EqualityComparer.Equals(value, value)); } } [Theory] [InlineData(3, "foo")] [InlineData(5, "foo")] [InlineData(2, "foobar")] [InlineData(100, "barbizbuzzbooze")] [InlineData(0, "a")] [InlineData(3, "aa")] [InlineData(2, "aaa")] public void NextDistinct_WithLength(int length, String other) { var characters = CharacterSets.AsciiPrintable; var generator = new StringGenerator(length); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextDistinct(other); Assert.NotEqual(value, other); Assert.Equal(length, value.Length); Assert.DoesNotContain(value, character => !characters.Contains(character)); Assert.False(generator.EqualityComparer.Equals(other, value)); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void Next_WithLengthAndCharacters(int length) { var generator = new StringGenerator(length, alphabet); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.Next(); Assert.Equal(length, value.Length); Assert.DoesNotContain(value, character => !alphabet.Contains(character)); Assert.True(generator.EqualityComparer.Equals(value, value)); } } public static IEnumerable<object[]> NextDistinct_WithLengthAndCharacters_Data { get { yield return ToArray(3, alphabet, "foo"); yield return ToArray(5, new HashSet<Char> { 'a' }, "foo"); yield return ToArray(2, new HashSet<Char> { 'a' }, "foobar"); yield return ToArray(100, CharacterSets.AsciiPrintable, "barbizbuzzbooze"); yield return ToArray(0, new HashSet<Char>{ 'a' }, "a"); // => "" yield return ToArray(3, new HashSet<Char>{ 'a' }, "aa"); // => "aaa" yield return ToArray(2, new HashSet<Char>{ 'a' }, "aaa"); // => "aa" yield return ToArray(3, new HashSet<Char>{ 'a' }, "aab"); // => "aaa" yield return ToArray(3, new HashSet<Char>{ 'a' }, "aba"); // => "aaa" yield return ToArray(3, new HashSet<Char>{ 'a' }, "baa"); // => "aaa" } } [Theory] [MemberData(nameof(NextDistinct_WithLengthAndCharacters_Data))] public void NextDistinct_WithLengthAndCharacters( int length, ISet<Char> characters, String other) { var generator = new StringGenerator(length, characters); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextDistinct(other); Assert.NotEqual(value, other); Assert.Equal(length, value.Length); Assert.DoesNotContain(value, character => !characters.Contains(character)); Assert.False(generator.EqualityComparer.Equals(other, value)); } } [Fact] public void NextDistinct_WithLengthAndCharacters_UnableToGenerateValueException() { var length = 1; var characters = new HashSet<Char> { 'a' }; var other = "a"; var generator = new StringGenerator(length, characters); Assert.Throws<UnableToGenerateValueException>( () => generator.NextDistinct(other) ); } [Theory] [InlineData(0, 0)] [InlineData(0, 100)] [InlineData(100, 100)] [InlineData(100, 1000)] public void Next_WithRange(int minimum, int maximum) { var characters = CharacterSets.AsciiPrintable; var generator = new StringGenerator(minimum, maximum); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.Next(); Assert.InRange(value.Length, minimum, maximum); Assert.DoesNotContain(value, character => !characters.Contains(character)); Assert.True(generator.EqualityComparer.Equals(value, value)); } } [Theory] [InlineData(0, 100, "foo")] [InlineData(100, 200, "barbizbuzzbooze")] [InlineData(0, 10, "aaaaaaaaaa")] [InlineData(0, 0, "a")] [InlineData(2, 3, "aa")] [InlineData(2, 3, "aaa")] [InlineData(3, 3, "aab")] [InlineData(3, 3, "aba")] [InlineData(3, 3, "baa")] public void NextDistinct_WithRange(int minimum, int maximum, String other) { var characters = CharacterSets.AsciiPrintable; var generator = new StringGenerator(minimum, maximum); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextDistinct(other); Assert.NotEqual(value, other); Assert.InRange(value.Length, minimum, maximum); Assert.DoesNotContain(value, character => !characters.Contains(character)); Assert.False(generator.EqualityComparer.Equals(other, value)); } } [Theory] [InlineData(0, 0)] [InlineData(0, 100)] [InlineData(100, 100)] [InlineData(100, 1000)] public void Next_WithRangeAndCharacters(int minimum, int maximum) { var generator = new StringGenerator(minimum, maximum, alphabet); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.Next(); Assert.InRange(value.Length, minimum, maximum); Assert.DoesNotContain(value, character => !alphabet.Contains(character)); Assert.True(generator.EqualityComparer.Equals(value, value)); } } public static IEnumerable<object[]> NextDistinct_WithRangeAndCharacters_Data { get { yield return ToArray(0, 100, alphabet, "foo"); yield return ToArray(5, 10, new HashSet<Char> { 'a' }, "foo"); yield return ToArray(1, 2, new HashSet<Char> { 'a' }, "foobar"); yield return ToArray(100, 200, CharacterSets.AsciiPrintable, "barbizbuzzbooze"); yield return ToArray(0, 100, new HashSet<Char> { 'a' }, new String('a', 100)); yield return ToArray(0, 0, new HashSet<Char>{ 'a' }, "a"); // => "" yield return ToArray(2, 3, new HashSet<Char>{ 'a' }, "aa"); // => "aaa" yield return ToArray(2, 3, new HashSet<Char>{ 'a' }, "aaa"); // => "aa" yield return ToArray(3, 3, new HashSet<Char>{ 'a' }, "aab"); // => "aaa" yield return ToArray(3, 3, new HashSet<Char>{ 'a' }, "aba"); // => "aaa" yield return ToArray(3, 3, new HashSet<Char>{ 'a' }, "baa"); // => "aaa" } } [Theory] [MemberData(nameof(NextDistinct_WithRangeAndCharacters_Data))] public void NextDistinct_WithRangeAndCharacters( int minimum, int maximum, ISet<Char> characters, String other) { var generator = new StringGenerator(minimum, maximum, characters); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextDistinct(other); Assert.NotEqual(value, other); Assert.InRange(value.Length, minimum, maximum); Assert.DoesNotContain(value, character => !characters.Contains(character)); Assert.False(generator.EqualityComparer.Equals(other, value)); } } [Fact] public void NextDistinct_WithRangeAndCharacters_UnableToGenerateValueException() { var length = 1; var characters = new HashSet<Char> { 'a' }; var other = "a"; var generator = new StringGenerator(length, length, characters); Assert.Throws<UnableToGenerateValueException>( () => generator.NextDistinct(other) ); } [Fact] public async Task ThreadSafety() { // Arrange var generator = new StringGenerator(0, 1000); var consecutiveEmptyStrings = new ConcurrentStack<String>(); Action createThread = () => this.ThreadSafetyImpl(generator, consecutiveEmptyStrings); // Act var threads = Enumerable .Range(0, 10) .Select(_ => Task.Run(createThread)) .ToArray(); await Task.WhenAll(threads); // Assert Assert.True( consecutiveEmptyStrings.Count < 50, $"System.Random is not thread safe. If one of its .Next() " + $"implementations is called simultaneously on several " + $"threads, it breaks and starts returning zero exclusively. " + $"The last {consecutiveEmptyStrings.Count:N0} values were " + $"the empty string, signifying its internal System.Random " + $"is in a broken state." ); } private void ThreadSafetyImpl( IGenerator<String> generator, ConcurrentStack<String> consecutiveEmptyStrings) { var count = 0; while (count++ < 10000) { if (generator.Next().Equals(String.Empty)) { consecutiveEmptyStrings.Push(String.Empty); } else { consecutiveEmptyStrings.Clear(); } } } // Syntactic sugar. // 'yield return ToArray( ... )' is shorter than 'yield return new object[] { ... }' private static object[] ToArray(params object[] objects) { return objects; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; using Akka.Actor; using Automatonymous; using Google.Protobuf.WellKnownTypes; using GridDomain.Common; using GridDomain.Configuration; using GridDomain.Configuration.MessageRouting; using GridDomain.CQRS; using GridDomain.EventSourcing; using GridDomain.EventSourcing.CommonDomain; using GridDomain.Node.Actors.Aggregates.Messages; using GridDomain.Node.Actors.CommandPipe.Messages; using GridDomain.Node.Actors.EventSourced; using GridDomain.Node.Actors.EventSourced.Messages; using GridDomain.Node.Actors.ProcessManagers.Messages; using GridDomain.Transport.Extension; namespace GridDomain.Node.Actors.Aggregates { public class CommandAlreadyExecutedException:Exception { } /// <summary> /// Name should be parse by AggregateActorName /// </summary> /// <typeparam name="TAggregate"></typeparam> public class AggregateActor<TAggregate> : DomainEventSourcedActor<TAggregate> where TAggregate : class,IAggregate { private readonly IActorRef _customHandlersActor; private readonly ProcessEntry _domainEventProcessEntry; private readonly ProcessEntry _domainEventProcessFailEntry; private readonly ProcessEntry _commandCompletedProcessEntry; private readonly IPublisher _publisher; private readonly IAggregateCommandsHandler<TAggregate> _aggregateCommandsHandler; private AggregateCommandExecutionContext ExecutionContext { get; } = new AggregateCommandExecutionContext(); public AggregateActor(IAggregateCommandsHandler<TAggregate> handler, ISnapshotsPersistencePolicy snapshotsPersistencePolicy, IConstructAggregates aggregateConstructor, IConstructSnapshots snapshotsConstructor, IActorRef customHandlersActor) : base(aggregateConstructor, snapshotsConstructor, snapshotsPersistencePolicy) { _aggregateCommandsHandler = handler; _publisher = Context.System.GetTransport(); _customHandlersActor = customHandlersActor; _domainEventProcessEntry = new ProcessEntry(Self.Path.Name, AggregateActorConstants.PublishingEvent, AggregateActorConstants.CommandExecutionCreatedAnEvent); _domainEventProcessFailEntry = new ProcessEntry(Self.Path.Name, AggregateActorConstants.CommandExecutionFinished, AggregateActorConstants.CommandRaisedAnError); _commandCompletedProcessEntry = new ProcessEntry(Self.Path.Name, AggregateActorConstants.CommandExecutionFinished, AggregateActorConstants.ExecutedCommand); Behavior.Become(AwaitingCommandBehavior, nameof(AwaitingCommandBehavior)); } protected void ValidatingCommandBehavior() { DefaultBehavior(); Command<CommandStateActor.Accepted>(a => { Behavior.Become(ProcessingCommandBehavior, nameof(ProcessingCommandBehavior)); Log.Debug("Executing command. {@m}", ExecutionContext); _aggregateCommandsHandler.ExecuteAsync(State, ExecutionContext.Command) .ContinueWith(t => { ExecutionContext.ProducedState = t.Result; return ExecutionContext.ProducedState.GetUncommittedEvents(); }) .PipeTo(Self); }); Command<CommandStateActor.Rejected>(a => { var commandAlreadyExecutedException = new CommandAlreadyExecutedException(); PublishError(commandAlreadyExecutedException); Behavior.Become(AwaitingCommandBehavior, nameof(AwaitingCommandBehavior)); // throw commandAlreadyExecutedException; Stash.UnstashAll(); }); CommandAny(StashMessage); } protected virtual void AwaitingCommandBehavior() { DefaultBehavior(); Command<IMessageMetadataEnvelop>(m => { Monitor.Increment(nameof(CQRS.Command)); var cmd = (ICommand)m.Message; var name = cmd.Id.ToString(); Log.Debug($"Received command {cmd.Id}"); var actorRef = Context.Child(name); ExecutionContext.Validator = actorRef != ActorRefs.Nobody ? actorRef : Context.ActorOf<CommandStateActor>(name); ExecutionContext.Command = cmd; ExecutionContext.CommandMetadata = m.Metadata; ExecutionContext.CommandSender = Sender; ExecutionContext.Validator.Tell(CommandStateActor.AcceptCommandExecution.Instance); Behavior.Become(ValidatingCommandBehavior,nameof(ValidatingCommandBehavior)); }, m => m.Message is ICommand); } protected override bool CanShutdown(out string description) { if (!ExecutionContext.InProgress) return base.CanShutdown(out description); description = $"Command {ExecutionContext.Command.Id} is in progress"; return false; } private void ProcessingCommandBehavior() { var producedEventsMetadata = ExecutionContext.CommandMetadata.CreateChild(Id, _domainEventProcessEntry); //just for catching Failures on events persist Command<IReadOnlyCollection<DomainEvent>>(domainEvents => { Monitor.Increment(nameof(PersistEventPack)); if (!domainEvents.Any()) { Log.Warning("Trying to persist events but no events is presented. {@context}", ExecutionContext); return; } //dirty hack, but we know nobody will modify domain events before us foreach (var evt in domainEvents) evt.ProcessId = ExecutionContext.Command.ProcessId; int messagesToPersistCount = domainEvents.Count; PersistAll(domainEvents, persistedEvent => { NotifyPersistenceWatchers(persistedEvent); Project(persistedEvent, producedEventsMetadata); SaveSnapshot(ExecutionContext.ProducedState, persistedEvent); if (--messagesToPersistCount != 0) return; CompleteExecution(); }); }); Command<AllHandlersCompleted>(c => { ExecutionContext.MessagesToProject--; if (ExecutionContext.Projecting) return; ExecutionContext.CommandSender.Tell(AggregateActor.CommandProjected.Instance); WaitForNewCommand(); }); //aggregate raised an error during command execution Command<Status.Failure>(f => { ExecutionContext.Exception = f.Cause.UnwrapSingle(); ExecutionContext.Validator.Tell(CommandStateActor.CommandFailed.Instance); PublishError(ExecutionContext.Exception); Behavior.Become(() => { Command<AllHandlersCompleted>(c => throw new CommandExecutionFailedException(ExecutionContext.Command, ExecutionContext.Exception)); CommandAny(StashMessage); },"Waiting for command exception projection"); }); DefaultBehavior(); CommandAny(StashMessage); } private void CompleteExecution() { Log.Info("Command executed. {@context}", ExecutionContext.CommandMetadata); State = ExecutionContext.ProducedState as TAggregate; if(State == null) throw new InvalidOperationException("Aggregate state was null after command execution"); State.ClearUncommitedEvents(); var completedMetadata = ExecutionContext.CommandMetadata .CreateChild(ExecutionContext.Command.Id, _commandCompletedProcessEntry); _publisher.Publish(AggregateActor.CommandExecuted.Instance, completedMetadata); ExecutionContext.CommandSender.Tell(AggregateActor.CommandExecuted.Instance); ExecutionContext.Validator.Tell(CommandStateActor.CommandSucceed.Instance); //waiting to some events been projecting if(ExecutionContext.Projecting) return; WaitForNewCommand(); } private void WaitForNewCommand() { ExecutionContext.Clear(); Behavior.Become(AwaitingCommandBehavior, nameof(AwaitingCommandBehavior)); Stash.Unstash(); } private IFault PublishError(Exception exception) { var command = ExecutionContext.Command; Log.Error(exception, "An error occured while command execution. {@context}", ExecutionContext); var producedFaultMetadata = ExecutionContext.CommandMetadata.CreateChild(command.Id, _domainEventProcessFailEntry); var fault = Fault.NewGeneric(command, exception, command.ProcessId, typeof(TAggregate)); Project(fault, producedFaultMetadata); ExecutionContext.CommandSender.Tell(fault); return fault; } private void Project(object evt, IMessageMetadata commandMetadata) { ExecutionContext.MessagesToProject++; _customHandlersActor.Tell(new MessageMetadataEnvelop(evt, commandMetadata)); _publisher.Publish(evt,commandMetadata); } } public static class AggregateActor { //Stages of command processing notifications: // 1. Executed // 2. Projected public class CommandExecuted { private CommandExecuted() { } public static CommandExecuted Instance { get; } = new CommandExecuted(); } public class CommandProjected { private CommandProjected() { } public static CommandProjected Instance { get; } = new CommandProjected(); } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Models { /// <summary> /// PipelineRunImpllinks /// </summary> [DataContract(Name = "PipelineRunImpllinks")] public partial class PipelineRunImpllinks : IEquatable<PipelineRunImpllinks>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PipelineRunImpllinks" /> class. /// </summary> /// <param name="nodes">nodes.</param> /// <param name="log">log.</param> /// <param name="self">self.</param> /// <param name="actions">actions.</param> /// <param name="steps">steps.</param> /// <param name="_class">_class.</param> public PipelineRunImpllinks(Link nodes = default(Link), Link log = default(Link), Link self = default(Link), Link actions = default(Link), Link steps = default(Link), string _class = default(string)) { this.Nodes = nodes; this.Log = log; this.Self = self; this.Actions = actions; this.Steps = steps; this.Class = _class; } /// <summary> /// Gets or Sets Nodes /// </summary> [DataMember(Name = "nodes", EmitDefaultValue = false)] public Link Nodes { get; set; } /// <summary> /// Gets or Sets Log /// </summary> [DataMember(Name = "log", EmitDefaultValue = false)] public Link Log { get; set; } /// <summary> /// Gets or Sets Self /// </summary> [DataMember(Name = "self", EmitDefaultValue = false)] public Link Self { get; set; } /// <summary> /// Gets or Sets Actions /// </summary> [DataMember(Name = "actions", EmitDefaultValue = false)] public Link Actions { get; set; } /// <summary> /// Gets or Sets Steps /// </summary> [DataMember(Name = "steps", EmitDefaultValue = false)] public Link Steps { get; set; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { 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 PipelineRunImpllinks {\n"); sb.Append(" Nodes: ").Append(Nodes).Append("\n"); sb.Append(" Log: ").Append(Log).Append("\n"); sb.Append(" Self: ").Append(Self).Append("\n"); sb.Append(" Actions: ").Append(Actions).Append("\n"); sb.Append(" Steps: ").Append(Steps).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PipelineRunImpllinks); } /// <summary> /// Returns true if PipelineRunImpllinks instances are equal /// </summary> /// <param name="input">Instance of PipelineRunImpllinks to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineRunImpllinks input) { if (input == null) return false; return ( this.Nodes == input.Nodes || (this.Nodes != null && this.Nodes.Equals(input.Nodes)) ) && ( this.Log == input.Log || (this.Log != null && this.Log.Equals(input.Log)) ) && ( this.Self == input.Self || (this.Self != null && this.Self.Equals(input.Self)) ) && ( this.Actions == input.Actions || (this.Actions != null && this.Actions.Equals(input.Actions)) ) && ( this.Steps == input.Steps || (this.Steps != null && this.Steps.Equals(input.Steps)) ) && ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Nodes != null) hashCode = hashCode * 59 + this.Nodes.GetHashCode(); if (this.Log != null) hashCode = hashCode * 59 + this.Log.GetHashCode(); if (this.Self != null) hashCode = hashCode * 59 + this.Self.GetHashCode(); if (this.Actions != null) hashCode = hashCode * 59 + this.Actions.GetHashCode(); if (this.Steps != null) hashCode = hashCode * 59 + this.Steps.GetHashCode(); if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
/* Josip Medved <jmedved@jmedved.com> * www.medo64.com * MIT License */ //2021-11-25: Refactored to use pattern matching //2021-11-08: Refactored for .NET 6 //2021-10-10: Initial version namespace Medo.IO; using System; using System.Collections.Generic; using System.IO; using System.Text; /// <summary> /// Basic terminal operations. /// </summary> /// <example> /// <code> /// Terminal.Blue().Write("In blue").NoColor().Write(" not in blue"); /// </code> /// </example> public static class Terminal { /// <summary> /// Setups ANSI output. /// </summary> public static void Setup() { OutputStream = null; ErrorStream = null; UseAnsi = true; SuppressAttributes = false; } /// <summary> /// Setups ANSI output. /// </summary> /// <param name="outputStream">Output stream.</param> /// <exception cref="ArgumentNullException">Output stream cannot be null.</exception> public static void Setup(Stream outputStream) { Setup(outputStream, outputStream); } /// <summary> /// Setups ANSI output. /// </summary> /// <param name="outputStream">Output stream.</param> /// <param name="errorStream">Error stream.</param> /// <exception cref="ArgumentNullException">Output stream cannot be null. -or- Error stream cannot be null.</exception> public static void Setup(Stream outputStream, Stream errorStream) { if (outputStream is null) { throw new ArgumentNullException(nameof(outputStream), "Output stream cannot be null."); } if (errorStream is null) { throw new ArgumentNullException(nameof(errorStream), "Error stream cannot be null."); } OutputStream = outputStream; ErrorStream = errorStream; UseAnsi = true; SuppressAttributes = false; } /// <summary> /// Setups plain console output. /// </summary> public static void SetupPlain() { OutputStream = null; ErrorStream = null; UseAnsi = false; SuppressAttributes = false; } private static Stream? OutputStream; private static Stream? ErrorStream; private static bool UsingErrorStream; private static readonly object SyncOutput = new(); private static bool _useAnsi; /// <summary> /// Gets/sets if ANSI is to be used. /// </summary> public static bool UseAnsi { get { lock (SyncOutput) { return _useAnsi; } } set { lock (SyncOutput) { _useAnsi = value; } } } private static bool _suppressAttributes; /// <summary> /// Gets/sets if color (and other ANSI sequences) are to be supressed. /// </summary> public static bool SuppressAttributes { get { lock (SyncOutput) { return _suppressAttributes; } } set { lock (SyncOutput) { _suppressAttributes = value; } } } /// <summary> /// All write operations will use standard output stream. /// </summary> public static void UseStandardStream() { lock (SyncOutput) { UsingErrorStream = false; } } /// <summary> /// All write operations will use error output stream. /// </summary> public static void UseErrorStream() { lock (SyncOutput) { UsingErrorStream = true; } } /// <summary> /// Clears the screen. /// </summary> public static Sequence Clear() { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x32; // 2 ComposingBytes[3] = 0x4A; // J ComposingBytes[4] = 0x1B; // Esc ComposingBytes[5] = 0x5B; // [ ComposingBytes[6] = 0x48; // H stream.Write(ComposingBytes, 0, 7); } else { // Fallback Console.Clear(); } } return Sequence.Chain; } /// <summary> /// Resets color and other attributes. /// </summary> public static Sequence Reset() { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x30; // 0 ComposingBytes[3] = 0x6D; // m stream.Write(ComposingBytes, 0, 4); } else { // FallBack: reset colors and variables Console.ResetColor(); FallbackIsBold = false; FallbackIsInverted = false; } } return Sequence.Chain; } /// <summary> /// Sets foreground color to black. /// </summary> public static Sequence Black() => Foreground(ConsoleColor.Black); /// <summary> /// Sets foreground color to dark red. /// </summary> public static Sequence DarkRed() => Foreground(ConsoleColor.DarkRed); /// <summary> /// Sets foreground color to dark green. /// </summary> public static Sequence DarkGreen() => Foreground(ConsoleColor.DarkGreen); /// <summary> /// Sets foreground color to dark yellow. /// </summary> public static Sequence DarkYellow() => Foreground(ConsoleColor.DarkYellow); /// <summary> /// Sets foreground color to dark blue. /// </summary> public static Sequence DarkBlue() => Foreground(ConsoleColor.DarkBlue); /// <summary> /// Sets foreground color to dark magenta. /// </summary> public static Sequence DarkMagenta() => Foreground(ConsoleColor.DarkMagenta); /// <summary> /// Sets foreground color to cyan. /// </summary> public static Sequence DarkCyan() => Foreground(ConsoleColor.DarkCyan); /// <summary> /// Sets foreground color to gray. /// </summary> public static Sequence Gray() => Foreground(ConsoleColor.Gray); /// <summary> /// Sets foreground color to dark gray. /// </summary> public static Sequence DarkGray() => Foreground(ConsoleColor.DarkGray); /// <summary> /// Sets foreground color to red. /// </summary> public static Sequence Red() => Foreground(ConsoleColor.Red); /// <summary> /// Sets foreground color to green. /// </summary> public static Sequence Green() => Foreground(ConsoleColor.Green); /// <summary> /// Sets foreground color to yellow. /// </summary> public static Sequence Yellow() => Foreground(ConsoleColor.Yellow); /// <summary> /// Sets foreground color to blue. /// </summary> public static Sequence Blue() => Foreground(ConsoleColor.Blue); /// <summary> /// Sets foreground color to magenta. /// </summary> public static Sequence Magenta() => Foreground(ConsoleColor.Magenta); /// <summary> /// Sets foreground color to cyan. /// </summary> public static Sequence Cyan() => Foreground(ConsoleColor.Cyan); /// <summary> /// Sets foreground color to white. /// </summary> public static Sequence White() => Foreground(ConsoleColor.White); /// <summary> /// Resets foreground color. /// </summary> public static Sequence NoColor() => NoForeground(); /// <summary> /// Sets foreground color. /// </summary> /// <param name="color">Color to use.</param> public static Sequence Foreground(ConsoleColor color) { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { var (colorByte, isColorBright) = GetColorByte(color); ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = isColorBright ? (byte)0x39 : (byte)0x33; // 3 or 9 ComposingBytes[3] = colorByte; ComposingBytes[4] = 0x6D; // m stream.Write(ComposingBytes, 0, 5); } else { // Fallback: just use color directly if (UsingErrorStream) { return Sequence.Chain; } // no color for error stream Console.ForegroundColor = color; } } return Sequence.Chain; } /// <summary> /// Resets foreground color. /// </summary> public static Sequence NoForeground() { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x33; // 3 ComposingBytes[3] = 0x39; // 9 ComposingBytes[4] = 0x6D; // m stream.Write(ComposingBytes, 0, 5); } else { // Fallback: just use color directly if (UsingErrorStream) { return Sequence.Chain; } // no color for error stream var backColor = Console.BackgroundColor; Console.ResetColor(); Console.BackgroundColor = backColor; } } return Sequence.Chain; } /// <summary> /// Sets background color. /// </summary> /// <param name="color">Color to use.</param> public static Sequence Background(ConsoleColor color) { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { var (colorByte, isColorBright) = GetColorByte(color); ComposingBytes[1] = 0x5B; // [ if (!isColorBright) { ComposingBytes[2] = 0x34; // 4 ComposingBytes[3] = colorByte; ComposingBytes[4] = 0x6D; // m stream.Write(ComposingBytes, 0, 5); } else { ComposingBytes[2] = 0x31; // 1 ComposingBytes[3] = 0x30; // 0 ComposingBytes[4] = colorByte; ComposingBytes[5] = 0x6D; // m stream.Write(ComposingBytes, 0, 6); } } else { // Fallback: just use color directly if (UsingErrorStream) { return Sequence.Chain; } // no color for error stream Console.BackgroundColor = color; } } return Sequence.Chain; } /// <summary> /// Resets background color. /// </summary> public static Sequence NoBackground() { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x34; // 4 ComposingBytes[3] = 0x39; // 9 ComposingBytes[4] = 0x6D; // m stream.Write(ComposingBytes, 0, 5); } else { // Fallback: just use color directly if (UsingErrorStream) { return Sequence.Chain; } // no color for error stream var foreColor = Console.ForegroundColor; Console.ResetColor(); Console.ForegroundColor = foreColor; } } return Sequence.Chain; } /// <summary> /// Sets bold attribute. /// </summary> public static Sequence Bold() { return SetBold(newState: true); } /// <summary> /// Resets bold attribute. /// </summary> public static Sequence NoBold() { return SetBold(newState: false); } private static Sequence SetBold(bool newState) { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { if (newState) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x31; // 1 ComposingBytes[3] = 0x6D; // m stream.Write(ComposingBytes, 0, 4); } else { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x32; // 2 ComposingBytes[3] = 0x32; // 2 ComposingBytes[4] = 0x6D; // m stream.Write(ComposingBytes, 0, 5); } } else { // Fallback: let's try to use brightness if (newState) { var colorValue = (int)Console.ForegroundColor; if (colorValue <= 7) { // just do it for dark colors FallbackIsBold = true; Console.ForegroundColor = (ConsoleColor)(colorValue + 8); } } else { var colorValue = (int)Console.ForegroundColor; if (FallbackIsBold && (colorValue > 7)) { // just do it for bright colors Console.ForegroundColor = (ConsoleColor)(colorValue - 8); } FallbackIsBold = false; // cancel bold either way } } } return Sequence.Chain; } /// <summary> /// Sets underline attribute. /// No fallback for Console. /// </summary> public static Sequence Underline() { return SetUnderline(newState: true); } /// <summary> /// Resets underline. /// </summary> public static Sequence NoUnderline() { return SetUnderline(newState: false); } private static Sequence SetUnderline(bool newState) { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { if (newState) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x34; // 4 ComposingBytes[3] = 0x6D; // m stream.Write(ComposingBytes, 0, 4); } else { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x32; // 2 ComposingBytes[3] = 0x34; // 4 ComposingBytes[4] = 0x6D; // m stream.Write(ComposingBytes, 0, 5); } } else { // Fallback: none } } return Sequence.Chain; } /// <summary> /// Sets color invert attribute. /// </summary> public static Sequence Invert() { return SetInvert(newState: true); } /// <summary> /// Resets color invert attribute. /// </summary> public static Sequence NoInvert() { return SetInvert(newState: false); } private static Sequence SetInvert(bool newState) { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { if (newState) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x37; // 7 ComposingBytes[3] = 0x6D; // m stream.Write(ComposingBytes, 0, 4); } else { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x32; // 2 ComposingBytes[3] = 0x37; // 7 ComposingBytes[4] = 0x6D; // m stream.Write(ComposingBytes, 0, 5); } } else { // Fallback if (newState) { if (!FallbackIsInverted) { (Console.BackgroundColor, Console.ForegroundColor) = (Console.ForegroundColor, Console.BackgroundColor); FallbackIsInverted = true; } } else { if (FallbackIsInverted) { (Console.BackgroundColor, Console.ForegroundColor) = (Console.ForegroundColor, Console.BackgroundColor); FallbackIsInverted = false; } } } } return Sequence.Chain; } /// <summary> /// Moves cursor left. /// </summary> public static Sequence MoveLeft() { return MoveLeft(amount: 1); } /// <summary> /// Moves cursor left. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Amount must be a positive number less than 65536.</exception> public static Sequence MoveLeft(int amount) { if (amount is < 1 or > 65535) { throw new ArgumentNullException(nameof(amount), "Amount must be a positive number less than 65536."); } return MoveHorizontally(-amount); } /// <summary> /// Moves cursor right. /// </summary> public static Sequence MoveRight() { return MoveRight(amount: 1); } /// <summary> /// Moves cursor right. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Amount must be a positive number less than 65536.</exception> public static Sequence MoveRight(int amount) { if (amount is < 1 or > 65535) { throw new ArgumentNullException(nameof(amount), "Amount must be a positive number less than 65536."); } return MoveHorizontally(amount); } private static Sequence MoveHorizontally(int amount) { if (amount == 0) { return Sequence.Chain; } lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ int nextIndex; if (amount > 0) { // move forward nextIndex = InsertNumber((ushort)amount, ComposingBytes, 2); ComposingBytes[nextIndex] = 0x43; // C } else { // move backward nextIndex = InsertNumber((ushort)(-amount), ComposingBytes, 2); ComposingBytes[nextIndex] = 0x44; // D } stream.Write(ComposingBytes, 0, nextIndex + 1); } else { // FallBack: use CursorLeft if (amount > 0) { // move forward if (Console.CursorLeft + amount >= Console.BufferWidth) { Console.CursorLeft = Console.BufferWidth - 1; } else { Console.CursorLeft += amount; } } else { // move backward if (Console.CursorLeft + amount < 0) { Console.CursorLeft = 0; } else { Console.CursorLeft += amount; } } } } return Sequence.Chain; } /// <summary> /// Moves cursor up. /// </summary> public static Sequence MoveUp() { return MoveUp(amount: 1); } /// <summary> /// Moves cursor up. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Amount must be a positive number less than 65536.</exception> public static Sequence MoveUp(int amount) { if (amount is < 1 or > 65535) { throw new ArgumentNullException(nameof(amount), "Amount must be a positive number less than 65536."); } return MoveVertically(-amount); } /// <summary> /// Moves cursor down. /// </summary> public static Sequence MoveDown() { return MoveVertically(amount: 1); } /// <summary> /// Moves cursor down. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Amount must be a positive number less than 65536.</exception> public static Sequence MoveDown(int amount) { if (amount is < 1 or > 65535) { throw new ArgumentNullException(nameof(amount), "Amount must be a positive number less than 65536."); } return MoveVertically(amount); } private static Sequence MoveVertically(int amount) { if (amount == 0) { return Sequence.Chain; } lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ int nextIndex; if (amount > 0) { // move forward nextIndex = InsertNumber((ushort)amount, ComposingBytes, 2); ComposingBytes[nextIndex] = 0x42; // B } else { // move backward nextIndex = InsertNumber((ushort)(-amount), ComposingBytes, 2); ComposingBytes[nextIndex] = 0x41; // A } stream.Write(ComposingBytes, 0, nextIndex + 1); } else { // FallBack: use CursorTop if (amount > 0) { // move forward if (Console.CursorTop + amount >= Console.BufferHeight) { Console.CursorTop = Console.BufferHeight - 1; } else { Console.CursorTop += amount; } } else { // move backward if (Console.CursorTop + amount < 0) { Console.CursorTop = 0; } else { Console.CursorTop += amount; } } } } return Sequence.Chain; } /// <summary> /// Moves to specified coordinates. /// </summary> /// <param name="x">X coordinate; 0 ignores the parameter.</param> /// <param name="y">Y coordinate; 0 ignores the parameter.</param> /// <exception cref="ArgumentOutOfRangeException">X must be either 0 or between 1 and 65535. -or- Y must be either 0 or between 1 and 65535.</exception> public static Sequence MoveTo(int x, int y) { if (x is < 0 or > 65535) { throw new ArgumentOutOfRangeException(nameof(x), "X must be either 0 or between 1 and 65535."); } if (y is < 0 or > 65535) { throw new ArgumentOutOfRangeException(nameof(y), "Y must be either 0 or between 1 and 65535."); } var moveHor = (x > 0); var moveVer = (y > 0); if (!moveHor && !moveVer) { return Sequence.Chain; } lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ if (moveHor && moveVer) { // move both horizontally and vertically var nextIndex = InsertNumber((ushort)y, ComposingBytes, 2); ComposingBytes[nextIndex++] = 0x3B; // ; nextIndex = InsertNumber((ushort)x, ComposingBytes, nextIndex); ComposingBytes[nextIndex] = 0x48; // H stream.Write(ComposingBytes, 0, nextIndex + 1); } else if (moveHor) { // move just horizontally var nextIndex = InsertNumber((ushort)x, ComposingBytes, 2); ComposingBytes[nextIndex] = 0x47; // G stream.Write(ComposingBytes, 0, nextIndex + 1); } else if (moveVer) { // move just vertically var nextIndex = InsertNumber((ushort)y, ComposingBytes, 2); ComposingBytes[nextIndex] = 0x64; // d stream.Write(ComposingBytes, 0, nextIndex + 1); } } else { // FallBack: use CursorLeft and CursorTop if (moveHor) { if (x > Console.BufferWidth) { Console.CursorLeft = Console.BufferWidth - 1; } else { Console.CursorLeft = x - 1; } } if (moveVer) { if (y > Console.BufferHeight) { Console.CursorTop = Console.BufferHeight - 1; } else { Console.CursorTop = y - 1; } } } } return Sequence.Chain; } /// <summary> /// Stores cursor location. /// </summary> public static Sequence StoreCursor() { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x73; // s stream.Write(ComposingBytes, 0, 3); } else { // FallBack: save coordinates FallbackLeft = Console.CursorLeft; FallbackTop = Console.CursorTop; } } return Sequence.Chain; } /// <summary> /// Restores cursor location. /// </summary> public static Sequence RestoreCursor() { lock (SyncOutput) { if (SuppressAttributes) { return Sequence.Chain; } var stream = GetAppropriateStream(); if (stream is not null) { ComposingBytes[1] = 0x5B; // [ ComposingBytes[2] = 0x75; // u stream.Write(ComposingBytes, 0, 3); } else { // FallBack: use saved coordinates Console.CursorLeft = FallbackLeft; Console.CursorTop = FallbackTop; } } return Sequence.Chain; } /// <summary> /// Writes text. /// </summary> /// <param name="text">Text to write.</param> public static Sequence Write(string text) { if (string.IsNullOrEmpty(text)) { return Sequence.Chain; } // just ignore lock (SyncOutput) { var stream = GetAppropriateStream(); if (stream is not null) { var bytes = Utf8.GetBytes(text); stream.Write(bytes, 0, bytes.Length); } else { // Fallback: just write Console.Write(text); } } return Sequence.Chain; } /// <summary> /// Writes text. /// Color is reset to default after write is complete. /// </summary> /// <param name="text">Text to write.</param> /// <param name="foregroundColor">Foreground color.</param> public static Sequence Write(string text, ConsoleColor foregroundColor) { lock (SyncOutput) { Foreground(foregroundColor); Write(text); NoForeground(); } return Sequence.Chain; } /// <summary> /// Writes text. /// Color is reset to default after write is complete. /// </summary> /// <param name="text">Text to write.</param> /// <param name="foregroundColor">Foreground color.</param> /// <param name="backgroundColor">Background color.</param> public static Sequence Write(string text, ConsoleColor foregroundColor, ConsoleColor backgroundColor) { lock (SyncOutput) { Foreground(foregroundColor); Background(backgroundColor); Write(text); NoBackground(); NoForeground(); } return Sequence.Chain; } /// <summary> /// Writes a new line. /// </summary> public static Sequence WriteLine() { Write(Environment.NewLine); return Sequence.Chain; } /// <summary> /// Writes text and ends it with a new line. /// </summary> /// <param name="text">Text to write.</param> public static Sequence WriteLine(string text) { Write(text); Write(Environment.NewLine); return Sequence.Chain; } /// <summary> /// Writes text and ends it with a new line. /// Color is reset to default after write is complete. /// </summary> /// <param name="text">Text to write.</param> /// <param name="foregroundColor">Foreground color.</param> public static Sequence WriteLine(string text, ConsoleColor foregroundColor) { lock (SyncOutput) { Foreground(foregroundColor); WriteLine(text); NoForeground(); } return Sequence.Chain; } /// <summary> /// Writes text and ends it with a new line. /// Color is reset to default after write is complete. /// </summary> /// <param name="text">Text to write.</param> /// <param name="foregroundColor">Foreground color.</param> /// <param name="backgroundColor">Background color.</param> public static Sequence WriteLine(string text, ConsoleColor foregroundColor, ConsoleColor backgroundColor) { lock (SyncOutput) { Foreground(foregroundColor); Background(backgroundColor); WriteLine(text); NoBackground(); NoForeground(); } return Sequence.Chain; } private static readonly object SyncInput = new(); /// <summary> /// Returns the next character available. /// Character is always read from Console. /// </summary> public static char? ReadCharIfAvailable() { lock (SyncInput) { return Console.KeyAvailable ? Console.ReadKey(intercept: true).KeyChar : null; } } /// <summary> /// Returns the next character available. /// Character is always read from Console. /// </summary> public static char ReadChar() { lock (SyncInput) { return Console.ReadKey(intercept: true).KeyChar; } } /// <summary> /// Returns all currently available keys. /// Character is always read from Console. /// </summary> public static IEnumerable<char> ReadAvailableChars() { lock (SyncInput) { while (Console.KeyAvailable) { yield return Console.ReadKey(intercept: true).KeyChar; } } } /// <summary> /// Returns the next key available. /// Character is always read from Console. /// </summary> public static ConsoleKey ReadKey() { lock (SyncInput) { return Console.ReadKey(intercept: true).Key; } } /// <summary> /// Returns the next key available. /// Character is always read from Console. /// </summary> public static ConsoleKey? ReadKeyIfAvailable() { lock (SyncInput) { return Console.KeyAvailable ? Console.ReadKey(intercept: true).Key : null; } } /// <summary> /// Returns all currently available keys. /// Character is always read from Console. /// </summary> public static IEnumerable<ConsoleKey> ReadAvailableKeys() { lock (SyncInput) { while (Console.KeyAvailable) { yield return Console.ReadKey(intercept: true).Key; } } } /// <summary> /// Gets/sets if Ctrl+C will be treated as a normal input. /// </summary> public static bool TreatControlCAsInput { get { return Console.TreatControlCAsInput; } set { Console.TreatControlCAsInput = value; } } #region Sequences /// <summary> /// Helper class used to chain calls. /// </summary> public sealed class Sequence { private Sequence() { } internal static Sequence Chain { get; } = new Sequence(); #pragma warning disable CA1822 // Mark members as static - used for chaining so intentional /// <summary> /// Clears the screen. /// </summary> public Sequence Clear() => Terminal.Clear(); /// <summary> /// Resets color and other attributes. /// </summary> public Sequence Reset() => Terminal.Reset(); /// <summary> /// Sets foreground color to black. /// </summary> public Sequence Black() => Terminal.Black(); /// <summary> /// Sets foreground color to dark red. /// </summary> public Sequence DarkRed() => Terminal.DarkRed(); /// <summary> /// Sets foreground color to dark green. /// </summary> public Sequence DarkGreen() => Terminal.DarkGreen(); /// <summary> /// Sets foreground color to dark yellow. /// </summary> public Sequence DarkYellow() => Terminal.DarkYellow(); /// <summary> /// Sets foreground color to dark blue. /// </summary> public Sequence DarkBlue() => Terminal.DarkBlue(); /// <summary> /// Sets foreground color to dark magenta. /// </summary> public Sequence DarkMagenta() => Terminal.DarkMagenta(); /// <summary> /// Sets foreground color to cyan. /// </summary> public Sequence DarkCyan() => Terminal.DarkCyan(); /// <summary> /// Sets foreground color to gray. /// </summary> public Sequence Gray() => Terminal.Gray(); /// <summary> /// Sets foreground color to dark gray. /// </summary> public Sequence DarkGray() => Terminal.DarkGray(); /// <summary> /// Sets foreground color to red. /// </summary> public Sequence Red() => Terminal.Red(); /// <summary> /// Sets foreground color to green. /// </summary> public Sequence Green() => Terminal.Green(); /// <summary> /// Sets foreground color to yellow. /// </summary> public Sequence Yellow() => Terminal.Yellow(); /// <summary> /// Sets foreground color to blue. /// </summary> public Sequence Blue() => Terminal.Blue(); /// <summary> /// Sets foreground color to magenta. /// </summary> public Sequence Magenta() => Terminal.Magenta(); /// <summary> /// Sets foreground color to cyan. /// </summary> public Sequence Cyan() => Terminal.Cyan(); /// <summary> /// Sets foreground color to white. /// </summary> public Sequence White() => Terminal.White(); /// <summary> /// Resets foreground color. /// </summary> public Sequence NoColor() => Terminal.NoColor(); /// <summary> /// Sets foreground color. /// </summary> /// <param name="color">Color to use.</param> public Sequence Foreground(ConsoleColor color) => Terminal.Foreground(color); /// <summary> /// Resets foreground color. /// </summary> public Sequence NoForeground() => Terminal.NoForeground(); /// <summary> /// Sets background color. /// </summary> /// <param name="color">Color to use.</param> public Sequence Background(ConsoleColor color) => Terminal.Background(color); /// <summary> /// Resets background color. /// </summary> public Sequence NoBackground() => Terminal.NoBackground(); /// <summary> /// Sets bold attribute. /// </summary> public Sequence Bold() => Terminal.Bold(); /// <summary> /// Resets bold attribute. /// </summary> public Sequence NoBold() => Terminal.NoBold(); /// <summary> /// Sets underline attribute. /// No fallback for Console. /// </summary> public Sequence Underline() => Terminal.Underline(); /// <summary> /// Resets underline. /// </summary> public Sequence NoUnderline() => Terminal.NoUnderline(); /// <summary> /// Sets color invert attribute. /// </summary> public Sequence Invert() => Terminal.Invert(); /// <summary> /// Resets color invert attribute. /// </summary> public Sequence NoInvert() => Terminal.NoInvert(); /// <summary> /// Moves cursor left. /// </summary> public Sequence MoveLeft() => Terminal.MoveLeft(); /// <summary> /// Moves cursor left. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Amount must be a positive number less than 65536.</exception> public Sequence MoveLeft(int amount) => Terminal.MoveLeft(amount); /// <summary> /// Moves cursor right. /// </summary> public Sequence MoveRight() => Terminal.MoveRight(); /// <summary> /// Moves cursor right. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Amount must be a positive number less than 65536.</exception> public Sequence MoveRight(int amount) => Terminal.MoveRight(amount); /// <summary> /// Moves cursor up. /// </summary> public Sequence MoveUp() => Terminal.MoveUp(); /// <summary> /// Moves cursor up. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Amount must be a positive number less than 65536.</exception> public Sequence MoveUp(int amount) => Terminal.MoveUp(amount); /// <summary> /// Moves cursor down. /// </summary> public Sequence MoveDown() => Terminal.MoveDown(); /// <summary> /// Moves cursor down. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Amount must be a positive number less than 65536.</exception> public Sequence MoveDown(int amount) => Terminal.MoveDown(amount); /// <summary> /// Moves to specified coordinates. /// </summary> /// <param name="x">X coordinate; 0 ignores the parameter.</param> /// <param name="y">Y coordinate; 0 ignores the parameter.</param> /// <exception cref="ArgumentOutOfRangeException">X must be either 0 or between 1 and 65535. -or- Y must be either 0 or between 1 and 65535.</exception> public Sequence MoveTo(int x, int y) => Terminal.MoveTo(x, y); /// <summary> /// Stores cursor location. /// </summary> public Sequence StoreCursor() => Terminal.StoreCursor(); /// <summary> /// Restores cursor location. /// </summary> public Sequence RestoreCursor() => Terminal.RestoreCursor(); /// <summary> /// Writes text. /// </summary> /// <param name="text">Text to write.</param> public Sequence Write(string text) => Terminal.Write(text); /// <summary> /// Writes text. /// Color is reset to default after write is complete. /// </summary> /// <param name="text">Text to write.</param> /// <param name="foregroundColor">Foreground color.</param> public Sequence Write(string text, ConsoleColor foregroundColor) => Terminal.Write(text, foregroundColor); /// <summary> /// Writes text. /// Color is reset to default after write is complete. /// </summary> /// <param name="text">Text to write.</param> /// <param name="foregroundColor">Foreground color.</param> /// <param name="backgroundColor">Background color.</param> public Sequence Write(string text, ConsoleColor foregroundColor, ConsoleColor backgroundColor) => Terminal.Write(text, foregroundColor, backgroundColor); /// <summary> /// Writes a new line. /// </summary> public Sequence WriteLine() => Terminal.WriteLine(); /// <summary> /// Writes text and ends it with a new line. /// </summary> /// <param name="text">Text to write.</param> public Sequence WriteLine(string text) => Terminal.WriteLine(text); /// <summary> /// Writes text and ends it with a new line. /// Color is reset to default after write is complete. /// </summary> /// <param name="text">Text to write.</param> /// <param name="foregroundColor">Foreground color.</param> public Sequence WriteLine(string text, ConsoleColor foregroundColor) => Terminal.WriteLine(text, foregroundColor); /// <summary> /// Writes text and ends it with a new line. /// Color is reset to default after write is complete. /// </summary> /// <param name="text">Text to write.</param> /// <param name="foregroundColor">Foreground color.</param> /// <param name="backgroundColor">Background color.</param> public Sequence WriteLine(string text, ConsoleColor foregroundColor, ConsoleColor backgroundColor) => Terminal.WriteLine(text, foregroundColor, backgroundColor); #pragma warning restore CA1822 // Mark members as static } #endregion Sequences #region Privates private static readonly byte[] ComposingBytes = new byte[] { 0x1B, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // used to compose escape sequences, escape char already in private static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private static bool FallbackIsBold; // remember bold status for console fallback private static bool FallbackIsInverted; // remember inversion status for console fallback private static int FallbackLeft; private static int FallbackTop; private static (byte colorIndex, bool isColorBright) GetColorByte(ConsoleColor color) { return color switch { // convert to ansi byte ConsoleColor.Black => (0x30, false), ConsoleColor.DarkRed => (0x31, false), ConsoleColor.DarkGreen => (0x32, false), ConsoleColor.DarkYellow => (0x33, false), ConsoleColor.DarkBlue => (0x34, false), ConsoleColor.DarkMagenta => (0x35, false), ConsoleColor.DarkCyan => (0x36, false), ConsoleColor.Gray => (0x37, false), ConsoleColor.DarkGray => (0x30, true), ConsoleColor.Red => (0x31, true), ConsoleColor.Green => (0x32, true), ConsoleColor.Yellow => (0x33, true), ConsoleColor.Blue => (0x34, true), ConsoleColor.Magenta => (0x35, true), ConsoleColor.Cyan => (0x36, true), ConsoleColor.White => (0x37, true), _ => (0x37, false),// should never actually happen unless console colors are expanded }; } private static int InsertNumber(ushort number, byte[] bytes, int offset) { var numberBytes = new byte[5]; var numberOffset = 0; while (number > 0) { numberBytes[numberOffset] = (byte)(number % 10); // take last digit numberOffset += 1; number /= 10; } for (var i = 0; i < numberOffset; i++) { bytes[offset + i] = (byte)(0x30 + numberBytes[numberOffset - i - 1]); } return offset + numberOffset; } private static Stream? GetAppropriateStream() { if (UseAnsi) { if (OutputStream is null) { OutputStream = Console.OpenStandardOutput(); } if (ErrorStream is null) { ErrorStream = Console.OpenStandardError(); } return UsingErrorStream ? ErrorStream : OutputStream; } else { return null; } } #endregion Privates }
using System; using System.Collections.Generic; using Irony.Ast; namespace Irony.Parsing { [Flags] public enum StringOptions : short { None = 0, IsChar = 0x01, AllowsDoubledQuote = 0x02, //Convert doubled start/end symbol to a single symbol; for ex. in SQL, '' -> ' AllowsLineBreak = 0x04, IsTemplate = 0x08, //Can include embedded expressions that should be evaluated on the fly; ex in Ruby: "hello #{name}" NoEscapes = 0x10, AllowsUEscapes = 0x20, AllowsXEscapes = 0x40, AllowsOctalEscapes = 0x80, AllowsAllEscapes = AllowsUEscapes | AllowsXEscapes | AllowsOctalEscapes } //Container for settings of tempate string parser, to interpet strings having embedded values or expressions // like in Ruby: // "Hello, #{name}" // Default values match settings for Ruby strings public class StringTemplateSettings { public string EndTag = "}"; public NonTerminal ExpressionRoot; public string StartTag = "#{"; } public class StringLiteral : CompoundTerminalBase { public enum StringFlagsInternal : short { HasEscapes = 0x100 } #region StringSubType private class StringSubType { internal readonly StringOptions Flags; internal readonly byte Index; internal readonly string Start, End; internal StringSubType(string start, string end, StringOptions flags, byte index) { Start = start; End = end; Flags = flags; Index = index; } internal static int LongerStartFirst(StringSubType x, StringSubType y) { try { //in case any of them is null if (x.Start.Length > y.Start.Length) return -1; } catch { } return 0; } } private class StringSubTypeList : List<StringSubType> { internal void Add(string start, string end, StringOptions flags) { base.Add(new StringSubType(start, end, flags, (byte) Count)); } } #endregion #region constructors and initialization public StringLiteral(string name) : base(name) { SetFlag(TermFlags.IsLiteral); } public StringLiteral(string name, string startEndSymbol, StringOptions options) : this(name) { _subtypes.Add(startEndSymbol, startEndSymbol, options); } public StringLiteral(string name, string startEndSymbol) : this(name, startEndSymbol, StringOptions.None) { } public StringLiteral(string name, string startEndSymbol, StringOptions options, Type astNodeType) : this(name, startEndSymbol, options) { AstConfig.NodeType = astNodeType; } public StringLiteral(string name, string startEndSymbol, StringOptions options, AstNodeCreator astNodeCreator) : this(name, startEndSymbol, options) { AstConfig.NodeCreator = astNodeCreator; } public void AddStartEnd(string startEndSymbol, StringOptions stringOptions) { AddStartEnd(startEndSymbol, startEndSymbol, stringOptions); } public void AddStartEnd(string startSymbol, string endSymbol, StringOptions stringOptions) { _subtypes.Add(startSymbol, endSymbol, stringOptions); } public void AddPrefix(string prefix, StringOptions flags) { AddPrefixFlag(prefix, (short) flags); } #endregion #region Properties/Fields private readonly StringSubTypeList _subtypes = new StringSubTypeList(); private string _startSymbolsFirsts; //first chars of start-end symbols #endregion #region overrides: Init, GetFirsts, ReadBody, etc... public override void Init(GrammarData grammarData) { base.Init(grammarData); _startSymbolsFirsts = string.Empty; if (_subtypes.Count == 0) { grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrInvStrDef, Name); //"Error in string literal [{0}]: No start/end symbols specified." return; } //collect all start-end symbols in lists and create strings of first chars var allStartSymbols = new StringSet(); //to detect duplicate start symbols _subtypes.Sort(StringSubType.LongerStartFirst); var isTemplate = false; foreach (var subType in _subtypes) { if (allStartSymbols.Contains(subType.Start)) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrDupStartSymbolStr, subType.Start, Name); //"Duplicate start symbol {0} in string literal [{1}]." allStartSymbols.Add(subType.Start); _startSymbolsFirsts += subType.Start[0].ToString(); if ((subType.Flags & StringOptions.IsTemplate) != 0) isTemplate = true; } if (!CaseSensitivePrefixesSuffixes) _startSymbolsFirsts = _startSymbolsFirsts.ToLower() + _startSymbolsFirsts.ToUpper(); //Set multiline flag foreach (var info in _subtypes) { if ((info.Flags & StringOptions.AllowsLineBreak) != 0) { SetFlag(TermFlags.IsMultiline); break; } } //For templates only if (isTemplate) { //Check that template settings object is provided var templateSettings = AstConfig.Data as StringTemplateSettings; if (templateSettings == null) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplNoSettings, Name); //"Error in string literal [{0}]: IsTemplate flag is set, but TemplateSettings is not provided." else if (templateSettings.ExpressionRoot == null) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplMissingExprRoot, Name); //"" else if (!Grammar.SnippetRoots.Contains(templateSettings.ExpressionRoot)) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplExprNotRoot, Name); //"" } //if //Create editor info if (EditorInfo == null) EditorInfo = new TokenEditorInfo(TokenType.String, TokenColor.String, TokenTriggers.None); } //method public override IList<string> GetFirsts() { var result = new StringList(); result.AddRange(Prefixes); //we assume that prefix is always optional, so string can start with start-end symbol foreach (var ch in _startSymbolsFirsts) result.Add(ch.ToString()); return result; } protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) { if (!details.PartialContinues) { if (!ReadStartSymbol(source, details)) return false; } return CompleteReadBody(source, details); } private bool CompleteReadBody(ISourceStream source, CompoundTokenDetails details) { var escapeEnabled = !details.IsSet((short) StringOptions.NoEscapes); var start = source.PreviewPosition; var endQuoteSymbol = details.EndSymbol; var endQuoteDoubled = endQuoteSymbol + endQuoteSymbol; //doubled quote symbol var lineBreakAllowed = details.IsSet((short) StringOptions.AllowsLineBreak); //1. Find the string end // first get the position of the next line break; we are interested in it to detect malformed string, // therefore do it only if linebreak is NOT allowed; if linebreak is allowed, set it to -1 (we don't care). var nlPos = lineBreakAllowed ? -1 : source.Text.IndexOf('\n', source.PreviewPosition); //fix by ashmind for EOF right after opening symbol while (true) { var endPos = source.Text.IndexOf(endQuoteSymbol, source.PreviewPosition); //Check for partial token in line-scanning mode if (endPos < 0 && details.PartialOk && lineBreakAllowed) { ProcessPartialBody(source, details); return true; } //Check for malformed string: either EndSymbol not found, or LineBreak is found before EndSymbol var malformed = endPos < 0 || nlPos >= 0 && nlPos < endPos; if (malformed) { //Set source position for recovery: move to the next line if linebreak is not allowed. if (nlPos > 0) endPos = nlPos; if (endPos > 0) source.PreviewPosition = endPos + 1; details.Error = Resources.ErrBadStrLiteral; // "Mal-formed string literal - cannot find termination symbol."; return true; //we did find start symbol, so it is definitely string, only malformed } //if malformed if (source.EOF()) return true; //We found EndSymbol - check if it is escaped; if yes, skip it and continue search if (escapeEnabled && IsEndQuoteEscaped(source.Text, endPos)) { source.PreviewPosition = endPos + endQuoteSymbol.Length; continue; //searching for end symbol } //Check if it is doubled end symbol source.PreviewPosition = endPos; if (details.IsSet((short) StringOptions.AllowsDoubledQuote) && source.MatchSymbol(endQuoteDoubled)) { source.PreviewPosition = endPos + endQuoteDoubled.Length; continue; } //checking for doubled end symbol //Ok, this is normal endSymbol that terminates the string. // Advance source position and get out from the loop details.Body = source.Text.Substring(start, endPos - start); source.PreviewPosition = endPos + endQuoteSymbol.Length; return true; //if we come here it means we're done - we found string end. } //end of loop to find string end; } private void ProcessPartialBody(ISourceStream source, CompoundTokenDetails details) { var from = source.PreviewPosition; source.PreviewPosition = source.Text.Length; details.Body = source.Text.Substring(from, source.PreviewPosition - from); details.IsPartial = true; } protected override void InitDetails(ParsingContext context, CompoundTokenDetails details) { base.InitDetails(context, details); if (context.VsLineScanState.Value != 0) { //we are continuing partial string on the next line details.Flags = context.VsLineScanState.TerminalFlags; details.SubTypeIndex = context.VsLineScanState.TokenSubType; var stringInfo = _subtypes[context.VsLineScanState.TokenSubType]; details.StartSymbol = stringInfo.Start; details.EndSymbol = stringInfo.End; } } protected override void ReadSuffix(ISourceStream source, CompoundTokenDetails details) { base.ReadSuffix(source, details); //"char" type can be identified by suffix (like VB where c suffix identifies char) // in this case we have details.TypeCodes[0] == char and we need to set the IsChar flag if (details.TypeCodes != null && details.TypeCodes[0] == TypeCode.Char) details.Flags |= (int) StringOptions.IsChar; else //we may have IsChar flag set (from startEndSymbol, like in c# single quote identifies char) // in this case set type code if (details.IsSet((short) StringOptions.IsChar)) details.TypeCodes = new[] {TypeCode.Char}; } private bool IsEndQuoteEscaped(string text, int quotePosition) { var escaped = false; var p = quotePosition - 1; while (p > 0 && text[p] == EscapeChar) { escaped = !escaped; p--; } return escaped; } private bool ReadStartSymbol(ISourceStream source, CompoundTokenDetails details) { if (_startSymbolsFirsts.IndexOf(source.PreviewChar) < 0) return false; foreach (var subType in _subtypes) { if (!source.MatchSymbol(subType.Start)) continue; //We found start symbol details.StartSymbol = subType.Start; details.EndSymbol = subType.End; details.Flags |= (short) subType.Flags; details.SubTypeIndex = subType.Index; source.PreviewPosition += subType.Start.Length; return true; } //foreach return false; } //method //Extract the string content from lexeme, adjusts the escaped and double-end symbols protected override bool ConvertValue(CompoundTokenDetails details) { var value = details.Body; var escapeEnabled = !details.IsSet((short) StringOptions.NoEscapes); //Fix all escapes if (escapeEnabled && value.IndexOf(EscapeChar) >= 0) { details.Flags |= (int) StringFlagsInternal.HasEscapes; var arr = value.Split(EscapeChar); var ignoreNext = false; //we skip the 0 element as it is not preceeded by "\" for (var i = 1; i < arr.Length; i++) { if (ignoreNext) { ignoreNext = false; continue; } var s = arr[i]; if (string.IsNullOrEmpty(s)) { //it is "\\" - escaped escape symbol. arr[i] = @"\"; ignoreNext = true; continue; } //The char is being escaped is the first one; replace it with char in Escapes table var first = s[0]; char newFirst; if (Escapes.TryGetValue(first, out newFirst)) arr[i] = newFirst + s.Substring(1); else { arr[i] = HandleSpecialEscape(arr[i], details); } //else } //for i value = string.Join(string.Empty, arr); } // if EscapeEnabled //Check for doubled end symbol var endSymbol = details.EndSymbol; if (details.IsSet((short) StringOptions.AllowsDoubledQuote) && value.IndexOf(endSymbol) >= 0) value = value.Replace(endSymbol + endSymbol, endSymbol); if (details.IsSet((short) StringOptions.IsChar)) { if (value.Length != 1) { details.Error = Resources.ErrBadChar; //"Invalid length of char literal - should be a single character."; return false; } details.Value = value[0]; } else { details.TypeCodes = new[] {TypeCode.String}; details.Value = value; } return true; } //Should support: \Udddddddd, \udddd, \xdddd, \N{name}, \0, \ddd (octal), protected virtual string HandleSpecialEscape(string segment, CompoundTokenDetails details) { if (string.IsNullOrEmpty(segment)) return string.Empty; int len, p; string digits; char ch; string result; var first = segment[0]; switch (first) { case 'u': case 'U': if (details.IsSet((short) StringOptions.AllowsUEscapes)) { len = (first == 'u' ? 4 : 8); if (segment.Length < len + 1) { details.Error = string.Format(Resources.ErrBadUnEscape, segment.Substring(len + 1), len); // "Invalid unicode escape ({0}), expected {1} hex digits." return segment; } digits = segment.Substring(1, len); ch = (char) Convert.ToUInt32(digits, 16); result = ch + segment.Substring(len + 1); return result; } //if break; case 'x': if (details.IsSet((short) StringOptions.AllowsXEscapes)) { //x-escape allows variable number of digits, from one to 4; let's count them p = 1; //current position while (p < 5 && p < segment.Length) { if (Strings.HexDigits.IndexOf(segment[p]) < 0) break; p++; } //p now point to char right after the last digit if (p <= 1) { details.Error = Resources.ErrBadXEscape; // @"Invalid \x escape, at least one digit expected."; return segment; } digits = segment.Substring(1, p - 1); ch = (char) Convert.ToUInt32(digits, 16); result = ch + segment.Substring(p); return result; } //if break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (details.IsSet((short) StringOptions.AllowsOctalEscapes)) { //octal escape allows variable number of digits, from one to 3; let's count them p = 0; //current position while (p < 3 && p < segment.Length) { if (Strings.OctalDigits.IndexOf(segment[p]) < 0) break; p++; } //p now point to char right after the last digit digits = segment.Substring(0, p); ch = (char) Convert.ToUInt32(digits, 8); result = ch + segment.Substring(p); return result; } //if break; } //switch details.Error = string.Format(Resources.ErrInvEscape, segment); //"Invalid escape sequence: \{0}" return segment; } //method #endregion } //class } //namespace
using System; using System.IO; using System.Web.Http; using System.Threading.Tasks; using System.IO.Compression; using System.Drawing; using System.Drawing.Imaging; namespace Aspose.Tasks.Live.Demos.UI.Models { ///<Summary> /// CADBase class to have base methods ///</Summary> public abstract class TasksBase : ApiController { ///<Summary> /// ActionDelegate ///</Summary> protected delegate void ActionDelegate(string inFilePath, string outPath, string zipOutFolder); ///<Summary> /// inFileActionDelegate ///</Summary> protected delegate void inFileActionDelegate(string inFilePath); ///<Summary> /// Get File extension ///</Summary> protected string GetoutFileExtension(string fileName, string folderName) { string sourceFolder = Config.Configuration.WorkingDirectory + folderName; fileName = sourceFolder + "\\" + fileName; return Path.GetExtension(fileName); } protected Response Process(string modelName, string fileName, string folderName, string outFileExtension, bool createZip, bool checkNumberofPages, string methodName, ActionDelegate action, bool deleteSourceFolder = true, string zipFileName = null) { string guid = Guid.NewGuid().ToString(); string outFolder = ""; string sourceFolder = Config.Configuration.WorkingDirectory + folderName; fileName = sourceFolder + "\\" + fileName; string fileExtension = Path.GetExtension(fileName).ToLower(); string outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension; string outPath = ""; string zipOutFolder = Config.Configuration.OutputDirectory + guid; string zipOutfileName, zipOutPath; if (string.IsNullOrEmpty(zipFileName)) { zipOutfileName = guid + ".zip"; zipOutPath = Config.Configuration.OutputDirectory + zipOutfileName; } else { var guid2 = Guid.NewGuid().ToString(); outFolder = guid2; zipOutfileName = zipFileName + ".zip"; zipOutPath = Config.Configuration.OutputDirectory + guid2; Directory.CreateDirectory(zipOutPath); zipOutPath += "/" + zipOutfileName; } if (createZip) { outfileName = Path.GetFileNameWithoutExtension(fileName) + outFileExtension; outPath = zipOutFolder + "/" + outfileName; Directory.CreateDirectory(zipOutFolder); } else { outFolder = guid; outPath = Config.Configuration.OutputDirectory + outFolder; Directory.CreateDirectory(outPath); outPath += "/" + outfileName; } string statusValue = "OK"; int statusCodeValue = 200; try { action(fileName, outPath, zipOutFolder); if (createZip) { ZipFile.CreateFromDirectory(zipOutFolder, zipOutPath); Directory.Delete(zipOutFolder, true); outfileName = zipOutfileName; } if (deleteSourceFolder) { System.GC.Collect(); System.GC.WaitForPendingFinalizers(); Directory.Delete(sourceFolder, true); } } catch (Exception ex) { statusCodeValue = 500; statusValue = "500 " + ex.Message; } return new Response { FileName = outfileName, FolderName = outFolder, Status = statusValue, StatusCode = statusCodeValue, }; } ///<Summary> /// Aspose Cells Options Class ///</Summary> protected class Options { ///<Summary> /// AppName ///</Summary> public string AppName; ///<Summary> /// FolderName ///</Summary> public string FolderName; ///<Summary> /// FileName ///</Summary> public string FileName; private string _outputType; /// <summary> /// By default, it is the extension of FileName /// </summary> public string OutputType { get => _outputType; set { if (!value.StartsWith(".")) value = "." + value; _outputType = value; } } /// <summary> /// Check if OuputType is a picture extension /// </summary> public bool IsPicture { get { switch (_outputType.ToLower()) { case ".bmp": case ".png": case ".jpg": case ".jpeg": return true; default: return false; } } } ///<Summary> /// ResultFileName ///</Summary> public string ResultFileName; ///<Summary> /// MethodName ///</Summary> public string MethodName; ///<Summary> /// ModelName ///</Summary> public string ModelName; ///<Summary> /// CreateZip ///</Summary> public bool CreateZip; ///<Summary> /// CheckNumberOfPages ///</Summary> public bool CheckNumberOfPages = false; ///<Summary> /// DeleteSourceFolder ///</Summary> public bool DeleteSourceFolder = false; ///<Summary> /// CalculateZipFileName ///</Summary> public bool CalculateZipFileName = true; /// <summary> /// Output zip filename (without '.zip'), if CreateZip property is true /// By default, FileName + AppName /// </summary> public string ZipFileName; /// <summary> /// AppSettings.WorkingDirectory + FolderName + "/" + FileName /// </summary> public string WorkingFileName { get { if (File.Exists(Config.Configuration.WorkingDirectory + FolderName + "/" + FileName)) return Config.Configuration.WorkingDirectory + FolderName + "/" + FileName; return Config.Configuration.OutputDirectory + FolderName + "/" + FileName; } } } /// <summary> /// Process /// </summary> protected Response Process(ActionDelegate action) { if (string.IsNullOrEmpty(Opts.OutputType)) Opts.OutputType = Path.GetExtension(Opts.FileName); if (Opts.OutputType.ToLower() == ".html" || Opts.OutputType == ".SVG" || Opts.IsPicture) Opts.CreateZip = true; if (string.IsNullOrEmpty(Opts.ZipFileName) && Opts.CalculateZipFileName) Opts.ZipFileName = Path.GetFileNameWithoutExtension(Opts.FileName) + Opts.AppName; return Process(GetType().Name, Opts.ResultFileName, Opts.FolderName, Opts.OutputType, Opts.CreateZip, Opts.CheckNumberOfPages, Opts.MethodName, action, Opts.DeleteSourceFolder, Opts.ZipFileName); } /// <summary> /// init Options /// </summary> protected Options Opts = new Options(); ///<Summary> /// Process ///</Summary> /// <param name="controllerName"></param> /// <param name="fileName"></param> /// <param name="folderName"></param> /// <param name="productName"></param> /// <param name="productFamily"></param> /// <param name="methodName"></param> /// <param name="action"></param> protected async Task<Response> Process(string controllerName, string fileName, string folderName, string productName, string productFamily, string methodName, inFileActionDelegate action) { string tempFileName = fileName; string sourceFolder = Config.Configuration.WorkingDirectory + folderName; fileName = sourceFolder + "/" + fileName; string statusValue = "OK"; int statusCodeValue = 200; try { action(fileName); //Directory.Delete(sourceFolder, true); } catch (Exception ex) { statusCodeValue = 500; statusValue = "500 " + ex.Message; } return new Response { Status = statusValue, StatusCode = statusCodeValue, }; } } }
// ------------------------------------------------------------------------------------------- // <copyright file="ItemUtil.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // ------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------------------------------- namespace Sitecore.Ecommerce.Utils { using System; using System.Web; using Globalization; using Layouts; using Links; using Sitecore.Data.Fields; using Sitecore.Data.Items; /// <summary> /// Util class for eCommerce module /// </summary> public static class ItemUtil { /// <summary> Gets the first ascendant or self with value from item. </summary> /// <param name="field"> The field name </param> /// <param name="item"> The item to proceed </param> /// <returns>returns value from item </returns> public static string GetFirstAscendantOrSelfWithValueFromItem(string field, Item item) { while (item != null && item[field] == string.Empty) { item = item.Parent; } return item != null ? item[field] : string.Empty; } /// <summary> Gets the title or dictionary entry if title is empty </summary> /// <param name="item"> The item. </param> /// <param name="isEditModeEnabled"> if set to <c>true</c> [is edit mode enabled]. </param> /// <returns>returns title or dictionary entry </returns> public static string GetTitleOrDictionaryEntry(Item item, bool isEditModeEnabled) { string title = item["Title"]; return title; } /// <summary> Gets a navigation link item wich is descendant of current sitecore item </summary> /// <param name="key"> The key to proceed </param> /// <returns>returns navigation link item</returns> public static Item GetNavigationLinkItem(string key) { return GetNavigationLinkItem(key, Sitecore.Context.Item); } /// <summary> Gets the navigation link item wich is descendant of selected sitecore item </summary> /// <param name="key"> The key to prcceed </param> /// <param name="item"> The selected sitecore item. </param> /// <returns>returns item </returns> public static Item GetNavigationLinkItem(string key, Item item) { Item navigationLinkitem = item.Axes.SelectSingleItem(string.Format("./*[@@templatename='Navigation Links']/*[@key='{0}']", key)); return navigationLinkitem; } /// <summary> /// Gets the navigation link title. /// </summary> /// <param name="navigationLinkItem"> /// The navigation link item. /// </param> /// <returns> /// </returns> public static string GetNavigationLinkTitle(Item navigationLinkItem) { return GetNavigationLinkTitle(navigationLinkItem, false); } /// <summary> Gets the navigation link title. </summary> /// <param name="key"> The key. </param> /// <param name="isEditModeEnabled"> if set to <c>true</c> [is edit mode enabled]. </param> /// <returns>returns navigation link title </returns> public static string GetNavigationLinkTitle(string key, bool isEditModeEnabled) { Item navigationLinkItem = GetNavigationLinkItem(key); if (navigationLinkItem != null) { return GetNavigationLinkTitle(navigationLinkItem, isEditModeEnabled); } return string.Empty; } /// <summary> /// Gets the navigation link title. /// </summary> /// <param name="navigationLinkItem"> /// The navigation link item. /// </param> /// <param name="isEditModeEnabled"> /// if set to <c>true</c> [is edit mode enabled]. /// </param> /// <returns> /// </returns> public static string GetNavigationLinkTitle(Item navigationLinkItem, bool isEditModeEnabled) { return GetTitleOrDictionaryEntry(navigationLinkItem, isEditModeEnabled); } /// <summary> /// Gets the navigation link path. /// </summary> /// <param name="key"> /// The key. /// </param> /// <param name="includeQuery"> /// if set to <c>true</c> [include query]. /// </param> /// <returns> /// </returns> public static string GetNavigationLinkPath(string key, bool includeQuery) { Item navigationLinkItem = GetNavigationLinkItem(key); if (navigationLinkItem != null) { return GetNavigationLinkPath(navigationLinkItem, includeQuery); } return null; } /// <summary> /// Gets the navigation link path. /// </summary> /// <param name="navigationLinkItem"> /// The navigation link item. /// </param> /// <param name="includeQuery"> /// if set to <c>true</c> [include query]. /// </param> /// <returns> /// </returns> public static string GetNavigationLinkPath(Item navigationLinkItem, bool includeQuery) { LinkField generalLink = navigationLinkItem.Fields["Link"]; if (generalLink != null) { if (generalLink.TargetItem != null) { if (includeQuery) { return LinkManager.GetItemUrl(generalLink.TargetItem) + HttpContext.Current.Request.Url.Query; } return LinkManager.GetItemUrl(generalLink.TargetItem); } } return string.Empty; } /// <summary> /// Gets the navigation link path. /// </summary> /// <param name="key">The key of the link.</param> /// <returns>the navigation link path.</returns> public static string GetNavigationLinkPath(string key) { return GetNavigationLinkPath(key, true); } /// <summary> /// Gets the navigation link path. /// </summary> /// <param name="navigationLinkItem">The navigation link item.</param> /// <returns>the navigation link path.</returns> public static string GetNavigationLinkPath(Item navigationLinkItem) { return GetNavigationLinkPath(navigationLinkItem, true); } /// <summary> /// Gets the link to an item from item ID /// </summary> /// <param name="itemID"> /// The item Id. /// </param> /// <param name="addQueryString"> /// Whether add the query string. /// </param> /// <returns> /// The item url for website. /// </returns> public static string GetItemUrl(string itemID, bool addQueryString) { if (!string.IsNullOrEmpty(itemID)) { Item item = Sitecore.Context.Database.GetItem(itemID); if (item != null) { string itemUrl = LinkManager.GetItemUrl(item); return addQueryString ? string.Format("{0}{1}", itemUrl, HttpContext.Current.Request.Url.Query) : itemUrl; } } return String.Empty; } /// <summary> /// Gets the item full URL. /// </summary> /// <param name="itemID">The item ID.</param> /// <param name="addQueryString">if set to <c>true</c> [add query string].</param> /// <returns>The item full url</returns> public static string GetItemFullUrl(string itemID, bool addQueryString) { if (!string.IsNullOrEmpty(itemID)) { Item item = Sitecore.Context.Database.GetItem(itemID); if (item != null) { string itemUrl = item.Paths.FullPath; return addQueryString ? string.Format("{0}{1}", itemUrl, HttpContext.Current.Request.Url.Query) : itemUrl; } } return String.Empty; } /// <summary> /// Chekcs if current sitecore item has print layout /// </summary> /// <returns>The result.</returns> public static bool CurrentItemHasPrintLayout() { Item item = Sitecore.Context.Item; if (item == null) { return false; } Item print = Sitecore.Context.Device.InnerItem.Axes.SelectSingleItem("../*[@@name='Print']"); if (print != null) { var device = new DeviceItem(print); RenderingReference[] renderings = item.Visualization.GetRenderings(device, false); return renderings != null && renderings.Length != 0; } return false; } /// <summary> /// Redirects to navigation link. /// </summary> /// <param name="key">The key.</param> /// <param name="includeQuery">if set to <c>true</c> [include query].</param> public static void RedirectToNavigationLink(string key, bool includeQuery) { string path = GetNavigationLinkPath(key, includeQuery); if (!string.IsNullOrEmpty(path) && HttpContext.Current != null) { HttpContext.Current.Response.Redirect(path); } } } }